reformat_manager.cpp 29.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13
/**
 * \file src/gopt/impl/reformat_manager.cpp
 * MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
 *
 * Copyright (c) 2014-2021 Megvii Inc. All rights reserved.
 *
 * 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/gopt/reformat_manager.h"
14
#include "./utils.h"
15
#include "megbrain/opr/tensor_manip.h"
16
#include "megbrain/utils/arith_helper.h"
17 18 19 20

using namespace mgb;
using namespace gopt;
using NamedTensorShape = megdnn::NamedTensorShape;
21
using Dimension = megdnn::Dimension;
22 23

namespace {
24
static inline int gcd(const int& p, const int& q) {
25 26 27 28 29 30 31 32 33 34 35
    int x = p, y = q;
    while (y != 0) {
        if (x < y) {
            y = (y % x);
        } else {
            x = (x % y);
            std::swap(x, y);
        }
    }
    return x;
}
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72

static inline size_t extra_alignment(
        ReformatManager::ReformatKey::Attribute attr,
        TensorFormats target_formats, DType dt, size_t channel_alignment) {
    using Attribute = ReformatManager::ReformatKey::Attribute;
    if (attr & Attribute::AUTO_PADDING_NHWC) {
        constexpr size_t alignment_in_bits = 32;
        size_t dtype_bits = dt.is_low_bit() ? dt.low_bit() : dt.size(1) * 8;
        size_t extra_alignment = alignment_in_bits >= dtype_bits
                                         ? alignment_in_bits / dtype_bits
                                         : 1;
        if (target_formats == TensorFormats::NHWC)
            channel_alignment = extra_alignment * channel_alignment /
                                gcd(channel_alignment, extra_alignment);
        return channel_alignment;
    }
    return channel_alignment;
}

static inline std::tuple<size_t, size_t> extra_alignment(
        const ReformatManager::ReformatKey& key, DType dt,
        size_t input_channel_alignment, size_t output_channel_alignment) {
    using Attribute = ReformatManager::ReformatKey::Attribute;
    if (key.attribute & Attribute::AUTO_PADDING_NHWC) {
        constexpr size_t alignment_in_bits = 32;
        size_t dtype_bits = dt.is_low_bit() ? dt.low_bit() : dt.size(1) * 8;
        size_t extra_alignment = alignment_in_bits >= dtype_bits
                                         ? alignment_in_bits / dtype_bits
                                         : 1;
        if (key.input_format == TensorFormats::NHWC)
            input_channel_alignment =
                    input_channel_alignment * extra_alignment /
                    gcd(input_channel_alignment, extra_alignment);
        if (key.output_format == TensorFormats::NHWC)
            output_channel_alignment =
                    output_channel_alignment * extra_alignment /
                    gcd(output_channel_alignment, extra_alignment);
M
Megvii Engine Team 已提交
73 74
        return std::make_tuple(input_channel_alignment,
                               output_channel_alignment);
75
    }
M
Megvii Engine Team 已提交
76
    return std::make_tuple(input_channel_alignment, output_channel_alignment);
77
}
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
};  // namespace

// =================== ReformatManager::ReformatKey ====================*/
std::string ReformatManager::ReformatKey::to_string() const {
    auto&& i = tensor_formats_to_named_tensor_shape(input_format);
    auto&& o = tensor_formats_to_named_tensor_shape(output_format);
    std::string input_name, output_name;

#define cb(_name)                          \
    if (input_dtype == DTypeEnum::_name) { \
        input_name = #_name;               \
    } else
    MEGDNN_FOREACH_DTYPE_NAME(cb)
    MEGDNN_FOREACH_PARAMETERIZED_DTYPE(cb) {
        mgb_throw(MegBrainError, "invalid input dtype enum(%u)",
                  static_cast<uint32_t>(input_dtype));
    }
#undef cb
#define cb(_name)                           \
    if (output_dtype == DTypeEnum::_name) { \
        output_name = #_name;               \
    } else
    MEGDNN_FOREACH_DTYPE_NAME(cb)
    MEGDNN_FOREACH_PARAMETERIZED_DTYPE(cb) {
        mgb_throw(MegBrainError, "invalid output dtype enum(%u)",
                  static_cast<uint32_t>(output_dtype));
    }
#undef cb
    return ssprintf("%s;%s;%s;%s;%s", i.to_string().c_str(),
                    o.to_string().c_str(),
                    std::to_string(static_cast<uint32_t>(attribute)).c_str(),
                    input_name.c_str(), output_name.c_str());
}

size_t ReformatManager::ReformatKey::Hash::operator()(
        const ReformatKey& key) const {
    auto enumhash = mgb::enumhash();
    size_t h = enumhash(key.input_format);
    h = mgb::hash_pair_combine(h, enumhash(key.output_format));
    h = mgb::hash_pair_combine(h, enumhash(key.attribute));
    h = mgb::hash_pair_combine(h, enumhash(key.input_dtype));
    h = mgb::hash_pair_combine(h, enumhash(key.output_dtype));
    return h;
}

bool ReformatManager::ReformatKey::Equal::operator()(
        const ReformatKey& lhs, const ReformatKey& rhs) const {
    return lhs.input_format == rhs.input_format &&
           lhs.output_format == rhs.output_format &&
           lhs.input_dtype == rhs.input_dtype &&
           lhs.output_dtype == rhs.output_dtype &&
           lhs.attribute == rhs.attribute;
}

// =================== ReformatManager ====================*/
ReformatManager::ReformatManager() {
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
    using Attribute = ReformatKey::Attribute;
    {
        auto i = TensorFormats::NCHWc4, o = TensorFormats::CHWNc4;
        auto&& impl1 = [](const VarNodeArray& vars) {
            return opr::RelayoutFormat::make(
                           vars[0],
                           megdnn::param::RelayoutFormat::Mode::NCHW4_CHWN4)
                    .node();
        };
        m_cache.emplace(ReformatKey{i, o}, impl1);
        auto&& impl2 = [](const VarNodeArray& vars) {
            return opr::RelayoutFormat::make(
                           vars[0],
                           megdnn::param::RelayoutFormat::Mode::CHWN4_NCHW4)
                    .node();
        };
        m_cache.emplace(ReformatKey{o, i}, impl2);
151 152 153 154 155 156 157 158 159 160 161 162
    }
    {
        auto i = TensorFormats::NCHW, o = TensorFormats::NCHWc4;
        auto&& impl = [](const VarNodeArray& vars) {
            return opr::RelayoutFormat::make(vars[0],
                                             megdnn::param::RelayoutFormat::
                                                     Mode::NCHW_NCHW4_IC_SMALL)
                    .node();
        };
        m_cache.emplace(ReformatKey{i, o, Attribute::IC_SMALL}, impl);
    }
    {
163
        auto i = TensorFormats::KCRS, o = TensorFormats::KCRSc4;
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
        auto&& impl = [](const VarNodeArray& vars) {
            return opr::RelayoutFormat::make(
                           vars[0],
                           megdnn::param::RelayoutFormat::Mode::
                                   NCHW_NCHW4_IC_SMALL_CONV_DENSE_WEIGHT)
                    .node();
        };
        m_cache.emplace(ReformatKey{i, o, Attribute::IC_SMALL}, impl);
    }
    {
        auto i = TensorFormats::NCHW, o = TensorFormats::NCHWc64;
        auto&& impl = [](const VarNodeArray& vars) {
            return opr::RelayoutFormat::make(
                           vars[0],
                           megdnn::param::RelayoutFormat::Mode::NCHW_NCHW64)
                    .node();
        };
        m_cache.emplace(
                ReformatKey{i, o, Attribute::DEFAULT, DTypeEnum::QuantizedS4,
                            DTypeEnum::QuantizedS4},
                impl);
        m_cache.emplace(ReformatKey{i, o, Attribute::DEFAULT,
                                    DTypeEnum::Quantized4Asymm,
                                    DTypeEnum::Quantized4Asymm},
                        impl);
    }
    {
        auto i = TensorFormats::NCHWc64, o = TensorFormats::NCHW;
        auto&& impl = [](const VarNodeArray& vars) {
            return opr::RelayoutFormat::make(
                           vars[0],
195
                           megdnn::param::RelayoutFormat::Mode::NCHW64_NCHW)
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
                    .node();
        };
        m_cache.emplace(
                ReformatKey{i, o, Attribute::DEFAULT, DTypeEnum::QuantizedS4,
                            DTypeEnum::QuantizedS4},
                impl);
        m_cache.emplace(ReformatKey{i, o, Attribute::DEFAULT,
                                    DTypeEnum::Quantized4Asymm,
                                    DTypeEnum::Quantized4Asymm},
                        impl);
    }
    {
        auto i = TensorFormats::NCHW, o = TensorFormats::NHWC;
        auto&& impl = [](const VarNodeArray& vars) {
            return opr::RelayoutFormat::make(
                           vars[0],
                           megdnn::param::RelayoutFormat::Mode::NCHW_NHWC)
                    .node();
        };
        m_cache.emplace(
                ReformatKey{i, o, Attribute::DEFAULT, DTypeEnum::QuantizedS4,
                            DTypeEnum::QuantizedS4},
                impl);
        m_cache.emplace(ReformatKey{i, o, Attribute::DEFAULT,
                                    DTypeEnum::Quantized4Asymm,
                                    DTypeEnum::Quantized4Asymm},
                        impl);
    }
    {
        auto i = TensorFormats::NHWC, o = TensorFormats::NCHW;
        auto&& impl = [](const VarNodeArray& vars) {
            return opr::RelayoutFormat::make(
                           vars[0],
229
                           megdnn::param::RelayoutFormat::Mode::NHWC_NCHW)
230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328
                    .node();
        };
        m_cache.emplace(
                ReformatKey{i, o, Attribute::DEFAULT, DTypeEnum::QuantizedS4,
                            DTypeEnum::QuantizedS4},
                impl);
        m_cache.emplace(ReformatKey{i, o, Attribute::DEFAULT,
                                    DTypeEnum::Quantized4Asymm,
                                    DTypeEnum::Quantized4Asymm},
                        impl);
    }
    // nhcw4
    {
        auto i = TensorFormats::KCRS, o = TensorFormats::KRSCk4;
        auto&& impl = [](const VarNodeArray& vars) {
            return opr::RelayoutFormat::make(vars[0],
                                             megdnn::param::RelayoutFormat::
                                                     Mode::INTER_WEIGHT_DENSEI)
                    .node();
        };
        m_cache.emplace(ReformatKey{i, o, Attribute::IMAGE2D}, impl);
    }
    {
        auto i = TensorFormats::KCRS, o = TensorFormats::GKRSCk4;
        auto&& impl = [](const VarNodeArray& vars) {
            return opr::RelayoutFormat::make(vars[0],
                                             megdnn::param::RelayoutFormat::
                                                     Mode::INTER_WEIGHT_GROUPI)
                    .node();
        };
        m_cache.emplace(ReformatKey{i, o, Attribute::IMAGE2D}, impl);
    }
    {
        auto i = TensorFormats::KCRS, o = TensorFormats::C1RSc4;
        auto&& impl = [](const VarNodeArray& vars) {
            return opr::RelayoutFormat::make(vars[0],
                                             megdnn::param::RelayoutFormat::
                                                     Mode::INTER_WEIGHT_CHANI)
                    .node();
        };
        m_cache.emplace(ReformatKey{i, o, Attribute::IMAGE2D}, impl);
    }
    {
        auto i = TensorFormats::NCHW, o = TensorFormats::NHCWc4;
        auto&& impl = [](const VarNodeArray& vars) {
            return opr::RelayoutFormat::make(
                           vars[0],
                           megdnn::param::RelayoutFormat::Mode::NCHW_NHWCD4I)
                    .node();
        };
        m_cache.emplace(ReformatKey{i, o, Attribute::IMAGE2D}, impl);
    }
    {
        auto i = TensorFormats::NHCWc4, o = TensorFormats::NCHW;
        auto&& impl = [](const VarNodeArray& vars) {
            return opr::RelayoutFormat::make(
                           vars[0],
                           megdnn::param::RelayoutFormat::Mode::NCHW_NHWCD4I)
                    .node();
        };
        m_cache.emplace(ReformatKey{i, o, Attribute::IMAGE2D}, impl);
    }
    // nhcw4-dot
    {
        auto i = TensorFormats::KCRS, o = TensorFormats::KRSCk4c4;
        auto&& impl = [](const VarNodeArray& vars) {
            return opr::RelayoutFormat::make(
                           vars[0], megdnn::param::RelayoutFormat::Mode::
                                            INTER_WEIGHT_DENSEI_DOT)
                    .node();
        };
        m_cache.emplace(
                ReformatKey{i, o, Attribute::IMAGE2D, DTypeEnum::QuantizedS8,
                            DTypeEnum::QuantizedS8},
                impl);
        m_cache.emplace(ReformatKey{i, o, Attribute::IMAGE2D,
                                    DTypeEnum::Quantized8Asymm,
                                    DTypeEnum::Quantized8Asymm},
                        impl);
    }
    {
        auto i = TensorFormats::GKCRS, o = TensorFormats::GKRSCk4c4;
        auto&& impl = [](const VarNodeArray& vars) {
            return opr::RelayoutFormat::make(
                           vars[0], megdnn::param::RelayoutFormat::Mode::
                                            INTER_WEIGHT_GROUPI_DOT)
                    .node();
        };
        m_cache.emplace(
                ReformatKey{i, o, Attribute::IMAGE2D, DTypeEnum::QuantizedS8,
                            DTypeEnum::QuantizedS8},
                impl);
        m_cache.emplace(ReformatKey{i, o, Attribute::IMAGE2D,
                                    DTypeEnum::Quantized8Asymm,
                                    DTypeEnum::Quantized8Asymm},
                        impl);
    }
}

329
ReformatManager::ReformatImpl ReformatManager::get(
330
        const ReformatKey& key) const {
331
    using Attribute = ReformatKey::Attribute;
332
    MGB_TRY {
333 334 335 336 337 338 339 340 341 342 343 344 345 346 347
        {
            auto find = m_cache.find(key);
            if (find != m_cache.end()) {
                auto rst = find->second;
                return rst;
            }
        }
        if (key.attribute == Attribute::AUTO_PADDING_NHWC) {
            auto key_ = key;
            key_.attribute = Attribute::DEFAULT;
            auto find = m_cache.find(key_);
            if (find != m_cache.end()) {
                auto rst = find->second;
                return rst;
            }
348
        }
349 350
        mgb_assert(!(key.attribute & Attribute::IMAGE2D) &&
                   !(key.attribute & Attribute::IC_SMALL));
351 352 353 354 355 356
        auto&& i = key.input_format;
        auto&& o = key.output_format;
        auto ishp = tensor_formats_to_named_tensor_shape(i);
        auto oshp = tensor_formats_to_named_tensor_shape(o);
        auto builder = std::get<0>(ReformatEmitter{ishp, oshp}.emit());
        return builder;
357 358 359 360 361 362 363 364 365 366
    }
    MGB_CATCH(std::exception & exc, {
        mgb_log_error(
                "cannot find ReformatImpl for ReformatKey(%s), extra "
                "message(%s)",
                key.to_string().c_str(), exc.what());
        throw;
    })
}

367 368 369 370 371 372 373
ReformatManager::ReformatImpl ReformatManager::auto_aligned_reformat_featrue(
        const VarNode* orig_var, TensorFormats orig_format,
        const ReformatKey& key) const {
    NamedTensorShape input_shape =
            tensor_formats_to_named_tensor_shape(key.input_format);
    NamedTensorShape output_shape =
            tensor_formats_to_named_tensor_shape(key.output_format);
374 375 376 377
    size_t input_alignment = 0;
    size_t output_alignment = 0;
    size_t input_channel_idx = input_shape.ndim,
           output_channel_idx = input_shape.ndim;
378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393
    for (size_t i = 0; i < input_shape.ndim; ++i) {
        if (input_shape[i].name() == Dimension::Name::C &&
            input_shape[i].extent() == Dimension::UNDETERMINED_EXTENT) {
            input_channel_idx = i;
            input_alignment = input_shape[i].stride();
            break;
        }
    }
    for (size_t i = 0; i < output_shape.ndim; ++i) {
        if (output_shape[i].name() == Dimension::Name::C &&
            output_shape[i].extent() == Dimension::UNDETERMINED_EXTENT) {
            output_channel_idx = i;
            output_alignment = output_shape[i].stride();
            break;
        }
    }
394 395 396 397 398 399 400 401 402
    mgb_assert(input_channel_idx < input_shape.ndim &&
                       output_channel_idx < input_shape.ndim,
               "invalid channel idx(in_channel:%zu, out_channel:%zu, shp:%s)",
               input_channel_idx, output_channel_idx,
               input_shape.to_string().c_str());
    mgb_assert(input_alignment > 0 && output_alignment > 0,
               "invalid alignment(in_channel:%zu, out_channel:%zu, shp:%s)",
               input_alignment, output_alignment,
               input_shape.to_string().c_str());
403 404
    std::tie(input_alignment, output_alignment) = extra_alignment(
            key, orig_var->dtype(), input_alignment, output_alignment);
405 406 407
    NamedTensorShape orig_shape =
            tensor_formats_to_named_tensor_shape(orig_format);
    size_t orig_channel = 0;
408 409 410 411 412
    mgb_assert(orig_var->shape().ndim == orig_shape.ndim,
               "incompatible NamedTensorShape for "
               "feature(var:%s;shape:%s)",
               cg::dump_var_info({const_cast<VarNode*>(orig_var)}).c_str(),
               orig_shape.to_string().c_str());
413 414 415 416 417 418 419 420
    for (size_t i = 0; i < orig_shape.ndim; ++i) {
        if (orig_shape[i].name() == Dimension::Name::C &&
            orig_shape[i].extent() == Dimension::UNDETERMINED_EXTENT) {
            orig_channel = orig_var->shape()[i] * orig_shape[i].stride();
            break;
        }
    }
    mgb_assert(orig_channel > 0,
421 422 423
               "incompatible NamedTensorShape for "
               "feature(var:%s;shape:%s)",
               cg::dump_var_info({const_cast<VarNode*>(orig_var)}).c_str(),
424 425 426 427 428
               orig_shape.to_string().c_str());
    size_t aligned_in_channel =
            divup(orig_channel, input_alignment) * input_alignment;
    size_t aligned_out_channel =
            divup(orig_channel, output_alignment) * output_alignment;
429
    size_t common_alignment = input_alignment * output_alignment /
430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448
                              gcd(input_alignment, output_alignment);
    size_t aligned_channel =
            divup(orig_channel, common_alignment) * common_alignment;
    auto builder = [key, aligned_channel, aligned_in_channel,
                    aligned_out_channel, input_shape, input_channel_idx,
                    output_shape,
                    output_channel_idx](const VarNodeArray& vars) {
        VarNode *x, *cur;
        x = cur = vars[0];
        if (aligned_channel > aligned_in_channel) {
            auto padding_shape = input_shape;
            auto&& dim = padding_shape[input_channel_idx];
            size_t const_extent =
                    (aligned_channel - aligned_in_channel) / dim.stride();
            padding_shape[input_channel_idx] =
                    Dimension(dim.name(), dim.stride(), const_extent);
            auto make_shape = std::get<0>(
                    MakeShapeEmitter{input_shape, padding_shape}.emit());
            auto padding_shp_var = make_shape({x});
449 450 451
            auto padding = std::get<0>(PaddingEmitter{
                    padding_shape, const_extent, input_channel_idx}
                                               .emit());
452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470
            cur = padding({cur, padding_shp_var});
        }
        cur = ReformatManager::instance().get(key)({cur});
        if (aligned_channel > aligned_out_channel) {
            auto&& dim = output_shape[output_channel_idx];
            size_t const_extent = aligned_out_channel / dim.stride();
            auto sub = std::get<0>(
                    SubtensorEmitter{const_extent, output_channel_idx}.emit());
            cur = sub({cur});
        }
        return cur;
    };
    return builder;
}

ReformatManager::ReformatImpl ReformatManager::auto_aligned_reformat_weight(
        const VarNode* orig_var, const ReformatKey& key,
        const AlignmentDesc& extra_alignment) const {
    size_t in_channels = 0, out_channels = 0;
471
    Dimension::Name out_channel_name = Dimension::Name::C;
472
    auto input_shape = tensor_formats_to_named_tensor_shape(key.input_format);
473 474
    size_t input_channel_idx = input_shape.ndim,
           output_channel_idx = input_shape.ndim;
475 476 477
    for (size_t i = 0; i < input_shape.ndim; ++i) {
        if (input_shape[i].name() == Dimension::Name::C &&
            input_shape[i].extent() == Dimension::UNDETERMINED_EXTENT) {
478
            in_channels = orig_var->shape()[i] * input_shape[i].stride();
479
            input_channel_idx = i;
480 481 482
//            mgb_assert(input_shape[i].stride() == 1,
//                       "unsupport weight format(got:%s)",
//                       input_shape.to_string().c_str());
483 484 485 486 487 488 489 490 491 492 493
        } else if ((input_shape[i].name() == Dimension::Name::K ||
                    input_shape[i].name() == Dimension::Name::N) &&
                   input_shape[i].extent() == Dimension::UNDETERMINED_EXTENT) {
            out_channels = orig_var->shape()[i];
            out_channel_name = input_shape[i].name();
            output_channel_idx = i;
            mgb_assert(input_shape[i].stride() == 1,
                       "unsupport weight format(got:%s)",
                       input_shape.to_string().c_str());
        }
    }
494 495 496 497 498 499 500 501 502
    mgb_assert(out_channel_name == Dimension::Name::K ||
                       out_channel_name == Dimension::Name::N,
               "invalid out channel(shp:%s)", input_shape.to_string().c_str());
    mgb_assert(input_channel_idx < input_shape.ndim &&
                       output_channel_idx < input_shape.ndim,
               "invalid channel idx(in_channel:%zu, out_channel:%zu, shp:%s)",
               input_channel_idx, output_channel_idx,
               input_shape.to_string().c_str());
    size_t in_channel_alignment = 0, out_channel_alignment = 0;
503 504 505 506 507 508 509 510 511 512
    auto output_shape = tensor_formats_to_named_tensor_shape(key.output_format);
    for (size_t i = 0; i < output_shape.ndim; ++i) {
        if (output_shape[i].name() == Dimension::Name::C &&
            output_shape[i].extent() == Dimension::UNDETERMINED_EXTENT) {
            in_channel_alignment = output_shape[i].stride();
        } else if (output_shape[i].name() == out_channel_name &&
                   output_shape[i].extent() == Dimension::UNDETERMINED_EXTENT) {
            out_channel_alignment = output_shape[i].stride();
        }
    }
513 514 515 516
    mgb_assert(in_channel_alignment > 0 && out_channel_alignment > 0,
               "invalid alignment(in_channel:%zu, out_channel:%zu, shp:%s)",
               in_channel_alignment, out_channel_alignment,
               output_shape.to_string().c_str());
517 518 519 520 521 522
    in_channel_alignment =
            ::extra_alignment(key.attribute, key.output_format,
                              orig_var->dtype(), in_channel_alignment);
    out_channel_alignment =
            ::extra_alignment(key.attribute, key.output_format,
                              orig_var->dtype(), out_channel_alignment);
523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546
    size_t aligned_in_channel =
            divup(in_channels, in_channel_alignment) * in_channel_alignment;
    if (extra_alignment.name == out_channel_name) {
        out_channel_alignment =
                extra_alignment.alignment * out_channel_alignment /
                gcd(extra_alignment.alignment, out_channel_alignment);
    }
    size_t aligned_out_channel =
            divup(out_channels, out_channel_alignment) * out_channel_alignment;
    auto builder = [key, input_shape, in_channels, input_channel_idx,
                    aligned_in_channel, out_channels, output_channel_idx,
                    aligned_out_channel](const VarNodeArray& vars) {
        VarNode *x, *cur;
        x = cur = vars[0];
        if (aligned_in_channel > in_channels) {
            auto padding_shape = input_shape;
            auto&& dim = padding_shape[input_channel_idx];
            size_t const_extent =
                    (aligned_in_channel - in_channels) / dim.stride();
            padding_shape[input_channel_idx] =
                    Dimension(dim.name(), dim.stride(), const_extent);
            auto make_shape = std::get<0>(
                    MakeShapeEmitter{input_shape, padding_shape}.emit());
            auto padding_shp_var = make_shape({x});
547 548 549
            auto padding = std::get<0>(PaddingEmitter{
                    padding_shape, const_extent, input_channel_idx}
                                               .emit());
550 551 552 553 554 555 556 557 558 559 560 561
            cur = padding({cur, padding_shp_var});
        }
        if (aligned_out_channel > out_channels) {
            auto padding_shape = input_shape;
            auto&& dim = padding_shape[output_channel_idx];
            size_t const_extent =
                    (aligned_out_channel - out_channels) / dim.stride();
            padding_shape[output_channel_idx] =
                    Dimension(dim.name(), dim.stride(), const_extent);
            auto make_shape = std::get<0>(
                    MakeShapeEmitter{input_shape, padding_shape}.emit());
            auto padding_shp_var = make_shape({cur});
562 563 564
            auto padding = std::get<0>(PaddingEmitter{
                    padding_shape, const_extent, output_channel_idx}
                                               .emit());
565 566 567 568 569 570 571 572
            cur = padding({cur, padding_shp_var});
        }
        cur = ReformatManager::instance().get(key)({cur});
        return cur;
    };
    return builder;
}

573
const ReformatManager& ReformatManager::instance() {
574 575
    static ReformatManager inst;
    return inst;
576
}
577

578 579 580
TensorShape ReformatManager::make_aligned_tensor_shape(
        const VarNode* var, TensorFormats orig_formats,
        TensorFormats target_formats, ReformatKey::Attribute extra_attribute) {
581 582 583 584 585 586 587 588 589 590 591 592
    using Dimension = megdnn::Dimension;
    static constexpr uint32_t UNDETERMINED_EXTENT =
            Dimension::UNDETERMINED_EXTENT;
    auto orig_shape = tensor_formats_to_named_tensor_shape(orig_formats);
    auto target_shape = tensor_formats_to_named_tensor_shape(target_formats);

    TensorShape oshp = var->shape();
    mgb_assert(oshp.is_scalar() || oshp.ndim == orig_shape.ndim,
               "orig shape of var node is not compatible with tensor "
               "formats(var:%s;shp:%s;fmt:%s)",
               var->cname(), oshp.to_string().c_str(),
               orig_shape.to_string().c_str());
593 594
    if (oshp.is_scalar())
        return oshp;
595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616
    TensorShape tshp;
    ThinHashMap<Dimension::Name, int> name2dominant;
    for (size_t i = 0; i < orig_shape.ndim; ++i) {
        auto name = orig_shape[i].name();
        if (orig_shape[i].extent() == UNDETERMINED_EXTENT) {
            auto insert = name2dominant.insert(std::make_pair(name, i));
            mgb_assert(insert.second);
        }
    }

    tshp.ndim = target_shape.ndim;
    for (size_t i = 0; i < target_shape.ndim; ++i) {
        auto name = target_shape[i].name();
        if (target_shape[i].extent() == UNDETERMINED_EXTENT) {
            int idx = name2dominant.at(name);
            bool mul = orig_shape[idx] < target_shape[i];
            size_t factor = mul ? (target_shape[i] / orig_shape[idx]).extent()
                                : (orig_shape[idx] / target_shape[i]).extent();
            if (mul)
                tshp[i] = oshp[idx] * factor;
            else
                tshp[i] = divup(oshp[idx], factor);
617 618 619 620 621 622 623 624 625
            if (name == Dimension::Name::C) {
                size_t channel_alignment = target_shape[i].stride();
                size_t channels = tshp[i] * channel_alignment;
                size_t new_channel_alignment =
                        extra_alignment(extra_attribute, target_formats,
                                        var->dtype(), channel_alignment);
                tshp[i] = divup(channels, new_channel_alignment) *
                          new_channel_alignment / channel_alignment;
            }
626 627 628 629 630 631 632
        } else {
            tshp[i] = target_shape[i].extent();
        }
    }
    return tshp;
}

633 634 635 636 637 638
TensorShape ReformatManager::make_aligned_weight_shape(
        const VarNode* var, TensorFormats orig_formats,
        TensorFormats target_formats, TensorFormats extra_formats,
        ReformatKey::Attribute extra_attribute) {
    auto tshp = make_aligned_tensor_shape(var, orig_formats, target_formats,
                                          extra_attribute);
639 640 641 642 643 644 645 646 647 648
    auto extra_shape = tensor_formats_to_named_tensor_shape(extra_formats);
    using Dimension = megdnn::Dimension;
    static constexpr uint32_t UNDETERMINED_EXTENT =
            Dimension::UNDETERMINED_EXTENT;
    size_t out_channel_alignment = 1;
    for (size_t i = 0; i < extra_shape.ndim; ++i) {
        auto name = extra_shape[i].name();
        if (name == Dimension::Name::C &&
            extra_shape[i].extent() == UNDETERMINED_EXTENT) {
            out_channel_alignment = extra_shape[i].stride();
649 650 651
            out_channel_alignment =
                    extra_alignment(extra_attribute, target_formats,
                                    var->dtype(), out_channel_alignment);
652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667
        }
    }

    auto target_shape = tensor_formats_to_named_tensor_shape(target_formats);
    for (size_t i = 0; i < target_shape.ndim; ++i) {
        auto name = target_shape[i].name();
        if ((name == Dimension::Name::K || name == Dimension::Name::N) &&
            target_shape[i].extent() == UNDETERMINED_EXTENT) {
            size_t out_channels = tshp[i] * target_shape[i].stride();
            tshp[i] = divup(out_channels, out_channel_alignment) *
                      out_channel_alignment / target_shape[i].stride();
        }
    }
    return tshp;
}

668
ReformatManager::AlignmentDesc ReformatManager::make_aligned_desc(
669 670 671 672 673 674 675 676 677 678 679 680 681 682
        TensorFormats weight_format, TensorFormats out_feature_format) {
    using Name = Dimension::Name;
    auto weight_shape = tensor_formats_to_named_tensor_shape(weight_format);
    auto out_shape = tensor_formats_to_named_tensor_shape(out_feature_format);
    size_t out_channel_alignment = 1;
    for (size_t i = 0; i < out_shape.ndim; ++i) {
        auto name = out_shape[i].name();
        auto extent = out_shape[i].extent();
        if ((name == Name::C || name == Name::K) &&
            extent == Dimension::UNDETERMINED_EXTENT) {
            out_channel_alignment = out_shape[i].stride();
            break;
        }
    }
M
Megvii Engine Team 已提交
683
    Name out_channel_name = Name::N;
684 685 686 687 688 689 690 691 692 693 694
    for (size_t i = 0; i < weight_shape.ndim; ++i) {
        auto name = weight_shape[i].name();
        auto extent = weight_shape[i].extent();
        if ((name == Name::N || name == Name::K) &&
            extent == Dimension::UNDETERMINED_EXTENT) {
            out_channel_name = name;
        }
    }
    return AlignmentDesc{out_channel_name, out_channel_alignment};
}

695
// vim: syntax=cpp.doxygen