1 /*
2  * Copyright (C) 2019 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 // This header file defines an unified structure for a model under test, and provides helper
18 // functions checking test results. Multiple instances of the test model structure will be
19 // generated from the model specification files under nn/runtime/test/specs directory.
20 // Both CTS and VTS will consume this test structure and convert into their own model and
21 // request format.
22 
23 #ifndef ANDROID_FRAMEWORKS_ML_NN_TOOLS_TEST_GENERATOR_TEST_HARNESS_TEST_HARNESS_H
24 #define ANDROID_FRAMEWORKS_ML_NN_TOOLS_TEST_GENERATOR_TEST_HARNESS_TEST_HARNESS_H
25 
26 #include <algorithm>
27 #include <cstdlib>
28 #include <cstring>
29 #include <functional>
30 #include <iostream>
31 #include <limits>
32 #include <map>
33 #include <memory>
34 #include <random>
35 #include <string>
36 #include <utility>
37 #include <vector>
38 
39 namespace test_helper {
40 
41 // This class is a workaround for two issues our code relies on:
42 // 1. sizeof(bool) is implementation defined.
43 // 2. vector<bool> does not allow direct pointer access via the data() method.
44 class bool8 {
45    public:
bool8()46     bool8() : mValue() {}
bool8(bool value)47     /* implicit */ bool8(bool value) : mValue(value) {}
48     inline operator bool() const { return mValue != 0; }
49 
50    private:
51     uint8_t mValue;
52 };
53 
54 static_assert(sizeof(bool8) == 1, "size of bool8 must be 8 bits");
55 
56 // We need the following enum classes since the test harness can neither depend on NDK nor HIDL
57 // definitions.
58 
59 enum class TestOperandType {
60     FLOAT32 = 0,
61     INT32 = 1,
62     UINT32 = 2,
63     TENSOR_FLOAT32 = 3,
64     TENSOR_INT32 = 4,
65     TENSOR_QUANT8_ASYMM = 5,
66     BOOL = 6,
67     TENSOR_QUANT16_SYMM = 7,
68     TENSOR_FLOAT16 = 8,
69     TENSOR_BOOL8 = 9,
70     FLOAT16 = 10,
71     TENSOR_QUANT8_SYMM_PER_CHANNEL = 11,
72     TENSOR_QUANT16_ASYMM = 12,
73     TENSOR_QUANT8_SYMM = 13,
74     TENSOR_QUANT8_ASYMM_SIGNED = 14,
75     SUBGRAPH = 15,
76 };
77 
78 enum class TestOperandLifeTime {
79     TEMPORARY_VARIABLE = 0,
80     SUBGRAPH_INPUT = 1,
81     SUBGRAPH_OUTPUT = 2,
82     CONSTANT_COPY = 3,
83     CONSTANT_REFERENCE = 4,
84     NO_VALUE = 5,
85     SUBGRAPH = 6,
86     // DEPRECATED. Use SUBGRAPH_INPUT.
87     // This value is used in pre-1.3 VTS tests.
88     MODEL_INPUT = SUBGRAPH_INPUT,
89     // DEPRECATED. Use SUBGRAPH_OUTPUT.
90     // This value is used in pre-1.3 VTS tests.
91     MODEL_OUTPUT = SUBGRAPH_OUTPUT,
92 };
93 
94 enum class TestOperationType {
95     ADD = 0,
96     AVERAGE_POOL_2D = 1,
97     CONCATENATION = 2,
98     CONV_2D = 3,
99     DEPTHWISE_CONV_2D = 4,
100     DEPTH_TO_SPACE = 5,
101     DEQUANTIZE = 6,
102     EMBEDDING_LOOKUP = 7,
103     FLOOR = 8,
104     FULLY_CONNECTED = 9,
105     HASHTABLE_LOOKUP = 10,
106     L2_NORMALIZATION = 11,
107     L2_POOL_2D = 12,
108     LOCAL_RESPONSE_NORMALIZATION = 13,
109     LOGISTIC = 14,
110     LSH_PROJECTION = 15,
111     LSTM = 16,
112     MAX_POOL_2D = 17,
113     MUL = 18,
114     RELU = 19,
115     RELU1 = 20,
116     RELU6 = 21,
117     RESHAPE = 22,
118     RESIZE_BILINEAR = 23,
119     RNN = 24,
120     SOFTMAX = 25,
121     SPACE_TO_DEPTH = 26,
122     SVDF = 27,
123     TANH = 28,
124     BATCH_TO_SPACE_ND = 29,
125     DIV = 30,
126     MEAN = 31,
127     PAD = 32,
128     SPACE_TO_BATCH_ND = 33,
129     SQUEEZE = 34,
130     STRIDED_SLICE = 35,
131     SUB = 36,
132     TRANSPOSE = 37,
133     ABS = 38,
134     ARGMAX = 39,
135     ARGMIN = 40,
136     AXIS_ALIGNED_BBOX_TRANSFORM = 41,
137     BIDIRECTIONAL_SEQUENCE_LSTM = 42,
138     BIDIRECTIONAL_SEQUENCE_RNN = 43,
139     BOX_WITH_NMS_LIMIT = 44,
140     CAST = 45,
141     CHANNEL_SHUFFLE = 46,
142     DETECTION_POSTPROCESSING = 47,
143     EQUAL = 48,
144     EXP = 49,
145     EXPAND_DIMS = 50,
146     GATHER = 51,
147     GENERATE_PROPOSALS = 52,
148     GREATER = 53,
149     GREATER_EQUAL = 54,
150     GROUPED_CONV_2D = 55,
151     HEATMAP_MAX_KEYPOINT = 56,
152     INSTANCE_NORMALIZATION = 57,
153     LESS = 58,
154     LESS_EQUAL = 59,
155     LOG = 60,
156     LOGICAL_AND = 61,
157     LOGICAL_NOT = 62,
158     LOGICAL_OR = 63,
159     LOG_SOFTMAX = 64,
160     MAXIMUM = 65,
161     MINIMUM = 66,
162     NEG = 67,
163     NOT_EQUAL = 68,
164     PAD_V2 = 69,
165     POW = 70,
166     PRELU = 71,
167     QUANTIZE = 72,
168     QUANTIZED_16BIT_LSTM = 73,
169     RANDOM_MULTINOMIAL = 74,
170     REDUCE_ALL = 75,
171     REDUCE_ANY = 76,
172     REDUCE_MAX = 77,
173     REDUCE_MIN = 78,
174     REDUCE_PROD = 79,
175     REDUCE_SUM = 80,
176     ROI_ALIGN = 81,
177     ROI_POOLING = 82,
178     RSQRT = 83,
179     SELECT = 84,
180     SIN = 85,
181     SLICE = 86,
182     SPLIT = 87,
183     SQRT = 88,
184     TILE = 89,
185     TOPK_V2 = 90,
186     TRANSPOSE_CONV_2D = 91,
187     UNIDIRECTIONAL_SEQUENCE_LSTM = 92,
188     UNIDIRECTIONAL_SEQUENCE_RNN = 93,
189     RESIZE_NEAREST_NEIGHBOR = 94,
190     QUANTIZED_LSTM = 95,
191     IF = 96,
192     WHILE = 97,
193     ELU = 98,
194     HARD_SWISH = 99,
195     FILL = 100,
196     RANK = 101,
197 };
198 
199 enum class TestHalVersion { UNKNOWN, V1_0, V1_1, V1_2, V1_3 };
200 
201 // Manages the data buffer for a test operand.
202 class TestBuffer {
203    public:
204     // The buffer must be aligned on a boundary of a byte size that is a multiple of the element
205     // type byte size. In NNAPI, 4-byte boundary should be sufficient for all current data types.
206     static constexpr size_t kAlignment = 4;
207 
208     // Create the buffer of a given size and initialize from data.
209     // If data is nullptr, the allocated memory stays uninitialized.
mSize(size)210     TestBuffer(size_t size = 0, const void* data = nullptr) : mSize(size) {
211         if (size > 0) {
212             // The size for aligned_alloc must be an integral multiple of alignment.
213             mBuffer.reset(aligned_alloc(kAlignment, alignedSize()), free);
214             if (data) memcpy(mBuffer.get(), data, size);
215         }
216     }
217 
218     // Explicitly create a deep copy.
copy()219     TestBuffer copy() const { return TestBuffer(mSize, mBuffer.get()); }
220 
221     // Factory method creating the buffer from a typed vector.
222     template <typename T>
createFromVector(const std::vector<T> & vec)223     static TestBuffer createFromVector(const std::vector<T>& vec) {
224         return TestBuffer(vec.size() * sizeof(T), vec.data());
225     }
226 
227     // Factory method for creating a randomized buffer with "size" number of
228     // bytes.
createRandom(size_t size,std::default_random_engine * gen)229     static TestBuffer createRandom(size_t size, std::default_random_engine* gen) {
230         static_assert(kAlignment % sizeof(uint32_t) == 0);
231         TestBuffer testBuffer(size);
232         std::uniform_int_distribution<uint32_t> dist{};
233         const size_t count = testBuffer.alignedSize() / sizeof(uint32_t);
234         std::generate_n(testBuffer.getMutable<uint32_t>(), count, [&] { return dist(*gen); });
235         return testBuffer;
236     }
237 
238     template <typename T>
get()239     const T* get() const {
240         return reinterpret_cast<const T*>(mBuffer.get());
241     }
242 
243     template <typename T>
getMutable()244     T* getMutable() {
245         return reinterpret_cast<T*>(mBuffer.get());
246     }
247 
248     // Returns the byte size of the buffer.
size()249     size_t size() const { return mSize; }
250 
251     // Returns the byte size that is aligned to kAlignment.
alignedSize()252     size_t alignedSize() const { return ((mSize + kAlignment - 1) / kAlignment) * kAlignment; }
253 
254     bool operator==(std::nullptr_t) const { return mBuffer == nullptr; }
255     bool operator!=(std::nullptr_t) const { return mBuffer != nullptr; }
256 
257    private:
258     std::shared_ptr<void> mBuffer;
259     size_t mSize = 0;
260 };
261 
262 struct TestSymmPerChannelQuantParams {
263     std::vector<float> scales;
264     uint32_t channelDim = 0;
265 };
266 
267 struct TestOperand {
268     TestOperandType type;
269     std::vector<uint32_t> dimensions;
270     uint32_t numberOfConsumers;
271     float scale = 0.0f;
272     int32_t zeroPoint = 0;
273     TestOperandLifeTime lifetime;
274     TestSymmPerChannelQuantParams channelQuant;
275 
276     // For SUBGRAPH_OUTPUT only. Set to true to skip the accuracy check on this operand.
277     bool isIgnored = false;
278 
279     // For CONSTANT_COPY/REFERENCE and SUBGRAPH_INPUT, this is the data set in model and request.
280     // For SUBGRAPH_OUTPUT, this is the expected results.
281     // For TEMPORARY_VARIABLE and NO_VALUE, this is nullptr.
282     TestBuffer data;
283 };
284 
285 struct TestOperation {
286     TestOperationType type;
287     std::vector<uint32_t> inputs;
288     std::vector<uint32_t> outputs;
289 };
290 
291 struct TestSubgraph {
292     std::vector<TestOperand> operands;
293     std::vector<TestOperation> operations;
294     std::vector<uint32_t> inputIndexes;
295     std::vector<uint32_t> outputIndexes;
296 };
297 
298 struct TestModel {
299     TestSubgraph main;
300     std::vector<TestSubgraph> referenced;
301     bool isRelaxed = false;
302 
303     // Additional testing information and flags associated with the TestModel.
304 
305     // Specifies the RANDOM_MULTINOMIAL distribution tolerance.
306     // If set to greater than zero, the input is compared as log-probabilities
307     // to the output and must be within this tolerance to pass.
308     float expectedMultinomialDistributionTolerance = 0.0f;
309 
310     // If set to true, the TestModel specifies a validation test that is expected to fail during
311     // compilation or execution.
312     bool expectFailure = false;
313 
314     // The minimum supported HAL version.
315     TestHalVersion minSupportedVersion = TestHalVersion::UNKNOWN;
316 
forEachSubgraphTestModel317     void forEachSubgraph(std::function<void(const TestSubgraph&)> handler) const {
318         handler(main);
319         for (const TestSubgraph& subgraph : referenced) {
320             handler(subgraph);
321         }
322     }
323 
forEachSubgraphTestModel324     void forEachSubgraph(std::function<void(TestSubgraph&)> handler) {
325         handler(main);
326         for (TestSubgraph& subgraph : referenced) {
327             handler(subgraph);
328         }
329     }
330 
331     // Explicitly create a deep copy.
copyTestModel332     TestModel copy() const {
333         TestModel newTestModel(*this);
334         newTestModel.forEachSubgraph([](TestSubgraph& subgraph) {
335             for (TestOperand& operand : subgraph.operands) {
336                 operand.data = operand.data.copy();
337             }
338         });
339         return newTestModel;
340     }
341 
hasQuant8CoupledOperandsTestModel342     bool hasQuant8CoupledOperands() const {
343         bool result = false;
344         forEachSubgraph([&result](const TestSubgraph& subgraph) {
345             if (result) {
346                 return;
347             }
348             for (const TestOperation& operation : subgraph.operations) {
349                 /*
350                  *  There are several ops that are exceptions to the general quant8
351                  *  types coupling:
352                  *  HASHTABLE_LOOKUP -- due to legacy reasons uses
353                  *    TENSOR_QUANT8_ASYMM tensor as if it was TENSOR_BOOL. It
354                  *    doesn't make sense to have coupling in this case.
355                  *  LSH_PROJECTION -- hashes an input tensor treating it as raw
356                  *    bytes. We can't expect same results for coupled inputs.
357                  *  PAD_V2 -- pad_value is set using int32 scalar, so coupling
358                  *    produces a wrong result.
359                  *  CAST -- converts tensors without taking into account input's
360                  *    scale and zero point. Coupled models shouldn't produce same
361                  *    results.
362                  *  QUANTIZED_16BIT_LSTM -- the op is made for a specific use case,
363                  *    supporting signed quantization is not worth the compications.
364                  */
365                 if (operation.type == TestOperationType::HASHTABLE_LOOKUP ||
366                     operation.type == TestOperationType::LSH_PROJECTION ||
367                     operation.type == TestOperationType::PAD_V2 ||
368                     operation.type == TestOperationType::CAST ||
369                     operation.type == TestOperationType::QUANTIZED_16BIT_LSTM) {
370                     continue;
371                 }
372                 for (const auto operandIndex : operation.inputs) {
373                     if (subgraph.operands[operandIndex].type ==
374                         TestOperandType::TENSOR_QUANT8_ASYMM) {
375                         result = true;
376                         return;
377                     }
378                 }
379                 for (const auto operandIndex : operation.outputs) {
380                     if (subgraph.operands[operandIndex].type ==
381                         TestOperandType::TENSOR_QUANT8_ASYMM) {
382                         result = true;
383                         return;
384                     }
385                 }
386             }
387         });
388         return result;
389     }
390 
hasScalarOutputsTestModel391     bool hasScalarOutputs() const {
392         bool result = false;
393         forEachSubgraph([&result](const TestSubgraph& subgraph) {
394             if (result) {
395                 return;
396             }
397             for (const TestOperation& operation : subgraph.operations) {
398                 // RANK op returns a scalar and therefore shouldn't be tested
399                 // for dynamic output shape support.
400                 if (operation.type == TestOperationType::RANK) {
401                     result = true;
402                     return;
403                 }
404                 // Control flow operations do not support referenced model
405                 // outputs with dynamic shapes.
406                 if (operation.type == TestOperationType::IF ||
407                     operation.type == TestOperationType::WHILE) {
408                     result = true;
409                     return;
410                 }
411             }
412         });
413         return result;
414     }
415 
isInfiniteLoopTimeoutTestTestModel416     bool isInfiniteLoopTimeoutTest() const {
417         // This should only match the TestModel generated from while_infinite_loop.mod.py.
418         return expectFailure && main.operations[0].type == TestOperationType::WHILE;
419     }
420 };
421 
422 // Manages all generated test models.
423 class TestModelManager {
424    public:
425     // Returns the singleton manager.
get()426     static TestModelManager& get() {
427         static TestModelManager instance;
428         return instance;
429     }
430 
431     // Registers a TestModel to the manager. Returns a placeholder integer for global variable
432     // initialization.
add(std::string name,const TestModel & testModel)433     int add(std::string name, const TestModel& testModel) {
434         mTestModels.emplace(std::move(name), &testModel);
435         return 0;
436     }
437 
438     // Returns a vector of selected TestModels for which the given "filter" returns true.
439     using TestParam = std::pair<std::string, const TestModel*>;
getTestModels(std::function<bool (const TestModel &)> filter)440     std::vector<TestParam> getTestModels(std::function<bool(const TestModel&)> filter) {
441         std::vector<TestParam> testModels;
442         testModels.reserve(mTestModels.size());
443         std::copy_if(mTestModels.begin(), mTestModels.end(), std::back_inserter(testModels),
444                      [filter](const auto& nameTestPair) { return filter(*nameTestPair.second); });
445         return testModels;
446     }
447 
448     // Returns a vector of selected TestModels for which the given "filter" returns true.
getTestModels(std::function<bool (const std::string &)> filter)449     std::vector<TestParam> getTestModels(std::function<bool(const std::string&)> filter) {
450         std::vector<TestParam> testModels;
451         testModels.reserve(mTestModels.size());
452         std::copy_if(mTestModels.begin(), mTestModels.end(), std::back_inserter(testModels),
453                      [filter](const auto& nameTestPair) { return filter(nameTestPair.first); });
454         return testModels;
455     }
456 
457    private:
458     TestModelManager() = default;
459     TestModelManager(const TestModelManager&) = delete;
460     TestModelManager& operator=(const TestModelManager&) = delete;
461 
462     // Contains all TestModels generated from nn/runtime/test/specs directory.
463     // The TestModels are sorted by name to ensure a predictable order.
464     std::map<std::string, const TestModel*> mTestModels;
465 };
466 
467 struct AccuracyCriterion {
468     // We expect the driver results to be unbiased.
469     // Formula: abs(sum_{i}(diff) / sum(1)) <= bias, where
470     // * fixed point: diff = actual - expected
471     // * floating point: diff = (actual - expected) / max(1, abs(expected))
472     float bias = std::numeric_limits<float>::max();
473 
474     // Set the threshold on Mean Square Error (MSE).
475     // Formula: sum_{i}(diff ^ 2) / sum(1) <= mse
476     float mse = std::numeric_limits<float>::max();
477 
478     // We also set accuracy thresholds on each element to detect any particular edge cases that may
479     // be shadowed in bias or MSE. We use the similar approach as our CTS unit tests, but with much
480     // relaxed criterion.
481     // Formula: abs(actual - expected) <= atol + rtol * abs(expected)
482     //   where atol stands for Absolute TOLerance and rtol for Relative TOLerance.
483     float atol = 0.0f;
484     float rtol = 0.0f;
485 };
486 
487 struct AccuracyCriteria {
488     AccuracyCriterion float32;
489     AccuracyCriterion float16;
490     AccuracyCriterion int32;
491     AccuracyCriterion quant8Asymm;
492     AccuracyCriterion quant8AsymmSigned;
493     AccuracyCriterion quant8Symm;
494     AccuracyCriterion quant16Asymm;
495     AccuracyCriterion quant16Symm;
496     float bool8AllowedErrorRatio = 0.1f;
497     bool allowInvalidFpValues = true;
498 };
499 
500 // Check the output results against the expected values in test model by calling
501 // GTEST_ASSERT/EXPECT. The index of the results corresponds to the index in
502 // model.main.outputIndexes. E.g., results[i] corresponds to model.main.outputIndexes[i].
503 void checkResults(const TestModel& model, const std::vector<TestBuffer>& results);
504 void checkResults(const TestModel& model, const std::vector<TestBuffer>& results,
505                   const AccuracyCriteria& criteria);
506 
507 bool isQuantizedType(TestOperandType type);
508 
509 TestModel convertQuant8AsymmOperandsToSigned(const TestModel& testModel);
510 
511 const char* toString(TestOperandType type);
512 const char* toString(TestOperationType type);
513 
514 // Dump a test model in the format of a spec file for debugging and visualization purpose.
515 class SpecDumper {
516    public:
SpecDumper(const TestModel & testModel,std::ostream & os)517     SpecDumper(const TestModel& testModel, std::ostream& os) : kTestModel(testModel), mOs(os) {}
518     void dumpTestModel();
519     void dumpResults(const std::string& name, const std::vector<TestBuffer>& results);
520 
521    private:
522     // Dump a test model operand.
523     // e.g. op0 = Input("op0", "TENSOR_FLOAT32", "{1, 2, 6, 1}")
524     // e.g. op1 = Parameter("op1", "INT32", "{}", [2])
525     void dumpTestOperand(const TestOperand& operand, uint32_t index);
526 
527     // Dump a test model operation.
528     // e.g. model = model.Operation("CONV_2D", op0, op1, op2, op3, op4, op5, op6).To(op7)
529     void dumpTestOperation(const TestOperation& operation);
530 
531     // Dump a test buffer as a python 1D list.
532     // e.g. [1, 2, 3, 4, 5]
533     //
534     // If useHexFloat is set to true and the operand type is float, the buffer values will be
535     // dumped in hex representation.
536     void dumpTestBuffer(TestOperandType type, const TestBuffer& buffer, bool useHexFloat);
537 
538     const TestModel& kTestModel;
539     std::ostream& mOs;
540 };
541 
542 // Convert the test model to an equivalent float32 model. It will return std::nullopt if the
543 // conversion is not supported, or if there is no equivalent float32 model.
544 std::optional<TestModel> convertToFloat32Model(const TestModel& testModel);
545 
546 // Used together with convertToFloat32Model. Convert the results computed from the float model to
547 // the actual data type in the original model.
548 void setExpectedOutputsFromFloat32Results(const std::vector<TestBuffer>& results, TestModel* model);
549 
550 }  // namespace test_helper
551 
552 #endif  // ANDROID_FRAMEWORKS_ML_NN_TOOLS_TEST_GENERATOR_TEST_HARNESS_TEST_HARNESS_H
553