network.cpp 13.5 KB
Newer Older
1
#include "./network.h"
2
#include "megbrain/opr/tensor_manip.h"
3 4 5

using namespace mgb;

M
Megvii Engine Team 已提交
6 7 8
SymbolVar Network::add_conv(
        SymbolVar f, size_t output_channels, KernSize kern_size, DType out_dtype,
        bool has_relu, Stride stride, Padding padding) {
9 10 11 12 13 14 15
    static int weight_idx = 0;
    static int bias_idx = 0;

    size_t input_channels = f.node()->shape()[1];
    auto weight = add_cvar(
            ssprintf("w%d", weight_idx).c_str(),
            {output_channels, input_channels, kern_size[0], kern_size[1]});
M
Megvii Engine Team 已提交
16
    auto bias = add_cvar(ssprintf("b%d", bias_idx).c_str(), {1, output_channels, 1, 1});
17 18 19 20 21 22 23 24 25 26 27 28 29
    if (out_dtype.category() == DTypeCategory::QUANTIZED) {
        weight = add_type_cvt(weight, out_dtype);
        bias = add_type_cvt(bias, dtype::QuantizedS32{1.f});
    }
    opr::ConvBias::Param param;
    param.stride_h = stride[0], param.stride_w = stride[1];
    param.pad_h = padding[0], param.pad_w = padding[1];
    if (has_relu) {
        param.nonlineMode = opr::ConvBias::Param::NonlineMode::RELU;
    } else {
        param.nonlineMode = opr::ConvBias::Param::NonlineMode::IDENTITY;
    }

30 31 32 33 34 35 36
    SymbolVar conv;
    if (out_dtype.category() == DTypeCategory::QUANTIZED) {
        conv = opr::ConvBias::make(
                f, weight, bias, param, {}, OperatorNodeConfig{out_dtype});
    } else {
        conv = opr::ConvBias::make(f, weight, bias, param, {});
    }
37 38 39 40 41
    weight_idx++;
    bias_idx++;
    return conv;
}

42 43 44 45 46 47 48 49 50 51 52 53
SymbolVar Network::add_group_conv(
        SymbolVar f, size_t output_channels, size_t groups, KernSize kern_size,
        DType out_dtype, bool has_relu, Stride stride, Padding padding) {
    static int weight_idx = 0;
    static int bias_idx = 0;

    size_t input_channels = f.node()->shape()[1];
    auto weight = add_cvar(
            ssprintf("w%d", weight_idx).c_str(),
            {groups, output_channels / groups, input_channels / groups, kern_size[0],
             kern_size[1]});
    auto bias = add_cvar(ssprintf("b%d", bias_idx).c_str(), {1, output_channels, 1, 1});
54 55 56 57
    if (out_dtype.category() == DTypeCategory::QUANTIZED) {
        weight = add_type_cvt(weight, out_dtype);
        bias = add_type_cvt(bias, dtype::QuantizedS32{1.f});
    }
58 59 60 61 62 63 64 65 66 67
    opr::ConvBias::Param param;
    param.sparse = opr::ConvBias::Param::Sparse::GROUP;
    param.stride_h = stride[0], param.stride_w = stride[1];
    param.pad_h = padding[0], param.pad_w = padding[1];
    if (has_relu) {
        param.nonlineMode = opr::ConvBias::Param::NonlineMode::RELU;
    } else {
        param.nonlineMode = opr::ConvBias::Param::NonlineMode::IDENTITY;
    }

68 69 70 71 72 73 74 75 76
    weight_idx++;
    bias_idx++;
    SymbolVar conv;
    if (out_dtype.category() == DTypeCategory::QUANTIZED) {
        conv = opr::ConvBias::make(
                f, weight, bias, param, {}, OperatorNodeConfig{out_dtype});
    } else {
        conv = opr::ConvBias::make(f, weight, bias, param, {});
    }
77 78 79 80 81
    weight_idx++;
    bias_idx++;
    return conv;
}

M
Megvii Engine Team 已提交
82 83
SymbolVar Network::add_deconv(
        SymbolVar f, size_t ratio, size_t output_channels, DType out_dtype) {
84 85 86 87 88
    static int weight_idx = 0;
    size_t kernel = ratio * 2 - ratio % 2;
    size_t pad = ratio / 2;

    size_t input_channels = f.node()->shape()[1];
M
Megvii Engine Team 已提交
89 90 91
    auto weight = add_cvar(
            ssprintf("w%d", weight_idx).c_str(),
            {input_channels, output_channels, kernel, kernel});
92 93 94 95 96 97 98 99 100 101 102 103 104 105

    if (out_dtype.category() == DTypeCategory::QUANTIZED) {
        weight = add_type_cvt(weight, out_dtype);
    }
    opr::ConvolutionBackwardData::Param param;
    param.stride_h = param.stride_w = ratio;
    param.pad_h = param.pad_w = pad;

    auto deconv = opr::ConvolutionBackwardData::make(
            weight, f, param, {}, OperatorNodeConfig{out_dtype});
    weight_idx++;
    return deconv;
}

M
Megvii Engine Team 已提交
106 107
SymbolVar Network::add_elemwise(
        const SymbolVarArray inps, DType out_dtype, opr::Elemwise::Param::Mode mode) {
108 109 110 111 112 113 114
    using ElemMode = opr::Elemwise::Param::Mode;
    using MultiMode = opr::ElemwiseMultiType::Param::Mode;
    static const ThinHashMap<ElemMode, MultiMode> map = {
            {ElemMode::ADD, MultiMode::QADD},
            {ElemMode::FUSE_ADD_RELU, MultiMode::QFUSE_ADD_RELU}};
    if (out_dtype.category() == DTypeCategory::QUANTIZED) {
        MultiMode alter_mode = map.at(mode);
M
Megvii Engine Team 已提交
115 116
        return opr::ElemwiseMultiType::make(
                inps, {alter_mode}, OperatorNodeConfig{out_dtype});
117 118 119 120 121
    } else {
        return opr::Elemwise::make(inps, mode);
    }
}

M
Megvii Engine Team 已提交
122 123 124
SymbolVar Network::add_pooling(
        SymbolVar f, Window window, Stride stride, Padding padding,
        opr::Pooling::Param::Mode mode) {
125 126 127 128 129 130 131 132 133 134 135 136
    opr::Pooling::Param param;
    param.window_h = window[0], param.window_w = window[1];
    param.stride_h = stride[0], param.stride_w = stride[1];
    param.pad_h = padding[0], param.pad_w = padding[1];
    param.mode = mode;
    return opr::Pooling::make(f, param);
}

SymbolVar Network::add_type_cvt(SymbolVar f, DType out_dtype) {
    return opr::TypeCvt::make(f, out_dtype);
}

137 138 139 140
SymbolVar Network::add_concat(SymbolVar f, SymbolVar g, int axis) {
    return opr::Concat::make({f, g}, axis);
}

141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
SymbolVar Network::add_dimshuffle(SymbolVar f, std::vector<int> pattern) {
    return opr::Dimshuffle::make(f, pattern);
}

SymbolVar Network::add_axisaddremove(SymbolVar f) {
    return opr::AxisAddRemove::make(
            f, {{opr::AxisAddRemove::AxisDesc::Method::REMOVE, {0}}});
}

SymbolVar Network::add_subtensor(SymbolVar f) {
    using AIdx = opr::indexing::AxisIndexer;
    return opr::Subtensor::make(
            f, {AIdx::make_interval(0, f.make_scalar(0), None, None)});
}

SymbolVar Network::add_reshape(SymbolVar f) {
    auto shp = opr::GetVarShape::make(f);
    return opr::Reshape::make(f, shp);
}

SymbolVar Network::add_broadcast(SymbolVar f) {
    auto shp = opr::GetVarShape::make(f);
    return opr::Broadcast::make(f, shp);
}

SymbolVar Network::add_copy(SymbolVar f) {
    return opr::Copy::make(f);
}

M
Megvii Engine Team 已提交
170 171 172
SymbolVar mgb::create_block(
        Network& network, SymbolVar f_in, size_t stride, size_t num_outputs1,
        bool has_proj, DType out_dtype) {
173 174
    auto proj = f_in;
    if (has_proj) {
M
Megvii Engine Team 已提交
175 176
        proj = network.add_conv(
                f_in, num_outputs1, {1, 1}, out_dtype, false, {stride, stride});
177 178
    }

M
Megvii Engine Team 已提交
179 180
    auto f = network.add_conv(
            f_in, num_outputs1, {3, 3}, out_dtype, true, {stride, stride}, {1, 1});
181

M
Megvii Engine Team 已提交
182
    f = network.add_conv(f, num_outputs1, {3, 3}, out_dtype, true, {1, 1}, {1, 1});
183

M
Megvii Engine Team 已提交
184
    f = network.add_elemwise({f, proj}, out_dtype, opr::Elemwise::Mode::FUSE_ADD_RELU);
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
    return f;
}

SymbolVar mgb::make_resnet18(Network& network, size_t batch, DType out_dtype) {
    auto data = network.add_var("data", {batch, 4, 224, 224});
    if (out_dtype.category() == DTypeCategory::QUANTIZED)
        data = network.add_type_cvt(data, dtype::QuantizedS8{1.f});
    auto first = out_dtype;
    if (out_dtype.category() == DTypeCategory::QUANTIZED)
        first = dtype::QuantizedS8{1.f};
    auto f = network.add_conv(data, 64, {7, 7}, first, true, {2, 2}, {3, 3});
    if (out_dtype.enumv() == DTypeEnum::QuantizedS4 ||
        out_dtype.enumv() == DTypeEnum::Quantized4Asymm) {
        f = network.add_type_cvt(f, out_dtype);
    }
    f = network.add_pooling(f, {3, 3}, {2, 2}, {1, 1});

    using Vector = SmallVector<size_t, 4>;
    Vector stages = {2, 2, 2, 2};
    Vector mid_outputs = {64, 128, 256, 512};
    Vector enable_stride = {0, 1, 1, 1};
    for (size_t i = 0; i < 4; ++i) {
        auto s = stages[i];
        auto o = mid_outputs[i];
        auto es = enable_stride[i];
        for (size_t j = 0; j < s; ++j) {
            size_t stride = !es || j > 0 ? 1 : 2;
            bool has_proj = j > 0 ? false : true;
            f = create_block(network, f, stride, o, has_proj, out_dtype);
        }
    }
M
Megvii Engine Team 已提交
216 217
    f = network.add_pooling(
            f, {7, 7}, {7, 7}, {0, 0}, opr::Pooling::Param::Mode::AVERAGE);
218 219 220 221 222 223 224 225 226 227 228 229 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

    f = network.add_type_cvt(f, dtype::Float32());
    return f;
}

namespace {
SymbolVarArray make_pyramids(Network& network, size_t batch, DType out_dtype) {
    SymbolVarArray pyramids;
    auto data = network.add_var("data", {batch, 3, 256, 256});
    data = data + (-128.f);
    if (out_dtype.category() == DTypeCategory::QUANTIZED)
        data = network.add_type_cvt(data, dtype::QuantizedS8{1.f});
    auto first = out_dtype;
    if (out_dtype.category() == DTypeCategory::QUANTIZED)
        first = dtype::QuantizedS8{1.f};
    auto f = network.add_conv(data, 16, {3, 3}, first, true, {2, 2}, {1, 1});
    f = network.add_conv(f, 16, {3, 3}, first, true, {1, 1}, {1, 1});
    f = network.add_conv(f, 32, {3, 3}, first, true, {2, 2}, {1, 1});
    if (out_dtype.enumv() == DTypeEnum::QuantizedS4 ||
        out_dtype.enumv() == DTypeEnum::Quantized4Asymm) {
        f = network.add_type_cvt(f, out_dtype);
    }

    using Vector = SmallVector<size_t, 4>;
    Vector stages = {3, 6, 6, 3};
    Vector mid_outputs = {32, 64, 128, 256};
    Vector enable_stride = {0, 1, 1, 1};
    for (size_t i = 0; i < 4; ++i) {
        auto s = stages[i];
        auto o = mid_outputs[i];
        auto es = enable_stride[i];
        for (size_t j = 0; j < s; ++j) {
            size_t stride = !es || j > 0 ? 1 : 2;
            bool has_proj = j > 0 ? false : true;
            f = create_block(network, f, stride, o, has_proj, out_dtype);
        }
        pyramids.push_back(f);
    }

    for (size_t i = 0; i < pyramids.size(); ++i) {
        pyramids[i] = network.add_type_cvt(pyramids[i], first);
    }
    return pyramids;
}

M
Megvii Engine Team 已提交
263 264
SymbolVarArray fusion_pyramids_feature(
        Network& network, SymbolVarArray pyramids, size_t fpn_conv_channels) {
265 266 267 268
    bool touch = false;
    SymbolVar x;
    SymbolVarArray fpn;
    for (int i = 5; i >= 3; --i) {
M
Megvii Engine Team 已提交
269 270 271
        auto f = network.add_conv(
                pyramids[i - 2], fpn_conv_channels, {1, 1}, dtype::QuantizedS8{1.f},
                false, {1, 1}, {0, 0});
272 273
        if (!touch) {
            x = f;
274
            touch = true;
275 276
        } else {
            x = network.add_deconv(x, 2, 16, dtype::QuantizedS8{1.f});
M
Megvii Engine Team 已提交
277 278
            x = network.add_elemwise(
                    {x, f}, dtype::QuantizedS8{1.f}, opr::Elemwise::Mode::ADD);
279 280 281 282 283 284
        }
        fpn.push_back(x);
    }

    x = fpn[0];
    for (int i = 6; i < 8; ++i) {
M
Megvii Engine Team 已提交
285 286 287
        x = network.add_conv(
                x, fpn_conv_channels, {3, 3}, dtype::QuantizedS8{1.f}, true, {2, 2},
                {1, 1});
288 289 290 291 292 293 294 295 296 297 298 299 300 301 302
    }
    return fpn;
}
}  // namespace

SymbolVarArray mgb::make_det(Network& network, size_t batch, DType out_dtype) {
    SymbolVarArray outputs;
    auto pyramids = make_pyramids(network, batch, out_dtype);
    auto fpn_hv = fusion_pyramids_feature(network, pyramids, 16);
    auto fpn_plate = fusion_pyramids_feature(network, pyramids, 16);
    outputs.insert(outputs.end(), fpn_hv.begin(), fpn_hv.end());
    outputs.insert(outputs.end(), fpn_plate.begin(), fpn_plate.end());
    return outputs;
}

303 304
SymbolVar mgb::bottleneck(
        Network& network, SymbolVar f, size_t input_channels, size_t channels, size_t t,
305
        size_t stride, DType out_dtype) {
306 307 308 309
    size_t in_channels = f.node()->shape()[1];
    SymbolVar x = f;
    if (t != 1) {
        x = network.add_conv(
310
                f, input_channels * t, {1, 1}, out_dtype, true, {1, 1}, {0, 0});
311 312
    }
    x = network.add_group_conv(
313
            x, input_channels * t, input_channels * t, {3, 3}, out_dtype, true,
314
            {stride, stride}, {1, 1});
315
    x = network.add_conv(x, channels, {1, 1}, out_dtype, false, {1, 1}, {0, 0});
316 317 318 319 320 321 322
    if (stride == 1 && in_channels == channels)
        x = f + x;
    return x;
}

SymbolVar mgb::bottleneck_group(
        Network& network, SymbolVar f, size_t input_channels, size_t channels,
323
        size_t stages, size_t s, size_t t, DType out_dtype) {
324 325 326
    SymbolVar x = f;
    for (size_t i = 0; i < stages; ++i) {
        size_t stride = i == 0 ? s : 1;
327
        x = bottleneck(network, x, input_channels, channels, t, stride, out_dtype);
328 329 330 331 332 333 334 335 336 337 338 339 340 341 342
        input_channels = channels;
    }
    return x;
}

namespace {
size_t make_divisible(size_t v, size_t divisor) {
    size_t min_value = divisor;
    size_t new_v = std::max(min_value, (v + divisor / 2) / divisor * divisor);
    if (new_v < 0.9 * v)
        new_v += divisor;
    return new_v;
}
}  // namespace

343
SymbolVar mgb::make_mobilenet_v2(Network& network, size_t batch, DType out_dtype) {
344
    auto data = network.add_var("data", {batch, 3, 224, 224});
345 346 347
    if (out_dtype.category() == DTypeCategory::QUANTIZED) {
        data = network.add_type_cvt(data, dtype::QuantizedS8{1.f});
    }
348 349
    constexpr size_t round_nearest = 8;
    auto x = network.add_conv(
350 351 352 353 354 355 356 357 358 359 360 361 362 363 364
            data, make_divisible(32, round_nearest), {3, 3}, out_dtype, true, {2, 2},
            {1, 1});
    x = bottleneck(network, x, 32, make_divisible(16, round_nearest), 1, 1, out_dtype);
    x = bottleneck_group(
            network, x, 16, make_divisible(24, round_nearest), 2, 2, 6, out_dtype);
    x = bottleneck_group(
            network, x, 24, make_divisible(32, round_nearest), 3, 2, 6, out_dtype);
    x = bottleneck_group(
            network, x, 32, make_divisible(64, round_nearest), 4, 2, 6, out_dtype);
    x = bottleneck_group(
            network, x, 64, make_divisible(96, round_nearest), 3, 1, 6, out_dtype);
    x = bottleneck_group(
            network, x, 96, make_divisible(160, round_nearest), 3, 2, 6, out_dtype);
    x = bottleneck_group(
            network, x, 160, make_divisible(320, round_nearest), 1, 1, 6, out_dtype);
365
    x = network.add_conv(
366 367 368 369 370
            x, make_divisible(1280, round_nearest), {1, 1}, out_dtype, true, {1, 1},
            {0, 0});
    if (out_dtype.category() == DTypeCategory::QUANTIZED) {
        x = network.add_type_cvt(x, dtype::Float32());
    }
371 372 373
    return x;
}

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