1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
|
/*
* Copyright (C) 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "Burst.h"
#include <android-base/logging.h>
#include <nnapi/IBurst.h>
#include <nnapi/Result.h>
#include <nnapi/TypeUtils.h>
#include <nnapi/Types.h>
#include <nnapi/Validation.h>
#include <nnapi/hal/1.0/Conversions.h>
#include <nnapi/hal/1.0/HandleError.h>
#include <nnapi/hal/1.0/ProtectCallback.h>
#include <nnapi/hal/1.2/BurstUtils.h>
#include <nnapi/hal/1.2/Conversions.h>
#include <nnapi/hal/TransferValue.h>
#include <algorithm>
#include <cstring>
#include <limits>
#include <map>
#include <memory>
#include <tuple>
#include <utility>
#include <vector>
#include "Tracing.h"
namespace android::hardware::neuralnetworks::adapter {
namespace {
constexpr V1_2::Timing kTiming = {std::numeric_limits<uint64_t>::max(),
std::numeric_limits<uint64_t>::max()};
nn::GeneralResult<std::vector<nn::SharedMemory>> getMemoriesCallback(
V1_0::ErrorStatus status, const hidl_vec<hidl_memory>& memories) {
HANDLE_STATUS_HIDL(status) << "getting burst memories failed with " << toString(status);
std::vector<nn::SharedMemory> canonicalMemories;
canonicalMemories.reserve(memories.size());
for (const auto& memory : memories) {
canonicalMemories.push_back(NN_TRY(nn::convert(memory)));
}
return canonicalMemories;
}
} // anonymous namespace
Burst::MemoryCache::MemoryCache(nn::SharedBurst burstExecutor,
sp<V1_2::IBurstCallback> burstCallback)
: kBurstExecutor(std::move(burstExecutor)), kBurstCallback(std::move(burstCallback)) {
CHECK(kBurstExecutor != nullptr);
CHECK(kBurstCallback != nullptr);
}
nn::GeneralResult<std::vector<std::pair<nn::SharedMemory, nn::IBurst::OptionalCacheHold>>>
Burst::MemoryCache::getCacheEntries(const std::vector<int32_t>& slots) {
std::lock_guard guard(mMutex);
NN_TRY(ensureCacheEntriesArePresentLocked(slots));
std::vector<std::pair<nn::SharedMemory, nn::IBurst::OptionalCacheHold>> results;
results.reserve(slots.size());
for (int32_t slot : slots) {
results.push_back(NN_TRY(getCacheEntryLocked(slot)));
}
return results;
}
nn::GeneralResult<void> Burst::MemoryCache::ensureCacheEntriesArePresentLocked(
const std::vector<int32_t>& slots) {
const auto slotIsKnown = [this](int32_t slot)
REQUIRES(mMutex) { return mCache.count(slot) > 0; };
// find unique unknown slots
std::vector<int32_t> unknownSlots = slots;
std::sort(unknownSlots.begin(), unknownSlots.end());
auto unknownSlotsEnd = std::unique(unknownSlots.begin(), unknownSlots.end());
unknownSlotsEnd = std::remove_if(unknownSlots.begin(), unknownSlotsEnd, slotIsKnown);
unknownSlots.erase(unknownSlotsEnd, unknownSlots.end());
// quick-exit if all slots are known
if (unknownSlots.empty()) {
return {};
}
auto cb = neuralnetworks::utils::CallbackValue(getMemoriesCallback);
const auto ret = kBurstCallback->getMemories(unknownSlots, cb);
HANDLE_TRANSPORT_FAILURE(ret);
auto returnedMemories = NN_TRY(cb.take());
if (returnedMemories.size() != unknownSlots.size()) {
return NN_ERROR() << "Burst::MemoryCache::ensureCacheEntriesArePresentLocked: Error "
"retrieving memories -- count mismatch between requested memories ("
<< unknownSlots.size() << ") and returned memories ("
<< returnedMemories.size() << ")";
}
// add memories to unknown slots
for (size_t i = 0; i < unknownSlots.size(); ++i) {
addCacheEntryLocked(unknownSlots[i], std::move(returnedMemories[i]));
}
return {};
}
nn::GeneralResult<std::pair<nn::SharedMemory, nn::IBurst::OptionalCacheHold>>
Burst::MemoryCache::getCacheEntryLocked(int32_t slot) {
if (const auto iter = mCache.find(slot); iter != mCache.end()) {
return iter->second;
}
return NN_ERROR() << "Burst::MemoryCache::getCacheEntryLocked failed because slot " << slot
<< " is not present in the cache";
}
void Burst::MemoryCache::addCacheEntryLocked(int32_t slot, nn::SharedMemory memory) {
auto hold = kBurstExecutor->cacheMemory(memory);
mCache.emplace(slot, std::make_pair(std::move(memory), std::move(hold)));
}
void Burst::MemoryCache::removeCacheEntry(int32_t slot) {
std::lock_guard guard(mMutex);
mCache.erase(slot);
}
// Burst methods
nn::GeneralResult<sp<Burst>> Burst::create(
const sp<V1_2::IBurstCallback>& callback,
const MQDescriptorSync<V1_2::FmqRequestDatum>& requestChannel,
const MQDescriptorSync<V1_2::FmqResultDatum>& resultChannel, nn::SharedBurst burstExecutor,
std::chrono::microseconds pollingTimeWindow) {
// check inputs
if (callback == nullptr || burstExecutor == nullptr) {
return NN_ERROR() << "Burst::create passed a nullptr";
}
// create FMQ objects
auto requestChannelReceiver =
NN_TRY(V1_2::utils::RequestChannelReceiver::create(requestChannel, pollingTimeWindow));
auto resultChannelSender = NN_TRY(V1_2::utils::ResultChannelSender::create(resultChannel));
// check FMQ objects
CHECK(requestChannelReceiver != nullptr);
CHECK(resultChannelSender != nullptr);
// make and return context
return sp<Burst>::make(PrivateConstructorTag{}, callback, std::move(requestChannelReceiver),
std::move(resultChannelSender), std::move(burstExecutor));
}
Burst::Burst(PrivateConstructorTag /*tag*/, const sp<V1_2::IBurstCallback>& callback,
std::unique_ptr<V1_2::utils::RequestChannelReceiver> requestChannel,
std::unique_ptr<V1_2::utils::ResultChannelSender> resultChannel,
nn::SharedBurst burstExecutor)
: mCallback(callback),
mRequestChannelReceiver(std::move(requestChannel)),
mResultChannelSender(std::move(resultChannel)),
mBurstExecutor(std::move(burstExecutor)),
mMemoryCache(mBurstExecutor, mCallback) {
// TODO: highly document the threading behavior of this class
mWorker = std::thread([this] { task(); });
}
Burst::~Burst() {
// set teardown flag
mTeardown = true;
mRequestChannelReceiver->invalidate();
// wait for task thread to end
mWorker.join();
}
Return<void> Burst::freeMemory(int32_t slot) {
mMemoryCache.removeCacheEntry(slot);
return Void();
}
void Burst::task() {
// loop until the burst object is being destroyed
while (!mTeardown) {
// receive request
auto arguments = mRequestChannelReceiver->getBlocking();
// if the request packet was not properly received, return a generic error and skip the
// execution
//
// if the burst is being torn down, skip the execution so the "task" function can end
if (!arguments.has_value()) {
if (!mTeardown) {
mResultChannelSender->send(V1_0::ErrorStatus::GENERAL_FAILURE, {}, kTiming);
}
continue;
}
// unpack the arguments; types are Request, std::vector<int32_t>, and V1_2::MeasureTiming,
// respectively
const auto [requestWithoutPools, slotsOfPools, measure] = std::move(arguments).value();
auto result = execute(requestWithoutPools, slotsOfPools, measure);
// return result
if (result.has_value()) {
const auto& [outputShapes, timing] = result.value();
mResultChannelSender->send(V1_0::ErrorStatus::NONE, outputShapes, timing);
} else {
const auto& [message, code, outputShapes] = result.error();
LOG(ERROR) << "IBurst::execute failed with " << code << ": " << message;
mResultChannelSender->send(V1_2::utils::convert(code).value(),
V1_2::utils::convert(outputShapes).value(), kTiming);
}
}
}
nn::ExecutionResult<std::pair<hidl_vec<V1_2::OutputShape>, V1_2::Timing>> Burst::execute(
const V1_0::Request& requestWithoutPools, const std::vector<int32_t>& slotsOfPools,
V1_2::MeasureTiming measure) {
NNTRACE_FULL(NNTRACE_LAYER_IPC, NNTRACE_PHASE_EXECUTION,
"Burst getting memory, executing, and returning results");
// ensure executor with cache has required memory
const auto cacheEntries = NN_TRY(mMemoryCache.getCacheEntries(slotsOfPools));
// convert request, populating its pools
// This code performs an unvalidated convert because the request object without its pools is
// invalid because it is incomplete. Instead, the validation is performed after the memory pools
// have been added to the request.
auto canonicalRequest = NN_TRY(nn::unvalidatedConvert(requestWithoutPools));
CHECK(canonicalRequest.pools.empty());
std::transform(cacheEntries.begin(), cacheEntries.end(),
std::back_inserter(canonicalRequest.pools),
[](const auto& cacheEntry) { return cacheEntry.first; });
NN_TRY(validate(canonicalRequest));
nn::MeasureTiming canonicalMeasure = NN_TRY(nn::convert(measure));
const auto [outputShapes, timing] =
NN_TRY(mBurstExecutor->execute(canonicalRequest, canonicalMeasure, {}, {}));
return std::make_pair(NN_TRY(V1_2::utils::convert(outputShapes)),
NN_TRY(V1_2::utils::convert(timing)));
}
} // namespace android::hardware::neuralnetworks::adapter
|