aboutsummaryrefslogtreecommitdiff
path: root/src/armnn/test/JsonPrinterTests.cpp
blob: 93f32cc5404957b4c05f3f361b5cb22e86a0182a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
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
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
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
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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
//
// Copyright © 2017 Arm Ltd. All rights reserved.
// SPDX-License-Identifier: MIT
//
#include <boost/test/unit_test.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>
#include <stack>
#include <string>
#include <vector>
#include <sstream>

#include <Profiling.hpp>
#include <armnn/Descriptors.hpp>
#include <armnn/IRuntime.hpp>
#include <armnn/INetwork.hpp>
#include <backends/cl/test/ClContextControlFixture.hpp>
#include <backends/cl/ClWorkloadFactory.hpp>

BOOST_FIXTURE_TEST_SUITE(JsonPrinterTests, ClProfilingContextControlFixture)

bool AreMatchingPair(const char opening, const char closing)
{
    return (opening == '{' && closing == '}') || (opening == '[' && closing == ']');
}

bool AreParenthesesMatching(const std::string& exp)
{
    std::stack<char> expStack;
    for (size_t i = 0; i < exp.length(); ++i)
    {
        if (exp[i] == '{' || exp[i] == '[')
        {
            expStack.push(exp[i]);
        }
        else if (exp[i] == '}' || exp[i] == ']')
        {
            if (expStack.empty() || !AreMatchingPair(expStack.top(), exp[i]))
            {
                return false;
            }
            else
            {
                expStack.pop();
            }
        }
    }
    return expStack.empty();
}

std::vector<double> ExtractMeasurements(const std::string& exp)
{
    std::vector<double> numbers;
    bool inArray = false;
    std::string numberString;
    for (size_t i = 0; i < exp.size(); ++i)
    {
        if (exp[i] == '[')
        {
            inArray = true;
        }
        else if (exp[i] == ']' && inArray)
        {
            try
            {
                boost::trim_if(numberString, boost::is_any_of("\t,\n"));
                numbers.push_back(std::stod(numberString));
            }
            catch (std::invalid_argument const& e)
            {
                BOOST_FAIL("Could not convert measurements to double: " + numberString);
            }

            numberString.clear();
            inArray = false;
        }
        else if (exp[i] == ',' && inArray)
        {
            try
            {
                boost::trim_if(numberString, boost::is_any_of("\t,\n"));
                numbers.push_back(std::stod(numberString));
            }
            catch (std::invalid_argument const& e)
            {
                BOOST_FAIL("Could not convert measurements to double: " + numberString);
            }
            numberString.clear();
        }
        else if (exp[i] != '[' && inArray && exp[i] != ',' && exp[i] != ' ')
        {
            numberString += exp[i];
        }
    }
    return numbers;
}

std::vector<std::string> ExtractSections(const std::string& exp)
{
    std::vector<std::string> sections;

    std::stack<size_t> s;
    for (size_t i = 0; i < exp.size(); i++)
    {
        if (exp.at(i) == '{')
        {
            s.push(i);
        }
        else if (exp.at(i) == '}')
        {
            size_t from = s.top();
            s.pop();
            sections.push_back(exp.substr(from, i - from + 1));
        }
    }

    return sections;
}

std::string SoftmaxProfilerTestSetupHelper(const std::vector<armnn::BackendId>& backends)
{
    using namespace armnn;

    BOOST_CHECK(!backends.empty());

    ProfilerManager& profilerManager = armnn::ProfilerManager::GetInstance();

    // Create runtime in which test will run
    IRuntime::CreationOptions options;
    options.m_EnableGpuProfiling = backends.front() == armnn::Compute::GpuAcc;
    IRuntimePtr runtime(IRuntime::Create(options));

    // build up the structure of the network
    INetworkPtr net(INetwork::Create());

    IConnectableLayer* input = net->AddInputLayer(0, "input");
    IConnectableLayer* softmax = net->AddSoftmaxLayer(SoftmaxDescriptor(), "softmax");
    IConnectableLayer* output  = net->AddOutputLayer(0, "output");

    input->GetOutputSlot(0).Connect(softmax->GetInputSlot(0));
    softmax->GetOutputSlot(0).Connect(output->GetInputSlot(0));

    // set the tensors in the network
    TensorInfo inputTensorInfo(TensorShape({1, 5}), DataType::QuantisedAsymm8);
    inputTensorInfo.SetQuantizationOffset(100);
    inputTensorInfo.SetQuantizationScale(10000.0f);
    input->GetOutputSlot(0).SetTensorInfo(inputTensorInfo);

    TensorInfo outputTensorInfo(TensorShape({1, 5}), DataType::QuantisedAsymm8);
    outputTensorInfo.SetQuantizationOffset(0);
    outputTensorInfo.SetQuantizationScale(1.0f / 256.0f);
    softmax->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);

    // optimize the network
    IOptimizedNetworkPtr optNet = Optimize(*net, backends, runtime->GetDeviceSpec());
    if(!optNet)
    {
        BOOST_FAIL("Error occurred during Optimization, Optimize() returned nullptr.");
    }
    // load it into the runtime
    NetworkId netId;
    auto error = runtime->LoadNetwork(netId, std::move(optNet));
    BOOST_TEST(error == Status::Success);

    // create structures for input & output
    std::vector<uint8_t> inputData
        {
            1, 10, 3, 200, 5
            // one of inputs is sufficiently larger than the others to saturate softmax
        };
    std::vector<uint8_t> outputData(5);

    armnn::InputTensors inputTensors
        {
            {0, armnn::ConstTensor(runtime->GetInputTensorInfo(netId, 0), inputData.data())}
        };
    armnn::OutputTensors outputTensors
        {
            {0, armnn::Tensor(runtime->GetOutputTensorInfo(netId, 0), outputData.data())}
        };

    runtime->GetProfiler(netId)->EnableProfiling(true);

    // do the inferences
    runtime->EnqueueWorkload(netId, inputTensors, outputTensors);
    runtime->EnqueueWorkload(netId, inputTensors, outputTensors);
    runtime->EnqueueWorkload(netId, inputTensors, outputTensors);

    // retrieve the Profiler.Print() output
    std::stringstream ss;
    profilerManager.GetProfiler()->Print(ss);

    return ss.str();
}

void SoftmaxProfilerTestValidationHelper(std::string& result, const std::string& testData)
{
    // ensure all measurements are greater than zero
    std::vector<double> measurementsVector = ExtractMeasurements(result);
    BOOST_CHECK(!measurementsVector.empty());

    // check sections contain raw and unit tags
    // first ensure Parenthesis are balanced
    if (AreParenthesesMatching(result))
    {
        // remove parent sections that will not have raw or unit tag
        std::vector<std::string> sectionVector = ExtractSections(result);
        for (size_t i = 0; i < sectionVector.size(); ++i)
        {
            if (boost::contains(sectionVector[i], "\"ArmNN\":")
                || boost::contains(sectionVector[i], "\"inference_measurements\":"))
            {
                sectionVector.erase(sectionVector.begin() + static_cast<int>(i));
            }
        }
        BOOST_CHECK(!sectionVector.empty());

        BOOST_CHECK(std::all_of(sectionVector.begin(), sectionVector.end(),
                                [](std::string i) { return boost::contains(i, "\"raw\":"); }));

        BOOST_CHECK(std::all_of(sectionVector.begin(), sectionVector.end(),
                                [](std::string i) { return boost::contains(i, "\"unit\":"); }));
    }

    // remove the time measurements as they vary from test to test
    result.erase(std::remove_if (result.begin(),result.end(),
                                 [](char c) { return c == '.'; }), result.end());
    result.erase(std::remove_if (result.begin(), result.end(), &isdigit), result.end());
    result.erase(std::remove_if (result.begin(),result.end(),
                                 [](char c) { return c == '\t'; }), result.end());

    BOOST_CHECK(boost::contains(result, "ArmNN"));
    BOOST_CHECK(boost::contains(result, "inference_measurements"));
    BOOST_CHECK(boost::contains(result, "layer_measurements"));
    BOOST_CHECK_EQUAL(result, testData);

    // ensure no spare parenthesis present in print output
    BOOST_CHECK(AreParenthesesMatching(result));
}

void SetupSoftmaxProfilerWithSpecifiedBackendsAndValidateJSONPrinterResult(
        const std::vector<armnn::BackendId>& backends)
{
    // setup the test fixture and obtain JSON Printer result
    std::string result = SoftmaxProfilerTestSetupHelper(backends);

    std::string backend = "Ref";
    std::string changeLine31 = "\n},\n\"CopyMemGeneric_Execute\": {";
    std::string changeLine39 = "us\"";
    std::string changeLine40;
    std::string changeLine45;

    if (backends[0] == armnn::Compute::GpuAcc) {
        backend = "Cl";
        changeLine31 = ",\n\"OpenClKernelTimer/: softmax_layer_max_shift_exp_sum_quantized_serial GWS[,,]\": {";
        changeLine39 = R"(us"
},
"OpenClKernelTimer/: softmax_layer_norm_quantized GWS[,,]": {
"raw": [
,
,

],
"unit": "us")";

        changeLine40 = R"(
},
"CopyMemGeneric_Execute": {
"raw": [
,
,

],
"unit": "us")";
        changeLine45 = "}\n";
    }
    else if (backends[0] == armnn::Compute::CpuAcc)
    {
        backend = "Neon";
        changeLine31 = ",\n\"NeonKernelTimer/: NEFillBorderKernel\": {";
        changeLine39 = R"(us"
},
"NeonKernelTimer/: NELogitsDMaxKernel": {
"raw": [
,
,

],
"unit": "us"
},
"NeonKernelTimer/: NELogitsDSoftmaxKernel": {
"raw": [
,
,

],
"unit": "us")";
        changeLine40 = R"(
},
"CopyMemGeneric_Execute": {
"raw": [
,
,

],
"unit": "us")";
        changeLine45 = "}\n";
    }

    std::string testData = R"({
"ArmNN": {
"inference_measurements": {
"raw": [
,
,

],
"unit": "us",
"layer_measurements": {
"raw": [
,
,

],
"unit": "us",
"CopyMemGeneric_Execute": {
"raw": [
,
,

],
"unit": "us"
},
")" + backend + R"(SoftmaxUintWorkload_Execute": {
"raw": [
,
,

],
"unit": "us")" + changeLine31 + R"(
"raw": [
,
,

],
"unit": ")" + changeLine39 + R"(
})" + changeLine40 + R"(
}
}
}
}
)" + changeLine45 + R"()";

    // validate the JSON Printer result
    SoftmaxProfilerTestValidationHelper(result, testData);
}

BOOST_AUTO_TEST_CASE(SoftmaxProfilerJSONPrinterCpuRefTest)
{
    SetupSoftmaxProfilerWithSpecifiedBackendsAndValidateJSONPrinterResult({armnn::Compute::CpuRef});
}


#if ARMCOMPUTENEON_ENABLED
BOOST_AUTO_TEST_CASE(SoftmaxProfilerJSONPrinterCpuAccTest)
{
    SetupSoftmaxProfilerWithSpecifiedBackendsAndValidateJSONPrinterResult({armnn::Compute::CpuAcc});
}
#endif

#if ARMCOMPUTECL_ENABLED
BOOST_AUTO_TEST_CASE(SoftmaxProfilerJSONPrinterGpuAccTest)
{
    SetupSoftmaxProfilerWithSpecifiedBackendsAndValidateJSONPrinterResult({armnn::Compute::GpuAcc});
}
#endif

BOOST_AUTO_TEST_SUITE_END()