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 #include "fuzzing/OperationManager.h"
18
19 #include <vector>
20
21 #include "TestNeuralNetworksWrapper.h"
22 #include "fuzzing/RandomGraphGeneratorUtils.h"
23
24 namespace android {
25 namespace nn {
26 namespace fuzzing_test {
27
28 using namespace test_helper;
29
30 template <typename T>
hasValue(const std::vector<T> & vec,const T & val)31 inline bool hasValue(const std::vector<T>& vec, const T& val) {
32 // Empty vector indicates "no filter", i.e. always true.
33 return vec.empty() || std::count(vec.begin(), vec.end(), val) > 0;
34 }
35
matchFilter(const OperationFilter & filter)36 bool OperationSignature::matchFilter(const OperationFilter& filter) {
37 if (!hasValue(filter.opcodes, opType) || !hasValue(filter.versions, version)) {
38 return false;
39 }
40
41 // Match data types.
42 std::vector<TestOperandType> combinedDataTypes;
43 for (auto dataType : supportedDataTypes) {
44 if (hasValue(filter.dataTypes, dataType)) combinedDataTypes.push_back(dataType);
45 }
46 if (combinedDataTypes.empty()) return false;
47 supportedDataTypes = combinedDataTypes;
48
49 // Match rank.
50 std::vector<uint32_t> combinedRanks;
51 for (auto rank : supportedRanks) {
52 if (hasValue(filter.ranks, rank)) combinedRanks.push_back(rank);
53 }
54 if (combinedRanks.empty()) return false;
55 supportedRanks = combinedRanks;
56 return true;
57 }
58
get()59 OperationManager* OperationManager::get() {
60 static OperationManager instance;
61 return &instance;
62 }
63
addSignature(const std::string & name,const OperationSignature & signature)64 void OperationManager::addSignature(const std::string& name, const OperationSignature& signature) {
65 mOperationSignatures.emplace(name, signature);
66 }
67
applyFilter(const OperationFilter & filter)68 void OperationManager::applyFilter(const OperationFilter& filter) {
69 mFilteredSignatures.clear();
70 for (const auto& pair : mOperationSignatures) {
71 mFilteredSignatures.push_back(pair.second);
72 if (!mFilteredSignatures.back().matchFilter(filter)) mFilteredSignatures.pop_back();
73 }
74 }
75
getRandomOperation() const76 const OperationSignature& OperationManager::getRandomOperation() const {
77 NN_FUZZER_CHECK(!mFilteredSignatures.empty());
78 return getRandomChoice(mFilteredSignatures);
79 }
80
81 } // namespace fuzzing_test
82 } // namespace nn
83 } // namespace android
84