blob: 82e63ac5463016ea2d162c30616c6e8618e71cfd [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"
Lev Proleev13fdfcd2019-08-30 11:35:34 +010048#include "ExecutionBurstController.h"
49#include "MemoryUtils.h"
50#include "TestHarness.h"
51#include "Utils.h"
52#include "VtsHalNeuralnetworks.h"
53
Lev Proleev26d1bc82019-08-30 11:57:18 +010054namespace android::hardware::neuralnetworks::V1_3::vts::functional {
Lev Proleev13fdfcd2019-08-30 11:35:34 +010055
56using namespace test_helper;
57using hidl::memory::V1_0::IMemory;
Michael Butler79a41d72019-12-11 19:08:08 -080058using implementation::ExecutionCallback;
Xusong Wangcc47dff2019-10-23 10:35:07 -070059using implementation::PreparedModelCallback;
Lev Proleev13fdfcd2019-08-30 11:35:34 +010060using V1_0::DataLocation;
Xusong Wange9da9852020-01-13 11:44:45 -080061using V1_0::RequestArgument;
Lev Proleev13fdfcd2019-08-30 11:35:34 +010062using V1_1::ExecutionPreference;
Lev Proleev26d1bc82019-08-30 11:57:18 +010063using V1_2::Constant;
Lev Proleev26d1bc82019-08-30 11:57:18 +010064using V1_2::MeasureTiming;
Lev Proleev26d1bc82019-08-30 11:57:18 +010065using V1_2::OutputShape;
66using V1_2::SymmPerChannelQuantParams;
67using V1_2::Timing;
Lev Proleev13fdfcd2019-08-30 11:35:34 +010068using HidlToken = hidl_array<uint8_t, static_cast<uint32_t>(Constant::BYTE_SIZE_OF_CACHE_TOKEN)>;
69
Lev Proleev0d4ba3f2019-10-02 17:32:06 +010070namespace {
71
72enum class Executor { ASYNC, SYNC, BURST };
73
Lev Proleev13fdfcd2019-08-30 11:35:34 +010074enum class OutputType { FULLY_SPECIFIED, UNSPECIFIED, INSUFFICIENT };
75
Xusong Wange9da9852020-01-13 11:44:45 -080076enum class MemoryType { SHARED, DEVICE };
77
78enum class IOType { INPUT, OUTPUT };
79
Lev Proleev0d4ba3f2019-10-02 17:32:06 +010080struct TestConfig {
81 Executor executor;
82 MeasureTiming measureTiming;
83 OutputType outputType;
Xusong Wange9da9852020-01-13 11:44:45 -080084 MemoryType memoryType;
Lev Proleev9226c1e2019-10-03 14:43:18 +010085 // `reportSkipping` indicates if a test should print an info message in case
86 // it is skipped. The field is set to true by default and is set to false in
87 // quantization coupling tests to suppress skipping a test
88 bool reportSkipping;
Xusong Wange9da9852020-01-13 11:44:45 -080089 TestConfig(Executor executor, MeasureTiming measureTiming, OutputType outputType,
90 MemoryType memoryType)
Lev Proleev9226c1e2019-10-03 14:43:18 +010091 : executor(executor),
92 measureTiming(measureTiming),
93 outputType(outputType),
Xusong Wange9da9852020-01-13 11:44:45 -080094 memoryType(memoryType),
Lev Proleev9226c1e2019-10-03 14:43:18 +010095 reportSkipping(true) {}
96 TestConfig(Executor executor, MeasureTiming measureTiming, OutputType outputType,
Xusong Wange9da9852020-01-13 11:44:45 -080097 MemoryType memoryType, bool reportSkipping)
Lev Proleev9226c1e2019-10-03 14:43:18 +010098 : executor(executor),
99 measureTiming(measureTiming),
100 outputType(outputType),
Xusong Wange9da9852020-01-13 11:44:45 -0800101 memoryType(memoryType),
Lev Proleev9226c1e2019-10-03 14:43:18 +0100102 reportSkipping(reportSkipping) {}
Lev Proleev0d4ba3f2019-10-02 17:32:06 +0100103};
104
Xusong Wange9da9852020-01-13 11:44:45 -0800105class DeviceMemoryAllocator {
106 public:
107 DeviceMemoryAllocator(const sp<IDevice>& device, const sp<IPreparedModel>& preparedModel,
108 const TestModel& testModel)
109 : kDevice(device), kPreparedModel(preparedModel), kTestModel(testModel) {}
110
111 // Allocate device memory for a target input/output operand.
112 // Return {IBuffer object, token} if successful.
113 // Return {nullptr, 0} if device memory is not supported.
114 template <IOType ioType>
115 std::pair<sp<IBuffer>, int32_t> allocate(uint32_t index) {
116 std::pair<sp<IBuffer>, int32_t> buffer;
117 allocateInternal<ioType>(index, &buffer);
118 return buffer;
119 }
120
121 private:
122 template <IOType ioType>
123 void allocateInternal(uint32_t index, std::pair<sp<IBuffer>, int32_t>* result) {
124 ASSERT_NE(result, nullptr);
125
126 // Prepare arguments.
127 BufferRole role = {.modelIndex = 0, .ioIndex = index, .frequency = 1.0f};
128 hidl_vec<BufferRole> inputRoles, outputRoles;
129 if constexpr (ioType == IOType::INPUT) {
130 inputRoles = {role};
131 } else {
132 outputRoles = {role};
133 }
134
135 // Allocate device memory.
136 ErrorStatus status;
137 sp<IBuffer> buffer;
138 int32_t token;
139 const auto ret = kDevice->allocate(
140 {}, {kPreparedModel}, inputRoles, outputRoles,
141 [&status, &buffer, &token](ErrorStatus error, const sp<IBuffer>& buf, int32_t tok) {
142 status = error;
143 buffer = buf;
144 token = tok;
145 });
146
147 // Check allocation results.
148 ASSERT_TRUE(ret.isOk());
149 if (status == ErrorStatus::NONE) {
150 ASSERT_NE(buffer, nullptr);
151 ASSERT_GT(token, 0);
152 } else {
153 ASSERT_EQ(status, ErrorStatus::GENERAL_FAILURE);
154 ASSERT_EQ(buffer, nullptr);
155 ASSERT_EQ(token, 0);
156 }
157
158 // Initialize input data from TestBuffer.
159 if constexpr (ioType == IOType::INPUT) {
160 if (buffer != nullptr) {
161 // TestBuffer -> Shared memory.
162 const auto& testBuffer = kTestModel.operands[kTestModel.inputIndexes[index]].data;
163 ASSERT_GT(testBuffer.size(), 0);
164 hidl_memory tmp = nn::allocateSharedMemory(testBuffer.size());
165 sp<IMemory> inputMemory = mapMemory(tmp);
166 ASSERT_NE(inputMemory.get(), nullptr);
167 uint8_t* inputPtr =
168 static_cast<uint8_t*>(static_cast<void*>(inputMemory->getPointer()));
169 ASSERT_NE(inputPtr, nullptr);
170 const uint8_t* begin = testBuffer.get<uint8_t>();
171 const uint8_t* end = begin + testBuffer.size();
172 std::copy(begin, end, inputPtr);
173
174 // Shared memory -> IBuffer.
175 auto ret = buffer->copyFrom(tmp, {});
176 ASSERT_TRUE(ret.isOk());
177 ASSERT_EQ(static_cast<ErrorStatus>(ret), ErrorStatus::NONE);
178 }
179 }
180 *result = {std::move(buffer), token};
181 }
182
183 const sp<IDevice> kDevice;
184 const sp<IPreparedModel> kPreparedModel;
185 const TestModel& kTestModel;
186};
187
Lev Proleev0d4ba3f2019-10-02 17:32:06 +0100188} // namespace
189
Lev Proleev13fdfcd2019-08-30 11:35:34 +0100190Model createModel(const TestModel& testModel) {
191 // Model operands.
192 hidl_vec<Operand> operands(testModel.operands.size());
193 size_t constCopySize = 0, constRefSize = 0;
194 for (uint32_t i = 0; i < testModel.operands.size(); i++) {
195 const auto& op = testModel.operands[i];
196
197 DataLocation loc = {};
198 if (op.lifetime == TestOperandLifeTime::CONSTANT_COPY) {
199 loc = {.poolIndex = 0,
200 .offset = static_cast<uint32_t>(constCopySize),
201 .length = static_cast<uint32_t>(op.data.size())};
202 constCopySize += op.data.alignedSize();
203 } else if (op.lifetime == TestOperandLifeTime::CONSTANT_REFERENCE) {
204 loc = {.poolIndex = 0,
205 .offset = static_cast<uint32_t>(constRefSize),
206 .length = static_cast<uint32_t>(op.data.size())};
207 constRefSize += op.data.alignedSize();
208 }
209
210 Operand::ExtraParams extraParams;
211 if (op.type == TestOperandType::TENSOR_QUANT8_SYMM_PER_CHANNEL) {
212 extraParams.channelQuant(SymmPerChannelQuantParams{
213 .scales = op.channelQuant.scales, .channelDim = op.channelQuant.channelDim});
214 }
215
216 operands[i] = {.type = static_cast<OperandType>(op.type),
217 .dimensions = op.dimensions,
218 .numberOfConsumers = op.numberOfConsumers,
219 .scale = op.scale,
220 .zeroPoint = op.zeroPoint,
221 .lifetime = static_cast<OperandLifeTime>(op.lifetime),
222 .location = loc,
223 .extraParams = std::move(extraParams)};
224 }
225
226 // Model operations.
227 hidl_vec<Operation> operations(testModel.operations.size());
228 std::transform(testModel.operations.begin(), testModel.operations.end(), operations.begin(),
229 [](const TestOperation& op) -> Operation {
230 return {.type = static_cast<OperationType>(op.type),
231 .inputs = op.inputs,
232 .outputs = op.outputs};
233 });
234
235 // Constant copies.
236 hidl_vec<uint8_t> operandValues(constCopySize);
237 for (uint32_t i = 0; i < testModel.operands.size(); i++) {
238 const auto& op = testModel.operands[i];
239 if (op.lifetime == TestOperandLifeTime::CONSTANT_COPY) {
240 const uint8_t* begin = op.data.get<uint8_t>();
241 const uint8_t* end = begin + op.data.size();
242 std::copy(begin, end, operandValues.data() + operands[i].location.offset);
243 }
244 }
245
246 // Shared memory.
247 hidl_vec<hidl_memory> pools = {};
248 if (constRefSize > 0) {
249 hidl_vec_push_back(&pools, nn::allocateSharedMemory(constRefSize));
250 CHECK_NE(pools[0].size(), 0u);
251
252 // load data
253 sp<IMemory> mappedMemory = mapMemory(pools[0]);
254 CHECK(mappedMemory.get() != nullptr);
255 uint8_t* mappedPtr =
256 reinterpret_cast<uint8_t*>(static_cast<void*>(mappedMemory->getPointer()));
257 CHECK(mappedPtr != nullptr);
258
259 for (uint32_t i = 0; i < testModel.operands.size(); i++) {
260 const auto& op = testModel.operands[i];
261 if (op.lifetime == TestOperandLifeTime::CONSTANT_REFERENCE) {
262 const uint8_t* begin = op.data.get<uint8_t>();
263 const uint8_t* end = begin + op.data.size();
264 std::copy(begin, end, mappedPtr + operands[i].location.offset);
265 }
266 }
267 }
268
Slava Shklyaevf8124a82019-12-13 12:24:35 +0000269 return {.main = {.operands = std::move(operands),
270 .operations = std::move(operations),
271 .inputIndexes = testModel.inputIndexes,
272 .outputIndexes = testModel.outputIndexes},
Lev Proleev13fdfcd2019-08-30 11:35:34 +0100273 .operandValues = std::move(operandValues),
274 .pools = std::move(pools),
275 .relaxComputationFloat32toFloat16 = testModel.isRelaxed};
276}
277
278static bool isOutputSizeGreaterThanOne(const TestModel& testModel, uint32_t index) {
279 const auto byteSize = testModel.operands[testModel.outputIndexes[index]].data.size();
280 return byteSize > 1u;
281}
282
Xusong Wange9da9852020-01-13 11:44:45 -0800283static void makeOutputInsufficientSize(uint32_t outputIndex, Request* request) {
Lev Proleev13fdfcd2019-08-30 11:35:34 +0100284 auto& length = request->outputs[outputIndex].location.length;
285 ASSERT_GT(length, 1u);
286 length -= 1u;
287}
288
289static void makeOutputDimensionsUnspecified(Model* model) {
Slava Shklyaevf8124a82019-12-13 12:24:35 +0000290 for (auto i : model->main.outputIndexes) {
291 auto& dims = model->main.operands[i].dimensions;
Lev Proleev13fdfcd2019-08-30 11:35:34 +0100292 std::fill(dims.begin(), dims.end(), 0);
293 }
294}
295
Xusong Wange9da9852020-01-13 11:44:45 -0800296constexpr uint32_t kInputPoolIndex = 0;
297constexpr uint32_t kOutputPoolIndex = 1;
298constexpr uint32_t kDeviceMemoryBeginIndex = 2;
299
300static std::pair<Request, std::vector<sp<IBuffer>>> createRequest(
301 const sp<IDevice>& device, const sp<IPreparedModel>& preparedModel,
302 const TestModel& testModel, bool preferDeviceMemory) {
303 // Memory pools are organized as:
304 // - 0: Input shared memory pool
305 // - 1: Output shared memory pool
306 // - [2, 2+i): Input device memories
307 // - [2+i, 2+i+o): Output device memories
308 DeviceMemoryAllocator allocator(device, preparedModel, testModel);
309 std::vector<sp<IBuffer>> buffers;
310 std::vector<int32_t> tokens;
311
312 // Model inputs.
313 hidl_vec<RequestArgument> inputs(testModel.inputIndexes.size());
314 size_t inputSize = 0;
315 for (uint32_t i = 0; i < testModel.inputIndexes.size(); i++) {
316 const auto& op = testModel.operands[testModel.inputIndexes[i]];
317 if (op.data.size() == 0) {
318 // Omitted input.
319 inputs[i] = {.hasNoValue = true};
320 continue;
321 } else if (preferDeviceMemory) {
322 SCOPED_TRACE("Input index = " + std::to_string(i));
323 auto [buffer, token] = allocator.allocate<IOType::INPUT>(i);
324 if (buffer != nullptr) {
325 DataLocation loc = {.poolIndex = static_cast<uint32_t>(buffers.size() +
326 kDeviceMemoryBeginIndex)};
327 buffers.push_back(std::move(buffer));
328 tokens.push_back(token);
329 inputs[i] = {.hasNoValue = false, .location = loc, .dimensions = {}};
330 continue;
331 }
332 }
333
334 // Reserve shared memory for input.
335 DataLocation loc = {.poolIndex = kInputPoolIndex,
336 .offset = static_cast<uint32_t>(inputSize),
337 .length = static_cast<uint32_t>(op.data.size())};
338 inputSize += op.data.alignedSize();
339 inputs[i] = {.hasNoValue = false, .location = loc, .dimensions = {}};
340 }
341
342 // Model outputs.
343 hidl_vec<RequestArgument> outputs(testModel.outputIndexes.size());
344 size_t outputSize = 0;
345 for (uint32_t i = 0; i < testModel.outputIndexes.size(); i++) {
346 const auto& op = testModel.operands[testModel.outputIndexes[i]];
347 if (preferDeviceMemory) {
348 SCOPED_TRACE("Output index = " + std::to_string(i));
349 auto [buffer, token] = allocator.allocate<IOType::OUTPUT>(i);
350 if (buffer != nullptr) {
351 DataLocation loc = {.poolIndex = static_cast<uint32_t>(buffers.size() +
352 kDeviceMemoryBeginIndex)};
353 buffers.push_back(std::move(buffer));
354 tokens.push_back(token);
355 outputs[i] = {.hasNoValue = false, .location = loc, .dimensions = {}};
356 continue;
357 }
358 }
359
360 // In the case of zero-sized output, we should at least provide a one-byte buffer.
361 // This is because zero-sized tensors are only supported internally to the driver, or
362 // reported in output shapes. It is illegal for the client to pre-specify a zero-sized
363 // tensor as model output. Otherwise, we will have two semantic conflicts:
364 // - "Zero dimension" conflicts with "unspecified dimension".
365 // - "Omitted operand buffer" conflicts with "zero-sized operand buffer".
366 size_t bufferSize = std::max<size_t>(op.data.size(), 1);
367
368 // Reserve shared memory for output.
369 DataLocation loc = {.poolIndex = kOutputPoolIndex,
370 .offset = static_cast<uint32_t>(outputSize),
371 .length = static_cast<uint32_t>(bufferSize)};
372 outputSize += op.data.size() == 0 ? TestBuffer::kAlignment : op.data.alignedSize();
373 outputs[i] = {.hasNoValue = false, .location = loc, .dimensions = {}};
374 }
375
376 // Memory pools.
377 hidl_vec<Request::MemoryPool> pools(kDeviceMemoryBeginIndex + buffers.size());
378 pools[kInputPoolIndex].hidlMemory(nn::allocateSharedMemory(std::max<size_t>(inputSize, 1)));
379 pools[kOutputPoolIndex].hidlMemory(nn::allocateSharedMemory(std::max<size_t>(outputSize, 1)));
380 CHECK_NE(pools[kInputPoolIndex].hidlMemory().size(), 0u);
381 CHECK_NE(pools[kOutputPoolIndex].hidlMemory().size(), 0u);
382 for (uint32_t i = 0; i < buffers.size(); i++) {
383 pools[kDeviceMemoryBeginIndex + i].token(tokens[i]);
384 }
385
386 // Copy input data to the input shared memory pool.
387 sp<IMemory> inputMemory = mapMemory(pools[kInputPoolIndex].hidlMemory());
388 CHECK(inputMemory.get() != nullptr);
389 uint8_t* inputPtr = static_cast<uint8_t*>(static_cast<void*>(inputMemory->getPointer()));
390 CHECK(inputPtr != nullptr);
391 for (uint32_t i = 0; i < testModel.inputIndexes.size(); i++) {
392 if (!inputs[i].hasNoValue && inputs[i].location.poolIndex == kInputPoolIndex) {
393 const auto& op = testModel.operands[testModel.inputIndexes[i]];
394 const uint8_t* begin = op.data.get<uint8_t>();
395 const uint8_t* end = begin + op.data.size();
396 std::copy(begin, end, inputPtr + inputs[i].location.offset);
397 }
398 }
399
400 Request request = {
401 .inputs = std::move(inputs), .outputs = std::move(outputs), .pools = std::move(pools)};
402 return {std::move(request), std::move(buffers)};
403}
404
405// Get a TestBuffer with data copied from an IBuffer object.
406static void getBuffer(const sp<IBuffer>& buffer, size_t size, TestBuffer* testBuffer) {
407 // IBuffer -> Shared memory.
408 hidl_memory tmp = nn::allocateSharedMemory(size);
409 const auto ret = buffer->copyTo(tmp);
410 ASSERT_TRUE(ret.isOk());
411 ASSERT_EQ(static_cast<ErrorStatus>(ret), ErrorStatus::NONE);
412
413 // Shared memory -> TestBuffer.
414 sp<IMemory> outputMemory = mapMemory(tmp);
415 ASSERT_NE(outputMemory.get(), nullptr);
416 uint8_t* outputPtr = static_cast<uint8_t*>(static_cast<void*>(outputMemory->getPointer()));
417 ASSERT_NE(outputPtr, nullptr);
418 ASSERT_NE(testBuffer, nullptr);
419 *testBuffer = TestBuffer(size, outputPtr);
420}
421
422static std::vector<TestBuffer> getOutputBuffers(const TestModel& testModel, const Request& request,
423 const std::vector<sp<IBuffer>>& buffers) {
424 sp<IMemory> outputMemory = mapMemory(request.pools[kOutputPoolIndex].hidlMemory());
425 CHECK(outputMemory.get() != nullptr);
426 uint8_t* outputPtr = static_cast<uint8_t*>(static_cast<void*>(outputMemory->getPointer()));
427 CHECK(outputPtr != nullptr);
428
429 // Copy out output results.
430 std::vector<TestBuffer> outputBuffers;
431 for (uint32_t i = 0; i < request.outputs.size(); i++) {
432 const auto& outputLoc = request.outputs[i].location;
433 if (outputLoc.poolIndex == kOutputPoolIndex) {
434 outputBuffers.emplace_back(outputLoc.length, outputPtr + outputLoc.offset);
435 } else {
436 const auto& op = testModel.operands[testModel.outputIndexes[i]];
437 if (op.data.size() == 0) {
438 outputBuffers.emplace_back();
439 } else {
440 SCOPED_TRACE("Output index = " + std::to_string(i));
441 const uint32_t bufferIndex = outputLoc.poolIndex - kDeviceMemoryBeginIndex;
442 TestBuffer buffer;
443 getBuffer(buffers[bufferIndex], op.data.size(), &buffer);
444 outputBuffers.push_back(std::move(buffer));
445 }
446 }
447 }
448 return outputBuffers;
449}
450
Lev Proleev13fdfcd2019-08-30 11:35:34 +0100451static Return<ErrorStatus> ExecutePreparedModel(const sp<IPreparedModel>& preparedModel,
452 const Request& request, MeasureTiming measure,
453 sp<ExecutionCallback>& callback) {
Michael Butler79a41d72019-12-11 19:08:08 -0800454 return preparedModel->execute_1_3(request, measure, {}, callback);
Lev Proleev13fdfcd2019-08-30 11:35:34 +0100455}
456static Return<ErrorStatus> ExecutePreparedModel(const sp<IPreparedModel>& preparedModel,
457 const Request& request, MeasureTiming measure,
458 hidl_vec<OutputShape>* outputShapes,
459 Timing* timing) {
460 ErrorStatus result;
Xusong Wangd4a060b2019-10-28 11:11:19 -0700461 Return<void> ret = preparedModel->executeSynchronously_1_3(
Michael Butler79a41d72019-12-11 19:08:08 -0800462 request, measure, {},
Lev Proleev13fdfcd2019-08-30 11:35:34 +0100463 [&result, outputShapes, timing](ErrorStatus error, const hidl_vec<OutputShape>& shapes,
464 const Timing& time) {
465 result = error;
466 *outputShapes = shapes;
467 *timing = time;
468 });
469 if (!ret.isOk()) {
470 return ErrorStatus::GENERAL_FAILURE;
471 }
472 return result;
473}
474static std::shared_ptr<::android::nn::ExecutionBurstController> CreateBurst(
475 const sp<IPreparedModel>& preparedModel) {
Michael Butler648ada52019-07-25 17:22:11 -0700476 return android::nn::ExecutionBurstController::create(preparedModel,
477 std::chrono::microseconds{0});
Lev Proleev13fdfcd2019-08-30 11:35:34 +0100478}
Lev Proleev13fdfcd2019-08-30 11:35:34 +0100479
Xusong Wange9da9852020-01-13 11:44:45 -0800480void EvaluatePreparedModel(const sp<IDevice>& device, const sp<IPreparedModel>& preparedModel,
481 const TestModel& testModel, const TestConfig& testConfig,
482 bool* skipped = nullptr) {
Lev Proleev9226c1e2019-10-03 14:43:18 +0100483 if (skipped != nullptr) {
484 *skipped = false;
485 }
Lev Proleev13fdfcd2019-08-30 11:35:34 +0100486 // If output0 does not have size larger than one byte, we can not test with insufficient buffer.
Lev Proleev0d4ba3f2019-10-02 17:32:06 +0100487 if (testConfig.outputType == OutputType::INSUFFICIENT &&
488 !isOutputSizeGreaterThanOne(testModel, 0)) {
Lev Proleev13fdfcd2019-08-30 11:35:34 +0100489 return;
490 }
491
Xusong Wange9da9852020-01-13 11:44:45 -0800492 auto [request, buffers] =
493 createRequest(device, preparedModel, testModel,
494 /*preferDeviceMemory=*/testConfig.memoryType == MemoryType::DEVICE);
495 // Skip if testing memory domain but no device memory has been allocated.
496 if (testConfig.memoryType == MemoryType::DEVICE && buffers.empty()) {
497 return;
Lev Proleev13fdfcd2019-08-30 11:35:34 +0100498 }
Xusong Wange9da9852020-01-13 11:44:45 -0800499 if (testConfig.outputType == OutputType::INSUFFICIENT) {
500 makeOutputInsufficientSize(/*outputIndex=*/0, &request);
501 }
Lev Proleev13fdfcd2019-08-30 11:35:34 +0100502
503 ErrorStatus executionStatus;
504 hidl_vec<OutputShape> outputShapes;
505 Timing timing;
Lev Proleev0d4ba3f2019-10-02 17:32:06 +0100506 switch (testConfig.executor) {
Lev Proleev13fdfcd2019-08-30 11:35:34 +0100507 case Executor::ASYNC: {
508 SCOPED_TRACE("asynchronous");
509
510 // launch execution
511 sp<ExecutionCallback> executionCallback = new ExecutionCallback();
Lev Proleev0d4ba3f2019-10-02 17:32:06 +0100512 Return<ErrorStatus> executionLaunchStatus = ExecutePreparedModel(
513 preparedModel, request, testConfig.measureTiming, executionCallback);
Lev Proleev13fdfcd2019-08-30 11:35:34 +0100514 ASSERT_TRUE(executionLaunchStatus.isOk());
515 EXPECT_EQ(ErrorStatus::NONE, static_cast<ErrorStatus>(executionLaunchStatus));
516
517 // retrieve execution status
518 executionCallback->wait();
519 executionStatus = executionCallback->getStatus();
520 outputShapes = executionCallback->getOutputShapes();
521 timing = executionCallback->getTiming();
522
523 break;
524 }
525 case Executor::SYNC: {
526 SCOPED_TRACE("synchronous");
527
528 // execute
Lev Proleev0d4ba3f2019-10-02 17:32:06 +0100529 Return<ErrorStatus> executionReturnStatus = ExecutePreparedModel(
530 preparedModel, request, testConfig.measureTiming, &outputShapes, &timing);
Lev Proleev13fdfcd2019-08-30 11:35:34 +0100531 ASSERT_TRUE(executionReturnStatus.isOk());
532 executionStatus = static_cast<ErrorStatus>(executionReturnStatus);
533
534 break;
535 }
536 case Executor::BURST: {
Xusong Wangb345a462019-11-27 12:46:48 -0800537 // TODO(butlermichael): Check if we need to test burst in V1_3 if the interface remains
538 // V1_2.
Lev Proleev13fdfcd2019-08-30 11:35:34 +0100539 SCOPED_TRACE("burst");
540
Xusong Wange9da9852020-01-13 11:44:45 -0800541 // check compliance
542 ASSERT_TRUE(nn::compliantWithV1_0(request));
543 V1_0::Request request10 = nn::convertToV1_0(request);
544
Lev Proleev13fdfcd2019-08-30 11:35:34 +0100545 // create burst
546 const std::shared_ptr<::android::nn::ExecutionBurstController> controller =
547 CreateBurst(preparedModel);
548 ASSERT_NE(nullptr, controller.get());
549
550 // create memory keys
Xusong Wangb345a462019-11-27 12:46:48 -0800551 std::vector<intptr_t> keys(request10.pools.size());
Lev Proleev13fdfcd2019-08-30 11:35:34 +0100552 for (size_t i = 0; i < keys.size(); ++i) {
Xusong Wangb345a462019-11-27 12:46:48 -0800553 keys[i] = reinterpret_cast<intptr_t>(&request10.pools[i]);
Lev Proleev13fdfcd2019-08-30 11:35:34 +0100554 }
555
556 // execute burst
Michael Butler648ada52019-07-25 17:22:11 -0700557 int n;
558 std::tie(n, outputShapes, timing, std::ignore) =
Xusong Wangb345a462019-11-27 12:46:48 -0800559 controller->compute(request10, testConfig.measureTiming, keys);
Michael Butler648ada52019-07-25 17:22:11 -0700560 executionStatus = nn::convertResultCodeToErrorStatus(n);
Lev Proleev13fdfcd2019-08-30 11:35:34 +0100561
562 break;
563 }
564 }
565
Lev Proleev0d4ba3f2019-10-02 17:32:06 +0100566 if (testConfig.outputType != OutputType::FULLY_SPECIFIED &&
Lev Proleev13fdfcd2019-08-30 11:35:34 +0100567 executionStatus == ErrorStatus::GENERAL_FAILURE) {
Lev Proleev9226c1e2019-10-03 14:43:18 +0100568 if (skipped != nullptr) {
569 *skipped = true;
570 }
571 if (!testConfig.reportSkipping) {
572 return;
573 }
Lev Proleev13fdfcd2019-08-30 11:35:34 +0100574 LOG(INFO) << "NN VTS: Early termination of test because vendor service cannot "
575 "execute model that it does not support.";
576 std::cout << "[ ] Early termination of test because vendor service cannot "
577 "execute model that it does not support."
578 << std::endl;
579 GTEST_SKIP();
580 }
Lev Proleev0d4ba3f2019-10-02 17:32:06 +0100581 if (testConfig.measureTiming == MeasureTiming::NO) {
Lev Proleev13fdfcd2019-08-30 11:35:34 +0100582 EXPECT_EQ(UINT64_MAX, timing.timeOnDevice);
583 EXPECT_EQ(UINT64_MAX, timing.timeInDriver);
584 } else {
585 if (timing.timeOnDevice != UINT64_MAX && timing.timeInDriver != UINT64_MAX) {
586 EXPECT_LE(timing.timeOnDevice, timing.timeInDriver);
587 }
588 }
589
Lev Proleev0d4ba3f2019-10-02 17:32:06 +0100590 switch (testConfig.outputType) {
Lev Proleev13fdfcd2019-08-30 11:35:34 +0100591 case OutputType::FULLY_SPECIFIED:
592 // If the model output operands are fully specified, outputShapes must be either
593 // either empty, or have the same number of elements as the number of outputs.
594 ASSERT_EQ(ErrorStatus::NONE, executionStatus);
595 ASSERT_TRUE(outputShapes.size() == 0 ||
596 outputShapes.size() == testModel.outputIndexes.size());
597 break;
598 case OutputType::UNSPECIFIED:
599 // If the model output operands are not fully specified, outputShapes must have
600 // the same number of elements as the number of outputs.
601 ASSERT_EQ(ErrorStatus::NONE, executionStatus);
602 ASSERT_EQ(outputShapes.size(), testModel.outputIndexes.size());
603 break;
604 case OutputType::INSUFFICIENT:
605 ASSERT_EQ(ErrorStatus::OUTPUT_INSUFFICIENT_SIZE, executionStatus);
606 ASSERT_EQ(outputShapes.size(), testModel.outputIndexes.size());
607 ASSERT_FALSE(outputShapes[0].isSufficient);
608 return;
609 }
610
611 // Go through all outputs, check returned output shapes.
612 for (uint32_t i = 0; i < outputShapes.size(); i++) {
613 EXPECT_TRUE(outputShapes[i].isSufficient);
614 const auto& expect = testModel.operands[testModel.outputIndexes[i]].dimensions;
615 const std::vector<uint32_t> actual = outputShapes[i].dimensions;
616 EXPECT_EQ(expect, actual);
617 }
618
619 // Retrieve execution results.
Xusong Wange9da9852020-01-13 11:44:45 -0800620 const std::vector<TestBuffer> outputs = getOutputBuffers(testModel, request, buffers);
Lev Proleev13fdfcd2019-08-30 11:35:34 +0100621
622 // We want "close-enough" results.
623 checkResults(testModel, outputs);
624}
625
Xusong Wange9da9852020-01-13 11:44:45 -0800626void EvaluatePreparedModel(const sp<IDevice>& device, const sp<IPreparedModel>& preparedModel,
627 const TestModel& testModel, TestKind testKind) {
Lev Proleev56cda832019-12-05 14:49:47 +0000628 std::vector<OutputType> outputTypesList;
629 std::vector<MeasureTiming> measureTimingList;
630 std::vector<Executor> executorList;
Xusong Wange9da9852020-01-13 11:44:45 -0800631 MemoryType memoryType = MemoryType::SHARED;
Lev Proleev0d4ba3f2019-10-02 17:32:06 +0100632
Lev Proleev9226c1e2019-10-03 14:43:18 +0100633 switch (testKind) {
634 case TestKind::GENERAL: {
635 outputTypesList = {OutputType::FULLY_SPECIFIED};
636 measureTimingList = {MeasureTiming::NO, MeasureTiming::YES};
637 executorList = {Executor::ASYNC, Executor::SYNC, Executor::BURST};
638 } break;
639 case TestKind::DYNAMIC_SHAPE: {
640 outputTypesList = {OutputType::UNSPECIFIED, OutputType::INSUFFICIENT};
641 measureTimingList = {MeasureTiming::NO, MeasureTiming::YES};
642 executorList = {Executor::ASYNC, Executor::SYNC, Executor::BURST};
643 } break;
Xusong Wange9da9852020-01-13 11:44:45 -0800644 case TestKind::MEMORY_DOMAIN: {
645 outputTypesList = {OutputType::FULLY_SPECIFIED};
646 measureTimingList = {MeasureTiming::NO};
647 executorList = {Executor::ASYNC, Executor::SYNC};
648 memoryType = MemoryType::DEVICE;
649 } break;
Lev Proleev9226c1e2019-10-03 14:43:18 +0100650 case TestKind::QUANTIZATION_COUPLING: {
651 LOG(FATAL) << "Wrong TestKind for EvaluatePreparedModel";
652 return;
653 } break;
Lev Proleev0d4ba3f2019-10-02 17:32:06 +0100654 }
655
656 for (const OutputType outputType : outputTypesList) {
657 for (const MeasureTiming measureTiming : measureTimingList) {
658 for (const Executor executor : executorList) {
Xusong Wange9da9852020-01-13 11:44:45 -0800659 const TestConfig testConfig(executor, measureTiming, outputType, memoryType);
660 EvaluatePreparedModel(device, preparedModel, testModel, testConfig);
Lev Proleev0d4ba3f2019-10-02 17:32:06 +0100661 }
662 }
Lev Proleev13fdfcd2019-08-30 11:35:34 +0100663 }
664}
665
Xusong Wange9da9852020-01-13 11:44:45 -0800666void EvaluatePreparedCoupledModels(const sp<IDevice>& device,
667 const sp<IPreparedModel>& preparedModel,
Lev Proleev9226c1e2019-10-03 14:43:18 +0100668 const TestModel& testModel,
669 const sp<IPreparedModel>& preparedCoupledModel,
670 const TestModel& coupledModel) {
Lev Proleev56cda832019-12-05 14:49:47 +0000671 const std::vector<OutputType> outputTypesList = {OutputType::FULLY_SPECIFIED};
672 const std::vector<MeasureTiming> measureTimingList = {MeasureTiming::NO, MeasureTiming::YES};
673 const std::vector<Executor> executorList = {Executor::ASYNC, Executor::SYNC, Executor::BURST};
Lev Proleev9226c1e2019-10-03 14:43:18 +0100674
675 for (const OutputType outputType : outputTypesList) {
676 for (const MeasureTiming measureTiming : measureTimingList) {
677 for (const Executor executor : executorList) {
Xusong Wange9da9852020-01-13 11:44:45 -0800678 const TestConfig testConfig(executor, measureTiming, outputType, MemoryType::SHARED,
Lev Proleev9226c1e2019-10-03 14:43:18 +0100679 /*reportSkipping=*/false);
680 bool baseSkipped = false;
Xusong Wange9da9852020-01-13 11:44:45 -0800681 EvaluatePreparedModel(device, preparedModel, testModel, testConfig, &baseSkipped);
Lev Proleev9226c1e2019-10-03 14:43:18 +0100682 bool coupledSkipped = false;
Xusong Wange9da9852020-01-13 11:44:45 -0800683 EvaluatePreparedModel(device, preparedCoupledModel, coupledModel, testConfig,
Lev Proleev9226c1e2019-10-03 14:43:18 +0100684 &coupledSkipped);
685 ASSERT_EQ(baseSkipped, coupledSkipped);
686 if (baseSkipped) {
687 LOG(INFO) << "NN VTS: Early termination of test because vendor service cannot "
688 "execute model that it does not support.";
689 std::cout << "[ ] Early termination of test because vendor service "
690 "cannot "
691 "execute model that it does not support."
692 << std::endl;
693 GTEST_SKIP();
694 }
695 }
696 }
697 }
698}
699
700void Execute(const sp<IDevice>& device, const TestModel& testModel, TestKind testKind) {
Lev Proleev13fdfcd2019-08-30 11:35:34 +0100701 Model model = createModel(testModel);
Lev Proleev9226c1e2019-10-03 14:43:18 +0100702 if (testKind == TestKind::DYNAMIC_SHAPE) {
Lev Proleev13fdfcd2019-08-30 11:35:34 +0100703 makeOutputDimensionsUnspecified(&model);
704 }
705
706 sp<IPreparedModel> preparedModel;
Lev Proleev9226c1e2019-10-03 14:43:18 +0100707 switch (testKind) {
Xusong Wange9da9852020-01-13 11:44:45 -0800708 case TestKind::GENERAL:
709 case TestKind::DYNAMIC_SHAPE:
710 case TestKind::MEMORY_DOMAIN: {
Lev Proleev9226c1e2019-10-03 14:43:18 +0100711 createPreparedModel(device, model, &preparedModel);
712 if (preparedModel == nullptr) return;
Xusong Wange9da9852020-01-13 11:44:45 -0800713 EvaluatePreparedModel(device, preparedModel, testModel, testKind);
Lev Proleev9226c1e2019-10-03 14:43:18 +0100714 } break;
715 case TestKind::QUANTIZATION_COUPLING: {
Lev Proleev673fdcf2020-01-02 18:22:30 +0000716 ASSERT_TRUE(testModel.hasQuant8CoupledOperands());
Lev Proleev9226c1e2019-10-03 14:43:18 +0100717 createPreparedModel(device, model, &preparedModel, /*reportSkipping*/ false);
718 TestModel signedQuantizedModel = convertQuant8AsymmOperandsToSigned(testModel);
719 sp<IPreparedModel> preparedCoupledModel;
720 createPreparedModel(device, createModel(signedQuantizedModel), &preparedCoupledModel,
721 /*reportSkipping*/ false);
722 // If we couldn't prepare a model with unsigned quantization, we must
723 // fail to prepare a model with signed quantization as well.
724 if (preparedModel == nullptr) {
725 ASSERT_EQ(preparedCoupledModel, nullptr);
726 // If we failed to prepare both of the models, we can safely skip
727 // the test.
728 LOG(INFO) << "NN VTS: Early termination of test because vendor service cannot "
729 "prepare model that it does not support.";
730 std::cout
731 << "[ ] Early termination of test because vendor service cannot "
732 "prepare model that it does not support."
733 << std::endl;
734 GTEST_SKIP();
735 }
736 ASSERT_NE(preparedCoupledModel, nullptr);
Xusong Wange9da9852020-01-13 11:44:45 -0800737 EvaluatePreparedCoupledModels(device, preparedModel, testModel, preparedCoupledModel,
Lev Proleev9226c1e2019-10-03 14:43:18 +0100738 signedQuantizedModel);
739 } break;
740 }
Lev Proleev13fdfcd2019-08-30 11:35:34 +0100741}
742
743void GeneratedTestBase::SetUp() {
744 testing::TestWithParam<GeneratedTestParam>::SetUp();
745 ASSERT_NE(kDevice, nullptr);
746}
747
748std::vector<NamedModel> getNamedModels(const FilterFn& filter) {
749 return TestModelManager::get().getTestModels(filter);
750}
751
752std::string printGeneratedTest(const testing::TestParamInfo<GeneratedTestParam>& info) {
753 const auto& [namedDevice, namedModel] = info.param;
754 return gtestCompliantName(getName(namedDevice) + "_" + getName(namedModel));
755}
756
757// Tag for the generated tests
758class GeneratedTest : public GeneratedTestBase {};
759
760// Tag for the dynamic output shape tests
761class DynamicOutputShapeTest : public GeneratedTest {};
762
Xusong Wange9da9852020-01-13 11:44:45 -0800763// Tag for the memory domain tests
764class MemoryDomainTest : public GeneratedTest {};
765
Lev Proleev9226c1e2019-10-03 14:43:18 +0100766// Tag for the dynamic output shape tests
Lev Proleev3c68b342020-01-09 16:37:28 +0000767class QuantizationCouplingTest : public GeneratedTest {};
Lev Proleev9226c1e2019-10-03 14:43:18 +0100768
Lev Proleev13fdfcd2019-08-30 11:35:34 +0100769TEST_P(GeneratedTest, Test) {
Lev Proleev9226c1e2019-10-03 14:43:18 +0100770 Execute(kDevice, kTestModel, /*testKind=*/TestKind::GENERAL);
Lev Proleev13fdfcd2019-08-30 11:35:34 +0100771}
772
773TEST_P(DynamicOutputShapeTest, Test) {
Lev Proleev9226c1e2019-10-03 14:43:18 +0100774 Execute(kDevice, kTestModel, /*testKind=*/TestKind::DYNAMIC_SHAPE);
775}
776
Xusong Wange9da9852020-01-13 11:44:45 -0800777TEST_P(MemoryDomainTest, Test) {
778 Execute(kDevice, kTestModel, /*testKind=*/TestKind::MEMORY_DOMAIN);
779}
780
Lev Proleev3c68b342020-01-09 16:37:28 +0000781TEST_P(QuantizationCouplingTest, Test) {
Lev Proleev9226c1e2019-10-03 14:43:18 +0100782 Execute(kDevice, kTestModel, /*testKind=*/TestKind::QUANTIZATION_COUPLING);
Lev Proleev13fdfcd2019-08-30 11:35:34 +0100783}
784
785INSTANTIATE_GENERATED_TEST(GeneratedTest,
786 [](const TestModel& testModel) { return !testModel.expectFailure; });
787
788INSTANTIATE_GENERATED_TEST(DynamicOutputShapeTest,
789 [](const TestModel& testModel) { return !testModel.expectFailure; });
790
Xusong Wange9da9852020-01-13 11:44:45 -0800791INSTANTIATE_GENERATED_TEST(MemoryDomainTest,
792 [](const TestModel& testModel) { return !testModel.expectFailure; });
793
Lev Proleev3c68b342020-01-09 16:37:28 +0000794INSTANTIATE_GENERATED_TEST(QuantizationCouplingTest, [](const TestModel& testModel) {
Lev Proleev673fdcf2020-01-02 18:22:30 +0000795 return testModel.hasQuant8CoupledOperands() && testModel.operations.size() == 1;
Lev Proleev9226c1e2019-10-03 14:43:18 +0100796});
797
Lev Proleev26d1bc82019-08-30 11:57:18 +0100798} // namespace android::hardware::neuralnetworks::V1_3::vts::functional