opr_impl.cpp 11.0 KB
Newer Older
1 2 3 4
/**
 * \file dnn/src/fallback/relayout/opr_impl.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 13
 *
 * 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 "src/fallback/relayout/opr_impl.h"
#include "src/common/relayout_helper.h"
M
Megvii Engine Team 已提交
14 15
#include "src/common/utils.h"
#include "src/naive/handle.h"
16 17 18 19 20 21 22 23 24 25 26 27

#include <cstring>

using namespace megdnn;
using namespace fallback;

namespace {

bool is_lastdim_contig(const TensorLayout& layout) {
    return layout.ndim <= 3 && layout.stride[layout.ndim - 1] == 1;
}

M
Megvii Engine Team 已提交
28
template <size_t sz, typename T0 = char>
29 30 31 32 33 34
struct equiv_ctype_storage {
    T0 _[sz];
};

template <typename dtype>
struct equiv_ctype {
M
Megvii Engine Team 已提交
35 36 37
    using type = std::aligned_storage_t<
            sizeof(typename DTypeTrait<dtype>::ctype),
            alignof(typename DTypeTrait<dtype>::ctype)>;
38 39
};

M
Megvii Engine Team 已提交
40
typedef void (*memcpy_policy_t)(void* cont, void* non_cont, size_t);
41

M
Megvii Engine Team 已提交
42
void memcpy_cont2noncont(void* cont, void* non_cont, size_t size) {
43 44 45
    memcpy(non_cont, cont, size);
}

M
Megvii Engine Team 已提交
46
void memcpy_noncont2cont(void* cont, void* non_cont, size_t size) {
47 48 49 50
    memcpy(cont, non_cont, size);
}

template <typename T>
M
Megvii Engine Team 已提交
51
void call_transpose(size_t batch, size_t m, size_t n, size_t ch, void* src, void* dst) {
52 53 54 55 56 57
    megdnn_assert(ch == 1);
    relayout::transpose_fallback::transpose<T>(
            batch, m, n, static_cast<T*>(src), static_cast<T*>(dst));
}

//! one operand contiguous, and the other non-contiguous
M
Megvii Engine Team 已提交
58
template <typename ctype>
59
void dispatch_on_dtype_cont(
M
Megvii Engine Team 已提交
60 61
        Handle* handle, const TensorND& cont, const TensorND& nonc,
        memcpy_policy_t mcp_pol) {
62 63 64 65 66
    auto ctptr = static_cast<uint8_t*>(cont.raw_ptr),
         ncptr = static_cast<uint8_t*>(nonc.raw_ptr);
    thin_function<void()> kern;
    switch (nonc.layout.ndim) {
        case 2: {
M
Megvii Engine Team 已提交
67
            auto shp0 = nonc.layout.shape[0], shp1 = nonc.layout.shape[1];
68 69 70 71 72
            auto strd0_n = nonc.layout.stride[0] * sizeof(ctype);
            auto strd0_c = shp1 * sizeof(ctype);
            kern = [=]() {
                auto cur_ctptr = ctptr;
                auto cur_ncptr = ncptr;
M
Megvii Engine Team 已提交
73
                for (size_t i = 0; i < shp0; ++i) {
74 75 76 77 78 79 80 81
                    mcp_pol(cur_ctptr, cur_ncptr, strd0_c);
                    cur_ctptr += strd0_c;
                    cur_ncptr += strd0_n;
                }
            };
            break;
        }
        case 3: {
M
Megvii Engine Team 已提交
82
            auto shp0 = nonc.layout.shape[0], shp1 = nonc.layout.shape[1],
83 84 85 86 87 88 89
                 shp2 = nonc.layout.shape[2];
            auto strd0_n = nonc.layout.stride[0] * sizeof(ctype),
                 strd1_n = nonc.layout.stride[1] * sizeof(ctype);
            auto strd1_c = shp2 * sizeof(ctype);
            kern = [=]() {
                auto cur_ctptr = ctptr;
                auto ncptr_row = ncptr;
M
Megvii Engine Team 已提交
90
                for (size_t i = 0; i < shp0; ++i) {
91
                    auto cur_ncptr = ncptr_row;
M
Megvii Engine Team 已提交
92
                    for (size_t j = 0; j < shp1; ++j) {
93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
                        mcp_pol(cur_ctptr, cur_ncptr, strd1_c);
                        cur_ctptr += strd1_c;
                        cur_ncptr += strd1_n;
                    }
                    ncptr_row += strd0_n;
                }
            };
            break;
        }
        default:
            megdnn_assert(0);
    }

    static_cast<naive::HandleImpl*>(handle)->dispatch_kern(std::move(kern));
}

M
Megvii Engine Team 已提交
109 110
void dispatch_cont(
        Handle* handle, const TensorND& cont, const TensorND& nonc,
111 112
        memcpy_policy_t mcp_pol) {
    switch (cont.layout.dtype.enumv()) {
M
Megvii Engine Team 已提交
113 114
#define cb(_dt)                                                       \
    case DTypeTrait<dtype::_dt>::enumv:                               \
115 116 117 118 119 120 121 122 123 124
        return dispatch_on_dtype_cont<equiv_ctype<dtype::_dt>::type>( \
                handle, cont, nonc, mcp_pol);
        MEGDNN_FOREACH_DTYPE_NAME(cb)
        MEGDNN_FOREACH_PARAMETERIZED_DTYPE(cb)
#undef cb
        megdnn_assert(0);
    }
}

const size_t BLOCK_SIZE = 16,
M
Megvii Engine Team 已提交
125
             TRANSPOSE_CV_MAX_C = relayout::transpose_fallback::BLOCK_LINE_SIZE_BYTES;
126 127 128 129 130

/*!
 * \tparam ctype The type of the data
 */
template <typename ctype>
M
Megvii Engine Team 已提交
131 132 133
void transpose_cv_block(
        size_t m, size_t n, size_t ch, size_t i, size_t j, size_t h, size_t w,
        void* src, void* dst) {
134 135 136
    auto batch_src = static_cast<const ctype*>(src);
    auto batch_dst = static_cast<ctype*>(dst);

M
Megvii Engine Team 已提交
137 138 139 140 141 142 143 144 145 146 147 148 149 150 151
#define SET_VAL(dst, src)                      \
    switch (ch) {                              \
        case 3:                                \
            dst[2] = src[2];                   \
            MEGDNN_FALLTHRU                    \
        case 2:                                \
            dst[1] = src[1];                   \
            MEGDNN_FALLTHRU                    \
        case 1:                                \
            dst[0] = src[0];                   \
            break;                             \
        default:                               \
            for (size_t _c = 0; _c < ch; ++_c) \
                dst[_c] = src[_c];             \
            break;                             \
152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
    }

    constexpr size_t B = BLOCK_SIZE;
    static_assert(TRANSPOSE_CV_MAX_C % sizeof(ctype) == 0, "bad ctype");
    ctype tmp[B][B][TRANSPOSE_CV_MAX_C / sizeof(ctype)];
    auto sptr = batch_src + i * n * ch + j * ch;
    for (size_t x = 0; x < h; ++x) {
        for (size_t y = 0; y < w; ++y) {
            SET_VAL(tmp[y][x], (sptr + y * ch))
        }
        sptr += n * ch;
    }

    auto dptr = batch_dst + j * m * ch + i * ch;
    for (size_t x = 0; x < w; ++x) {
        for (size_t y = 0; y < h; ++y) {
            SET_VAL((dptr + y * ch), tmp[x][y])
        }
        dptr += m * ch;
    }
#undef SET_VAL
}

template <typename ctype>
M
Megvii Engine Team 已提交
176 177
void transpose_cv_row(
        size_t m, size_t n, size_t ch, size_t i, size_t h, void* src, void* dst) {
178 179 180 181 182 183 184 185 186 187 188
    constexpr size_t B = BLOCK_SIZE;
    size_t j = 0;
    for (; j + B <= n; j += B) {
        transpose_cv_block<ctype>(m, n, ch, i, j, h, B, src, dst);
    }
    if (j < n) {
        transpose_cv_block<ctype>(m, n, ch, i, j, h, n - j, src, dst);
    }
}

template <typename ctype>
M
Megvii Engine Team 已提交
189
void transpose_cv(size_t batch, size_t m, size_t n, size_t ch, void* src, void* dst) {
190
    constexpr size_t B = BLOCK_SIZE;
M
Megvii Engine Team 已提交
191 192
    auto batch_src = static_cast<ctype*>(src);
    auto batch_dst = static_cast<ctype*>(dst);
193 194 195 196 197 198 199 200 201 202 203 204 205
    for (size_t b = 0; b < batch; ++b) {
        size_t i = 0;
        for (; i + B <= m; i += B) {
            transpose_cv_row<ctype>(m, n, ch, i, B, batch_src, batch_dst);
        }
        if (i < m) {
            transpose_cv_row<ctype>(m, n, ch, i, m - i, batch_src, batch_dst);
        }
        batch_src += m * n * ch;
        batch_dst += m * n * ch;
    }
}

M
Megvii Engine Team 已提交
206
}  // anonymous namespace
207 208

void RelayoutForwardImpl::exec(
M
Megvii Engine Team 已提交
209
        _megdnn_tensor_in src0, _megdnn_tensor_out dst0, Handle* src_handle) {
210 211 212 213 214
    check_cpu_handle(src_handle);
    TensorND src = src0, dst = dst0;
    check_layout_and_canonize(src.layout, dst.layout);

    bool has_neg_stride = false;
M
Megvii Engine Team 已提交
215
    for (size_t i = 0; i < src.layout.ndim; ++i) {
216 217 218 219 220
        if (src.layout.stride[i] < 0) {
            has_neg_stride = true;
            break;
        }
    }
M
Megvii Engine Team 已提交
221
    for (size_t i = 0; i < dst.layout.ndim; ++i) {
222 223 224 225 226 227 228 229 230 231
        if (dst.layout.stride[i] < 0) {
            has_neg_stride = true;
            break;
        }
    }
    if (has_neg_stride) {
        NaiveRelayoutForwardImpl::do_exec(src, dst);
        return;
    }

232 233 234 235 236 237 238
    // FIXME: optimize for lowbit cases
    if (src.layout.dtype.enumv() == DTypeEnum::QuantizedS4 ||
        src.layout.dtype.enumv() == DTypeEnum::Quantized4Asymm) {
        NaiveRelayoutForwardImpl::do_exec(src, dst);
        return;
    }

239 240 241 242 243 244
    relayout::TransposeParam trans_param;
    bool trans = relayout::is_transpose(src.layout, dst.layout, trans_param);
    exec_after_preprocess(src, dst, trans ? &trans_param : nullptr);
}

void RelayoutForwardImpl::exec_after_preprocess(
M
Megvii Engine Team 已提交
245
        const TensorND& src, const TensorND& dst, relayout::TransposeParam* transpose) {
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
    if (transpose) {
        auto dsize = src.layout.dtype.size() * transpose->c;
        void (*kptr)(size_t, size_t, size_t, size_t, void*, void*) = nullptr;
        auto src_addr = reinterpret_cast<uintptr_t>(src.raw_ptr),
             dst_addr = reinterpret_cast<uintptr_t>(dst.raw_ptr);
        if (dsize == 1) {
            megdnn_assert(transpose->c == 1);
            kptr = call_transpose<uint8_t>;
        } else if (dsize == 2) {
            transpose->c = 1;
            if (!((src_addr | dst_addr) & (alignof(uint16_t) - 1))) {
                kptr = call_transpose<uint16_t>;
            } else {
                kptr = call_transpose<equiv_ctype_storage<2>>;
                megdnn_log_error("unaligned addr in relayout");
            }
        } else if (dsize == 3) {
            transpose->c = 1;
            kptr = call_transpose<equiv_ctype_storage<3>>;
        } else if (dsize == 4) {
            transpose->c = 1;
            if (!((src_addr | dst_addr) & (alignof(uint32_t) - 1))) {
                kptr = call_transpose<uint32_t>;
            } else {
                kptr = call_transpose<equiv_ctype_storage<4>>;
                megdnn_log_error("unaligned addr in relayout");
            }
        } else if (dsize == 12) {
            transpose->c = 1;
            if (!((src_addr | dst_addr) & (alignof(uint32_t) - 1))) {
                kptr = call_transpose<equiv_ctype_storage<3, uint32_t>>;
            } else {
                kptr = call_transpose<equiv_ctype_storage<12>>;
                megdnn_log_error("unaligned addr in relayout");
            }
        } else if (dsize <= TRANSPOSE_CV_MAX_C) {
            switch (dst.layout.dtype.enumv()) {
#define cb(_dt)                                             \
    case DTypeTrait<dtype::_dt>::enumv:                     \
        kptr = transpose_cv<equiv_ctype<dtype::_dt>::type>; \
        break;
                MEGDNN_FOREACH_DTYPE_NAME(cb)
                MEGDNN_FOREACH_PARAMETERIZED_DTYPE(cb)
#undef cb
            }
            megdnn_assert(kptr);
        }

        if (kptr) {
M
Megvii Engine Team 已提交
295 296
            auto kern = [t = *transpose, sptr = src.raw_ptr, dptr = dst.raw_ptr,
                         kptr]() { kptr(t.batch, t.m, t.n, t.c, sptr, dptr); };
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
            static_cast<naive::HandleImpl*>(handle())->dispatch_kern(kern);
            return;
        } else {
            megdnn_assert(transpose->c != 1, "unsupported dtype size");
        }
    }

    using relayout::is_contig;

    if (is_contig(dst.layout) && is_contig(src.layout)) {
        auto sptr = src.raw_ptr, dptr = dst.raw_ptr;
        auto sz = src.layout.span().dist_byte();
        MEGDNN_DISPATCH_CPU_KERN_OPR(memcpy(dptr, sptr, sz));
        return;
    }

    if (is_contig(dst.layout) && is_lastdim_contig(src.layout)) {
        return dispatch_cont(handle(), dst, src, memcpy_noncont2cont);
    }

    if (is_contig(src.layout) && is_lastdim_contig(dst.layout)) {
        return dispatch_cont(handle(), src, dst, memcpy_cont2noncont);
    }
    NaiveRelayoutForwardImpl::do_exec(src, dst);
}

// vim: syntax=cpp.doxygen