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.
229     template <typename T>
createFromRng(size_t size,std::default_random_engine * gen)230     static TestBuffer createFromRng(size_t size, std::default_random_engine* gen) {
231         static_assert(kAlignment % sizeof(T) == 0);
232         TestBuffer testBuffer(size);
233         std::uniform_int_distribution<T> dist{};
234         const size_t adjustedSize = testBuffer.alignedSize() / sizeof(T);
235         std::generate_n(testBuffer.getMutable<T>(), adjustedSize, [&] { return dist(*gen); });
236         return testBuffer;
237     }
238 
239     template <typename T>
get()240     const T* get() const {
241         return reinterpret_cast<const T*>(mBuffer.get());
242     }
243 
244     template <typename T>
getMutable()245     T* getMutable() {
246         return reinterpret_cast<T*>(mBuffer.get());
247     }
248 
249     // Returns the byte size of the buffer.
size()250     size_t size() const { return mSize; }
251 
252     // Returns the byte size that is aligned to kAlignment.
alignedSize()253     size_t alignedSize() const { return ((mSize + kAlignment - 1) / kAlignment) * kAlignment; }
254 
255     bool operator==(std::nullptr_t) const { return mBuffer == nullptr; }
256     bool operator!=(std::nullptr_t) const { return mBuffer != nullptr; }
257 
258    private:
259     std::shared_ptr<void> mBuffer;
260     size_t mSize = 0;
261 };
262 
263 struct TestSymmPerChannelQuantParams {
264     std::vector<float> scales;
265     uint32_t channelDim = 0;
266 };
267 
268 struct TestOperand {
269     TestOperandType type;
270     std::vector<uint32_t> dimensions;
271     uint32_t numberOfConsumers;
272     float scale = 0.0f;
273     int32_t zeroPoint = 0;
274     TestOperandLifeTime lifetime;
275     TestSymmPerChannelQuantParams channelQuant;
276 
277     // For SUBGRAPH_OUTPUT only. Set to true to skip the accuracy check on this operand.
278     bool isIgnored = false;
279 
280     // For CONSTANT_COPY/REFERENCE and SUBGRAPH_INPUT, this is the data set in model and request.
281     // For SUBGRAPH_OUTPUT, this is the expected results.
282     // For TEMPORARY_VARIABLE and NO_VALUE, this is nullptr.
283     TestBuffer data;
284 };
285 
286 struct TestOperation {
287     TestOperationType type;
288     std::vector<uint32_t> inputs;
289     std::vector<uint32_t> outputs;
290 };
291 
292 struct TestSubgraph {
293     std::vector<TestOperand> operands;
294     std::vector<TestOperation> operations;
295     std::vector<uint32_t> inputIndexes;
296     std::vector<uint32_t> outputIndexes;
297 };
298 
299 struct TestModel {
300     TestSubgraph main;
301     std::vector<TestSubgraph> referenced;
302     bool isRelaxed = false;
303 
304     // Additional testing information and flags associated with the TestModel.
305 
306     // Specifies the RANDOM_MULTINOMIAL distribution tolerance.
307     // If set to greater than zero, the input is compared as log-probabilities
308     // to the output and must be within this tolerance to pass.
309     float expectedMultinomialDistributionTolerance = 0.0f;
310 
311     // If set to true, the TestModel specifies a validation test that is expected to fail during
312     // compilation or execution.
313     bool expectFailure = false;
314 
315     // The minimum supported HAL version.
316     TestHalVersion minSupportedVersion = TestHalVersion::UNKNOWN;
317 
forEachSubgraphTestModel318     void forEachSubgraph(std::function<void(const TestSubgraph&)> handler) const {
319         handler(main);
320         for (const TestSubgraph& subgraph : referenced) {
321             handler(subgraph);
322         }
323     }
324 
forEachSubgraphTestModel325     void forEachSubgraph(std::function<void(TestSubgraph&)> handler) {
326         handler(main);
327         for (TestSubgraph& subgraph : referenced) {
328             handler(subgraph);
329         }
330     }
331 
332     // Explicitly create a deep copy.
copyTestModel333     TestModel copy() const {
334         TestModel newTestModel(*this);
335         newTestModel.forEachSubgraph([](TestSubgraph& subgraph) {
336             for (TestOperand& operand : subgraph.operands) {
337                 operand.data = operand.data.copy();
338             }
339         });
340         return newTestModel;
341     }
342 
hasQuant8CoupledOperandsTestModel343     bool hasQuant8CoupledOperands() const {
344         bool result = false;
345         forEachSubgraph([&result](const TestSubgraph& subgraph) {
346             if (result) {
347                 return;
348             }
349             for (const TestOperation& operation : subgraph.operations) {
350                 /*
351                  *  There are several ops that are exceptions to the general quant8
352                  *  types coupling:
353                  *  HASHTABLE_LOOKUP -- due to legacy reasons uses
354                  *    TENSOR_QUANT8_ASYMM tensor as if it was TENSOR_BOOL. It
355                  *    doesn't make sense to have coupling in this case.
356                  *  LSH_PROJECTION -- hashes an input tensor treating it as raw
357                  *    bytes. We can't expect same results for coupled inputs.
358                  *  PAD_V2 -- pad_value is set using int32 scalar, so coupling
359                  *    produces a wrong result.
360                  *  CAST -- converts tensors without taking into account input's
361                  *    scale and zero point. Coupled models shouldn't produce same
362                  *    results.
363                  *  QUANTIZED_16BIT_LSTM -- the op is made for a specific use case,
364                  *    supporting signed quantization is not worth the compications.
365                  */
366                 if (operation.type == TestOperationType::HASHTABLE_LOOKUP ||
367                     operation.type == TestOperationType::LSH_PROJECTION ||
368                     operation.type == TestOperationType::PAD_V2 ||
369                     operation.type == TestOperationType::CAST ||
370                     operation.type == TestOperationType::QUANTIZED_16BIT_LSTM) {
371                     continue;
372                 }
373                 for (const auto operandIndex : operation.inputs) {
374                     if (subgraph.operands[operandIndex].type ==
375                         TestOperandType::TENSOR_QUANT8_ASYMM) {
376                         result = true;
377                         return;
378                     }
379                 }
380                 for (const auto operandIndex : operation.outputs) {
381                     if (subgraph.operands[operandIndex].type ==
382                         TestOperandType::TENSOR_QUANT8_ASYMM) {
383                         result = true;
384                         return;
385                     }
386                 }
387             }
388         });
389         return result;
390     }
391 
hasScalarOutputsTestModel392     bool hasScalarOutputs() const {
393         bool result = false;
394         forEachSubgraph([&result](const TestSubgraph& subgraph) {
395             if (result) {
396                 return;
397             }
398             for (const TestOperation& operation : subgraph.operations) {
399                 // RANK op returns a scalar and therefore shouldn't be tested
400                 // for dynamic output shape support.
401                 if (operation.type == TestOperationType::RANK) {
402                     result = true;
403                     return;
404                 }
405                 // Control flow operations do not support referenced model
406                 // outputs with dynamic shapes.
407                 if (operation.type == TestOperationType::IF ||
408                     operation.type == TestOperationType::WHILE) {
409                     result = true;
410                     return;
411                 }
412             }
413         });
414         return result;
415     }
416 
isInfiniteLoopTimeoutTestTestModel417     bool isInfiniteLoopTimeoutTest() const {
418         // This should only match the TestModel generated from while_infinite_loop.mod.py.
419         return expectFailure && main.operations[0].type == TestOperationType::WHILE;
420     }
421 };
422 
423 // Manages all generated test models.
424 class TestModelManager {
425    public:
426     // Returns the singleton manager.
get()427     static TestModelManager& get() {
428         static TestModelManager instance;
429         return instance;
430     }
431 
432     // Registers a TestModel to the manager. Returns a dummy integer for global variable
433     // initialization.
add(std::string name,const TestModel & testModel)434     int add(std::string name, const TestModel& testModel) {
435         mTestModels.emplace(std::move(name), &testModel);
436         return 0;
437     }
438 
439     // Returns a vector of selected TestModels for which the given "filter" returns true.
440     using TestParam = std::pair<std::string, const TestModel*>;
getTestModels(std::function<bool (const TestModel &)> filter)441     std::vector<TestParam> getTestModels(std::function<bool(const TestModel&)> filter) {
442         std::vector<TestParam> testModels;
443         testModels.reserve(mTestModels.size());
444         std::copy_if(mTestModels.begin(), mTestModels.end(), std::back_inserter(testModels),
445                      [filter](const auto& nameTestPair) { return filter(*nameTestPair.second); });
446         return testModels;
447     }
448 
449     // Returns a vector of selected TestModels for which the given "filter" returns true.
getTestModels(std::function<bool (const std::string &)> filter)450     std::vector<TestParam> getTestModels(std::function<bool(const std::string&)> filter) {
451         std::vector<TestParam> testModels;
452         testModels.reserve(mTestModels.size());
453         std::copy_if(mTestModels.begin(), mTestModels.end(), std::back_inserter(testModels),
454                      [filter](const auto& nameTestPair) { return filter(nameTestPair.first); });
455         return testModels;
456     }
457 
458    private:
459     TestModelManager() = default;
460     TestModelManager(const TestModelManager&) = delete;
461     TestModelManager& operator=(const TestModelManager&) = delete;
462 
463     // Contains all TestModels generated from nn/runtime/test/specs directory.
464     // The TestModels are sorted by name to ensure a predictable order.
465     std::map<std::string, const TestModel*> mTestModels;
466 };
467 
468 struct AccuracyCriterion {
469     // We expect the driver results to be unbiased.
470     // Formula: abs(sum_{i}(diff) / sum(1)) <= bias, where
471     // * fixed point: diff = actual - expected
472     // * floating point: diff = (actual - expected) / max(1, abs(expected))
473     float bias = std::numeric_limits<float>::max();
474 
475     // Set the threshold on Mean Square Error (MSE).
476     // Formula: sum_{i}(diff ^ 2) / sum(1) <= mse
477     float mse = std::numeric_limits<float>::max();
478 
479     // We also set accuracy thresholds on each element to detect any particular edge cases that may
480     // be shadowed in bias or MSE. We use the similar approach as our CTS unit tests, but with much
481     // relaxed criterion.
482     // Formula: abs(actual - expected) <= atol + rtol * abs(expected)
483     //   where atol stands for Absolute TOLerance and rtol for Relative TOLerance.
484     float atol = 0.0f;
485     float rtol = 0.0f;
486 };
487 
488 struct AccuracyCriteria {
489     AccuracyCriterion float32;
490     AccuracyCriterion float16;
491     AccuracyCriterion int32;
492     AccuracyCriterion quant8Asymm;
493     AccuracyCriterion quant8AsymmSigned;
494     AccuracyCriterion quant8Symm;
495     AccuracyCriterion quant16Asymm;
496     AccuracyCriterion quant16Symm;
497     float bool8AllowedErrorRatio = 0.1f;
498     bool allowInvalidFpValues = true;
499 };
500 
501 // Check the output results against the expected values in test model by calling
502 // GTEST_ASSERT/EXPECT. The index of the results corresponds to the index in
503 // model.main.outputIndexes. E.g., results[i] corresponds to model.main.outputIndexes[i].
504 void checkResults(const TestModel& model, const std::vector<TestBuffer>& results);
505 void checkResults(const TestModel& model, const std::vector<TestBuffer>& results,
506                   const AccuracyCriteria& criteria);
507 
508 bool isQuantizedType(TestOperandType type);
509 
510 TestModel convertQuant8AsymmOperandsToSigned(const TestModel& testModel);
511 
512 const char* toString(TestOperandType type);
513 const char* toString(TestOperationType type);
514 
515 // Dump a test model in the format of a spec file for debugging and visualization purpose.
516 class SpecDumper {
517    public:
SpecDumper(const TestModel & testModel,std::ostream & os)518     SpecDumper(const TestModel& testModel, std::ostream& os) : kTestModel(testModel), mOs(os) {}
519     void dumpTestModel();
520     void dumpResults(const std::string& name, const std::vector<TestBuffer>& results);
521 
522    private:
523     // Dump a test model operand.
524     // e.g. op0 = Input("op0", "TENSOR_FLOAT32", "{1, 2, 6, 1}")
525     // e.g. op1 = Parameter("op1", "INT32", "{}", [2])
526     void dumpTestOperand(const TestOperand& operand, uint32_t index);
527 
528     // Dump a test model operation.
529     // e.g. model = model.Operation("CONV_2D", op0, op1, op2, op3, op4, op5, op6).To(op7)
530     void dumpTestOperation(const TestOperation& operation);
531 
532     // Dump a test buffer as a python 1D list.
533     // e.g. [1, 2, 3, 4, 5]
534     //
535     // If useHexFloat is set to true and the operand type is float, the buffer values will be
536     // dumped in hex representation.
537     void dumpTestBuffer(TestOperandType type, const TestBuffer& buffer, bool useHexFloat);
538 
539     const TestModel& kTestModel;
540     std::ostream& mOs;
541 };
542 
543 // Convert the test model to an equivalent float32 model. It will return std::nullopt if the
544 // conversion is not supported, or if there is no equivalent float32 model.
545 std::optional<TestModel> convertToFloat32Model(const TestModel& testModel);
546 
547 // Used together with convertToFloat32Model. Convert the results computed from the float model to
548 // the actual data type in the original model.
549 void setExpectedOutputsFromFloat32Results(const std::vector<TestBuffer>& results, TestModel* model);
550 
551 }  // namespace test_helper
552 
553 #endif  // ANDROID_FRAMEWORKS_ML_NN_TOOLS_TEST_GENERATOR_TEST_HARNESS_TEST_HARNESS_H
554