1 /*
2  * Copyright (C) 2018 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #define LOG_TAG "neuralnetworks_hidl_hal_test"
18 
19 #include "VtsHalNeuralnetworks.h"
20 #include <android-base/logging.h>
21 #include <hidl/ServiceManagement.h>
22 #include <string>
23 #include <utility>
24 #include "1.0/Utils.h"
25 #include "1.3/Callbacks.h"
26 #include "1.3/Utils.h"
27 #include "GeneratedTestHarness.h"
28 #include "TestHarness.h"
29 #include "Utils.h"
30 
31 namespace android::hardware::neuralnetworks::V1_3::vts::functional {
32 
33 using HidlToken =
34         hidl_array<uint8_t, static_cast<uint32_t>(V1_2::Constant::BYTE_SIZE_OF_CACHE_TOKEN)>;
35 using implementation::PreparedModelCallback;
36 using V1_1::ExecutionPreference;
37 
38 // internal helper function
createPreparedModel(const sp<IDevice> & device,const Model & model,sp<IPreparedModel> * preparedModel,bool reportSkipping)39 void createPreparedModel(const sp<IDevice>& device, const Model& model,
40                          sp<IPreparedModel>* preparedModel, bool reportSkipping) {
41     ASSERT_NE(nullptr, preparedModel);
42     *preparedModel = nullptr;
43 
44     // see if service can handle model
45     bool fullySupportsModel = false;
46     const Return<void> supportedCall = device->getSupportedOperations_1_3(
47             model, [&fullySupportsModel](ErrorStatus status, const hidl_vec<bool>& supported) {
48                 ASSERT_EQ(ErrorStatus::NONE, status);
49                 ASSERT_NE(0ul, supported.size());
50                 fullySupportsModel = std::all_of(supported.begin(), supported.end(),
51                                                  [](bool valid) { return valid; });
52             });
53     ASSERT_TRUE(supportedCall.isOk());
54 
55     // launch prepare model
56     const sp<PreparedModelCallback> preparedModelCallback = new PreparedModelCallback();
57     const Return<ErrorStatus> prepareLaunchStatus = device->prepareModel_1_3(
58             model, ExecutionPreference::FAST_SINGLE_ANSWER, kDefaultPriority, {},
59             hidl_vec<hidl_handle>(), hidl_vec<hidl_handle>(), HidlToken(), preparedModelCallback);
60     ASSERT_TRUE(prepareLaunchStatus.isOk());
61     ASSERT_EQ(ErrorStatus::NONE, static_cast<ErrorStatus>(prepareLaunchStatus));
62 
63     // retrieve prepared model
64     preparedModelCallback->wait();
65     const ErrorStatus prepareReturnStatus = preparedModelCallback->getStatus();
66     *preparedModel = getPreparedModel_1_3(preparedModelCallback);
67 
68     // The getSupportedOperations_1_3 call returns a list of operations that are
69     // guaranteed not to fail if prepareModel_1_3 is called, and
70     // 'fullySupportsModel' is true i.f.f. the entire model is guaranteed.
71     // If a driver has any doubt that it can prepare an operation, it must
72     // return false. So here, if a driver isn't sure if it can support an
73     // operation, but reports that it successfully prepared the model, the test
74     // can continue.
75     if (!fullySupportsModel && prepareReturnStatus != ErrorStatus::NONE) {
76         ASSERT_EQ(nullptr, preparedModel->get());
77         if (!reportSkipping) {
78             return;
79         }
80         LOG(INFO) << "NN VTS: Early termination of test because vendor service cannot prepare "
81                      "model that it does not support.";
82         std::cout << "[          ]   Early termination of test because vendor service cannot "
83                      "prepare model that it does not support."
84                   << std::endl;
85         GTEST_SKIP();
86     }
87 
88     ASSERT_EQ(ErrorStatus::NONE, prepareReturnStatus);
89     ASSERT_NE(nullptr, preparedModel->get());
90 }
91 
SetUp()92 void NeuralnetworksHidlTest::SetUp() {
93     testing::TestWithParam<NeuralnetworksHidlTestParam>::SetUp();
94     ASSERT_NE(kDevice, nullptr);
95 }
96 
makeNamedDevice(const std::string & name)97 static NamedDevice makeNamedDevice(const std::string& name) {
98     return {name, IDevice::getService(name)};
99 }
100 
getNamedDevicesImpl()101 static std::vector<NamedDevice> getNamedDevicesImpl() {
102     // Retrieves the name of all service instances that implement IDevice,
103     // including any Lazy HAL instances.
104     const std::vector<std::string> names = hardware::getAllHalInstanceNames(IDevice::descriptor);
105 
106     // Get a handle to each device and pair it with its name.
107     std::vector<NamedDevice> namedDevices;
108     namedDevices.reserve(names.size());
109     std::transform(names.begin(), names.end(), std::back_inserter(namedDevices), makeNamedDevice);
110     return namedDevices;
111 }
112 
getNamedDevices()113 const std::vector<NamedDevice>& getNamedDevices() {
114     const static std::vector<NamedDevice> devices = getNamedDevicesImpl();
115     return devices;
116 }
117 
printNeuralnetworksHidlTest(const testing::TestParamInfo<NeuralnetworksHidlTestParam> & info)118 std::string printNeuralnetworksHidlTest(
119         const testing::TestParamInfo<NeuralnetworksHidlTestParam>& info) {
120     return gtestCompliantName(getName(info.param));
121 }
122 
123 INSTANTIATE_DEVICE_TEST(NeuralnetworksHidlTest);
124 
125 // Forward declaration from ValidateModel.cpp
126 void validateModel(const sp<IDevice>& device, const Model& model);
127 // Forward declaration from ValidateRequest.cpp
128 void validateRequest(const sp<IPreparedModel>& preparedModel, const Request& request);
129 // Forward declaration from ValidateRequest.cpp
130 void validateRequestFailure(const sp<IPreparedModel>& preparedModel, const Request& request);
131 // Forward declaration from ValidateBurst.cpp
132 void validateBurst(const sp<IPreparedModel>& preparedModel, const V1_0::Request& request);
133 
134 // Validate sync_fence handles for dispatch with valid input
validateExecuteFenced(const sp<IPreparedModel> & preparedModel,const Request & request)135 void validateExecuteFenced(const sp<IPreparedModel>& preparedModel, const Request& request) {
136     SCOPED_TRACE("Expecting request to fail [executeFenced]");
137     Return<void> ret_null = preparedModel->executeFenced(
138             request, {hidl_handle(nullptr)}, V1_2::MeasureTiming::NO, {}, {}, {},
139             [](ErrorStatus error, const hidl_handle& handle,
140                const sp<IFencedExecutionCallback>& callback) {
141                 ASSERT_EQ(ErrorStatus::INVALID_ARGUMENT, error);
142                 ASSERT_EQ(handle.getNativeHandle(), nullptr);
143                 ASSERT_EQ(callback, nullptr);
144             });
145     ASSERT_TRUE(ret_null.isOk());
146 }
147 
validateEverything(const sp<IDevice> & device,const Model & model,const Request & request)148 void validateEverything(const sp<IDevice>& device, const Model& model, const Request& request) {
149     validateModel(device, model);
150 
151     // Create IPreparedModel.
152     sp<IPreparedModel> preparedModel;
153     createPreparedModel(device, model, &preparedModel);
154     if (preparedModel == nullptr) return;
155 
156     validateRequest(preparedModel, request);
157     validateExecuteFenced(preparedModel, request);
158 
159     // TODO(butlermichael): Check if we need to test burst in V1_3 if the interface remains V1_2.
160     ASSERT_TRUE(nn::compliantWithV1_0(request));
161     V1_0::Request request10 = nn::convertToV1_0(request);
162     validateBurst(preparedModel, request10);
163 }
164 
validateFailure(const sp<IDevice> & device,const Model & model,const Request & request)165 void validateFailure(const sp<IDevice>& device, const Model& model, const Request& request) {
166     // TODO: Should this always succeed?
167     //       What if the invalid input is part of the model (i.e., a parameter).
168     validateModel(device, model);
169 
170     // Create IPreparedModel.
171     sp<IPreparedModel> preparedModel;
172     createPreparedModel(device, model, &preparedModel);
173     if (preparedModel == nullptr) return;
174 
175     validateRequestFailure(preparedModel, request);
176 }
177 
TEST_P(ValidationTest,Test)178 TEST_P(ValidationTest, Test) {
179     const Model model = createModel(kTestModel);
180     ExecutionContext context;
181     const Request request = nn::convertToV1_3(context.createRequest(kTestModel));
182     if (kTestModel.expectFailure) {
183         validateFailure(kDevice, model, request);
184     } else {
185         validateEverything(kDevice, model, request);
186     }
187 }
188 
__anon0223bf380402(const std::string& testName) 189 INSTANTIATE_GENERATED_TEST(ValidationTest, [](const std::string& testName) {
190     // Skip validation for the "inputs_as_internal" and "all_tensors_as_inputs"
191     // generated tests.
192     return testName.find("inputs_as_internal") == std::string::npos &&
193            testName.find("all_tensors_as_inputs") == std::string::npos;
194 });
195 
getPreparedModel_1_3(const sp<PreparedModelCallback> & callback)196 sp<IPreparedModel> getPreparedModel_1_3(const sp<PreparedModelCallback>& callback) {
197     sp<V1_0::IPreparedModel> preparedModelV1_0 = callback->getPreparedModel();
198     return IPreparedModel::castFrom(preparedModelV1_0).withDefault(nullptr);
199 }
200 
toString(Executor executor)201 std::string toString(Executor executor) {
202     switch (executor) {
203         case Executor::ASYNC:
204             return "ASYNC";
205         case Executor::SYNC:
206             return "SYNC";
207         case Executor::BURST:
208             return "BURST";
209         case Executor::FENCED:
210             return "FENCED";
211         default:
212             CHECK(false);
213     }
214 }
215 
216 }  // namespace android::hardware::neuralnetworks::V1_3::vts::functional
217