blob: 7df804645ac18cf854bc53fa6c7d4c3e51329dd1 [file] [log] [blame]
Lev Proleev13fdfcd2019-08-30 11:35:34 +01001/*
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#define LOG_TAG "neuralnetworks_hidl_hal_test"
18
19#include "VtsHalNeuralnetworks.h"
20
21#include "1.2/Callbacks.h"
22#include "ExecutionBurstController.h"
23#include "ExecutionBurstServer.h"
24#include "GeneratedTestHarness.h"
25#include "TestHarness.h"
26#include "Utils.h"
27
28#include <android-base/logging.h>
Michael Butler648ada52019-07-25 17:22:11 -070029#include <chrono>
Lev Proleev13fdfcd2019-08-30 11:35:34 +010030#include <cstring>
31
Lev Proleev26d1bc82019-08-30 11:57:18 +010032namespace android::hardware::neuralnetworks::V1_3::vts::functional {
Lev Proleev13fdfcd2019-08-30 11:35:34 +010033
34using nn::ExecutionBurstController;
35using nn::RequestChannelSender;
36using nn::ResultChannelReceiver;
37using V1_0::ErrorStatus;
38using V1_0::Request;
Lev Proleev26d1bc82019-08-30 11:57:18 +010039using V1_2::FmqRequestDatum;
40using V1_2::FmqResultDatum;
41using V1_2::IBurstCallback;
42using V1_2::IBurstContext;
Lev Proleev26d1bc82019-08-30 11:57:18 +010043using V1_2::MeasureTiming;
44using V1_2::Timing;
Lev Proleev13fdfcd2019-08-30 11:35:34 +010045using ExecutionBurstCallback = ExecutionBurstController::ExecutionBurstCallback;
46
47// This constant value represents the length of an FMQ that is large enough to
48// return a result from a burst execution for all of the generated test cases.
49constexpr size_t kExecutionBurstChannelLength = 1024;
50
51// This constant value represents a length of an FMQ that is not large enough
52// to return a result from a burst execution for some of the generated test
53// cases.
54constexpr size_t kExecutionBurstChannelSmallLength = 8;
55
56///////////////////////// UTILITY FUNCTIONS /////////////////////////
57
58static bool badTiming(Timing timing) {
59 return timing.timeOnDevice == UINT64_MAX && timing.timeInDriver == UINT64_MAX;
60}
61
62static void createBurst(const sp<IPreparedModel>& preparedModel, const sp<IBurstCallback>& callback,
63 std::unique_ptr<RequestChannelSender>* sender,
64 std::unique_ptr<ResultChannelReceiver>* receiver,
65 sp<IBurstContext>* context,
66 size_t resultChannelLength = kExecutionBurstChannelLength) {
67 ASSERT_NE(nullptr, preparedModel.get());
68 ASSERT_NE(nullptr, sender);
69 ASSERT_NE(nullptr, receiver);
70 ASSERT_NE(nullptr, context);
71
72 // create FMQ objects
73 auto [fmqRequestChannel, fmqRequestDescriptor] =
Michael Butler648ada52019-07-25 17:22:11 -070074 RequestChannelSender::create(kExecutionBurstChannelLength);
Lev Proleev13fdfcd2019-08-30 11:35:34 +010075 auto [fmqResultChannel, fmqResultDescriptor] =
Michael Butler648ada52019-07-25 17:22:11 -070076 ResultChannelReceiver::create(resultChannelLength, std::chrono::microseconds{0});
Lev Proleev13fdfcd2019-08-30 11:35:34 +010077 ASSERT_NE(nullptr, fmqRequestChannel.get());
78 ASSERT_NE(nullptr, fmqResultChannel.get());
79 ASSERT_NE(nullptr, fmqRequestDescriptor);
80 ASSERT_NE(nullptr, fmqResultDescriptor);
81
82 // configure burst
83 ErrorStatus errorStatus;
84 sp<IBurstContext> burstContext;
85 const Return<void> ret = preparedModel->configureExecutionBurst(
86 callback, *fmqRequestDescriptor, *fmqResultDescriptor,
87 [&errorStatus, &burstContext](ErrorStatus status, const sp<IBurstContext>& context) {
88 errorStatus = status;
89 burstContext = context;
90 });
91 ASSERT_TRUE(ret.isOk());
92 ASSERT_EQ(ErrorStatus::NONE, errorStatus);
93 ASSERT_NE(nullptr, burstContext.get());
94
95 // return values
96 *sender = std::move(fmqRequestChannel);
97 *receiver = std::move(fmqResultChannel);
98 *context = burstContext;
99}
100
101static void createBurstWithResultChannelLength(
102 const sp<IPreparedModel>& preparedModel, size_t resultChannelLength,
103 std::shared_ptr<ExecutionBurstController>* controller) {
104 ASSERT_NE(nullptr, preparedModel.get());
105 ASSERT_NE(nullptr, controller);
106
107 // create FMQ objects
108 std::unique_ptr<RequestChannelSender> sender;
109 std::unique_ptr<ResultChannelReceiver> receiver;
110 sp<ExecutionBurstCallback> callback = new ExecutionBurstCallback();
111 sp<IBurstContext> context;
112 ASSERT_NO_FATAL_FAILURE(createBurst(preparedModel, callback, &sender, &receiver, &context,
113 resultChannelLength));
114 ASSERT_NE(nullptr, sender.get());
115 ASSERT_NE(nullptr, receiver.get());
116 ASSERT_NE(nullptr, context.get());
117
118 // return values
119 *controller = std::make_shared<ExecutionBurstController>(std::move(sender), std::move(receiver),
120 context, callback);
121}
122
123// Primary validation function. This function will take a valid serialized
124// request, apply a mutation to it to invalidate the serialized request, then
125// pass it to interface calls that use the serialized request. Note that the
126// serialized request here is passed by value, and any mutation to the
127// serialized request does not leave this function.
128static void validate(RequestChannelSender* sender, ResultChannelReceiver* receiver,
129 const std::string& message, std::vector<FmqRequestDatum> serialized,
130 const std::function<void(std::vector<FmqRequestDatum>*)>& mutation) {
131 mutation(&serialized);
132
133 // skip if packet is too large to send
134 if (serialized.size() > kExecutionBurstChannelLength) {
135 return;
136 }
137
138 SCOPED_TRACE(message);
139
140 // send invalid packet
141 ASSERT_TRUE(sender->sendPacket(serialized));
142
143 // receive error
144 auto results = receiver->getBlocking();
145 ASSERT_TRUE(results.has_value());
146 const auto [status, outputShapes, timing] = std::move(*results);
147 EXPECT_NE(ErrorStatus::NONE, status);
148 EXPECT_EQ(0u, outputShapes.size());
149 EXPECT_TRUE(badTiming(timing));
150}
151
152// For validation, valid packet entries are mutated to invalid packet entries,
153// or invalid packet entries are inserted into valid packets. This function
154// creates pre-set invalid packet entries for convenience.
155static std::vector<FmqRequestDatum> createBadRequestPacketEntries() {
156 const FmqRequestDatum::PacketInformation packetInformation = {
157 /*.packetSize=*/10, /*.numberOfInputOperands=*/10, /*.numberOfOutputOperands=*/10,
158 /*.numberOfPools=*/10};
159 const FmqRequestDatum::OperandInformation operandInformation = {
160 /*.hasNoValue=*/false, /*.location=*/{}, /*.numberOfDimensions=*/10};
161 const int32_t invalidPoolIdentifier = std::numeric_limits<int32_t>::max();
162 std::vector<FmqRequestDatum> bad(7);
163 bad[0].packetInformation(packetInformation);
164 bad[1].inputOperandInformation(operandInformation);
165 bad[2].inputOperandDimensionValue(0);
166 bad[3].outputOperandInformation(operandInformation);
167 bad[4].outputOperandDimensionValue(0);
168 bad[5].poolIdentifier(invalidPoolIdentifier);
169 bad[6].measureTiming(MeasureTiming::YES);
170 return bad;
171}
172
173// For validation, valid packet entries are mutated to invalid packet entries,
174// or invalid packet entries are inserted into valid packets. This function
175// retrieves pre-set invalid packet entries for convenience. This function
176// caches these data so they can be reused on subsequent validation checks.
177static const std::vector<FmqRequestDatum>& getBadRequestPacketEntries() {
178 static const std::vector<FmqRequestDatum> bad = createBadRequestPacketEntries();
179 return bad;
180}
181
182///////////////////////// REMOVE DATUM ////////////////////////////////////
183
184static void removeDatumTest(RequestChannelSender* sender, ResultChannelReceiver* receiver,
185 const std::vector<FmqRequestDatum>& serialized) {
186 for (size_t index = 0; index < serialized.size(); ++index) {
187 const std::string message = "removeDatum: removed datum at index " + std::to_string(index);
188 validate(sender, receiver, message, serialized,
189 [index](std::vector<FmqRequestDatum>* serialized) {
190 serialized->erase(serialized->begin() + index);
191 });
192 }
193}
194
195///////////////////////// ADD DATUM ////////////////////////////////////
196
197static void addDatumTest(RequestChannelSender* sender, ResultChannelReceiver* receiver,
198 const std::vector<FmqRequestDatum>& serialized) {
199 const std::vector<FmqRequestDatum>& extra = getBadRequestPacketEntries();
200 for (size_t index = 0; index <= serialized.size(); ++index) {
201 for (size_t type = 0; type < extra.size(); ++type) {
202 const std::string message = "addDatum: added datum type " + std::to_string(type) +
203 " at index " + std::to_string(index);
204 validate(sender, receiver, message, serialized,
205 [index, type, &extra](std::vector<FmqRequestDatum>* serialized) {
206 serialized->insert(serialized->begin() + index, extra[type]);
207 });
208 }
209 }
210}
211
212///////////////////////// MUTATE DATUM ////////////////////////////////////
213
214static bool interestingCase(const FmqRequestDatum& lhs, const FmqRequestDatum& rhs) {
215 using Discriminator = FmqRequestDatum::hidl_discriminator;
216
217 const bool differentValues = (lhs != rhs);
218 const bool sameDiscriminator = (lhs.getDiscriminator() == rhs.getDiscriminator());
219 const auto discriminator = rhs.getDiscriminator();
220 const bool isDimensionValue = (discriminator == Discriminator::inputOperandDimensionValue ||
221 discriminator == Discriminator::outputOperandDimensionValue);
222
223 return differentValues && !(sameDiscriminator && isDimensionValue);
224}
225
226static void mutateDatumTest(RequestChannelSender* sender, ResultChannelReceiver* receiver,
227 const std::vector<FmqRequestDatum>& serialized) {
228 const std::vector<FmqRequestDatum>& change = getBadRequestPacketEntries();
229 for (size_t index = 0; index < serialized.size(); ++index) {
230 for (size_t type = 0; type < change.size(); ++type) {
231 if (interestingCase(serialized[index], change[type])) {
232 const std::string message = "mutateDatum: changed datum at index " +
233 std::to_string(index) + " to datum type " +
234 std::to_string(type);
235 validate(sender, receiver, message, serialized,
236 [index, type, &change](std::vector<FmqRequestDatum>* serialized) {
237 (*serialized)[index] = change[type];
238 });
239 }
240 }
241 }
242}
243
244///////////////////////// BURST VALIATION TESTS ////////////////////////////////////
245
246static void validateBurstSerialization(const sp<IPreparedModel>& preparedModel,
247 const Request& request) {
248 // create burst
249 std::unique_ptr<RequestChannelSender> sender;
250 std::unique_ptr<ResultChannelReceiver> receiver;
251 sp<ExecutionBurstCallback> callback = new ExecutionBurstCallback();
252 sp<IBurstContext> context;
253 ASSERT_NO_FATAL_FAILURE(createBurst(preparedModel, callback, &sender, &receiver, &context));
254 ASSERT_NE(nullptr, sender.get());
255 ASSERT_NE(nullptr, receiver.get());
256 ASSERT_NE(nullptr, context.get());
257
258 // load memory into callback slots
259 std::vector<intptr_t> keys;
260 keys.reserve(request.pools.size());
261 std::transform(request.pools.begin(), request.pools.end(), std::back_inserter(keys),
262 [](const auto& pool) { return reinterpret_cast<intptr_t>(&pool); });
263 const std::vector<int32_t> slots = callback->getSlots(request.pools, keys);
264
265 // ensure slot std::numeric_limits<int32_t>::max() doesn't exist (for
266 // subsequent slot validation testing)
267 ASSERT_TRUE(std::all_of(slots.begin(), slots.end(), [](int32_t slot) {
268 return slot != std::numeric_limits<int32_t>::max();
269 }));
270
271 // serialize the request
272 const auto serialized = android::nn::serialize(request, MeasureTiming::YES, slots);
273
274 // validations
275 removeDatumTest(sender.get(), receiver.get(), serialized);
276 addDatumTest(sender.get(), receiver.get(), serialized);
277 mutateDatumTest(sender.get(), receiver.get(), serialized);
278}
279
280// This test validates that when the Result message size exceeds length of the
281// result FMQ, the service instance gracefully fails and returns an error.
282static void validateBurstFmqLength(const sp<IPreparedModel>& preparedModel,
283 const Request& request) {
284 // create regular burst
285 std::shared_ptr<ExecutionBurstController> controllerRegular;
286 ASSERT_NO_FATAL_FAILURE(createBurstWithResultChannelLength(
287 preparedModel, kExecutionBurstChannelLength, &controllerRegular));
288 ASSERT_NE(nullptr, controllerRegular.get());
289
290 // create burst with small output channel
291 std::shared_ptr<ExecutionBurstController> controllerSmall;
292 ASSERT_NO_FATAL_FAILURE(createBurstWithResultChannelLength(
293 preparedModel, kExecutionBurstChannelSmallLength, &controllerSmall));
294 ASSERT_NE(nullptr, controllerSmall.get());
295
296 // load memory into callback slots
297 std::vector<intptr_t> keys(request.pools.size());
298 for (size_t i = 0; i < keys.size(); ++i) {
299 keys[i] = reinterpret_cast<intptr_t>(&request.pools[i]);
300 }
301
302 // collect serialized result by running regular burst
Michael Butler648ada52019-07-25 17:22:11 -0700303 const auto [nRegular, outputShapesRegular, timingRegular, fallbackRegular] =
Lev Proleev13fdfcd2019-08-30 11:35:34 +0100304 controllerRegular->compute(request, MeasureTiming::NO, keys);
Michael Butler648ada52019-07-25 17:22:11 -0700305 const ErrorStatus statusRegular = nn::convertResultCodeToErrorStatus(nRegular);
306 EXPECT_FALSE(fallbackRegular);
Lev Proleev13fdfcd2019-08-30 11:35:34 +0100307
308 // skip test if regular burst output isn't useful for testing a failure
309 // caused by having too small of a length for the result FMQ
310 const std::vector<FmqResultDatum> serialized =
311 android::nn::serialize(statusRegular, outputShapesRegular, timingRegular);
312 if (statusRegular != ErrorStatus::NONE ||
313 serialized.size() <= kExecutionBurstChannelSmallLength) {
314 return;
315 }
316
317 // by this point, execution should fail because the result channel isn't
318 // large enough to return the serialized result
Michael Butler648ada52019-07-25 17:22:11 -0700319 const auto [nSmall, outputShapesSmall, timingSmall, fallbackSmall] =
Lev Proleev13fdfcd2019-08-30 11:35:34 +0100320 controllerSmall->compute(request, MeasureTiming::NO, keys);
Michael Butler648ada52019-07-25 17:22:11 -0700321 const ErrorStatus statusSmall = nn::convertResultCodeToErrorStatus(nSmall);
Lev Proleev13fdfcd2019-08-30 11:35:34 +0100322 EXPECT_NE(ErrorStatus::NONE, statusSmall);
323 EXPECT_EQ(0u, outputShapesSmall.size());
324 EXPECT_TRUE(badTiming(timingSmall));
Michael Butler648ada52019-07-25 17:22:11 -0700325 EXPECT_FALSE(fallbackSmall);
Lev Proleev13fdfcd2019-08-30 11:35:34 +0100326}
327
328static bool isSanitized(const FmqResultDatum& datum) {
329 using Discriminator = FmqResultDatum::hidl_discriminator;
330
331 // check to ensure the padding values in the returned
332 // FmqResultDatum::OperandInformation are initialized to 0
333 if (datum.getDiscriminator() == Discriminator::operandInformation) {
334 static_assert(
335 offsetof(FmqResultDatum::OperandInformation, isSufficient) == 0,
336 "unexpected value for offset of FmqResultDatum::OperandInformation::isSufficient");
337 static_assert(
338 sizeof(FmqResultDatum::OperandInformation::isSufficient) == 1,
339 "unexpected value for size of FmqResultDatum::OperandInformation::isSufficient");
340 static_assert(offsetof(FmqResultDatum::OperandInformation, numberOfDimensions) == 4,
341 "unexpected value for offset of "
342 "FmqResultDatum::OperandInformation::numberOfDimensions");
343 static_assert(sizeof(FmqResultDatum::OperandInformation::numberOfDimensions) == 4,
344 "unexpected value for size of "
345 "FmqResultDatum::OperandInformation::numberOfDimensions");
346 static_assert(sizeof(FmqResultDatum::OperandInformation) == 8,
347 "unexpected value for size of "
348 "FmqResultDatum::OperandInformation");
349
350 constexpr size_t paddingOffset =
351 offsetof(FmqResultDatum::OperandInformation, isSufficient) +
352 sizeof(FmqResultDatum::OperandInformation::isSufficient);
353 constexpr size_t paddingSize =
354 offsetof(FmqResultDatum::OperandInformation, numberOfDimensions) - paddingOffset;
355
356 FmqResultDatum::OperandInformation initialized{};
357 std::memset(&initialized, 0, sizeof(initialized));
358
359 const char* initializedPaddingStart =
360 reinterpret_cast<const char*>(&initialized) + paddingOffset;
361 const char* datumPaddingStart =
362 reinterpret_cast<const char*>(&datum.operandInformation()) + paddingOffset;
363
364 return std::memcmp(datumPaddingStart, initializedPaddingStart, paddingSize) == 0;
365 }
366
367 // there are no other padding initialization checks required, so return true
368 // for any sum-type that isn't FmqResultDatum::OperandInformation
369 return true;
370}
371
372static void validateBurstSanitized(const sp<IPreparedModel>& preparedModel,
373 const Request& request) {
374 // create burst
375 std::unique_ptr<RequestChannelSender> sender;
376 std::unique_ptr<ResultChannelReceiver> receiver;
377 sp<ExecutionBurstCallback> callback = new ExecutionBurstCallback();
378 sp<IBurstContext> context;
379 ASSERT_NO_FATAL_FAILURE(createBurst(preparedModel, callback, &sender, &receiver, &context));
380 ASSERT_NE(nullptr, sender.get());
381 ASSERT_NE(nullptr, receiver.get());
382 ASSERT_NE(nullptr, context.get());
383
384 // load memory into callback slots
385 std::vector<intptr_t> keys;
386 keys.reserve(request.pools.size());
387 std::transform(request.pools.begin(), request.pools.end(), std::back_inserter(keys),
388 [](const auto& pool) { return reinterpret_cast<intptr_t>(&pool); });
389 const std::vector<int32_t> slots = callback->getSlots(request.pools, keys);
390
391 // send valid request
392 ASSERT_TRUE(sender->send(request, MeasureTiming::YES, slots));
393
394 // receive valid result
395 auto serialized = receiver->getPacketBlocking();
396 ASSERT_TRUE(serialized.has_value());
397
398 // sanitize result
399 ASSERT_TRUE(std::all_of(serialized->begin(), serialized->end(), isSanitized))
400 << "The result serialized data is not properly sanitized";
401}
402
403///////////////////////////// ENTRY POINT //////////////////////////////////
404
405void validateBurst(const sp<IPreparedModel>& preparedModel, const Request& request) {
406 ASSERT_NO_FATAL_FAILURE(validateBurstSerialization(preparedModel, request));
407 ASSERT_NO_FATAL_FAILURE(validateBurstFmqLength(preparedModel, request));
408 ASSERT_NO_FATAL_FAILURE(validateBurstSanitized(preparedModel, request));
409}
410
Lev Proleev26d1bc82019-08-30 11:57:18 +0100411} // namespace android::hardware::neuralnetworks::V1_3::vts::functional