Classifier.cpp 6.01 KB
Newer Older
liucong's avatar
liucong committed
1
2
#include <Classifier.h>

liucong's avatar
liucong committed
3
4
5
#include <migraphx/onnx.hpp>
#include <migraphx/gpu/target.hpp>
#include <migraphx/quantization.hpp>
liucong's avatar
liucong committed
6

liucong's avatar
liucong committed
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <Filesystem.h>
#include <SimpleLog.h>

namespace migraphxSamples
{

Classifier::Classifier()
{
}

Classifier::~Classifier()
{
    configurationFile.release();
}

ErrorCode Classifier::Initialize(InitializationParameterOfClassifier initializationParameterOfClassifier)
{
    // 读取配置文件
liucong's avatar
liucong committed
25
    std::string configFilePath=initializationParameterOfClassifier.configFilePath;
liucong's avatar
liucong committed
26
27
28
29
30
    if(Exists(configFilePath)==false)
    {
        LOG_ERROR(stdout, "no configuration file!\n");
        return CONFIG_FILE_NOT_EXIST;
    }
liucong's avatar
liucong committed
31
    if(!configurationFile.open(configFilePath, cv::FileStorage::READ))
liucong's avatar
liucong committed
32
33
34
35
36
37
38
    {
       LOG_ERROR(stdout, "fail to open configuration file\n");
       return FAIL_TO_OPEN_CONFIG_FILE;
    }
    LOG_INFO(stdout, "succeed to open configuration file\n");

    // 获取配置文件参数
liucong's avatar
liucong committed
39
    cv::FileNode netNode = configurationFile["Classifier"];
liucong's avatar
liucong committed
40
    std::string modelPath=(std::string)netNode["ModelPath"];
liucong's avatar
liucong committed
41
42
43
44
45
46
47
48
49
50
51
52
    scale=(float)netNode["Scale"];
    meanValue.val[0]=(float)netNode["MeanValue1"];
    meanValue.val[1]=(float)netNode["MeanValue2"];
    meanValue.val[2]=(float)netNode["MeanValue3"];
    swapRB=(bool)(int)netNode["SwapRB"];
    crop=(bool)(int)netNode["Crop"];
    useInt8=(bool)(int)netNode["UseInt8"];
    useFP16=(bool)(int)netNode["UseFP16"];

    // 加载模型
    if(Exists(modelPath)==false)
    {
liucong's avatar
liucong committed
53
        LOG_ERROR(stdout,"%s not exist!\n",modelPath.c_str());
liucong's avatar
liucong committed
54
55
56
        return MODEL_NOT_EXIST;
    }
    net = migraphx::parse_onnx(modelPath);
liucong's avatar
liucong committed
57
    LOG_INFO(stdout,"succeed to load model: %s\n",GetFileName(modelPath).c_str());
liucong's avatar
liucong committed
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96

    // 获取模型输入属性
    std::unordered_map<std::string, migraphx::shape> inputMap=net.get_parameter_shapes();
    inputName=inputMap.begin()->first;
    inputShape=inputMap.begin()->second;
    int N=inputShape.lens()[0];
    int C=inputShape.lens()[1];
    int H=inputShape.lens()[2];
    int W=inputShape.lens()[3];
    inputSize=cv::Size(W,H);

    // 设置模型为GPU模式
    migraphx::target gpuTarget = migraphx::gpu::target{};

    // 量化
    if(useInt8)
    {
        // 创建量化校准数据,建议使用测试集中的多张典型图像
        cv::Mat srcImage=cv::imread("../Resource/Images/ImageNet_01.jpg",1);
        std::vector<cv::Mat> srcImages;
        for(int i=0;i<inputShape.lens()[0];++i)
        {
            srcImages.push_back(srcImage);
        }
        cv::Mat inputBlob;
        cv::dnn::blobFromImages(srcImages,
                        inputBlob,
                        scale,
                        inputSize,
                        meanValue,
                        swapRB,
                        false);
        std::unordered_map<std::string, migraphx::argument> inputData;
        inputData[inputName]= migraphx::argument{inputShape, (float*)inputBlob.data};
        std::vector<std::unordered_map<std::string, migraphx::argument>> calibrationData = {inputData};

        // INT8量化
        migraphx::quantize_int8(net, gpuTarget, calibrationData);
    }
liucong's avatar
liucong committed
97
    else if(useFP16)
liucong's avatar
liucong committed
98
99
100
101
102
103
    {
        migraphx::quantize_fp16(net);
    }

    // 编译模型
    migraphx::compile_options options;
liucong's avatar
liucong committed
104
105
    options.device_id=0; // 设置GPU设备,默认为0号设备
    options.offload_copy=true;
liucong's avatar
liucong committed
106
    net.compile(gpuTarget,options);
liucong's avatar
liucong committed
107
    LOG_INFO(stdout,"succeed to compile model: %s\n",GetFileName(modelPath).c_str());
liucong's avatar
liucong committed
108

liucong's avatar
liucong committed
109
    // warm up
liucong's avatar
liucong committed
110
111
112
113
114
    std::unordered_map<std::string, migraphx::argument> inputData;
    inputData[inputName]=migraphx::argument{inputShape};
    net.eval(inputData);

    // log
liucong's avatar
liucong committed
115
116
117
118
119
120
121
122
123
    LOG_INFO(stdout,"InputSize:%dx%d\n",inputSize.width,inputSize.height);
    LOG_INFO(stdout,"InputName:%s\n",inputName.c_str());
    LOG_INFO(stdout,"Scale:%.6f\n",scale);
    LOG_INFO(stdout,"Mean:%.2f,%.2f,%.2f\n",meanValue.val[0],meanValue.val[1],meanValue.val[2]);
    LOG_INFO(stdout,"SwapRB:%d\n",(int)swapRB);
    LOG_INFO(stdout,"Crop:%d\n",(int)crop);
    LOG_INFO(stdout,"UseInt8:%d\n",(int)useInt8);
    LOG_INFO(stdout,"UseFP16:%d\n",(int)useFP16);

liucong's avatar
liucong committed
124
125
126
127
128
129
130
131
    return SUCCESS;

}

ErrorCode Classifier::Classify(const std::vector<cv::Mat> &srcImages,std::vector<std::vector<ResultOfPrediction>> &predictions)
{
    if(srcImages.size()==0||srcImages[0].empty()||srcImages[0].depth()!=CV_8U)
    {
liucong's avatar
liucong committed
132
        LOG_ERROR(stdout, "image error!\n");
liucong's avatar
liucong committed
133
134
135
        return IMAGE_ERROR;
    }
    
liucong's avatar
liucong committed
136
    // 数据预处理并转换为NCHW
liucong's avatar
liucong committed
137
138
139
140
141
142
143
144
145
    cv::Mat inputBlob;
    cv::dnn::blobFromImages(srcImages,
                    inputBlob,
                    scale,
                    inputSize,
                    meanValue,
                    swapRB,
                    false);

liucong's avatar
liucong committed
146
    // 创建输入数据
liucong's avatar
liucong committed
147
148
149
150
151
152
153
    std::unordered_map<std::string, migraphx::argument> inputData;
    inputData[inputName]= migraphx::argument{inputShape, (float*)inputBlob.data};

    // 推理
    std::vector<migraphx::argument> results = net.eval(inputData);

    // 获取输出节点的属性
liucong's avatar
liucong committed
154
155
156
157
158
    migraphx::argument result  = results[0]; // 获取第一个输出节点的数据
    migraphx::shape outputShape=result.get_shape(); // 输出节点的shape
    std::vector<std::size_t> outputSize=outputShape.lens();// 每一维大小,维度顺序为(N,C,H,W) 
    int numberOfOutput=outputShape.elements();// 输出节点元素的个数
    float *logits=(float *)result.data();// 输出节点数据指针
liucong's avatar
liucong committed
159
160
161
162
163
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

    // 获取每张图像的预测结果
    int numberOfClasses=numberOfOutput/srcImages.size();
    for(int i=0;i<srcImages.size();++i)
    {
        int startIndex=numberOfClasses*i;

        std::vector<float> logit;
        for(int j=0;j<numberOfClasses;++j)
        {
            logit.push_back(logits[startIndex+j]);
        }
        
        std::vector<ResultOfPrediction> resultOfPredictions;
        for(int j=0;j<numberOfClasses;++j)
        {
            ResultOfPrediction prediction;
            prediction.label=j;
            prediction.confidence=logit[j];

            resultOfPredictions.push_back(prediction);
        }

        predictions.push_back(resultOfPredictions);
    }

    return SUCCESS;

}

}