blob: cba1f7766c2de9cd90830a4d35570a65d6bed7fd [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#include "GeneratedTestHarness.h"
18
19#include <android-base/logging.h>
20#include <android/hardware/neuralnetworks/1.0/IDevice.h>
21#include <android/hardware/neuralnetworks/1.0/IExecutionCallback.h>
22#include <android/hardware/neuralnetworks/1.0/IPreparedModel.h>
23#include <android/hardware/neuralnetworks/1.0/IPreparedModelCallback.h>
24#include <android/hardware/neuralnetworks/1.0/types.h>
25#include <android/hardware/neuralnetworks/1.1/IDevice.h>
26#include <android/hardware/neuralnetworks/1.2/IDevice.h>
27#include <android/hardware/neuralnetworks/1.2/IExecutionCallback.h>
28#include <android/hardware/neuralnetworks/1.2/IPreparedModel.h>
29#include <android/hardware/neuralnetworks/1.2/IPreparedModelCallback.h>
Lev Proleev26d1bc82019-08-30 11:57:18 +010030#include <android/hardware/neuralnetworks/1.2/types.h>
31#include <android/hardware/neuralnetworks/1.3/IDevice.h>
Xusong Wang1b3f4262019-10-25 12:07:17 -070032#include <android/hardware/neuralnetworks/1.3/IPreparedModel.h>
Xusong Wangcc47dff2019-10-23 10:35:07 -070033#include <android/hardware/neuralnetworks/1.3/IPreparedModelCallback.h>
Lev Proleev26d1bc82019-08-30 11:57:18 +010034#include <android/hardware/neuralnetworks/1.3/types.h>
Lev Proleev13fdfcd2019-08-30 11:35:34 +010035#include <android/hidl/allocator/1.0/IAllocator.h>
36#include <android/hidl/memory/1.0/IMemory.h>
Lev Proleev56cda832019-12-05 14:49:47 +000037#include <gtest/gtest.h>
Lev Proleev13fdfcd2019-08-30 11:35:34 +010038#include <hidlmemory/mapping.h>
39
Lev Proleev13fdfcd2019-08-30 11:35:34 +010040#include <algorithm>
Michael Butler648ada52019-07-25 17:22:11 -070041#include <chrono>
Lev Proleev13fdfcd2019-08-30 11:35:34 +010042#include <iostream>
43#include <numeric>
Lev Proleev56cda832019-12-05 14:49:47 +000044#include <vector>
Lev Proleev13fdfcd2019-08-30 11:35:34 +010045
46#include "1.0/Utils.h"
Xusong Wangcc47dff2019-10-23 10:35:07 -070047#include "1.3/Callbacks.h"
Michael Butler95899b32020-01-07 14:52:44 -080048#include "1.3/Utils.h"
Lev Proleev13fdfcd2019-08-30 11:35:34 +010049#include "ExecutionBurstController.h"
50#include "MemoryUtils.h"
51#include "TestHarness.h"
52#include "Utils.h"
53#include "VtsHalNeuralnetworks.h"
54
Lev Proleev26d1bc82019-08-30 11:57:18 +010055namespace android::hardware::neuralnetworks::V1_3::vts::functional {
Lev Proleev13fdfcd2019-08-30 11:35:34 +010056
57using namespace test_helper;
58using hidl::memory::V1_0::IMemory;
Michael Butler79a41d72019-12-11 19:08:08 -080059using implementation::ExecutionCallback;
Xusong Wangcc47dff2019-10-23 10:35:07 -070060using implementation::PreparedModelCallback;
Lev Proleev13fdfcd2019-08-30 11:35:34 +010061using V1_0::DataLocation;
Xusong Wange9da9852020-01-13 11:44:45 -080062using V1_0::RequestArgument;
Lev Proleev13fdfcd2019-08-30 11:35:34 +010063using V1_1::ExecutionPreference;
Lev Proleev26d1bc82019-08-30 11:57:18 +010064using V1_2::Constant;
Lev Proleev26d1bc82019-08-30 11:57:18 +010065using V1_2::MeasureTiming;
Lev Proleev26d1bc82019-08-30 11:57:18 +010066using V1_2::OutputShape;
67using V1_2::SymmPerChannelQuantParams;
68using V1_2::Timing;
Lev Proleev13fdfcd2019-08-30 11:35:34 +010069using HidlToken = hidl_array<uint8_t, static_cast<uint32_t>(Constant::BYTE_SIZE_OF_CACHE_TOKEN)>;
70
Lev Proleev0d4ba3f2019-10-02 17:32:06 +010071namespace {
72
73enum class Executor { ASYNC, SYNC, BURST };
74
Lev Proleev13fdfcd2019-08-30 11:35:34 +010075enum class OutputType { FULLY_SPECIFIED, UNSPECIFIED, INSUFFICIENT };
76
Xusong Wange9da9852020-01-13 11:44:45 -080077enum class MemoryType { SHARED, DEVICE };
78
79enum class IOType { INPUT, OUTPUT };
80
Lev Proleev0d4ba3f2019-10-02 17:32:06 +010081struct TestConfig {
82 Executor executor;
83 MeasureTiming measureTiming;
84 OutputType outputType;
Xusong Wange9da9852020-01-13 11:44:45 -080085 MemoryType memoryType;
Lev Proleev9226c1e2019-10-03 14:43:18 +010086 // `reportSkipping` indicates if a test should print an info message in case
87 // it is skipped. The field is set to true by default and is set to false in
88 // quantization coupling tests to suppress skipping a test
89 bool reportSkipping;
Xusong Wange9da9852020-01-13 11:44:45 -080090 TestConfig(Executor executor, MeasureTiming measureTiming, OutputType outputType,
91 MemoryType memoryType)
Lev Proleev9226c1e2019-10-03 14:43:18 +010092 : executor(executor),
93 measureTiming(measureTiming),
94 outputType(outputType),
Xusong Wange9da9852020-01-13 11:44:45 -080095 memoryType(memoryType),
Lev Proleev9226c1e2019-10-03 14:43:18 +010096 reportSkipping(true) {}
97 TestConfig(Executor executor, MeasureTiming measureTiming, OutputType outputType,
Xusong Wange9da9852020-01-13 11:44:45 -080098 MemoryType memoryType, bool reportSkipping)
Lev Proleev9226c1e2019-10-03 14:43:18 +010099 : executor(executor),
100 measureTiming(measureTiming),
101 outputType(outputType),
Xusong Wange9da9852020-01-13 11:44:45 -0800102 memoryType(memoryType),
Lev Proleev9226c1e2019-10-03 14:43:18 +0100103 reportSkipping(reportSkipping) {}
Lev Proleev0d4ba3f2019-10-02 17:32:06 +0100104};
105
Xusong Wange9da9852020-01-13 11:44:45 -0800106class DeviceMemoryAllocator {
107 public:
108 DeviceMemoryAllocator(const sp<IDevice>& device, const sp<IPreparedModel>& preparedModel,
109 const TestModel& testModel)
110 : kDevice(device), kPreparedModel(preparedModel), kTestModel(testModel) {}
111
112 // Allocate device memory for a target input/output operand.
113 // Return {IBuffer object, token} if successful.
114 // Return {nullptr, 0} if device memory is not supported.
115 template <IOType ioType>
116 std::pair<sp<IBuffer>, int32_t> allocate(uint32_t index) {
117 std::pair<sp<IBuffer>, int32_t> buffer;
118 allocateInternal<ioType>(index, &buffer);
119 return buffer;
120 }
121
122 private:
123 template <IOType ioType>
124 void allocateInternal(uint32_t index, std::pair<sp<IBuffer>, int32_t>* result) {
125 ASSERT_NE(result, nullptr);
126
127 // Prepare arguments.
128 BufferRole role = {.modelIndex = 0, .ioIndex = index, .frequency = 1.0f};
129 hidl_vec<BufferRole> inputRoles, outputRoles;
130 if constexpr (ioType == IOType::INPUT) {
131 inputRoles = {role};
132 } else {
133 outputRoles = {role};
134 }
135
136 // Allocate device memory.
137 ErrorStatus status;
138 sp<IBuffer> buffer;
139 int32_t token;
140 const auto ret = kDevice->allocate(
141 {}, {kPreparedModel}, inputRoles, outputRoles,
142 [&status, &buffer, &token](ErrorStatus error, const sp<IBuffer>& buf, int32_t tok) {
143 status = error;
144 buffer = buf;
145 token = tok;
146 });
147
148 // Check allocation results.
149 ASSERT_TRUE(ret.isOk());
150 if (status == ErrorStatus::NONE) {
151 ASSERT_NE(buffer, nullptr);
152 ASSERT_GT(token, 0);
153 } else {
154 ASSERT_EQ(status, ErrorStatus::GENERAL_FAILURE);
155 ASSERT_EQ(buffer, nullptr);
156 ASSERT_EQ(token, 0);
157 }
158
159 // Initialize input data from TestBuffer.
160 if constexpr (ioType == IOType::INPUT) {
161 if (buffer != nullptr) {
162 // TestBuffer -> Shared memory.
163 const auto& testBuffer = kTestModel.operands[kTestModel.inputIndexes[index]].data;
164 ASSERT_GT(testBuffer.size(), 0);
165 hidl_memory tmp = nn::allocateSharedMemory(testBuffer.size());
166 sp<IMemory> inputMemory = mapMemory(tmp);
167 ASSERT_NE(inputMemory.get(), nullptr);
168 uint8_t* inputPtr =
169 static_cast<uint8_t*>(static_cast<void*>(inputMemory->getPointer()));
170 ASSERT_NE(inputPtr, nullptr);
171 const uint8_t* begin = testBuffer.get<uint8_t>();
172 const uint8_t* end = begin + testBuffer.size();
173 std::copy(begin, end, inputPtr);
174
175 // Shared memory -> IBuffer.
176 auto ret = buffer->copyFrom(tmp, {});
177 ASSERT_TRUE(ret.isOk());
178 ASSERT_EQ(static_cast<ErrorStatus>(ret), ErrorStatus::NONE);
179 }
180 }
181 *result = {std::move(buffer), token};
182 }
183
184 const sp<IDevice> kDevice;
185 const sp<IPreparedModel> kPreparedModel;
186 const TestModel& kTestModel;
187};
188
Lev Proleev0d4ba3f2019-10-02 17:32:06 +0100189} // namespace
190
Lev Proleev13fdfcd2019-08-30 11:35:34 +0100191Model createModel(const TestModel& testModel) {
192 // Model operands.
193 hidl_vec<Operand> operands(testModel.operands.size());
194 size_t constCopySize = 0, constRefSize = 0;
195 for (uint32_t i = 0; i < testModel.operands.size(); i++) {
196 const auto& op = testModel.operands[i];
197
198 DataLocation loc = {};
199 if (op.lifetime == TestOperandLifeTime::CONSTANT_COPY) {
200 loc = {.poolIndex = 0,
201 .offset = static_cast<uint32_t>(constCopySize),
202 .length = static_cast<uint32_t>(op.data.size())};
203 constCopySize += op.data.alignedSize();
204 } else if (op.lifetime == TestOperandLifeTime::CONSTANT_REFERENCE) {
205 loc = {.poolIndex = 0,
206 .offset = static_cast<uint32_t>(constRefSize),
207 .length = static_cast<uint32_t>(op.data.size())};
208 constRefSize += op.data.alignedSize();
209 }
210
211 Operand::ExtraParams extraParams;
212 if (op.type == TestOperandType::TENSOR_QUANT8_SYMM_PER_CHANNEL) {
213 extraParams.channelQuant(SymmPerChannelQuantParams{
214 .scales = op.channelQuant.scales, .channelDim = op.channelQuant.channelDim});
215 }
216
217 operands[i] = {.type = static_cast<OperandType>(op.type),
218 .dimensions = op.dimensions,
219 .numberOfConsumers = op.numberOfConsumers,
220 .scale = op.scale,
221 .zeroPoint = op.zeroPoint,
222 .lifetime = static_cast<OperandLifeTime>(op.lifetime),
223 .location = loc,
224 .extraParams = std::move(extraParams)};
225 }
226
227 // Model operations.
228 hidl_vec<Operation> operations(testModel.operations.size());
229 std::transform(testModel.operations.begin(), testModel.operations.end(), operations.begin(),
230 [](const TestOperation& op) -> Operation {
231 return {.type = static_cast<OperationType>(op.type),
232 .inputs = op.inputs,
233 .outputs = op.outputs};
234 });
235
236 // Constant copies.
237 hidl_vec<uint8_t> operandValues(constCopySize);
238 for (uint32_t i = 0; i < testModel.operands.size(); i++) {
239 const auto& op = testModel.operands[i];
240 if (op.lifetime == TestOperandLifeTime::CONSTANT_COPY) {
241 const uint8_t* begin = op.data.get<uint8_t>();
242 const uint8_t* end = begin + op.data.size();
243 std::copy(begin, end, operandValues.data() + operands[i].location.offset);
244 }
245 }
246
247 // Shared memory.
248 hidl_vec<hidl_memory> pools = {};
249 if (constRefSize > 0) {
250 hidl_vec_push_back(&pools, nn::allocateSharedMemory(constRefSize));
251 CHECK_NE(pools[0].size(), 0u);
252
253 // load data
254 sp<IMemory> mappedMemory = mapMemory(pools[0]);
255 CHECK(mappedMemory.get() != nullptr);
256 uint8_t* mappedPtr =
257 reinterpret_cast<uint8_t*>(static_cast<void*>(mappedMemory->getPointer()));
258 CHECK(mappedPtr != nullptr);
259
260 for (uint32_t i = 0; i < testModel.operands.size(); i++) {
261 const auto& op = testModel.operands[i];
262 if (op.lifetime == TestOperandLifeTime::CONSTANT_REFERENCE) {
263 const uint8_t* begin = op.data.get<uint8_t>();
264 const uint8_t* end = begin + op.data.size();
265 std::copy(begin, end, mappedPtr + operands[i].location.offset);
266 }
267 }
268 }
269
Slava Shklyaevf8124a82019-12-13 12:24:35 +0000270 return {.main = {.operands = std::move(operands),
271 .operations = std::move(operations),
272 .inputIndexes = testModel.inputIndexes,
273 .outputIndexes = testModel.outputIndexes},
Lev Proleev13fdfcd2019-08-30 11:35:34 +0100274 .operandValues = std::move(operandValues),
275 .pools = std::move(pools),
276 .relaxComputationFloat32toFloat16 = testModel.isRelaxed};
277}
278
279static bool isOutputSizeGreaterThanOne(const TestModel& testModel, uint32_t index) {
280 const auto byteSize = testModel.operands[testModel.outputIndexes[index]].data.size();
281 return byteSize > 1u;
282}
283
Xusong Wange9da9852020-01-13 11:44:45 -0800284static void makeOutputInsufficientSize(uint32_t outputIndex, Request* request) {
Lev Proleev13fdfcd2019-08-30 11:35:34 +0100285 auto& length = request->outputs[outputIndex].location.length;
286 ASSERT_GT(length, 1u);
287 length -= 1u;
288}
289
290static void makeOutputDimensionsUnspecified(Model* model) {
Slava Shklyaevf8124a82019-12-13 12:24:35 +0000291 for (auto i : model->main.outputIndexes) {
292 auto& dims = model->main.operands[i].dimensions;
Lev Proleev13fdfcd2019-08-30 11:35:34 +0100293 std::fill(dims.begin(), dims.end(), 0);
294 }
295}
296
Xusong Wange9da9852020-01-13 11:44:45 -0800297constexpr uint32_t kInputPoolIndex = 0;
298constexpr uint32_t kOutputPoolIndex = 1;
299constexpr uint32_t kDeviceMemoryBeginIndex = 2;
300
301static std::pair<Request, std::vector<sp<IBuffer>>> createRequest(
302 const sp<IDevice>& device, const sp<IPreparedModel>& preparedModel,
303 const TestModel& testModel, bool preferDeviceMemory) {
304 // Memory pools are organized as:
305 // - 0: Input shared memory pool
306 // - 1: Output shared memory pool
307 // - [2, 2+i): Input device memories
308 // - [2+i, 2+i+o): Output device memories
309 DeviceMemoryAllocator allocator(device, preparedModel, testModel);
310 std::vector<sp<IBuffer>> buffers;
311 std::vector<int32_t> tokens;
312
313 // Model inputs.
314 hidl_vec<RequestArgument> inputs(testModel.inputIndexes.size());
315 size_t inputSize = 0;
316 for (uint32_t i = 0; i < testModel.inputIndexes.size(); i++) {
317 const auto& op = testModel.operands[testModel.inputIndexes[i]];
318 if (op.data.size() == 0) {
319 // Omitted input.
320 inputs[i] = {.hasNoValue = true};
321 continue;
322 } else if (preferDeviceMemory) {
323 SCOPED_TRACE("Input index = " + std::to_string(i));
324 auto [buffer, token] = allocator.allocate<IOType::INPUT>(i);
325 if (buffer != nullptr) {
326 DataLocation loc = {.poolIndex = static_cast<uint32_t>(buffers.size() +
327 kDeviceMemoryBeginIndex)};
328 buffers.push_back(std::move(buffer));
329 tokens.push_back(token);
330 inputs[i] = {.hasNoValue = false, .location = loc, .dimensions = {}};
331 continue;
332 }
333 }
334
335 // Reserve shared memory for input.
336 DataLocation loc = {.poolIndex = kInputPoolIndex,
337 .offset = static_cast<uint32_t>(inputSize),
338 .length = static_cast<uint32_t>(op.data.size())};
339 inputSize += op.data.alignedSize();
340 inputs[i] = {.hasNoValue = false, .location = loc, .dimensions = {}};
341 }
342
343 // Model outputs.
344 hidl_vec<RequestArgument> outputs(testModel.outputIndexes.size());
345 size_t outputSize = 0;
346 for (uint32_t i = 0; i < testModel.outputIndexes.size(); i++) {
347 const auto& op = testModel.operands[testModel.outputIndexes[i]];
348 if (preferDeviceMemory) {
349 SCOPED_TRACE("Output index = " + std::to_string(i));
350 auto [buffer, token] = allocator.allocate<IOType::OUTPUT>(i);
351 if (buffer != nullptr) {
352 DataLocation loc = {.poolIndex = static_cast<uint32_t>(buffers.size() +
353 kDeviceMemoryBeginIndex)};
354 buffers.push_back(std::move(buffer));
355 tokens.push_back(token);
356 outputs[i] = {.hasNoValue = false, .location = loc, .dimensions = {}};
357 continue;
358 }
359 }
360
361 // In the case of zero-sized output, we should at least provide a one-byte buffer.
362 // This is because zero-sized tensors are only supported internally to the driver, or
363 // reported in output shapes. It is illegal for the client to pre-specify a zero-sized
364 // tensor as model output. Otherwise, we will have two semantic conflicts:
365 // - "Zero dimension" conflicts with "unspecified dimension".
366 // - "Omitted operand buffer" conflicts with "zero-sized operand buffer".
367 size_t bufferSize = std::max<size_t>(op.data.size(), 1);
368
369 // Reserve shared memory for output.
370 DataLocation loc = {.poolIndex = kOutputPoolIndex,
371 .offset = static_cast<uint32_t>(outputSize),
372 .length = static_cast<uint32_t>(bufferSize)};
373 outputSize += op.data.size() == 0 ? TestBuffer::kAlignment : op.data.alignedSize();
374 outputs[i] = {.hasNoValue = false, .location = loc, .dimensions = {}};
375 }
376
377 // Memory pools.
378 hidl_vec<Request::MemoryPool> pools(kDeviceMemoryBeginIndex + buffers.size());
379 pools[kInputPoolIndex].hidlMemory(nn::allocateSharedMemory(std::max<size_t>(inputSize, 1)));
380 pools[kOutputPoolIndex].hidlMemory(nn::allocateSharedMemory(std::max<size_t>(outputSize, 1)));
381 CHECK_NE(pools[kInputPoolIndex].hidlMemory().size(), 0u);
382 CHECK_NE(pools[kOutputPoolIndex].hidlMemory().size(), 0u);
383 for (uint32_t i = 0; i < buffers.size(); i++) {
384 pools[kDeviceMemoryBeginIndex + i].token(tokens[i]);
385 }
386
387 // Copy input data to the input shared memory pool.
388 sp<IMemory> inputMemory = mapMemory(pools[kInputPoolIndex].hidlMemory());
389 CHECK(inputMemory.get() != nullptr);
390 uint8_t* inputPtr = static_cast<uint8_t*>(static_cast<void*>(inputMemory->getPointer()));
391 CHECK(inputPtr != nullptr);
392 for (uint32_t i = 0; i < testModel.inputIndexes.size(); i++) {
393 if (!inputs[i].hasNoValue && inputs[i].location.poolIndex == kInputPoolIndex) {
394 const auto& op = testModel.operands[testModel.inputIndexes[i]];
395 const uint8_t* begin = op.data.get<uint8_t>();
396 const uint8_t* end = begin + op.data.size();
397 std::copy(begin, end, inputPtr + inputs[i].location.offset);
398 }
399 }
400
401 Request request = {
402 .inputs = std::move(inputs), .outputs = std::move(outputs), .pools = std::move(pools)};
403 return {std::move(request), std::move(buffers)};
404}
405
406// Get a TestBuffer with data copied from an IBuffer object.
407static void getBuffer(const sp<IBuffer>& buffer, size_t size, TestBuffer* testBuffer) {
408 // IBuffer -> Shared memory.
409 hidl_memory tmp = nn::allocateSharedMemory(size);
410 const auto ret = buffer->copyTo(tmp);
411 ASSERT_TRUE(ret.isOk());
412 ASSERT_EQ(static_cast<ErrorStatus>(ret), ErrorStatus::NONE);
413
414 // Shared memory -> TestBuffer.
415 sp<IMemory> outputMemory = mapMemory(tmp);
416 ASSERT_NE(outputMemory.get(), nullptr);
417 uint8_t* outputPtr = static_cast<uint8_t*>(static_cast<void*>(outputMemory->getPointer()));
418 ASSERT_NE(outputPtr, nullptr);
419 ASSERT_NE(testBuffer, nullptr);
420 *testBuffer = TestBuffer(size, outputPtr);
421}
422
423static std::vector<TestBuffer> getOutputBuffers(const TestModel& testModel, const Request& request,
424 const std::vector<sp<IBuffer>>& buffers) {
425 sp<IMemory> outputMemory = mapMemory(request.pools[kOutputPoolIndex].hidlMemory());
426 CHECK(outputMemory.get() != nullptr);
427 uint8_t* outputPtr = static_cast<uint8_t*>(static_cast<void*>(outputMemory->getPointer()));
428 CHECK(outputPtr != nullptr);
429
430 // Copy out output results.
431 std::vector<TestBuffer> outputBuffers;
432 for (uint32_t i = 0; i < request.outputs.size(); i++) {
433 const auto& outputLoc = request.outputs[i].location;
434 if (outputLoc.poolIndex == kOutputPoolIndex) {
435 outputBuffers.emplace_back(outputLoc.length, outputPtr + outputLoc.offset);
436 } else {
437 const auto& op = testModel.operands[testModel.outputIndexes[i]];
438 if (op.data.size() == 0) {
439 outputBuffers.emplace_back();
440 } else {
441 SCOPED_TRACE("Output index = " + std::to_string(i));
442 const uint32_t bufferIndex = outputLoc.poolIndex - kDeviceMemoryBeginIndex;
443 TestBuffer buffer;
444 getBuffer(buffers[bufferIndex], op.data.size(), &buffer);
445 outputBuffers.push_back(std::move(buffer));
446 }
447 }
448 }
449 return outputBuffers;
450}
451
Lev Proleev13fdfcd2019-08-30 11:35:34 +0100452static Return<ErrorStatus> ExecutePreparedModel(const sp<IPreparedModel>& preparedModel,
453 const Request& request, MeasureTiming measure,
454 sp<ExecutionCallback>& callback) {
Michael Butler79a41d72019-12-11 19:08:08 -0800455 return preparedModel->execute_1_3(request, measure, {}, callback);
Lev Proleev13fdfcd2019-08-30 11:35:34 +0100456}
457static Return<ErrorStatus> ExecutePreparedModel(const sp<IPreparedModel>& preparedModel,
458 const Request& request, MeasureTiming measure,
459 hidl_vec<OutputShape>* outputShapes,
460 Timing* timing) {
461 ErrorStatus result;
Xusong Wangd4a060b2019-10-28 11:11:19 -0700462 Return<void> ret = preparedModel->executeSynchronously_1_3(
Michael Butler79a41d72019-12-11 19:08:08 -0800463 request, measure, {},
Lev Proleev13fdfcd2019-08-30 11:35:34 +0100464 [&result, outputShapes, timing](ErrorStatus error, const hidl_vec<OutputShape>& shapes,
465 const Timing& time) {
466 result = error;
467 *outputShapes = shapes;
468 *timing = time;
469 });
470 if (!ret.isOk()) {
471 return ErrorStatus::GENERAL_FAILURE;
472 }
473 return result;
474}
475static std::shared_ptr<::android::nn::ExecutionBurstController> CreateBurst(
476 const sp<IPreparedModel>& preparedModel) {
Michael Butler648ada52019-07-25 17:22:11 -0700477 return android::nn::ExecutionBurstController::create(preparedModel,
478 std::chrono::microseconds{0});
Lev Proleev13fdfcd2019-08-30 11:35:34 +0100479}
Lev Proleev13fdfcd2019-08-30 11:35:34 +0100480
Xusong Wange9da9852020-01-13 11:44:45 -0800481void EvaluatePreparedModel(const sp<IDevice>& device, const sp<IPreparedModel>& preparedModel,
482 const TestModel& testModel, const TestConfig& testConfig,
483 bool* skipped = nullptr) {
Lev Proleev9226c1e2019-10-03 14:43:18 +0100484 if (skipped != nullptr) {
485 *skipped = false;
486 }
Lev Proleev13fdfcd2019-08-30 11:35:34 +0100487 // If output0 does not have size larger than one byte, we can not test with insufficient buffer.
Lev Proleev0d4ba3f2019-10-02 17:32:06 +0100488 if (testConfig.outputType == OutputType::INSUFFICIENT &&
489 !isOutputSizeGreaterThanOne(testModel, 0)) {
Lev Proleev13fdfcd2019-08-30 11:35:34 +0100490 return;
491 }
492
Xusong Wange9da9852020-01-13 11:44:45 -0800493 auto [request, buffers] =
494 createRequest(device, preparedModel, testModel,
495 /*preferDeviceMemory=*/testConfig.memoryType == MemoryType::DEVICE);
496 // Skip if testing memory domain but no device memory has been allocated.
497 if (testConfig.memoryType == MemoryType::DEVICE && buffers.empty()) {
498 return;
Lev Proleev13fdfcd2019-08-30 11:35:34 +0100499 }
Xusong Wange9da9852020-01-13 11:44:45 -0800500 if (testConfig.outputType == OutputType::INSUFFICIENT) {
501 makeOutputInsufficientSize(/*outputIndex=*/0, &request);
502 }
Lev Proleev13fdfcd2019-08-30 11:35:34 +0100503
504 ErrorStatus executionStatus;
505 hidl_vec<OutputShape> outputShapes;
506 Timing timing;
Lev Proleev0d4ba3f2019-10-02 17:32:06 +0100507 switch (testConfig.executor) {
Lev Proleev13fdfcd2019-08-30 11:35:34 +0100508 case Executor::ASYNC: {
509 SCOPED_TRACE("asynchronous");
510
511 // launch execution
512 sp<ExecutionCallback> executionCallback = new ExecutionCallback();
Lev Proleev0d4ba3f2019-10-02 17:32:06 +0100513 Return<ErrorStatus> executionLaunchStatus = ExecutePreparedModel(
514 preparedModel, request, testConfig.measureTiming, executionCallback);
Lev Proleev13fdfcd2019-08-30 11:35:34 +0100515 ASSERT_TRUE(executionLaunchStatus.isOk());
516 EXPECT_EQ(ErrorStatus::NONE, static_cast<ErrorStatus>(executionLaunchStatus));
517
518 // retrieve execution status
519 executionCallback->wait();
520 executionStatus = executionCallback->getStatus();
521 outputShapes = executionCallback->getOutputShapes();
522 timing = executionCallback->getTiming();
523
524 break;
525 }
526 case Executor::SYNC: {
527 SCOPED_TRACE("synchronous");
528
529 // execute
Lev Proleev0d4ba3f2019-10-02 17:32:06 +0100530 Return<ErrorStatus> executionReturnStatus = ExecutePreparedModel(
531 preparedModel, request, testConfig.measureTiming, &outputShapes, &timing);
Lev Proleev13fdfcd2019-08-30 11:35:34 +0100532 ASSERT_TRUE(executionReturnStatus.isOk());
533 executionStatus = static_cast<ErrorStatus>(executionReturnStatus);
534
535 break;
536 }
537 case Executor::BURST: {
Xusong Wangb345a462019-11-27 12:46:48 -0800538 // TODO(butlermichael): Check if we need to test burst in V1_3 if the interface remains
539 // V1_2.
Lev Proleev13fdfcd2019-08-30 11:35:34 +0100540 SCOPED_TRACE("burst");
541
Xusong Wange9da9852020-01-13 11:44:45 -0800542 // check compliance
543 ASSERT_TRUE(nn::compliantWithV1_0(request));
544 V1_0::Request request10 = nn::convertToV1_0(request);
545
Lev Proleev13fdfcd2019-08-30 11:35:34 +0100546 // create burst
547 const std::shared_ptr<::android::nn::ExecutionBurstController> controller =
548 CreateBurst(preparedModel);
549 ASSERT_NE(nullptr, controller.get());
550
551 // create memory keys
Xusong Wangb345a462019-11-27 12:46:48 -0800552 std::vector<intptr_t> keys(request10.pools.size());
Lev Proleev13fdfcd2019-08-30 11:35:34 +0100553 for (size_t i = 0; i < keys.size(); ++i) {
Xusong Wangb345a462019-11-27 12:46:48 -0800554 keys[i] = reinterpret_cast<intptr_t>(&request10.pools[i]);
Lev Proleev13fdfcd2019-08-30 11:35:34 +0100555 }
556
557 // execute burst
Michael Butler648ada52019-07-25 17:22:11 -0700558 int n;
559 std::tie(n, outputShapes, timing, std::ignore) =
Xusong Wangb345a462019-11-27 12:46:48 -0800560 controller->compute(request10, testConfig.measureTiming, keys);
Michael Butler648ada52019-07-25 17:22:11 -0700561 executionStatus = nn::convertResultCodeToErrorStatus(n);
Lev Proleev13fdfcd2019-08-30 11:35:34 +0100562
563 break;
564 }
565 }
566
Lev Proleev0d4ba3f2019-10-02 17:32:06 +0100567 if (testConfig.outputType != OutputType::FULLY_SPECIFIED &&
Lev Proleev13fdfcd2019-08-30 11:35:34 +0100568 executionStatus == ErrorStatus::GENERAL_FAILURE) {
Lev Proleev9226c1e2019-10-03 14:43:18 +0100569 if (skipped != nullptr) {
570 *skipped = true;
571 }
572 if (!testConfig.reportSkipping) {
573 return;
574 }
Lev Proleev13fdfcd2019-08-30 11:35:34 +0100575 LOG(INFO) << "NN VTS: Early termination of test because vendor service cannot "
576 "execute model that it does not support.";
577 std::cout << "[ ] Early termination of test because vendor service cannot "
578 "execute model that it does not support."
579 << std::endl;
580 GTEST_SKIP();
581 }
Lev Proleev0d4ba3f2019-10-02 17:32:06 +0100582 if (testConfig.measureTiming == MeasureTiming::NO) {
Lev Proleev13fdfcd2019-08-30 11:35:34 +0100583 EXPECT_EQ(UINT64_MAX, timing.timeOnDevice);
584 EXPECT_EQ(UINT64_MAX, timing.timeInDriver);
585 } else {
586 if (timing.timeOnDevice != UINT64_MAX && timing.timeInDriver != UINT64_MAX) {
587 EXPECT_LE(timing.timeOnDevice, timing.timeInDriver);
588 }
589 }
590
Lev Proleev0d4ba3f2019-10-02 17:32:06 +0100591 switch (testConfig.outputType) {
Lev Proleev13fdfcd2019-08-30 11:35:34 +0100592 case OutputType::FULLY_SPECIFIED:
593 // If the model output operands are fully specified, outputShapes must be either
594 // either empty, or have the same number of elements as the number of outputs.
595 ASSERT_EQ(ErrorStatus::NONE, executionStatus);
596 ASSERT_TRUE(outputShapes.size() == 0 ||
597 outputShapes.size() == testModel.outputIndexes.size());
598 break;
599 case OutputType::UNSPECIFIED:
600 // If the model output operands are not fully specified, outputShapes must have
601 // the same number of elements as the number of outputs.
602 ASSERT_EQ(ErrorStatus::NONE, executionStatus);
603 ASSERT_EQ(outputShapes.size(), testModel.outputIndexes.size());
604 break;
605 case OutputType::INSUFFICIENT:
606 ASSERT_EQ(ErrorStatus::OUTPUT_INSUFFICIENT_SIZE, executionStatus);
607 ASSERT_EQ(outputShapes.size(), testModel.outputIndexes.size());
608 ASSERT_FALSE(outputShapes[0].isSufficient);
609 return;
610 }
611
612 // Go through all outputs, check returned output shapes.
613 for (uint32_t i = 0; i < outputShapes.size(); i++) {
614 EXPECT_TRUE(outputShapes[i].isSufficient);
615 const auto& expect = testModel.operands[testModel.outputIndexes[i]].dimensions;
616 const std::vector<uint32_t> actual = outputShapes[i].dimensions;
617 EXPECT_EQ(expect, actual);
618 }
619
620 // Retrieve execution results.
Xusong Wange9da9852020-01-13 11:44:45 -0800621 const std::vector<TestBuffer> outputs = getOutputBuffers(testModel, request, buffers);
Lev Proleev13fdfcd2019-08-30 11:35:34 +0100622
623 // We want "close-enough" results.
624 checkResults(testModel, outputs);
625}
626
Xusong Wange9da9852020-01-13 11:44:45 -0800627void EvaluatePreparedModel(const sp<IDevice>& device, const sp<IPreparedModel>& preparedModel,
628 const TestModel& testModel, TestKind testKind) {
Lev Proleev56cda832019-12-05 14:49:47 +0000629 std::vector<OutputType> outputTypesList;
630 std::vector<MeasureTiming> measureTimingList;
631 std::vector<Executor> executorList;
Xusong Wange9da9852020-01-13 11:44:45 -0800632 MemoryType memoryType = MemoryType::SHARED;
Lev Proleev0d4ba3f2019-10-02 17:32:06 +0100633
Lev Proleev9226c1e2019-10-03 14:43:18 +0100634 switch (testKind) {
635 case TestKind::GENERAL: {
636 outputTypesList = {OutputType::FULLY_SPECIFIED};
637 measureTimingList = {MeasureTiming::NO, MeasureTiming::YES};
638 executorList = {Executor::ASYNC, Executor::SYNC, Executor::BURST};
639 } break;
640 case TestKind::DYNAMIC_SHAPE: {
641 outputTypesList = {OutputType::UNSPECIFIED, OutputType::INSUFFICIENT};
642 measureTimingList = {MeasureTiming::NO, MeasureTiming::YES};
643 executorList = {Executor::ASYNC, Executor::SYNC, Executor::BURST};
644 } break;
Xusong Wange9da9852020-01-13 11:44:45 -0800645 case TestKind::MEMORY_DOMAIN: {
646 outputTypesList = {OutputType::FULLY_SPECIFIED};
647 measureTimingList = {MeasureTiming::NO};
648 executorList = {Executor::ASYNC, Executor::SYNC};
649 memoryType = MemoryType::DEVICE;
650 } break;
Lev Proleev9226c1e2019-10-03 14:43:18 +0100651 case TestKind::QUANTIZATION_COUPLING: {
652 LOG(FATAL) << "Wrong TestKind for EvaluatePreparedModel";
653 return;
654 } break;
Lev Proleev0d4ba3f2019-10-02 17:32:06 +0100655 }
656
657 for (const OutputType outputType : outputTypesList) {
658 for (const MeasureTiming measureTiming : measureTimingList) {
659 for (const Executor executor : executorList) {
Xusong Wange9da9852020-01-13 11:44:45 -0800660 const TestConfig testConfig(executor, measureTiming, outputType, memoryType);
661 EvaluatePreparedModel(device, preparedModel, testModel, testConfig);
Lev Proleev0d4ba3f2019-10-02 17:32:06 +0100662 }
663 }
Lev Proleev13fdfcd2019-08-30 11:35:34 +0100664 }
665}
666
Xusong Wange9da9852020-01-13 11:44:45 -0800667void EvaluatePreparedCoupledModels(const sp<IDevice>& device,
668 const sp<IPreparedModel>& preparedModel,
Lev Proleev9226c1e2019-10-03 14:43:18 +0100669 const TestModel& testModel,
670 const sp<IPreparedModel>& preparedCoupledModel,
671 const TestModel& coupledModel) {
Lev Proleev56cda832019-12-05 14:49:47 +0000672 const std::vector<OutputType> outputTypesList = {OutputType::FULLY_SPECIFIED};
673 const std::vector<MeasureTiming> measureTimingList = {MeasureTiming::NO, MeasureTiming::YES};
674 const std::vector<Executor> executorList = {Executor::ASYNC, Executor::SYNC, Executor::BURST};
Lev Proleev9226c1e2019-10-03 14:43:18 +0100675
676 for (const OutputType outputType : outputTypesList) {
677 for (const MeasureTiming measureTiming : measureTimingList) {
678 for (const Executor executor : executorList) {
Xusong Wange9da9852020-01-13 11:44:45 -0800679 const TestConfig testConfig(executor, measureTiming, outputType, MemoryType::SHARED,
Lev Proleev9226c1e2019-10-03 14:43:18 +0100680 /*reportSkipping=*/false);
681 bool baseSkipped = false;
Xusong Wange9da9852020-01-13 11:44:45 -0800682 EvaluatePreparedModel(device, preparedModel, testModel, testConfig, &baseSkipped);
Lev Proleev9226c1e2019-10-03 14:43:18 +0100683 bool coupledSkipped = false;
Xusong Wange9da9852020-01-13 11:44:45 -0800684 EvaluatePreparedModel(device, preparedCoupledModel, coupledModel, testConfig,
Lev Proleev9226c1e2019-10-03 14:43:18 +0100685 &coupledSkipped);
686 ASSERT_EQ(baseSkipped, coupledSkipped);
687 if (baseSkipped) {
688 LOG(INFO) << "NN VTS: Early termination of test because vendor service cannot "
689 "execute model that it does not support.";
690 std::cout << "[ ] Early termination of test because vendor service "
691 "cannot "
692 "execute model that it does not support."
693 << std::endl;
694 GTEST_SKIP();
695 }
696 }
697 }
698 }
699}
700
701void Execute(const sp<IDevice>& device, const TestModel& testModel, TestKind testKind) {
Lev Proleev13fdfcd2019-08-30 11:35:34 +0100702 Model model = createModel(testModel);
Lev Proleev9226c1e2019-10-03 14:43:18 +0100703 if (testKind == TestKind::DYNAMIC_SHAPE) {
Lev Proleev13fdfcd2019-08-30 11:35:34 +0100704 makeOutputDimensionsUnspecified(&model);
705 }
706
707 sp<IPreparedModel> preparedModel;
Lev Proleev9226c1e2019-10-03 14:43:18 +0100708 switch (testKind) {
Xusong Wange9da9852020-01-13 11:44:45 -0800709 case TestKind::GENERAL:
710 case TestKind::DYNAMIC_SHAPE:
711 case TestKind::MEMORY_DOMAIN: {
Lev Proleev9226c1e2019-10-03 14:43:18 +0100712 createPreparedModel(device, model, &preparedModel);
713 if (preparedModel == nullptr) return;
Xusong Wange9da9852020-01-13 11:44:45 -0800714 EvaluatePreparedModel(device, preparedModel, testModel, testKind);
Lev Proleev9226c1e2019-10-03 14:43:18 +0100715 } break;
716 case TestKind::QUANTIZATION_COUPLING: {
Lev Proleev673fdcf2020-01-02 18:22:30 +0000717 ASSERT_TRUE(testModel.hasQuant8CoupledOperands());
Michael Butler95899b32020-01-07 14:52:44 -0800718 createPreparedModel(device, model, &preparedModel,
719 /*reportSkipping*/ false);
Lev Proleev9226c1e2019-10-03 14:43:18 +0100720 TestModel signedQuantizedModel = convertQuant8AsymmOperandsToSigned(testModel);
721 sp<IPreparedModel> preparedCoupledModel;
722 createPreparedModel(device, createModel(signedQuantizedModel), &preparedCoupledModel,
723 /*reportSkipping*/ false);
724 // If we couldn't prepare a model with unsigned quantization, we must
725 // fail to prepare a model with signed quantization as well.
726 if (preparedModel == nullptr) {
727 ASSERT_EQ(preparedCoupledModel, nullptr);
728 // If we failed to prepare both of the models, we can safely skip
729 // the test.
730 LOG(INFO) << "NN VTS: Early termination of test because vendor service cannot "
731 "prepare model that it does not support.";
732 std::cout
733 << "[ ] Early termination of test because vendor service cannot "
734 "prepare model that it does not support."
735 << std::endl;
736 GTEST_SKIP();
737 }
738 ASSERT_NE(preparedCoupledModel, nullptr);
Xusong Wange9da9852020-01-13 11:44:45 -0800739 EvaluatePreparedCoupledModels(device, preparedModel, testModel, preparedCoupledModel,
Lev Proleev9226c1e2019-10-03 14:43:18 +0100740 signedQuantizedModel);
741 } break;
742 }
Lev Proleev13fdfcd2019-08-30 11:35:34 +0100743}
744
745void GeneratedTestBase::SetUp() {
746 testing::TestWithParam<GeneratedTestParam>::SetUp();
747 ASSERT_NE(kDevice, nullptr);
Michael Butler95899b32020-01-07 14:52:44 -0800748
749 const Return<void> ret =
750 kDevice->supportsDeadlines([this](bool prepareModelDeadline, bool executionDeadline) {
751 mSupportsDeadlines = {prepareModelDeadline, executionDeadline};
752 });
753 ASSERT_TRUE(ret.isOk());
Lev Proleev13fdfcd2019-08-30 11:35:34 +0100754}
755
756std::vector<NamedModel> getNamedModels(const FilterFn& filter) {
757 return TestModelManager::get().getTestModels(filter);
758}
759
760std::string printGeneratedTest(const testing::TestParamInfo<GeneratedTestParam>& info) {
761 const auto& [namedDevice, namedModel] = info.param;
762 return gtestCompliantName(getName(namedDevice) + "_" + getName(namedModel));
763}
764
765// Tag for the generated tests
766class GeneratedTest : public GeneratedTestBase {};
767
768// Tag for the dynamic output shape tests
769class DynamicOutputShapeTest : public GeneratedTest {};
770
Xusong Wange9da9852020-01-13 11:44:45 -0800771// Tag for the memory domain tests
772class MemoryDomainTest : public GeneratedTest {};
773
Lev Proleev9226c1e2019-10-03 14:43:18 +0100774// Tag for the dynamic output shape tests
Lev Proleev3c68b342020-01-09 16:37:28 +0000775class QuantizationCouplingTest : public GeneratedTest {};
Lev Proleev9226c1e2019-10-03 14:43:18 +0100776
Lev Proleev13fdfcd2019-08-30 11:35:34 +0100777TEST_P(GeneratedTest, Test) {
Lev Proleev9226c1e2019-10-03 14:43:18 +0100778 Execute(kDevice, kTestModel, /*testKind=*/TestKind::GENERAL);
Lev Proleev13fdfcd2019-08-30 11:35:34 +0100779}
780
781TEST_P(DynamicOutputShapeTest, Test) {
Lev Proleev9226c1e2019-10-03 14:43:18 +0100782 Execute(kDevice, kTestModel, /*testKind=*/TestKind::DYNAMIC_SHAPE);
783}
784
Xusong Wange9da9852020-01-13 11:44:45 -0800785TEST_P(MemoryDomainTest, Test) {
786 Execute(kDevice, kTestModel, /*testKind=*/TestKind::MEMORY_DOMAIN);
787}
788
Lev Proleev3c68b342020-01-09 16:37:28 +0000789TEST_P(QuantizationCouplingTest, Test) {
Lev Proleev9226c1e2019-10-03 14:43:18 +0100790 Execute(kDevice, kTestModel, /*testKind=*/TestKind::QUANTIZATION_COUPLING);
Lev Proleev13fdfcd2019-08-30 11:35:34 +0100791}
792
793INSTANTIATE_GENERATED_TEST(GeneratedTest,
794 [](const TestModel& testModel) { return !testModel.expectFailure; });
795
Lev Proleev53a51cb2020-01-20 18:54:46 +0000796INSTANTIATE_GENERATED_TEST(DynamicOutputShapeTest, [](const TestModel& testModel) {
797 return !testModel.expectFailure && !testModel.hasScalarOutputs();
798});
Lev Proleev13fdfcd2019-08-30 11:35:34 +0100799
Xusong Wange9da9852020-01-13 11:44:45 -0800800INSTANTIATE_GENERATED_TEST(MemoryDomainTest,
801 [](const TestModel& testModel) { return !testModel.expectFailure; });
802
Lev Proleev3c68b342020-01-09 16:37:28 +0000803INSTANTIATE_GENERATED_TEST(QuantizationCouplingTest, [](const TestModel& testModel) {
Lev Proleev673fdcf2020-01-02 18:22:30 +0000804 return testModel.hasQuant8CoupledOperands() && testModel.operations.size() == 1;
Lev Proleev9226c1e2019-10-03 14:43:18 +0100805});
806
Lev Proleev26d1bc82019-08-30 11:57:18 +0100807} // namespace android::hardware::neuralnetworks::V1_3::vts::functional