1 /*
2  * Copyright (C) 2017 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 "GeneratedTestHarness.h"
18 
19 #include "1.0/Callbacks.h"
20 #include "1.0/Utils.h"
21 #include "MemoryUtils.h"
22 #include "TestHarness.h"
23 #include "VtsHalNeuralnetworks.h"
24 
25 #include <android-base/logging.h>
26 #include <android/hardware/neuralnetworks/1.0/IDevice.h>
27 #include <android/hardware/neuralnetworks/1.0/IPreparedModel.h>
28 #include <android/hardware/neuralnetworks/1.0/types.h>
29 #include <android/hidl/allocator/1.0/IAllocator.h>
30 #include <android/hidl/memory/1.0/IMemory.h>
31 #include <hidlmemory/mapping.h>
32 
33 #include <gtest/gtest.h>
34 #include <iostream>
35 
36 namespace android::hardware::neuralnetworks::V1_0::vts::functional {
37 
38 using namespace test_helper;
39 using hidl::memory::V1_0::IMemory;
40 using implementation::ExecutionCallback;
41 using implementation::PreparedModelCallback;
42 
createModel(const TestModel & testModel)43 Model createModel(const TestModel& testModel) {
44     // Model operands.
45     CHECK_EQ(testModel.referenced.size(), 0u);  // Not supported in 1.0.
46     hidl_vec<Operand> operands(testModel.main.operands.size());
47     size_t constCopySize = 0, constRefSize = 0;
48     for (uint32_t i = 0; i < testModel.main.operands.size(); i++) {
49         const auto& op = testModel.main.operands[i];
50 
51         DataLocation loc = {};
52         if (op.lifetime == TestOperandLifeTime::CONSTANT_COPY) {
53             loc = {.poolIndex = 0,
54                    .offset = static_cast<uint32_t>(constCopySize),
55                    .length = static_cast<uint32_t>(op.data.size())};
56             constCopySize += op.data.alignedSize();
57         } else if (op.lifetime == TestOperandLifeTime::CONSTANT_REFERENCE) {
58             loc = {.poolIndex = 0,
59                    .offset = static_cast<uint32_t>(constRefSize),
60                    .length = static_cast<uint32_t>(op.data.size())};
61             constRefSize += op.data.alignedSize();
62         }
63 
64         operands[i] = {.type = static_cast<OperandType>(op.type),
65                        .dimensions = op.dimensions,
66                        .numberOfConsumers = op.numberOfConsumers,
67                        .scale = op.scale,
68                        .zeroPoint = op.zeroPoint,
69                        .lifetime = static_cast<OperandLifeTime>(op.lifetime),
70                        .location = loc};
71     }
72 
73     // Model operations.
74     hidl_vec<Operation> operations(testModel.main.operations.size());
75     std::transform(testModel.main.operations.begin(), testModel.main.operations.end(),
76                    operations.begin(), [](const TestOperation& op) -> Operation {
77                        return {.type = static_cast<OperationType>(op.type),
78                                .inputs = op.inputs,
79                                .outputs = op.outputs};
80                    });
81 
82     // Constant copies.
83     hidl_vec<uint8_t> operandValues(constCopySize);
84     for (uint32_t i = 0; i < testModel.main.operands.size(); i++) {
85         const auto& op = testModel.main.operands[i];
86         if (op.lifetime == TestOperandLifeTime::CONSTANT_COPY) {
87             const uint8_t* begin = op.data.get<uint8_t>();
88             const uint8_t* end = begin + op.data.size();
89             std::copy(begin, end, operandValues.data() + operands[i].location.offset);
90         }
91     }
92 
93     // Shared memory.
94     hidl_vec<hidl_memory> pools;
95     if (constRefSize > 0) {
96         hidl_vec_push_back(&pools, nn::allocateSharedMemory(constRefSize));
97         CHECK_NE(pools[0].size(), 0u);
98 
99         // load data
100         sp<IMemory> mappedMemory = mapMemory(pools[0]);
101         CHECK(mappedMemory.get() != nullptr);
102         uint8_t* mappedPtr =
103                 reinterpret_cast<uint8_t*>(static_cast<void*>(mappedMemory->getPointer()));
104         CHECK(mappedPtr != nullptr);
105 
106         for (uint32_t i = 0; i < testModel.main.operands.size(); i++) {
107             const auto& op = testModel.main.operands[i];
108             if (op.lifetime == TestOperandLifeTime::CONSTANT_REFERENCE) {
109                 const uint8_t* begin = op.data.get<uint8_t>();
110                 const uint8_t* end = begin + op.data.size();
111                 std::copy(begin, end, mappedPtr + operands[i].location.offset);
112             }
113         }
114     }
115 
116     return {.operands = std::move(operands),
117             .operations = std::move(operations),
118             .inputIndexes = testModel.main.inputIndexes,
119             .outputIndexes = testModel.main.outputIndexes,
120             .operandValues = std::move(operandValues),
121             .pools = std::move(pools)};
122 }
123 
124 // Top level driver for models and examples generated by test_generator.py
125 // Test driver for those generated from ml/nn/runtime/test/spec
Execute(const sp<IDevice> & device,const TestModel & testModel)126 void Execute(const sp<IDevice>& device, const TestModel& testModel) {
127     const Model model = createModel(testModel);
128 
129     ExecutionContext context;
130     const Request request = context.createRequest(testModel);
131 
132     // Create IPreparedModel.
133     sp<IPreparedModel> preparedModel;
134     createPreparedModel(device, model, &preparedModel);
135     if (preparedModel == nullptr) return;
136 
137     // Launch execution.
138     sp<ExecutionCallback> executionCallback = new ExecutionCallback();
139     Return<ErrorStatus> executionLaunchStatus = preparedModel->execute(request, executionCallback);
140     ASSERT_TRUE(executionLaunchStatus.isOk());
141     EXPECT_EQ(ErrorStatus::NONE, static_cast<ErrorStatus>(executionLaunchStatus));
142 
143     // Retrieve execution status.
144     executionCallback->wait();
145     ASSERT_EQ(ErrorStatus::NONE, executionCallback->getStatus());
146 
147     // Retrieve execution results.
148     const std::vector<TestBuffer> outputs = context.getOutputBuffers(request);
149 
150     // We want "close-enough" results.
151     checkResults(testModel, outputs);
152 }
153 
SetUp()154 void GeneratedTestBase::SetUp() {
155     testing::TestWithParam<GeneratedTestParam>::SetUp();
156     ASSERT_NE(kDevice, nullptr);
157     const bool deviceIsResponsive = kDevice->ping().isOk();
158     ASSERT_TRUE(deviceIsResponsive);
159 }
160 
getNamedModels(const FilterFn & filter)161 std::vector<NamedModel> getNamedModels(const FilterFn& filter) {
162     return TestModelManager::get().getTestModels(filter);
163 }
164 
getNamedModels(const FilterNameFn & filter)165 std::vector<NamedModel> getNamedModels(const FilterNameFn& filter) {
166     return TestModelManager::get().getTestModels(filter);
167 }
168 
printGeneratedTest(const testing::TestParamInfo<GeneratedTestParam> & info)169 std::string printGeneratedTest(const testing::TestParamInfo<GeneratedTestParam>& info) {
170     const auto& [namedDevice, namedModel] = info.param;
171     return gtestCompliantName(getName(namedDevice) + "_" + getName(namedModel));
172 }
173 
174 // Tag for the generated tests
175 class GeneratedTest : public GeneratedTestBase {};
176 
TEST_P(GeneratedTest,Test)177 TEST_P(GeneratedTest, Test) {
178     Execute(kDevice, kTestModel);
179 }
180 
181 INSTANTIATE_GENERATED_TEST(GeneratedTest,
__anon06a758020202(const TestModel& testModel) 182                            [](const TestModel& testModel) { return !testModel.expectFailure; });
183 
184 }  // namespace android::hardware::neuralnetworks::V1_0::vts::functional
185