reformat_emitter.cpp 11.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13
/**
 * \file src/gopt/impl/reformat_emitter.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_emitter.h"
14
#include <numeric>
15
#include "megbrain/opr/tensor_manip.h"
16
#include "megbrain/opr/io.h"
17 18 19 20 21 22

using namespace mgb;
using namespace gopt;
using Dimension = megdnn::Dimension;
using NamedTensorShape = megdnn::NamedTensorShape;

23
// =================== ModifyShapeMixin ====================*/
24
ModifyShapeMixin::Pattern ModifyShapeMixin::mixin_analyze() const {
25 26 27 28 29 30 31 32 33 34 35
    static constexpr uint32_t UNDETERMINED_EXTENT =
            Dimension::UNDETERMINED_EXTENT;
    ThinHashMap<Dimension::Name, int> name2dominant;
    for (size_t i = 0; i < m_src.ndim; ++i) {
        auto name = m_src[i].name();
        if (m_src[i].extent() == UNDETERMINED_EXTENT) {
            auto insert = name2dominant.insert(std::make_pair(name, i));
            mgb_assert(insert.second);
        }
    }

36
    Pattern pattern(m_dest.ndim);
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
    for (size_t i = 0; i < m_dest.ndim; ++i) {
        auto name = m_dest[i].name();
        if (m_dest[i].extent() == UNDETERMINED_EXTENT) {
            int src_dim = name2dominant.at(name);
            bool mul = m_src[src_dim] < m_dest[i];
            int factor = mul ? (m_dest[i] / m_src[src_dim]).extent()
                             : (m_src[src_dim] / m_dest[i]).extent();
            pattern[i] = std::make_tuple(src_dim, factor, mul);
        } else {
            pattern[i] = std::make_tuple(-1, m_dest[i].extent(), false);
        }
    }
    return pattern;
}

52 53 54
ModifyShapeMixin::Checker ModifyShapeMixin::mixin_emit_checker(
        const Pattern& pattern) const {
    auto src = m_src;
55 56 57
    auto checker = [src, pattern](const VarNodeArray& input) {
        mgb_assert(input.size() >= 1);
        const auto& var = input.front();
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
        const auto& shp = var->shape();
        if (shp.ndim != src.ndim)
            return false;
        bool available = true;
        for (size_t i = 0; i < shp.ndim; ++i) {
            if (src[i].extent() != Dimension::UNDETERMINED_EXTENT) {
                available &= (shp[i] == src[i].extent());
            }
        }
        for (auto&& i : pattern) {
            int axis, factor;
            bool mul;
            std::tie(axis, factor, mul) = i;
            if (axis >= 0 && !mul) {
                available &= (shp[axis] % factor == 0);
            }
        }
        return available;
    };
    return checker;
}

80 81
// =================== MakeShapeEmitter ====================*/
MakeShapeEmitter::EmitResult MakeShapeEmitter::emit() const {
82
    auto pattern = mixin_analyze();
83 84 85 86 87
    auto builder = [pattern](const VarNodeArray& input) {
        mgb_assert(input.size() == 1,
                   "number of input of MakeShapeBuilder should be 1(got:%zu)",
                   input.size());
        auto sym_var = SymbolVar(input.front());
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
        auto shp = opr::GetVarShape::make(sym_var);
        auto cv = [&sym_var](int c) { return sym_var.make_scalar(c); };
        auto sub = [&shp, &cv](int ax) {
            return opr::IndexAt::make(shp, {{0, cv(ax)}});
        };
        SymbolVarArray axs;
        for (auto&& i : pattern) {
            int axis, factor;
            bool mul;
            std::tie(axis, factor, mul) = i;
            if (axis >= 0) {
                if (mul)
                    axs.emplace_back(sub(axis) * factor);
                else
                    axs.emplace_back(sub(axis) / factor);
            } else {
                axs.emplace_back(cv(factor));
            }
        }
        auto tshp = opr::Concat::make(axs, 0);
108 109 110 111 112 113 114 115 116 117 118 119 120 121
        return tshp.node();
    };
    auto checker = mixin_emit_checker(pattern);
    return std::make_tuple(builder, checker);
}

// =================== ReshapeEmitter ====================*/
ReshapeEmitter::EmitResult ReshapeEmitter::emit() const {
    auto pattern = mixin_analyze();
    auto builder = [pattern](const VarNodeArray& input) {
        mgb_assert(input.size() == 2,
                   "number of input of Reshape should be 2(got:%zu)",
                   input.size());
        auto ovar = opr::Reshape::make(input[0], input[1]);
122 123 124 125 126 127
        return ovar.node();
    };
    auto checker = mixin_emit_checker(pattern);
    return std::make_tuple(builder, checker);
}

128
// =================== DimshuffleEmitter ====================*/
129 130
DimshuffleEmitter::EmitResult DimshuffleEmitter::emit() const {
    auto&& pattern = m_pattern;
131 132 133 134 135
    auto builder = [pattern](const VarNodeArray& input) {
        mgb_assert(input.size() == 1,
                   "number of input of Dimshuffle should be 1(got:%zu)",
                   input.size());
        auto sym_var = SymbolVar(input.front());
136 137
        return opr::Dimshuffle::make(sym_var, pattern).node();
    };
138 139 140 141 142
    auto checker = [pattern](const VarNodeArray& input) {
        mgb_assert(input.size() == 1,
                   "number of input of Dimshuffle should be 1(got:%zu)",
                   input.size());
        return input.front()->shape().ndim == pattern.size();
143 144
    };
    return std::make_tuple(builder, checker);
145 146
}

147
// =================== ReformatEmitter ====================*/
148
ReformatEmitter::EmitResult ReformatEmitter::emit() const {
149 150 151 152 153 154 155 156 157 158 159 160
    auto builders = analyze();
    auto builder = [builders](const VarNodeArray& input) {
        VarNode *var, *ovar;
        var = ovar = input.front();
        if (builders.make_shape1) {
            auto shp1 = builders.make_shape1({var});
            ovar = builders.reshape1({ovar, shp1});
        }
        ovar = builders.dimshuffle({ovar});
        if (builders.make_shape2) {
            auto shp2 = builders.make_shape2({var});
            ovar = builders.reshape2({ovar, shp2});
161 162 163
        }
        return ovar;
    };
164 165 166
    auto pattern = mixin_analyze();
    auto checker = mixin_emit_checker(pattern);
    return std::make_tuple(builder, checker);
167 168
}

169
ReformatEmitter::UnderlyingBuilders ReformatEmitter::analyze() const {
170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233
    struct Dim {
        Dimension dim;
        int index;
        Dim(Dimension dim_, int index_) : dim{dim_}, index{index_} {}
    };
    SmallVector<Dim> src_dims;
    SmallVector<Dim> dest_dims;
    for (size_t i = 0; i < m_src.ndim; ++i)
        src_dims.emplace_back(Dim(m_src[i], i));
    for (size_t i = 0; i < m_dest.ndim; ++i)
        dest_dims.emplace_back(Dim(m_dest[i], i));
    auto compare = [](const Dim& lhs, const Dim& rhs) {
        return lhs.dim < rhs.dim;
    };
    std::sort(src_dims.begin(), src_dims.end(), compare);
    std::sort(dest_dims.begin(), dest_dims.end(), compare);
    auto src_iter = src_dims.begin();
    auto dest_iter = dest_dims.begin();
    for (; src_iter != src_dims.end() && dest_iter != dest_dims.end();) {
        if (src_iter->dim == dest_iter->dim) {
            src_iter++;
            dest_iter++;
        } else if (src_iter->dim < dest_iter->dim) {
            auto split = dest_iter->dim / src_iter->dim;
            int dim_idx = dest_iter->index;
            dest_iter =
                    dest_dims.insert(dest_iter, Dim(src_iter->dim, dim_idx));
            dest_iter++;
            dest_iter->dim = split;
            dest_iter->index = dim_idx;
            src_iter++;
        } else {
            auto split = src_iter->dim / dest_iter->dim;
            int dim_idx = src_iter->index;
            src_iter = src_dims.insert(src_iter, Dim(dest_iter->dim, dim_idx));
            src_iter++;
            src_iter->dim = split;
            src_iter->index = dim_idx;
            dest_iter++;
        }
    }
    mgb_assert(src_dims.size() == dest_dims.size());
    std::vector<int> src_perm(src_dims.size());
    std::vector<int> permute(dest_dims.size());
    std::iota(src_perm.begin(), src_perm.end(), 0);
    std::iota(permute.begin(), permute.end(), 0);
    std::sort(src_perm.begin(), src_perm.end(), [&](const int a, const int b) {
        if (src_dims[a].index != src_dims[b].index)
            return src_dims[a].index < src_dims[b].index;
        return src_dims[a].dim < src_dims[b].dim;
    });
    std::sort(permute.begin(), permute.end(), [&](const int a, const int b) {
        int perm_a = src_perm[a];
        int perm_b = src_perm[b];
        if (dest_dims[perm_a].index != dest_dims[perm_b].index)
            return dest_dims[perm_a].index < dest_dims[perm_b].index;
        return dest_dims[perm_a].dim < dest_dims[perm_b].dim;
    });
    NamedTensorShape i1, i2;
    i1.ndim = src_dims.size(), i2.ndim = dest_dims.size();
    for (size_t i = 0; i < src_dims.size(); ++i) {
        i1[i] = src_dims[src_perm[i]].dim;
        i2[i] = src_dims[src_perm[permute[i]]].dim;
    }
234 235
    UnderlyingBuilders builders;
    if (!m_src.eq_shape(i1)) {
236 237
        builders.make_shape1 = std::get<0>(MakeShapeEmitter(m_src, i1).emit());
        builders.reshape1 = std::get<0>(ReshapeEmitter(m_src, i1).emit());
238
    }
239
    builders.dimshuffle = std::get<0>(DimshuffleEmitter(permute).emit());
240 241
    if (!m_dest.eq_shape(i2)) {
        builders.make_shape2 =
242 243
                std::get<0>(MakeShapeEmitter(m_src, m_dest).emit());
        builders.reshape2 = std::get<0>(ReshapeEmitter(i2, m_dest).emit());
244 245
    }
    return builders;
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

/* ============== PaddingEmitter ================= */
PaddingEmitter::EmitResult PaddingEmitter::emit() const {
    auto&& const_extent = m_const_extent;
    auto&& axis = m_axis;
    auto builder = [const_extent, axis](const VarNodeArray& vars) {
        auto i = vars[0];
        auto padding_shp_var = vars[1];
        TensorShape shape;
        shape.ndim = i->shape().ndim;
        for (size_t ax = 0; ax < shape.ndim; ++ax)
            shape[ax] = 1;
        shape[axis] = const_extent;
        auto host_val =
                std::make_shared<HostTensorND>(i->comp_node(), i->dtype());
        host_val->resize(shape);
        auto ptr = host_val->raw_ptr();
        size_t size_bytes = TensorLayout{shape, i->dtype()}.span().dist_byte();
        std::memset(ptr, 0, size_bytes);
        auto padding =
                opr::ImmutableTensor::make(*i->owner_graph(), *host_val);
        padding = opr::Broadcast::make(padding, padding_shp_var);
        auto o = opr::Concat::make({i, padding}, axis);
        return o.node();
    };
    auto checker = [axis](const VarNodeArray& vars) {
        mgb_assert(vars.size() == 2);
        return vars[0]->shape().ndim > axis;
    };
    return std::make_tuple(builder, checker);
}

/* ============== SubtensorEmitter ================= */
SubtensorEmitter::EmitResult SubtensorEmitter::emit() const {
    auto&& const_extent = m_const_extent;
    auto&& axis = m_axis;
    auto builder = [const_extent, axis](const VarNodeArray& vars) {
        auto i = vars[0];
        auto x = SymbolVar(i);
        auto cv = [&x](int v) { return x.make_scalar(v); };
        using AIdx = opr::Subtensor::AxisIndexer;
        std::vector<AIdx> index(i->shape().ndim);
        for (size_t ax = 0; ax < index.size(); ++ax) {
            if (ax == axis)
                index[ax] =
                        AIdx::make_interval(ax, None, cv(const_extent), None);
            else
                index[ax] = AIdx::make_interval(ax, None, None, cv(1));
        }
        auto o = opr::Subtensor::make(x, index);
        return o.node();
    };
    auto checker = [axis](const VarNodeArray& vars) {
        mgb_assert(vars.size() == 2);
        return vars[0]->shape().ndim > axis;
    };
    return std::make_tuple(builder, checker);
}

306
// vim: syntax=cpp.doxygen