blob: d411da4819e5812f382372547f582f0b04ade375 [file] [log] [blame]
Slava Shklyaev871be942018-09-12 14:52:02 +01001/*
2 * Copyright (C) 2018 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#define LOG_TAG "neuralnetworks_hidl_hal_test"
18
19#include "VtsHalNeuralnetworks.h"
20
21#include "Callbacks.h"
Michael Butler814d8372019-01-15 11:02:55 -080022#include "ExecutionBurstController.h"
Slava Shklyaev871be942018-09-12 14:52:02 +010023#include "TestHarness.h"
24#include "Utils.h"
25
26#include <android-base/logging.h>
27#include <android/hidl/memory/1.0/IMemory.h>
28#include <hidlmemory/mapping.h>
29
30namespace android {
31namespace hardware {
32namespace neuralnetworks {
33namespace V1_2 {
34namespace vts {
35namespace functional {
36
Xusong Wangb5cb8f72018-10-31 08:43:12 -070037using ::android::hardware::neuralnetworks::V1_2::implementation::ExecutionCallback;
38using ::android::hardware::neuralnetworks::V1_2::implementation::PreparedModelCallback;
Slava Shklyaev871be942018-09-12 14:52:02 +010039using ::android::hidl::memory::V1_0::IMemory;
40using test_helper::for_all;
41using test_helper::MixedTyped;
Michael K. Sanders941d61a2018-10-19 14:39:09 +010042using test_helper::MixedTypedExample;
Slava Shklyaev871be942018-09-12 14:52:02 +010043
44///////////////////////// UTILITY FUNCTIONS /////////////////////////
45
David Grosse3013492019-01-23 14:01:52 -080046static bool badTiming(Timing timing) {
47 return timing.timeOnDevice == UINT64_MAX && timing.timeInDriver == UINT64_MAX;
48}
49
Slava Shklyaev871be942018-09-12 14:52:02 +010050static void createPreparedModel(const sp<IDevice>& device, const Model& model,
51 sp<IPreparedModel>* preparedModel) {
52 ASSERT_NE(nullptr, preparedModel);
53
54 // see if service can handle model
55 bool fullySupportsModel = false;
56 Return<void> supportedOpsLaunchStatus = device->getSupportedOperations_1_2(
57 model, [&fullySupportsModel](ErrorStatus status, const hidl_vec<bool>& supported) {
58 ASSERT_EQ(ErrorStatus::NONE, status);
59 ASSERT_NE(0ul, supported.size());
60 fullySupportsModel =
61 std::all_of(supported.begin(), supported.end(), [](bool valid) { return valid; });
62 });
63 ASSERT_TRUE(supportedOpsLaunchStatus.isOk());
64
65 // launch prepare model
66 sp<PreparedModelCallback> preparedModelCallback = new PreparedModelCallback();
67 ASSERT_NE(nullptr, preparedModelCallback.get());
68 Return<ErrorStatus> prepareLaunchStatus = device->prepareModel_1_2(
69 model, ExecutionPreference::FAST_SINGLE_ANSWER, preparedModelCallback);
70 ASSERT_TRUE(prepareLaunchStatus.isOk());
71 ASSERT_EQ(ErrorStatus::NONE, static_cast<ErrorStatus>(prepareLaunchStatus));
72
73 // retrieve prepared model
74 preparedModelCallback->wait();
75 ErrorStatus prepareReturnStatus = preparedModelCallback->getStatus();
Xusong Wangb5cb8f72018-10-31 08:43:12 -070076 *preparedModel = getPreparedModel_1_2(preparedModelCallback);
Slava Shklyaev871be942018-09-12 14:52:02 +010077
78 // The getSupportedOperations_1_2 call returns a list of operations that are
79 // guaranteed not to fail if prepareModel_1_2 is called, and
80 // 'fullySupportsModel' is true i.f.f. the entire model is guaranteed.
81 // If a driver has any doubt that it can prepare an operation, it must
82 // return false. So here, if a driver isn't sure if it can support an
83 // operation, but reports that it successfully prepared the model, the test
84 // can continue.
85 if (!fullySupportsModel && prepareReturnStatus != ErrorStatus::NONE) {
86 ASSERT_EQ(nullptr, preparedModel->get());
87 LOG(INFO) << "NN VTS: Unable to test Request validation because vendor service cannot "
88 "prepare model that it does not support.";
89 std::cout << "[ ] Unable to test Request validation because vendor service "
90 "cannot prepare model that it does not support."
91 << std::endl;
92 return;
93 }
94 ASSERT_EQ(ErrorStatus::NONE, prepareReturnStatus);
95 ASSERT_NE(nullptr, preparedModel->get());
96}
97
98// Primary validation function. This function will take a valid request, apply a
99// mutation to it to invalidate the request, then pass it to interface calls
100// that use the request. Note that the request here is passed by value, and any
101// mutation to the request does not leave this function.
102static void validate(const sp<IPreparedModel>& preparedModel, const std::string& message,
103 Request request, const std::function<void(Request*)>& mutation) {
104 mutation(&request);
Slava Shklyaev871be942018-09-12 14:52:02 +0100105
David Grosse3013492019-01-23 14:01:52 -0800106 // We'd like to test both with timing requested and without timing
107 // requested. Rather than running each test both ways, we'll decide whether
108 // to request timing by hashing the message. We do not use std::hash because
109 // it is not guaranteed stable across executions.
110 char hash = 0;
111 for (auto c : message) {
112 hash ^= c;
113 };
114 MeasureTiming measure = (hash & 1) ? MeasureTiming::YES : MeasureTiming::NO;
115
Michael Butler814d8372019-01-15 11:02:55 -0800116 // asynchronous
David Gross49e41672018-12-21 11:20:26 -0800117 {
118 SCOPED_TRACE(message + " [execute_1_2]");
Slava Shklyaev871be942018-09-12 14:52:02 +0100119
David Gross49e41672018-12-21 11:20:26 -0800120 sp<ExecutionCallback> executionCallback = new ExecutionCallback();
121 ASSERT_NE(nullptr, executionCallback.get());
122 Return<ErrorStatus> executeLaunchStatus =
David Grosse3013492019-01-23 14:01:52 -0800123 preparedModel->execute_1_2(request, measure, executionCallback);
David Gross49e41672018-12-21 11:20:26 -0800124 ASSERT_TRUE(executeLaunchStatus.isOk());
125 ASSERT_EQ(ErrorStatus::INVALID_ARGUMENT, static_cast<ErrorStatus>(executeLaunchStatus));
126
127 executionCallback->wait();
128 ErrorStatus executionReturnStatus = executionCallback->getStatus();
Xusong Wang187c5972018-11-07 09:33:59 -0800129 const auto& outputShapes = executionCallback->getOutputShapes();
David Grosse3013492019-01-23 14:01:52 -0800130 Timing timing = executionCallback->getTiming();
David Gross49e41672018-12-21 11:20:26 -0800131 ASSERT_EQ(ErrorStatus::INVALID_ARGUMENT, executionReturnStatus);
Xusong Wang187c5972018-11-07 09:33:59 -0800132 ASSERT_EQ(outputShapes.size(), 0);
David Grosse3013492019-01-23 14:01:52 -0800133 ASSERT_TRUE(badTiming(timing));
David Gross49e41672018-12-21 11:20:26 -0800134 }
135
Michael Butler814d8372019-01-15 11:02:55 -0800136 // synchronous
David Gross49e41672018-12-21 11:20:26 -0800137 {
138 SCOPED_TRACE(message + " [executeSynchronously]");
139
Xusong Wang187c5972018-11-07 09:33:59 -0800140 Return<void> executeStatus = preparedModel->executeSynchronously(
David Grosse3013492019-01-23 14:01:52 -0800141 request, measure,
142 [](ErrorStatus error, const hidl_vec<OutputShape>& outputShapes,
143 const Timing& timing) {
144 ASSERT_EQ(ErrorStatus::INVALID_ARGUMENT, error);
145 EXPECT_EQ(outputShapes.size(), 0);
146 EXPECT_TRUE(badTiming(timing));
147 });
David Gross49e41672018-12-21 11:20:26 -0800148 ASSERT_TRUE(executeStatus.isOk());
David Gross49e41672018-12-21 11:20:26 -0800149 }
Michael Butler814d8372019-01-15 11:02:55 -0800150
151 // burst
152 {
153 SCOPED_TRACE(message + " [burst]");
154
155 // create burst
156 std::unique_ptr<::android::nn::ExecutionBurstController> burst =
157 ::android::nn::createExecutionBurstController(preparedModel, /*blocking=*/true);
158 ASSERT_NE(nullptr, burst.get());
159
160 // create memory keys
161 std::vector<intptr_t> keys(request.pools.size());
162 for (size_t i = 0; i < keys.size(); ++i) {
163 keys[i] = reinterpret_cast<intptr_t>(&request.pools[i]);
164 }
165
166 // execute and verify
167 ErrorStatus error;
168 std::vector<OutputShape> outputShapes;
169 Timing timing;
170 std::tie(error, outputShapes, timing) = burst->compute(request, measure, keys);
171 EXPECT_EQ(ErrorStatus::INVALID_ARGUMENT, error);
172 EXPECT_EQ(outputShapes.size(), 0);
173 EXPECT_TRUE(badTiming(timing));
174
175 // additional burst testing
176 if (request.pools.size() > 0) {
177 // valid free
178 burst->freeMemory(keys.front());
179
180 // negative test: invalid free of unknown (blank) memory
181 burst->freeMemory(intptr_t{});
182
183 // negative test: double free of memory
184 burst->freeMemory(keys.front());
185 }
186 }
Slava Shklyaev871be942018-09-12 14:52:02 +0100187}
188
189// Delete element from hidl_vec. hidl_vec doesn't support a "remove" operation,
190// so this is efficiently accomplished by moving the element to the end and
191// resizing the hidl_vec to one less.
192template <typename Type>
193static void hidl_vec_removeAt(hidl_vec<Type>* vec, uint32_t index) {
194 if (vec) {
195 std::rotate(vec->begin() + index, vec->begin() + index + 1, vec->end());
196 vec->resize(vec->size() - 1);
197 }
198}
199
200template <typename Type>
201static uint32_t hidl_vec_push_back(hidl_vec<Type>* vec, const Type& value) {
202 // assume vec is valid
203 const uint32_t index = vec->size();
204 vec->resize(index + 1);
205 (*vec)[index] = value;
206 return index;
207}
208
209///////////////////////// REMOVE INPUT ////////////////////////////////////
210
211static void removeInputTest(const sp<IPreparedModel>& preparedModel, const Request& request) {
212 for (size_t input = 0; input < request.inputs.size(); ++input) {
213 const std::string message = "removeInput: removed input " + std::to_string(input);
214 validate(preparedModel, message, request,
215 [input](Request* request) { hidl_vec_removeAt(&request->inputs, input); });
216 }
217}
218
219///////////////////////// REMOVE OUTPUT ////////////////////////////////////
220
221static void removeOutputTest(const sp<IPreparedModel>& preparedModel, const Request& request) {
222 for (size_t output = 0; output < request.outputs.size(); ++output) {
223 const std::string message = "removeOutput: removed Output " + std::to_string(output);
224 validate(preparedModel, message, request,
225 [output](Request* request) { hidl_vec_removeAt(&request->outputs, output); });
226 }
227}
228
229///////////////////////////// ENTRY POINT //////////////////////////////////
230
Michael K. Sanders941d61a2018-10-19 14:39:09 +0100231std::vector<Request> createRequests(const std::vector<MixedTypedExample>& examples) {
Slava Shklyaev871be942018-09-12 14:52:02 +0100232 const uint32_t INPUT = 0;
233 const uint32_t OUTPUT = 1;
234
235 std::vector<Request> requests;
236
237 for (auto& example : examples) {
Michael K. Sanders941d61a2018-10-19 14:39:09 +0100238 const MixedTyped& inputs = example.operands.first;
239 const MixedTyped& outputs = example.operands.second;
Slava Shklyaev871be942018-09-12 14:52:02 +0100240
241 std::vector<RequestArgument> inputs_info, outputs_info;
242 uint32_t inputSize = 0, outputSize = 0;
243
244 // This function only partially specifies the metadata (vector of RequestArguments).
245 // The contents are copied over below.
246 for_all(inputs, [&inputs_info, &inputSize](int index, auto, auto s) {
247 if (inputs_info.size() <= static_cast<size_t>(index)) inputs_info.resize(index + 1);
248 RequestArgument arg = {
249 .location = {.poolIndex = INPUT, .offset = 0, .length = static_cast<uint32_t>(s)},
250 .dimensions = {},
251 };
252 RequestArgument arg_empty = {
253 .hasNoValue = true,
254 };
255 inputs_info[index] = s ? arg : arg_empty;
256 inputSize += s;
257 });
258 // Compute offset for inputs 1 and so on
259 {
260 size_t offset = 0;
261 for (auto& i : inputs_info) {
262 if (!i.hasNoValue) i.location.offset = offset;
263 offset += i.location.length;
264 }
265 }
266
267 // Go through all outputs, initialize RequestArgument descriptors
268 for_all(outputs, [&outputs_info, &outputSize](int index, auto, auto s) {
269 if (outputs_info.size() <= static_cast<size_t>(index)) outputs_info.resize(index + 1);
270 RequestArgument arg = {
271 .location = {.poolIndex = OUTPUT, .offset = 0, .length = static_cast<uint32_t>(s)},
272 .dimensions = {},
273 };
274 outputs_info[index] = arg;
275 outputSize += s;
276 });
277 // Compute offset for outputs 1 and so on
278 {
279 size_t offset = 0;
280 for (auto& i : outputs_info) {
281 i.location.offset = offset;
282 offset += i.location.length;
283 }
284 }
285 std::vector<hidl_memory> pools = {nn::allocateSharedMemory(inputSize),
286 nn::allocateSharedMemory(outputSize)};
287 if (pools[INPUT].size() == 0 || pools[OUTPUT].size() == 0) {
288 return {};
289 }
290
291 // map pool
292 sp<IMemory> inputMemory = mapMemory(pools[INPUT]);
293 if (inputMemory == nullptr) {
294 return {};
295 }
296 char* inputPtr = reinterpret_cast<char*>(static_cast<void*>(inputMemory->getPointer()));
297 if (inputPtr == nullptr) {
298 return {};
299 }
300
301 // initialize pool
302 inputMemory->update();
303 for_all(inputs, [&inputs_info, inputPtr](int index, auto p, auto s) {
304 char* begin = (char*)p;
305 char* end = begin + s;
306 // TODO: handle more than one input
307 std::copy(begin, end, inputPtr + inputs_info[index].location.offset);
308 });
309 inputMemory->commit();
310
311 requests.push_back({.inputs = inputs_info, .outputs = outputs_info, .pools = pools});
312 }
313
314 return requests;
315}
316
317void ValidationTest::validateRequests(const Model& model, const std::vector<Request>& requests) {
318 // create IPreparedModel
319 sp<IPreparedModel> preparedModel;
320 ASSERT_NO_FATAL_FAILURE(createPreparedModel(device, model, &preparedModel));
321 if (preparedModel == nullptr) {
322 return;
323 }
324
325 // validate each request
326 for (const Request& request : requests) {
327 removeInputTest(preparedModel, request);
328 removeOutputTest(preparedModel, request);
329 }
330}
331
332} // namespace functional
333} // namespace vts
334} // namespace V1_2
335} // namespace neuralnetworks
336} // namespace hardware
337} // namespace android