oneDNN icon indicating copy to clipboard operation
oneDNN copied to clipboard

How to connect two Convolutional layers using int8 ?

Open kala855 opened this issue 8 years ago • 12 comments

Hello, I'm using Intel MKL-DNN in order to implement an AlexNet topology for inference using int8. However I have some issues trying to connect two convolutional layers. There is some example where the connection of two convolutional layers was made ? I was trying to use the simple_net_int8_cpp example but just one Convolutional Layer is implemented. At this moment I have the Layer 1 + ReLu + Maxpooling with int8 but trying to add Layer 2 falls into this message: status: 5 message: could not create a primitive descriptor iterator

kala855 avatar Nov 29 '18 11:11 kala855

@kala855 , can you share your code?

nathan-greeneltch-intel avatar Nov 29 '18 17:11 nathan-greeneltch-intel

Yes, look this is my initial code working with Intel MKL-DNN. Sorry because I did not find where to share it like a file.

/*******************************************************************************
* Copyright 2018 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/

#include <iostream>
#include <numeric>
#include <string>
#include "mkldnn.hpp"

using namespace mkldnn;

void simple_net_int8_complete() {
    auto cpu_engine = engine(engine::cpu, 0);

    /* Create a vector to store the topology primitives */
    std::vector<primitive> net;

    const int batch = 1;

    /* AlexNet: conv1
     * {batch, 3, 227, 227} (x)  {96, 3, 11, 11}; -> {batch, 96, 55, 55}
     * strides: {1, 1}
     */
    memory::dims conv1_src_tz = {batch, 3, 227, 227 };
    memory::dims conv1_weights_tz = { 96, 3, 11, 11 };
    memory::dims conv1_bias_tz = { 96 };
    memory::dims conv1_dst_tz = { batch, 96, 55, 55 };
    memory::dims conv1_strides = { 4, 4 };
    auto conv1_padding = { 0, 0 };


    ////////////// Quantization ////////////////////////////////////////
    /* Set Scaling mode for int8 quantizing */
    const std::vector<float> src_scales = { 1.8f };
    const std::vector<float> weight_scales = { 2.0f };
    const std::vector<float> bias_scales = { 1.0f };
    const std::vector<float> dst_scales = { 0.55f };
    /* assign halves of vector with arbitrary values */
    std::vector<float> conv1_scales(96);
    const int scales_half = 96 / 2;
    std::fill(conv1_scales.begin(), conv1_scales.begin() + scales_half, 0.3f);
    std::fill(conv1_scales.begin() + scales_half + 1, conv1_scales.end(), 0.8f);

    const int src_mask = 0;
    const int weight_mask = 0;
    const int bias_mask = 0;
    const int dst_mask = 0;
    const int conv1_mask = 2; // 1 << output_channel_dim
    //////////////////////////////////////////////////////////////////////

    /* Allocate input and output buffers for user data */
    std::vector<float> user_src(batch * 3 * 227 * 227);
    /*Test just the first convolutional layer output*/
    std::vector<float> user_dst(batch * 256 * 27 * 27); // Change to fit conv2 output

    /* Allocate and fill buffers for weights and bias */
    std::vector<float> conv1_weights(std::accumulate(conv1_weights_tz.begin(),
            conv1_weights_tz.end(), 1, std::multiplies<uint32_t>()));
    std::vector<float> conv1_bias(std::accumulate(conv1_bias_tz.begin(),
            conv1_bias_tz.end(), 1, std::multiplies<uint32_t>()));

    /* create memory for user data */
    auto user_src_memory = memory(
            { { { conv1_src_tz }, memory::data_type::f32, memory::format::nchw },
                    cpu_engine },
            user_src.data());
    auto user_weights_memory
            = memory({ { { conv1_weights_tz }, memory::data_type::f32,
                               memory::format::oihw },
                             cpu_engine },
                    conv1_weights.data());
    auto user_bias_memory = memory(
            { { { conv1_bias_tz }, memory::data_type::f32, memory::format::x },
                    cpu_engine },
            conv1_bias.data());

    /* create memory descriptors for convolution data w/ no specified format */
    auto conv1_src_md = memory::desc(
            { conv1_src_tz }, memory::data_type::u8, memory::format::any);
    auto conv1_bias_md = memory::desc(
            { conv1_bias_tz }, memory::data_type::s8, memory::format::any);
    auto conv1_weights_md = memory::desc(
            { conv1_weights_tz }, memory::data_type::s8, memory::format::any);
    auto conv1_dst_md = memory::desc(
            { conv1_dst_tz }, memory::data_type::u8, memory::format::any);

    /* create a convolution */
    auto conv1_desc = convolution_forward::desc(prop_kind::forward,
            convolution_direct, conv1_src_md, conv1_weights_md, conv1_bias_md,
            conv1_dst_md, conv1_strides, conv1_padding, conv1_padding,
            padding_kind::zero);

    /* define the convolution attributes */
    primitive_attr conv1_attr;
    conv1_attr.set_int_output_round_mode(round_mode::round_nearest);
    conv1_attr.set_output_scales(conv1_mask, conv1_scales);

    /* AlexNet: execute ReLU as PostOps */
    const float ops_scale = 1.f;
    const float ops_alpha = 0.f; // relu negative slope
    const float ops_beta = 0.f;
    post_ops ops;
    ops.append_eltwise(ops_scale, algorithm::eltwise_relu, ops_alpha, ops_beta);
    conv1_attr.set_post_ops(ops);

    /* check if int8 convolution is supported */
    try {
        auto conv1_prim_desc = convolution_forward::primitive_desc(
                conv1_desc, conv1_attr, cpu_engine);
    } catch (error &e) {
        if (e.status == mkldnn_unimplemented) {
            std::cerr << "AVX512-BW support or Intel(R) MKL dependency is "
            "required for int8 convolution" << std::endl;
        }
        throw;
    }

    auto conv1_prim_desc = convolution_forward::primitive_desc(
            conv1_desc, conv1_attr, cpu_engine);

    /* Next: create memory primitives for the convolution's input data
     * and use reorder to quantize the values into int8 */
    auto conv1_src_memory = memory(conv1_prim_desc.src_primitive_desc());
    primitive_attr src_attr;
    src_attr.set_int_output_round_mode(round_mode::round_nearest);
    src_attr.set_output_scales(src_mask, src_scales);
    auto src_reorder_pd
            = reorder::primitive_desc(user_src_memory.get_primitive_desc(),
                    conv1_src_memory.get_primitive_desc(), src_attr);
    net.push_back(reorder(src_reorder_pd, user_src_memory, conv1_src_memory));

    auto conv1_weights_memory = memory(conv1_prim_desc.weights_primitive_desc());
    primitive_attr weight_attr;
    weight_attr.set_int_output_round_mode(round_mode::round_nearest);
    weight_attr.set_output_scales(weight_mask, weight_scales);
    auto weight_reorder_pd
            = reorder::primitive_desc(user_weights_memory.get_primitive_desc(),
                    conv1_weights_memory.get_primitive_desc(), weight_attr);
    net.push_back(reorder(
            weight_reorder_pd, user_weights_memory, conv1_weights_memory));

    auto conv1_bias_memory = memory(conv1_prim_desc.bias_primitive_desc());
    primitive_attr bias_attr;
    bias_attr.set_int_output_round_mode(round_mode::round_nearest);
    bias_attr.set_output_scales(bias_mask, bias_scales);
    auto bias_reorder_pd
            = reorder::primitive_desc(user_bias_memory.get_primitive_desc(),
                    conv1_bias_memory.get_primitive_desc(), bias_attr);
    net.push_back(reorder(bias_reorder_pd, user_bias_memory, conv1_bias_memory));

    auto conv1_dst_memory = memory(conv1_prim_desc.dst_primitive_desc());

    /* create convolution primitive and add it to net */
    net.push_back(convolution_forward(conv1_prim_desc, conv1_src_memory,
            conv1_weights_memory, conv1_bias_memory, conv1_dst_memory));


    /* The Local Response Normalization is not
     * necessary to do inference with int8
     * read "Lower Numerical Precision Deep
     * Learning Inference and Training"
     * -------- Read to understand -------------
     * AlexNet: lrn1
     * {batch, 96, 55, 55} -> {batch, 96, 55, 55}
     * local size: 5
     * alpha1: 0.0001
     * beta1: 0.75
     */
    /*const uint32_t local1_size = 5;
    const float alpha1 = 0.0001;
    const float beta1 = 0.75f;
    const float k1 = 1.0f;

    auto lrn1_desc = lrn_forward::desc(prop_kind::forward_inference,
	    lrn_across_channels,
            conv1_dst_memory.get_primitive_desc().desc(), local1_size,
            alpha1, beta1, k1);
    auto lrn1_prim_desc
            = lrn_forward::primitive_desc(lrn1_desc, cpu_engine);
    auto lrn1_dst_memory = memory(lrn1_prim_desc.dst_primitive_desc());

    net.push_back(lrn_forward(lrn1_prim_desc, conv1_dst_memory, lrn1_dst_memory));
    */


    /* Convert data back into fp32 and compare values with u8.
     * Note: data is unsigned since there are no negative values
     * after ReLU */

    /* AlexNet: pool1
     * {batch, 96, 55, 55} -> {batch, 96, 27, 27}
     * kernel: {3, 3}
     * strides: {2, 2}
     */

    memory::dims pool1_dst_tz = { batch, 96, 27, 27 };
    memory::dims pool1_kernel = { 3, 3 };
    memory::dims pool1_strides = { 2, 2 };
    auto pool_padding = { 0, 0 };

    auto pool1_dst_md = memory::desc(
            { pool1_dst_tz }, memory::data_type::u8, memory::format::any);

    /* create a pooling */
    auto pool1_desc = pooling_forward::desc(prop_kind::forward_inference,
            pooling_max, conv1_dst_memory.get_primitive_desc().desc(),
            pool1_dst_md, pool1_strides, pool1_kernel, pool_padding,
            pool_padding, padding_kind::zero);
    auto pool1_pd = pooling_forward::primitive_desc(pool1_desc, cpu_engine);
    auto pool1_dst_memory = memory(pool1_pd.dst_primitive_desc());

    /* create pooling primitive an add it to net */
    net.push_back(
            pooling_forward(pool1_pd, conv1_dst_memory, pool1_dst_memory));

    /*
     * AlexNet: conv2
     * {batch, 96, 27, 27} (x) {2, 128, 48, 5, 5} -> {batch, 256, 27, 27}
     * strides: {1, 1}
     */
    memory::dims conv2_src_tz = { batch, 96, 27, 27 };
    memory::dims conv2_weights_tz = { 2, 128, 48, 5, 5 };
    memory::dims conv2_bias_tz = { 256 };
    memory::dims conv2_dst_tz = { batch, 256, 27, 27 };
    memory::dims conv2_strides = { 1, 1 };
    auto conv2_padding = { 2, 2 };

    /* Set Scaling mode for int8 quantizing */
    const std::vector<float> src2_scales = { 1.8f };
    const std::vector<float> weight2_scales = { 2.0f };
    const std::vector<float> bias2_scales = { 1.0f };
    const std::vector<float> dst2_scales = { 0.55f };

    /* assign halves of vector with arbitrary values */
    std::vector<float> conv2_scales(128);
    const int scales2_half = 128 / 2;
    std::fill(conv2_scales.begin(), conv2_scales.begin() + scales2_half, 0.3f);
    std::fill(conv2_scales.begin() + scales2_half + 1, conv2_scales.end(), 0.8f);

    const int src2_mask = 0;
    const int weight2_mask = 0;
    const int bias2_mask = 0;
    const int dst2_mask = 0;
    const int conv2_mask = 2; // 1 << output_channel_dim

    /* Allocate and fill buffers for weights and bias */
    std::vector<uint8_t> conv2_weights(std::accumulate(conv2_weights_tz.begin(),
                conv2_weights_tz.end(), 1, std::multiplies<uint8_t>()));
    std::vector<uint8_t> conv2_bias(std::accumulate(conv2_bias_tz.begin(),
                conv2_bias_tz.end(), 1, std::multiplies<uint8_t>()));
    /* create memory for user data */
    auto conv2_user_weights_memory
        = memory({ { { conv2_weights_tz }, memory::data_type::u8,
                memory::format::goihw },
                cpu_engine },
                conv2_weights.data());

    auto conv2_bias_memory
        = memory({ { { conv2_bias_tz }, memory::data_type::u8,
                memory::format::x },
                cpu_engine },
                conv2_bias.data());


    /* create memory descriptors for convolution data w/ no specified format */
    auto conv2_src_md = memory::desc(
            { conv2_src_tz }, memory::data_type::u8, memory::format::any);
    auto conv2_bias_md = memory::desc(
            { conv2_bias_tz }, memory::data_type::s8, memory::format::any);
    auto conv2_weights_md = memory::desc(
            { conv2_weights_tz }, memory::data_type::s8, memory::format::any);
    auto conv2_dst_md = memory::desc(
            { conv2_dst_tz }, memory::data_type::u8, memory::format::any);

    /* create a convolution */
    auto conv2_desc = convolution_forward::desc(
            prop_kind::forward, convolution_direct, conv2_src_md,
            conv2_weights_md, conv2_bias_md, conv2_dst_md, conv2_strides,
            conv2_padding, conv2_padding, padding_kind::zero);


    /* define the convolution attributes */
    primitive_attr conv2_attr;
/*    conv2_attr.set_int_output_round_mode(round_mode::round_nearest);
    conv2_attr.set_output_scales(conv2_mask, conv2_scales);
*/
    /* AlexNet: execute ReLU as PostOps */
    const float ops2_scale = 1.f;
    const float ops2_alpha = 1.0f; // relu negative slope
    const float ops2_beta = 0.f;
    post_ops ops2;
    ops2.append_eltwise(ops2_scale, algorithm::eltwise_relu, ops2_alpha,
            ops2_beta);
    conv2_attr.set_post_ops(ops2);

    /*The problems occurs here*/
    auto conv2_prim_desc = convolution_forward::primitive_desc(
            conv2_desc, conv2_attr, cpu_engine);

    printf("I'm here\n");
    auto conv2_src_memory = pool1_dst_memory;
    if (memory::primitive_desc(conv2_prim_desc.src_primitive_desc())
            != conv2_src_memory.get_primitive_desc()) {
        conv2_src_memory = memory(conv2_prim_desc.src_primitive_desc());
        net.push_back(reorder(pool1_dst_memory, conv2_src_memory));
    }

    auto conv2_weights_memory = conv2_user_weights_memory;
    if (memory::primitive_desc(conv2_prim_desc.weights_primitive_desc())
            != conv2_user_weights_memory.get_primitive_desc()) {
        conv2_weights_memory
            = memory(conv2_prim_desc.weights_primitive_desc());
        net.push_back(
                reorder(conv2_user_weights_memory, conv2_weights_memory));
    }

    auto conv2_dst_memory = memory(conv2_prim_desc.dst_primitive_desc());

    /* create convolution primitive and add it to net */
    net.push_back(convolution_forward(conv2_prim_desc, conv2_src_memory,
                conv2_weights_memory, conv2_bias_memory, conv2_dst_memory));

    /* Convert data back into fp32 and compare values with u8.
     * Note: data is unsigned since there are no negative values
     * after ReLU */

    /* Create a memory primitive for user data output */
    auto user_dst_memory = memory(
            { { { conv2_dst_tz }, memory::data_type::f32, memory::format::nchw },
                    cpu_engine },
            user_dst.data());

    primitive_attr dst_attr;
    dst_attr.set_int_output_round_mode(round_mode::round_nearest);
    dst_attr.set_output_scales(dst_mask, dst_scales);
    auto dst_reorder_pd
            = reorder::primitive_desc(conv2_dst_memory.get_primitive_desc(),
                    user_dst_memory.get_primitive_desc(), dst_attr);

    /* Convert the destination memory from convolution into user
     * data format if necessary */
    if (conv2_dst_memory != user_dst_memory) {
        net.push_back(
                reorder(dst_reorder_pd, conv2_dst_memory, user_dst_memory));
    }

    stream(stream::kind::eager).submit(net).wait();

}

int main(int argc, char **argv) {
    try {
        /* Notes:
         * On convolution creating: check for Intel(R) MKL dependency execution.
         * output: warning if not found. */
        simple_net_int8_complete();
        std::cout << "Simple-net-int8_complete example passed!" << std::endl;
    } catch (error &e) {
        std::cerr << "status: " << e.status << std::endl;
        std::cerr << "message: " << e.message << std::endl;
    }
    return 0;
}

kala855 avatar Nov 29 '18 18:11 kala855

Hi. :-). Please let me know if you have some considerations on my code. Thank you. @nathan-greeneltch-intel .

kala855 avatar Dec 03 '18 14:12 kala855

Sorry for the delay. We are looking into it.

nathan-greeneltch-intel avatar Dec 04 '18 00:12 nathan-greeneltch-intel

@kala855 MKLDNN does not support negative slope with int8 processors on all processors. What generation are you running on?

Specifically see your code line: const float ops2_alpha = 1.0f; // relu negative slope if alpha = 0.0f, the code should compile and run on an processor.

nathan-greeneltch-intel avatar Dec 04 '18 23:12 nathan-greeneltch-intel

Hi @nathan-greeneltch-intel . I made the changes in order to test. But now I have a Segmentation Fault as response. I'm using a Skylake Processor and a Knight's Landing.

Thanks for your help.

kala855 avatar Dec 05 '18 09:12 kala855

@kala855 your accumulator is overflowing for ui8. Change to ui32 and you should be good to go.

/* Allocate and fill buffers for weights and bias */
std::vector<uint8_t> conv2_weights(std::accumulate(conv2_weights_tz.begin(),
            conv2_weights_tz.end(), 1, std::multiplies<uint32_t>()));
std::vector<uint8_t> conv2_bias(std::accumulate(conv2_bias_tz.begin(),
            conv2_bias_tz.end(), 1, std::multiplies<uint32_t>()));

nathan-greeneltch-intel avatar Dec 06 '18 23:12 nathan-greeneltch-intel

Thank you. Now it is working.

kala855 avatar Dec 07 '18 19:12 kala855

Support for negative slope in this case is added in d57673eb4c54142a1d159c42d852a639524eb537.

vpirogov avatar Dec 21 '18 22:12 vpirogov

If you have the code ready for the complete alexnet (all layers) with INT8, could you kindly share it. Thanks

shrutiramesh1988 avatar Feb 19 '19 05:02 shrutiramesh1988

We do not implement models directly with Intel MKL-DNN. Instead we rely on applications enabled with the library to run full workloads. There's a number of int8 models in IntelCaffe model zoo.

vpirogov avatar Feb 19 '19 16:02 vpirogov

Thanks for pointing out to the INT8 models of Caffe. We were looking for INT8 implementation of the CNN models in tensorflow. Our interest is to run the Tensorflow inference benchmarks in INT8 on CPUs. tf_cnn_benchmark doesn't support INT8 inference on CPUs, although there is support for INT8 on GPUs using tensorRT.

shrutiramesh1988 avatar Feb 20 '19 05:02 shrutiramesh1988