blob: 870d01748a3c61370f5f60280489cbf545992582 [file] [log] [blame]
Slava Shklyaevfeb87a92018-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 Butler29471a82019-01-15 11:02:55 -080022#include "ExecutionBurstController.h"
Slava Shklyaevfeb87a92018-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 Wang1a06e772018-10-31 08:43:12 -070037using ::android::hardware::neuralnetworks::V1_2::implementation::ExecutionCallback;
38using ::android::hardware::neuralnetworks::V1_2::implementation::PreparedModelCallback;
Slava Shklyaevfeb87a92018-09-12 14:52:02 +010039using ::android::hidl::memory::V1_0::IMemory;
Xusong Wanged0822b2019-02-25 16:58:58 -080040using HidlToken = hidl_array<uint8_t, static_cast<uint32_t>(Constant::BYTE_SIZE_OF_CACHE_TOKEN)>;
Slava Shklyaevfeb87a92018-09-12 14:52:02 +010041using test_helper::for_all;
42using test_helper::MixedTyped;
Michael K. Sandersda3bdbc2018-10-19 14:39:09 +010043using test_helper::MixedTypedExample;
Slava Shklyaevfeb87a92018-09-12 14:52:02 +010044
45///////////////////////// UTILITY FUNCTIONS /////////////////////////
46
David Gross55a3d322019-01-23 14:01:52 -080047static bool badTiming(Timing timing) {
48 return timing.timeOnDevice == UINT64_MAX && timing.timeInDriver == UINT64_MAX;
49}
50
Slava Shklyaevfeb87a92018-09-12 14:52:02 +010051static void createPreparedModel(const sp<IDevice>& device, const Model& model,
52 sp<IPreparedModel>* preparedModel) {
53 ASSERT_NE(nullptr, preparedModel);
54
55 // see if service can handle model
56 bool fullySupportsModel = false;
57 Return<void> supportedOpsLaunchStatus = device->getSupportedOperations_1_2(
58 model, [&fullySupportsModel](ErrorStatus status, const hidl_vec<bool>& supported) {
59 ASSERT_EQ(ErrorStatus::NONE, status);
60 ASSERT_NE(0ul, supported.size());
61 fullySupportsModel =
62 std::all_of(supported.begin(), supported.end(), [](bool valid) { return valid; });
63 });
64 ASSERT_TRUE(supportedOpsLaunchStatus.isOk());
65
66 // launch prepare model
67 sp<PreparedModelCallback> preparedModelCallback = new PreparedModelCallback();
68 ASSERT_NE(nullptr, preparedModelCallback.get());
69 Return<ErrorStatus> prepareLaunchStatus = device->prepareModel_1_2(
Xusong Wanged0822b2019-02-25 16:58:58 -080070 model, ExecutionPreference::FAST_SINGLE_ANSWER, hidl_vec<hidl_handle>(),
71 hidl_vec<hidl_handle>(), HidlToken(), preparedModelCallback);
Slava Shklyaevfeb87a92018-09-12 14:52:02 +010072 ASSERT_TRUE(prepareLaunchStatus.isOk());
73 ASSERT_EQ(ErrorStatus::NONE, static_cast<ErrorStatus>(prepareLaunchStatus));
74
75 // retrieve prepared model
76 preparedModelCallback->wait();
77 ErrorStatus prepareReturnStatus = preparedModelCallback->getStatus();
Xusong Wang1a06e772018-10-31 08:43:12 -070078 *preparedModel = getPreparedModel_1_2(preparedModelCallback);
Slava Shklyaevfeb87a92018-09-12 14:52:02 +010079
80 // The getSupportedOperations_1_2 call returns a list of operations that are
81 // guaranteed not to fail if prepareModel_1_2 is called, and
82 // 'fullySupportsModel' is true i.f.f. the entire model is guaranteed.
83 // If a driver has any doubt that it can prepare an operation, it must
84 // return false. So here, if a driver isn't sure if it can support an
85 // operation, but reports that it successfully prepared the model, the test
86 // can continue.
87 if (!fullySupportsModel && prepareReturnStatus != ErrorStatus::NONE) {
88 ASSERT_EQ(nullptr, preparedModel->get());
89 LOG(INFO) << "NN VTS: Unable to test Request validation because vendor service cannot "
90 "prepare model that it does not support.";
91 std::cout << "[ ] Unable to test Request validation because vendor service "
92 "cannot prepare model that it does not support."
93 << std::endl;
94 return;
95 }
96 ASSERT_EQ(ErrorStatus::NONE, prepareReturnStatus);
97 ASSERT_NE(nullptr, preparedModel->get());
98}
99
100// Primary validation function. This function will take a valid request, apply a
101// mutation to it to invalidate the request, then pass it to interface calls
102// that use the request. Note that the request here is passed by value, and any
103// mutation to the request does not leave this function.
104static void validate(const sp<IPreparedModel>& preparedModel, const std::string& message,
105 Request request, const std::function<void(Request*)>& mutation) {
106 mutation(&request);
Slava Shklyaevfeb87a92018-09-12 14:52:02 +0100107
David Gross55a3d322019-01-23 14:01:52 -0800108 // We'd like to test both with timing requested and without timing
109 // requested. Rather than running each test both ways, we'll decide whether
110 // to request timing by hashing the message. We do not use std::hash because
111 // it is not guaranteed stable across executions.
112 char hash = 0;
113 for (auto c : message) {
114 hash ^= c;
115 };
116 MeasureTiming measure = (hash & 1) ? MeasureTiming::YES : MeasureTiming::NO;
117
Michael Butler29471a82019-01-15 11:02:55 -0800118 // asynchronous
David Gross4592ed12018-12-21 11:20:26 -0800119 {
120 SCOPED_TRACE(message + " [execute_1_2]");
Slava Shklyaevfeb87a92018-09-12 14:52:02 +0100121
David Gross4592ed12018-12-21 11:20:26 -0800122 sp<ExecutionCallback> executionCallback = new ExecutionCallback();
123 ASSERT_NE(nullptr, executionCallback.get());
124 Return<ErrorStatus> executeLaunchStatus =
David Gross55a3d322019-01-23 14:01:52 -0800125 preparedModel->execute_1_2(request, measure, executionCallback);
David Gross4592ed12018-12-21 11:20:26 -0800126 ASSERT_TRUE(executeLaunchStatus.isOk());
127 ASSERT_EQ(ErrorStatus::INVALID_ARGUMENT, static_cast<ErrorStatus>(executeLaunchStatus));
128
129 executionCallback->wait();
130 ErrorStatus executionReturnStatus = executionCallback->getStatus();
Xusong Wangb50bc312018-11-07 09:33:59 -0800131 const auto& outputShapes = executionCallback->getOutputShapes();
David Gross55a3d322019-01-23 14:01:52 -0800132 Timing timing = executionCallback->getTiming();
David Gross4592ed12018-12-21 11:20:26 -0800133 ASSERT_EQ(ErrorStatus::INVALID_ARGUMENT, executionReturnStatus);
Xusong Wangb50bc312018-11-07 09:33:59 -0800134 ASSERT_EQ(outputShapes.size(), 0);
David Gross55a3d322019-01-23 14:01:52 -0800135 ASSERT_TRUE(badTiming(timing));
David Gross4592ed12018-12-21 11:20:26 -0800136 }
137
Michael Butler29471a82019-01-15 11:02:55 -0800138 // synchronous
David Gross4592ed12018-12-21 11:20:26 -0800139 {
140 SCOPED_TRACE(message + " [executeSynchronously]");
141
Xusong Wangb50bc312018-11-07 09:33:59 -0800142 Return<void> executeStatus = preparedModel->executeSynchronously(
David Gross55a3d322019-01-23 14:01:52 -0800143 request, measure,
144 [](ErrorStatus error, const hidl_vec<OutputShape>& outputShapes,
145 const Timing& timing) {
146 ASSERT_EQ(ErrorStatus::INVALID_ARGUMENT, error);
147 EXPECT_EQ(outputShapes.size(), 0);
148 EXPECT_TRUE(badTiming(timing));
149 });
David Gross4592ed12018-12-21 11:20:26 -0800150 ASSERT_TRUE(executeStatus.isOk());
David Gross4592ed12018-12-21 11:20:26 -0800151 }
Michael Butler29471a82019-01-15 11:02:55 -0800152
153 // burst
154 {
155 SCOPED_TRACE(message + " [burst]");
156
157 // create burst
Michael Butler51c72182019-03-27 10:59:25 -0700158 std::shared_ptr<::android::nn::ExecutionBurstController> burst =
Michael Butler60a22532019-03-28 13:41:14 -0700159 ::android::nn::ExecutionBurstController::create(preparedModel, /*blocking=*/true);
Michael Butler29471a82019-01-15 11:02:55 -0800160 ASSERT_NE(nullptr, burst.get());
161
162 // create memory keys
163 std::vector<intptr_t> keys(request.pools.size());
164 for (size_t i = 0; i < keys.size(); ++i) {
165 keys[i] = reinterpret_cast<intptr_t>(&request.pools[i]);
166 }
167
168 // execute and verify
169 ErrorStatus error;
170 std::vector<OutputShape> outputShapes;
171 Timing timing;
172 std::tie(error, outputShapes, timing) = burst->compute(request, measure, keys);
173 EXPECT_EQ(ErrorStatus::INVALID_ARGUMENT, error);
174 EXPECT_EQ(outputShapes.size(), 0);
175 EXPECT_TRUE(badTiming(timing));
176
177 // additional burst testing
178 if (request.pools.size() > 0) {
179 // valid free
180 burst->freeMemory(keys.front());
181
182 // negative test: invalid free of unknown (blank) memory
183 burst->freeMemory(intptr_t{});
184
185 // negative test: double free of memory
186 burst->freeMemory(keys.front());
187 }
188 }
Slava Shklyaevfeb87a92018-09-12 14:52:02 +0100189}
190
191// Delete element from hidl_vec. hidl_vec doesn't support a "remove" operation,
192// so this is efficiently accomplished by moving the element to the end and
193// resizing the hidl_vec to one less.
194template <typename Type>
195static void hidl_vec_removeAt(hidl_vec<Type>* vec, uint32_t index) {
196 if (vec) {
197 std::rotate(vec->begin() + index, vec->begin() + index + 1, vec->end());
198 vec->resize(vec->size() - 1);
199 }
200}
201
202template <typename Type>
203static uint32_t hidl_vec_push_back(hidl_vec<Type>* vec, const Type& value) {
204 // assume vec is valid
205 const uint32_t index = vec->size();
206 vec->resize(index + 1);
207 (*vec)[index] = value;
208 return index;
209}
210
211///////////////////////// REMOVE INPUT ////////////////////////////////////
212
213static void removeInputTest(const sp<IPreparedModel>& preparedModel, const Request& request) {
214 for (size_t input = 0; input < request.inputs.size(); ++input) {
215 const std::string message = "removeInput: removed input " + std::to_string(input);
216 validate(preparedModel, message, request,
217 [input](Request* request) { hidl_vec_removeAt(&request->inputs, input); });
218 }
219}
220
221///////////////////////// REMOVE OUTPUT ////////////////////////////////////
222
223static void removeOutputTest(const sp<IPreparedModel>& preparedModel, const Request& request) {
224 for (size_t output = 0; output < request.outputs.size(); ++output) {
225 const std::string message = "removeOutput: removed Output " + std::to_string(output);
226 validate(preparedModel, message, request,
227 [output](Request* request) { hidl_vec_removeAt(&request->outputs, output); });
228 }
229}
230
231///////////////////////////// ENTRY POINT //////////////////////////////////
232
Michael K. Sandersda3bdbc2018-10-19 14:39:09 +0100233std::vector<Request> createRequests(const std::vector<MixedTypedExample>& examples) {
Slava Shklyaevfeb87a92018-09-12 14:52:02 +0100234 const uint32_t INPUT = 0;
235 const uint32_t OUTPUT = 1;
236
237 std::vector<Request> requests;
238
239 for (auto& example : examples) {
Michael K. Sandersda3bdbc2018-10-19 14:39:09 +0100240 const MixedTyped& inputs = example.operands.first;
241 const MixedTyped& outputs = example.operands.second;
Slava Shklyaevfeb87a92018-09-12 14:52:02 +0100242
243 std::vector<RequestArgument> inputs_info, outputs_info;
244 uint32_t inputSize = 0, outputSize = 0;
245
246 // This function only partially specifies the metadata (vector of RequestArguments).
247 // The contents are copied over below.
248 for_all(inputs, [&inputs_info, &inputSize](int index, auto, auto s) {
249 if (inputs_info.size() <= static_cast<size_t>(index)) inputs_info.resize(index + 1);
250 RequestArgument arg = {
251 .location = {.poolIndex = INPUT, .offset = 0, .length = static_cast<uint32_t>(s)},
252 .dimensions = {},
253 };
254 RequestArgument arg_empty = {
255 .hasNoValue = true,
256 };
257 inputs_info[index] = s ? arg : arg_empty;
258 inputSize += s;
259 });
260 // Compute offset for inputs 1 and so on
261 {
262 size_t offset = 0;
263 for (auto& i : inputs_info) {
264 if (!i.hasNoValue) i.location.offset = offset;
265 offset += i.location.length;
266 }
267 }
268
269 // Go through all outputs, initialize RequestArgument descriptors
270 for_all(outputs, [&outputs_info, &outputSize](int index, auto, auto s) {
271 if (outputs_info.size() <= static_cast<size_t>(index)) outputs_info.resize(index + 1);
272 RequestArgument arg = {
273 .location = {.poolIndex = OUTPUT, .offset = 0, .length = static_cast<uint32_t>(s)},
274 .dimensions = {},
275 };
276 outputs_info[index] = arg;
277 outputSize += s;
278 });
279 // Compute offset for outputs 1 and so on
280 {
281 size_t offset = 0;
282 for (auto& i : outputs_info) {
283 i.location.offset = offset;
284 offset += i.location.length;
285 }
286 }
287 std::vector<hidl_memory> pools = {nn::allocateSharedMemory(inputSize),
288 nn::allocateSharedMemory(outputSize)};
289 if (pools[INPUT].size() == 0 || pools[OUTPUT].size() == 0) {
290 return {};
291 }
292
293 // map pool
294 sp<IMemory> inputMemory = mapMemory(pools[INPUT]);
295 if (inputMemory == nullptr) {
296 return {};
297 }
298 char* inputPtr = reinterpret_cast<char*>(static_cast<void*>(inputMemory->getPointer()));
299 if (inputPtr == nullptr) {
300 return {};
301 }
302
303 // initialize pool
304 inputMemory->update();
305 for_all(inputs, [&inputs_info, inputPtr](int index, auto p, auto s) {
306 char* begin = (char*)p;
307 char* end = begin + s;
308 // TODO: handle more than one input
309 std::copy(begin, end, inputPtr + inputs_info[index].location.offset);
310 });
311 inputMemory->commit();
312
313 requests.push_back({.inputs = inputs_info, .outputs = outputs_info, .pools = pools});
314 }
315
316 return requests;
317}
318
319void ValidationTest::validateRequests(const Model& model, const std::vector<Request>& requests) {
320 // create IPreparedModel
321 sp<IPreparedModel> preparedModel;
322 ASSERT_NO_FATAL_FAILURE(createPreparedModel(device, model, &preparedModel));
323 if (preparedModel == nullptr) {
324 return;
325 }
326
327 // validate each request
328 for (const Request& request : requests) {
329 removeInputTest(preparedModel, request);
330 removeOutputTest(preparedModel, request);
331 }
332}
333
334} // namespace functional
335} // namespace vts
336} // namespace V1_2
337} // namespace neuralnetworks
338} // namespace hardware
339} // namespace android