blob: 347e39b4c8d2967ccf6e9d9e3037474753dd0e72 [file] [log] [blame]
Laurent Carlier749294b2020-06-01 09:03:17 +01001//
Teresa Charlin52664732020-06-29 16:27:03 +01002// Copyright © 2017 Arm Ltd and Contributors. All rights reserved.
David Beckecb56cd2018-09-05 12:52:57 +01003// SPDX-License-Identifier: MIT
telsoa014fcda012018-03-09 14:13:49 +00004//
Matteo Martincigh49124022019-01-11 13:25:59 +00005
telsoa014fcda012018-03-09 14:13:49 +00006#include "Network.hpp"
7#include "Graph.hpp"
8#include "Layer.hpp"
telsoa01c577f2c2018-08-31 09:22:23 +01009#include "DeviceSpec.hpp"
telsoa014fcda012018-03-09 14:13:49 +000010#include "Optimizer.hpp"
Derek Lambertiff05cc52019-04-26 13:05:17 +010011#include "SubgraphViewSelector.hpp"
Matteo Martincigh49124022019-01-11 13:25:59 +000012#include "BackendSettings.hpp"
David Beckac42efd2018-09-26 17:41:13 +010013#include "optimizations/All.hpp"
telsoa014fcda012018-03-09 14:13:49 +000014
Aron Virginas-Tarc9cc8042018-11-01 16:15:57 +000015#include <backendsCommon/CpuTensorHandle.hpp>
16#include <backendsCommon/WorkloadFactory.hpp>
Matteo Martincighe5b8eb92019-11-28 15:45:42 +000017#include <armnn/backends/IBackendInternal.hpp>
Derek Lamberti84da38b2019-06-13 11:40:08 +010018#include <backendsCommon/TensorHandleFactoryRegistry.hpp>
David Beckac42efd2018-09-26 17:41:13 +010019
20#include <armnn/Exceptions.hpp>
telsoa014fcda012018-03-09 14:13:49 +000021#include <armnn/Utils.hpp>
telsoa01c577f2c2018-08-31 09:22:23 +010022#include <armnn/TypesUtils.hpp>
Matteo Martincighc601aa62019-10-29 15:03:22 +000023#include <armnn/BackendRegistry.hpp>
Matthew Benthamf48afc62020-01-15 17:55:08 +000024#include <armnn/Logging.hpp>
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +010025#include <armnn/utility/Assert.hpp>
Jan Eilers8eb25602020-03-09 12:13:48 +000026#include <armnn/utility/IgnoreUnused.hpp>
Jan Eilersbb446e52020-04-02 13:56:54 +010027#include <armnn/utility/PolymorphicDowncast.hpp>
telsoa014fcda012018-03-09 14:13:49 +000028
Jan Eilers99d9d4a2019-11-06 10:02:16 +000029#include <ProfilingService.hpp>
30
telsoa014fcda012018-03-09 14:13:49 +000031#include <fcntl.h>
32#include <algorithm>
33#include <fstream>
34#include <memory>
telsoa01c577f2c2018-08-31 09:22:23 +010035#include <vector>
36#include <algorithm>
telsoa014fcda012018-03-09 14:13:49 +000037
telsoa014fcda012018-03-09 14:13:49 +000038namespace armnn
39{
40
Finn Williamsf24effa2020-07-03 10:12:03 +010041armnn::INetwork* INetwork::CreateRaw(NetworkOptions networkOptions)
telsoa014fcda012018-03-09 14:13:49 +000042{
Finn Williamsf24effa2020-07-03 10:12:03 +010043 return new Network(networkOptions);
telsoa014fcda012018-03-09 14:13:49 +000044}
45
Finn Williamsf24effa2020-07-03 10:12:03 +010046armnn::INetworkPtr INetwork::Create(NetworkOptions networkOptions)
telsoa014fcda012018-03-09 14:13:49 +000047{
Finn Williamsf24effa2020-07-03 10:12:03 +010048 return INetworkPtr(CreateRaw(networkOptions), &INetwork::Destroy);
telsoa014fcda012018-03-09 14:13:49 +000049}
50
51void INetwork::Destroy(INetwork* network)
52{
Jan Eilersbb446e52020-04-02 13:56:54 +010053 delete PolymorphicDowncast<Network*>(network);
telsoa014fcda012018-03-09 14:13:49 +000054}
55
telsoa014fcda012018-03-09 14:13:49 +000056void IOptimizedNetwork::Destroy(IOptimizedNetwork* network)
57{
Jan Eilersbb446e52020-04-02 13:56:54 +010058 delete PolymorphicDowncast<OptimizedNetwork*>(network);
telsoa014fcda012018-03-09 14:13:49 +000059}
60
61Status OptimizedNetwork::PrintGraph()
62{
63 m_Graph->Print();
64 return Status::Success;
65}
66
surmeh01bceff2f2018-03-29 16:29:27 +010067Status OptimizedNetwork::SerializeToDot(std::ostream& stream) const
68{
69 return m_Graph->SerializeToDot(stream);
70}
71
Matteo Martincigh49124022019-01-11 13:25:59 +000072void ReportError(const std::string& errorMessage,
73 Optional<std::vector<std::string>&> errorMessages)
74{
75 std::stringstream fullErrorMessage;
76 fullErrorMessage << "ERROR: " << errorMessage;
Derek Lamberti08446972019-11-26 16:38:31 +000077 ARMNN_LOG(warning) << fullErrorMessage.str();
Matteo Martincigh49124022019-01-11 13:25:59 +000078 if (errorMessages)
79 {
80 errorMessages.value().push_back(fullErrorMessage.str());
81 }
82}
83
84void ReportWarning(const std::string& warningMessage,
85 Optional<std::vector<std::string>&> warningMessages)
86{
87 std::stringstream fullWarningMessage;
88 fullWarningMessage << "WARNING: " << warningMessage;
Derek Lamberti08446972019-11-26 16:38:31 +000089 ARMNN_LOG(warning) << fullWarningMessage.str();
Matteo Martincigh49124022019-01-11 13:25:59 +000090 if (warningMessages)
91 {
92 warningMessages.value().push_back(fullWarningMessage.str());
93 }
94}
95
Derek Lamberti4a9e24b2020-01-03 16:53:38 +000096OptimizationResult ReturnWithError(OptimizationResult res,
97 const Layer* layer,
98 const BackendSettings& backendSettings,
99 Optional<std::vector<std::string>&> errMessages)
100{
101 std::stringstream failureMsg;
102 failureMsg << "Layer of type " << GetLayerTypeAsCString(layer->GetType())
103 << " is not supported on any preferred backend " << backendSettings.m_PreferredBackends;
104 ReportError(failureMsg.str(), errMessages);
105
106 res.m_Error = true;
107 return res;
108}
109
110
jimfly016b0b53d2018-10-08 14:43:01 +0100111bool CheckScaleSetOnQuantizedType(Layer* layer, Optional<std::vector<std::string>&> errMessages)
112{
113 bool noErrors = true;
114 unsigned int numOutputs = layer->GetNumOutputSlots();
115 for (unsigned int i = 0; i < numOutputs; i++) {
David Monahanb8554702019-04-25 16:03:38 +0100116 OutputSlot& outputSlot = layer->GetOutputSlot(i);
117 TensorInfo info = outputSlot.GetTensorInfo();
Derek Lambertif90c56d2020-01-10 17:14:08 +0000118 if (DataType::QAsymmU8 == info.GetDataType()) {
jimfly016b0b53d2018-10-08 14:43:01 +0100119 if (0.f == info.GetQuantizationScale()) {
120 noErrors = false;
121 std::stringstream ss;
Matteo Martincigh49124022019-01-11 13:25:59 +0000122 ss << "output " << i << " of layer " << GetLayerTypeAsCString(layer->GetType())
jimfly016b0b53d2018-10-08 14:43:01 +0100123 << " (" << layer->GetNameStr() << ") is of type"
124 << " Quantized 8 bit but its scale parameter has not been set";
Matteo Martincigh49124022019-01-11 13:25:59 +0000125 ReportError(ss.str(), errMessages);
jimfly016b0b53d2018-10-08 14:43:01 +0100126 }
David Monahanb8554702019-04-25 16:03:38 +0100127 // Softmax under QuantisedAsymm8 must always be scale (1.0f/256.0f) and offset 0
128 if ((info.GetQuantizationScale() != (1.0f / 256.0f) ||
129 info.GetQuantizationOffset() != 0) &&
130 layer->GetType() == armnn::LayerType::Softmax)
131 {
132 std::stringstream ss;
133 ss << "Quantization parameters for Softmax layer (Scale: " <<
134 info.GetQuantizationScale() << " and Offset: " << info.GetQuantizationOffset() <<
135 ") are incorrect and have been updated to Scale: 0.00390625 and Offset: 0";
Derek Lamberti08446972019-11-26 16:38:31 +0000136 ARMNN_LOG(warning) << ss.str();
David Monahanb8554702019-04-25 16:03:38 +0100137 info.SetQuantizationScale((1.0f /256.0f));
138 info.SetQuantizationOffset(0);
139 outputSlot.SetTensorInfo(info);
140 }
jimfly016b0b53d2018-10-08 14:43:01 +0100141 }
142 }
143 return noErrors;
144}
145
Narumol Prangnawarat250d3922020-03-30 16:11:04 +0100146template <typename LayerT>
147LayerT* ConvertBf16ToFp32Weight(Layer* l)
148{
Jan Eilersbb446e52020-04-02 13:56:54 +0100149 LayerT* layer = PolymorphicDowncast<LayerT*>(l);
Narumol Prangnawarat250d3922020-03-30 16:11:04 +0100150 if ((layer->GetType() == LayerType::Convolution2d || layer->GetType() == LayerType::FullyConnected)
151 && layer->m_Weight)
152 {
153 const TensorInfo& info = layer->m_Weight->GetTensorInfo();
154
155 if (info.GetDataType() == DataType::BFloat16)
156 {
157 std::vector<float> newValues(info.GetNumElements());
158
159 armnnUtils::FloatingPointConverter::ConvertBFloat16ToFloat32(
160 layer->m_Weight->template GetTensor<armnn::BFloat16>(), info.GetNumElements(), newValues.data());
161
162 TensorInfo newInfo(info.GetShape(), DataType::Float32);
163 ConstTensor newInput(newInfo, newValues);
164 layer->m_Weight.reset(new ScopedCpuTensorHandle(newInput));
165 }
166 }
167 return layer;
168}
169
Derek Lamberti4a9e24b2020-01-03 16:53:38 +0000170OptimizationResult AttemptBackendAssignment(BackendSettings& backendSettings,
171 Graph& graph,
172 Layer* layer,
173 BackendId backend,
174 DataType dataTypeIn,
175 DataType dataTypeOut,
176 const std::vector<BackendId>& availablePreferredBackends,
177 std::string& reasonIfUnsupported,
178 Optional<std::vector<std::string>&> errMessages)
179{
180 OptimizationResult result;
181
182 // Helper lambda to compose meaningful error message before returning with error
183 auto ReturnError = [&](const Layer* layer)
184 {
185 return ReturnWithError(result, layer, backendSettings, errMessages);
186 };
187
188 // need to set the compute device on the layer
189 // before we can check if it is supported
190 layer->SetBackendId(backend);
191 if (!IWorkloadFactory::IsLayerSupported(*layer, EmptyOptional(), reasonIfUnsupported))
192 {
193 if (dataTypeIn == DataType::Float16 || dataTypeOut == DataType::Float16)
194 {
195 if (IWorkloadFactory::IsLayerSupported(*layer, DataType::Float32, reasonIfUnsupported)
196 && layer->GetType() != LayerType::ConvertFp32ToFp16
197 && layer->GetType() != LayerType::ConvertFp16ToFp32)
198 {
199 // Insert FP16 -> FP32 conversion layer before current layer
200 std::vector<ConvertFp16ToFp32Layer*> convertFp16ToFp32Layers;
201 if (dataTypeIn == DataType::Float16)
202 {
203 convertFp16ToFp32Layers =
204 InsertConvertFp16ToFp32LayersBefore(graph, *layer);
205 }
206
207 // Insert FP32 -> FP16 conversion layer after current layer
208 std::vector<ConvertFp32ToFp16Layer*> convertFp32ToFp16Layers;
209 if (dataTypeOut == DataType::Float16)
210 {
211 convertFp32ToFp16Layers =
212 InsertConvertFp32ToFp16LayersAfter(graph, *layer);
213 }
214
215 // Assign a supported backend to the newly introduced conversion layers
216 auto AssignFirstSupportedBackend = [&](Layer* layer, BackendId preferredBackend)
217 {
218 bool supportedBackendFound = false;
219 std::string reasonIfUnsupported;
220
221 // Try preferred backend first
222 layer->SetBackendId(preferredBackend);
223 if (IWorkloadFactory::IsLayerSupported(*layer,
224 EmptyOptional(),
225 reasonIfUnsupported))
226 {
227 supportedBackendFound = true;
228 }
229 else
230 {
231 for (const auto& backend : availablePreferredBackends)
232 {
233 // Skip preferred backend (we already determined that it is not supported)
234 if (backend == preferredBackend)
235 {
236 continue;
237 }
238
239 layer->SetBackendId(backend);
240 if (IWorkloadFactory::IsLayerSupported(*layer,
241 EmptyOptional(),
242 reasonIfUnsupported))
243 {
244 supportedBackendFound = true;
245 break;
246 }
247 }
248 }
249
250 return supportedBackendFound;
251 };
252
253 for (ConvertFp16ToFp32Layer* convertLayer : convertFp16ToFp32Layers)
254 {
255 if (!AssignFirstSupportedBackend(convertLayer, backend))
256 {
257 return ReturnError(convertLayer);
258 }
259 }
260
261 for (ConvertFp32ToFp16Layer* convertLayer : convertFp32ToFp16Layers)
262 {
263 if (!AssignFirstSupportedBackend(convertLayer, backend))
264 {
265 return ReturnError(convertLayer);
266 }
267 }
268
269 return result;
270 }
271 }
Narumol Prangnawaratbc7ffb52020-03-20 15:01:01 +0000272 else if (dataTypeIn == DataType::BFloat16 || dataTypeOut == DataType::BFloat16)
273 {
274 if (IWorkloadFactory::IsLayerSupported(*layer, DataType::Float32, reasonIfUnsupported)
275 && layer->GetType() != LayerType::ConvertFp32ToBf16
276 && layer->GetType() != LayerType::ConvertBf16ToFp32)
277 {
278 // Insert BF16 -> FP32 conversion layer before current layer
279 std::vector<ConvertBf16ToFp32Layer*> convertBf16ToFp32Layers;
280 if (dataTypeIn == DataType::BFloat16)
281 {
282 convertBf16ToFp32Layers =
283 InsertConvertBf16ToFp32LayersBefore(graph, *layer);
Narumol Prangnawarat250d3922020-03-30 16:11:04 +0100284 if (layer->GetType() == LayerType::Convolution2d)
285 {
286 ConvertBf16ToFp32Weight<Convolution2dLayer>(layer);
287 }
288 else if (layer->GetType() == LayerType::FullyConnected)
289 {
290 ConvertBf16ToFp32Weight<FullyConnectedLayer>(layer);
291 }
Narumol Prangnawaratbc7ffb52020-03-20 15:01:01 +0000292 }
293
294 // Insert FP32 -> BF16 conversion layer after current layer
295 std::vector<ConvertFp32ToBf16Layer*> convertFp32ToBf16Layers;
296 if (dataTypeOut == DataType::BFloat16)
297 {
298 convertFp32ToBf16Layers =
299 InsertConvertFp32ToBf16LayersAfter(graph, *layer);
300 }
301
302 // Assign a supported backend to the newly introduced conversion layers
303 auto AssignFirstSupportedBackend = [&](Layer* layer, BackendId preferredBackend)
304 {
305 bool supportedBackendFound = false;
306 std::string reasonIfUnsupported;
307
308 // Try preferred backend first
309 layer->SetBackendId(preferredBackend);
310 if (IWorkloadFactory::IsLayerSupported(*layer,
311 EmptyOptional(),
312 reasonIfUnsupported))
313 {
314 supportedBackendFound = true;
315 }
316 else
317 {
318 for (const auto& backend : availablePreferredBackends)
319 {
320 // Skip preferred backend (we already determined that it is not supported)
321 if (backend == preferredBackend)
322 {
323 continue;
324 }
325
326 layer->SetBackendId(backend);
327 if (IWorkloadFactory::IsLayerSupported(*layer,
328 EmptyOptional(),
329 reasonIfUnsupported))
330 {
331 supportedBackendFound = true;
332 break;
333 }
334 }
335 }
336
337 return supportedBackendFound;
338 };
339
340 for (ConvertBf16ToFp32Layer* convertLayer : convertBf16ToFp32Layers)
341 {
342 if (!AssignFirstSupportedBackend(convertLayer, backend))
343 {
344 return ReturnError(convertLayer);
345 }
346 }
347
348 for (ConvertFp32ToBf16Layer* convertLayer : convertFp32ToBf16Layers)
349 {
350 if (!AssignFirstSupportedBackend(convertLayer, backend))
351 {
352 return ReturnError(convertLayer);
353 }
354 }
355
356 return result;
357 }
358 }
359
Derek Lamberti4a9e24b2020-01-03 16:53:38 +0000360 std::stringstream warningMsg;
361 warningMsg << "Layer of type " << GetLayerTypeAsCString(layer->GetType())
362 << " is not supported on requested backend " << layer->GetBackendId().Get()
363 << " for input data type " << GetDataTypeName(dataTypeIn)
364 << " and output data type " << GetDataTypeName(dataTypeOut)
365 << " (reason: " << reasonIfUnsupported
366 << "), falling back to the next backend.";
367 ReportWarning(warningMsg.str(), errMessages);
368
369 return OptimizationResult(true, false);
370 }
371 else
372 {
373 return result;
374 }
375}
376
377
Matteo Martincigh49124022019-01-11 13:25:59 +0000378OptimizationResult AssignBackends(OptimizedNetwork* optNetObjPtr,
379 BackendSettings& backendSettings,
380 Graph::Iterator& firstLayer,
381 Graph::Iterator& lastLayer,
382 Optional<std::vector<std::string>&> errMessages)
telsoa014fcda012018-03-09 14:13:49 +0000383{
Matteo Martincigh49124022019-01-11 13:25:59 +0000384 OptimizationResult result;
telsoa014fcda012018-03-09 14:13:49 +0000385
Matteo Martincigh49124022019-01-11 13:25:59 +0000386 // Helper lambda to compose meaningful error message before returning with error
Derek Lamberti4a9e24b2020-01-03 16:53:38 +0000387 auto ReturnError = [&](const Layer* layer)
388 {
389 return ReturnWithError(result, layer, backendSettings, errMessages);
390 };
Matteo Martincigh49124022019-01-11 13:25:59 +0000391
telsoa01c577f2c2018-08-31 09:22:23 +0100392
Matteo Martincigh49124022019-01-11 13:25:59 +0000393 auto availablePreferredBackends = backendSettings.GetAvailablePreferredBackends();
394 if (availablePreferredBackends.empty())
telsoa01c577f2c2018-08-31 09:22:23 +0100395 {
Matteo Martincigh49124022019-01-11 13:25:59 +0000396 std::stringstream failureMsg;
397 failureMsg << "No preferred backends are available";
398 ReportError(failureMsg.str(), errMessages);
399
400 result.m_Error = true;
401 return result;
402 }
403
404 for (auto it = firstLayer; it != lastLayer; ++it)
405 {
406 auto layer = *it;
Aron Virginas-Tar87972be2019-11-13 15:16:28 +0000407
408 DataType dataTypeIn = layer->GetNumInputSlots() == 0 ? DataType::Float32 :
409 layer->GetInputSlot(0).GetConnectedOutputSlot()->GetTensorInfo().GetDataType();
410 DataType dataTypeOut = layer->GetNumOutputSlots() == 0 ? DataType::Float32 :
411 layer->GetOutputSlot(0).GetTensorInfo().GetDataType();
412
telsoa01c577f2c2018-08-31 09:22:23 +0100413 std::string reasonIfUnsupported;
414 bool found = false;
jimfly016b0b53d2018-10-08 14:43:01 +0100415 if (!CheckScaleSetOnQuantizedType(layer, errMessages))
416 {
417 // don't bomb immediately, find all the quantized outputs
418 // which haven't had a scale set and report them all back.
Matteo Martincigh49124022019-01-11 13:25:59 +0000419 result.m_Error = true;
jimfly016b0b53d2018-10-08 14:43:01 +0100420 }
Matteo Martincigh49124022019-01-11 13:25:59 +0000421
Derek Lamberti4a9e24b2020-01-03 16:53:38 +0000422 // First try assign layer to hint backend
423 if (layer->GetBackendHint().has_value() &&
424 backendSettings.IsBackendSupported(layer->GetBackendHint().value()) &&
425 AttemptBackendAssignment(backendSettings,
426 optNetObjPtr->GetGraph(),
427 layer,
428 layer->GetBackendHint().value(),
429 dataTypeIn,
430 dataTypeOut,
431 availablePreferredBackends,
432 reasonIfUnsupported,
433 errMessages).IsOk())
telsoa01c577f2c2018-08-31 09:22:23 +0100434 {
Derek Lamberti4a9e24b2020-01-03 16:53:38 +0000435 found = true;
436 backendSettings.m_SelectedBackends.insert(layer->GetBackendHint().value());
437 }
438 else
439 {
440 // Try assign layer to prefered list of backends
441 for (const auto& backend : availablePreferredBackends)
telsoa01c577f2c2018-08-31 09:22:23 +0100442 {
Derek Lamberti4a9e24b2020-01-03 16:53:38 +0000443 if (layer->GetBackendHint().has_value() &&
444 layer->GetBackendHint().value() == backend)
telsoa01c577f2c2018-08-31 09:22:23 +0100445 {
Derek Lamberti4a9e24b2020-01-03 16:53:38 +0000446 continue; //Don't re-test the backend hint
telsoa01c577f2c2018-08-31 09:22:23 +0100447 }
Derek Lamberti4a9e24b2020-01-03 16:53:38 +0000448
449 OptimizationResult res = AttemptBackendAssignment(backendSettings,
450 optNetObjPtr->GetGraph(),
451 layer,
452 backend,
453 dataTypeIn,
454 dataTypeOut,
455 availablePreferredBackends,
456 reasonIfUnsupported,
457 errMessages);
458
459 if (res.IsOk())
460 {
461 found = true;
462 backendSettings.m_SelectedBackends.insert(backend);
463 break;
464 }
465 else if (res.IsError())
466 {
467 return res; // Cannot continue.
468 // Note: we don't need to log the error as it would already
469 // be logged in AttemptBackendAssignment().
470 }
471 else
472 {
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +0100473 ARMNN_ASSERT_MSG(res.IsWarningOnly(), "OptimizationResult in unexpected state.");
Derek Lamberti4a9e24b2020-01-03 16:53:38 +0000474 }
telsoa01c577f2c2018-08-31 09:22:23 +0100475 }
476 }
477
478 // If the layer is unsupported by any devices, log and return a null network.
Matteo Martincigh49124022019-01-11 13:25:59 +0000479 if (!found)
480 {
telsoa01c577f2c2018-08-31 09:22:23 +0100481 // NOTE: if the layer is not an operation queue type AND we have not got CpuRef as a
482 // fallback we should set the compute device on the layer to CpuRef (these are not
483 // available as accelerated operations, or are only available under certain
484 // conditions, currently they comprise MemCopy, Constant, Permute)
485 armnn::LayerType layerType = layer->GetType();
Matteo Martincigh49124022019-01-11 13:25:59 +0000486 if (!backendSettings.IsCpuRefUsed() && (layerType == armnn::LayerType::MemCopy ||
487 layerType == armnn::LayerType::Constant ||
488 layerType == armnn::LayerType::Permute))
telsoa01c577f2c2018-08-31 09:22:23 +0100489 {
Matteo Martincigh49124022019-01-11 13:25:59 +0000490 BackendId cpuBackendId(armnn::Compute::CpuRef);
491 layer->SetBackendId(cpuBackendId);
492 backendSettings.m_SelectedBackends.insert(cpuBackendId);
telsoa01c577f2c2018-08-31 09:22:23 +0100493 }
494 else
495 {
Derek Lamberti4a9e24b2020-01-03 16:53:38 +0000496 return ReturnError(layer);
telsoa01c577f2c2018-08-31 09:22:23 +0100497 }
498 }
499 }
Matteo Martincigh49124022019-01-11 13:25:59 +0000500
501 return result;
502}
503
Matteo Martincighadddddb2019-01-24 14:06:23 +0000504OptimizationResult AssignBackends(OptimizedNetwork* optNetObjPtr,
505 BackendSettings& backendSettings,
Derek Lambertiff05cc52019-04-26 13:05:17 +0100506 SubgraphView& subgraph,
Matteo Martincighadddddb2019-01-24 14:06:23 +0000507 Optional<std::vector<std::string>&> errMessages)
Matteo Martincigh49124022019-01-11 13:25:59 +0000508{
Derek Lambertiff05cc52019-04-26 13:05:17 +0100509 Graph::Iterator firstLayer = subgraph.begin();
510 Graph::Iterator lastLayer = subgraph.end();
Matteo Martincighadddddb2019-01-24 14:06:23 +0000511 return AssignBackends(optNetObjPtr,
512 backendSettings,
513 firstLayer,
514 lastLayer,
515 errMessages);
516}
517
Derek Lamberti84da38b2019-06-13 11:40:08 +0100518BackendsMap CreateSupportedBackends(TensorHandleFactoryRegistry& handleFactoryRegistry,
519 BackendSettings& backendSettings)
520{
521 BackendsMap backends;
522 auto const& backendRegistry = BackendRegistryInstance();
523 for (auto&& selectedBackend : backendSettings.m_SupportedBackends)
524 {
525 auto backendFactory = backendRegistry.GetFactory(selectedBackend);
526 auto backendObjPtr = backendFactory();
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +0100527 ARMNN_ASSERT(backendObjPtr);
Derek Lamberti84da38b2019-06-13 11:40:08 +0100528
529 backendObjPtr->RegisterTensorHandleFactories(handleFactoryRegistry);
530
531 backends[backendObjPtr->GetId()] = std::move(backendObjPtr);
532 }
533
534 return backends;
535}
536
Matteo Martincighadddddb2019-01-24 14:06:23 +0000537OptimizationResult ApplyBackendOptimizations(OptimizedNetwork* optNetObjPtr,
538 BackendSettings& backendSettings,
Derek Lamberti84da38b2019-06-13 11:40:08 +0100539 BackendsMap& backends,
Matteo Martincighadddddb2019-01-24 14:06:23 +0000540 Optional<std::vector<std::string>&> errMessages)
541{
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +0100542 ARMNN_ASSERT(optNetObjPtr);
Matteo Martincigh49124022019-01-11 13:25:59 +0000543
544 OptimizationResult result;
545
Matteo Martincighadddddb2019-01-24 14:06:23 +0000546 // Get the optimized graph
547 Graph& optGraph = optNetObjPtr->GetGraph();
Matteo Martincigh49124022019-01-11 13:25:59 +0000548
Matteo Martincighadddddb2019-01-24 14:06:23 +0000549 // Run backend specific optimizations
Matteo Martincighadddddb2019-01-24 14:06:23 +0000550 for (auto&& selectedBackend : backendSettings.m_SelectedBackends)
Matteo Martincigh49124022019-01-11 13:25:59 +0000551 {
Derek Lamberti84da38b2019-06-13 11:40:08 +0100552 auto backendObjPtr = backends.find(selectedBackend)->second.get();
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +0100553 ARMNN_ASSERT(backendObjPtr);
Matteo Martincighadddddb2019-01-24 14:06:23 +0000554
555 // Select sub-graphs based on backend
Derek Lambertiff05cc52019-04-26 13:05:17 +0100556 SubgraphViewSelector::Subgraphs subgraphs =
Rob Hughes65c32262019-07-23 15:33:39 +0100557 SubgraphViewSelector::SelectSubgraphs(optGraph,
Matteo Martincigh602af092019-05-01 10:31:27 +0100558 // Select layers assigned to the requested backend
559 [&backendObjPtr](const Layer& layer)
560 {
561 return layer.GetType() != LayerType::Input &&
562 layer.GetType() != LayerType::Output &&
563 layer.GetBackendId() == backendObjPtr->GetId();
564 });
Derek Lambertiff05cc52019-04-26 13:05:17 +0100565 if (subgraphs.empty())
Matteo Martincigh49124022019-01-11 13:25:59 +0000566 {
Matteo Martincighadddddb2019-01-24 14:06:23 +0000567 // No sub-graphs found, try with next selected backend
568 continue;
Matteo Martincigh49124022019-01-11 13:25:59 +0000569 }
Matteo Martincighadddddb2019-01-24 14:06:23 +0000570
571 // Try to optimize each sub-graph
Derek Lambertiff05cc52019-04-26 13:05:17 +0100572 for (auto& subgraph : subgraphs)
Matteo Martincigh49124022019-01-11 13:25:59 +0000573 {
Matteo Martincighadddddb2019-01-24 14:06:23 +0000574 // Try to optimize the current sub-graph
Matteo Martincigh84924332019-05-09 12:46:16 +0100575 OptimizationViews optimizationViews = backendObjPtr->OptimizeSubgraphView(*subgraph);
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +0100576 ARMNN_ASSERT(optimizationViews.Validate(*subgraph));
Matteo Martincighadddddb2019-01-24 14:06:23 +0000577
578 // Optimization attempted, check the resulting optimized sub-graph
Matteo Martincigh84924332019-05-09 12:46:16 +0100579 for (auto& substitution : optimizationViews.GetSubstitutions())
Matteo Martincighadddddb2019-01-24 14:06:23 +0000580 {
581 // Sub-graph optimized, substitute the sub-graph with the new optimized one in the main optimized graph
Matteo Martincigh84924332019-05-09 12:46:16 +0100582 SubgraphView& replacementSubgraph = substitution.m_ReplacementSubgraph;
583 SubgraphView& substitutableSubgraph = substitution.m_SubstitutableSubgraph;
584 optGraph.SubstituteSubgraph(substitutableSubgraph, replacementSubgraph);
Matteo Martincighadddddb2019-01-24 14:06:23 +0000585
586 // Assign the current backend to the optimized sub-graph
Matteo Martincigh84924332019-05-09 12:46:16 +0100587 std::for_each(replacementSubgraph.begin(), replacementSubgraph.end(), [&selectedBackend](Layer* l)
Derek Lambertic2fe5fb2019-05-08 10:23:08 +0100588 {
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +0100589 ARMNN_ASSERT(l);
Derek Lambertic2fe5fb2019-05-08 10:23:08 +0100590 l->SetBackendId(selectedBackend);
591 });
Matteo Martincighadddddb2019-01-24 14:06:23 +0000592 }
Derek Lambertic2fe5fb2019-05-08 10:23:08 +0100593
Matteo Martincigh84924332019-05-09 12:46:16 +0100594 if (!optimizationViews.GetFailedSubgraphs().empty())
Matteo Martincighadddddb2019-01-24 14:06:23 +0000595 {
Matteo Martincighadddddb2019-01-24 14:06:23 +0000596 std::stringstream warningMsg;
Derek Lambertic2fe5fb2019-05-08 10:23:08 +0100597 warningMsg << "Some sub-graph(s) failed to optimized on " << backendObjPtr->GetId() << " backend.";
Matteo Martincighadddddb2019-01-24 14:06:23 +0000598 ReportWarning(warningMsg.str(), errMessages);
599
600 // Failed to optimize the given sub-graph, re-assign the sub-graph layers to other available backends
Derek Lambertic2fe5fb2019-05-08 10:23:08 +0100601 BackendSettings settingsCopy(backendSettings);
Matteo Martincighadddddb2019-01-24 14:06:23 +0000602 if (!backendObjPtr->GetId().IsCpuRef())
603 {
604 // Add the current backend to the list of backends to ignore
Derek Lambertic2fe5fb2019-05-08 10:23:08 +0100605 settingsCopy.m_IgnoredBackends.insert(backendObjPtr->GetId());
Matteo Martincighadddddb2019-01-24 14:06:23 +0000606 }
Derek Lambertic2fe5fb2019-05-08 10:23:08 +0100607
608 int count=0;
Matteo Martincigh84924332019-05-09 12:46:16 +0100609 for (auto& failedSubgraph : optimizationViews.GetFailedSubgraphs())
Matteo Martincighadddddb2019-01-24 14:06:23 +0000610 {
Derek Lambertic2fe5fb2019-05-08 10:23:08 +0100611 // An error occurred: the optimization was attempted but not performed, try different backends
612 std::stringstream subgraphMsg;
613 subgraphMsg << "Re-assigning backends to " << failedSubgraph.GetLayers().size()
614 << " layers inside sub-graph " << count++;
Matteo Martincigh328d92b2019-07-04 17:52:55 +0100615 ReportWarning(subgraphMsg.str(), errMessages);
Derek Lambertic2fe5fb2019-05-08 10:23:08 +0100616
617 OptimizationResult reassignmentResult = AssignBackends(optNetObjPtr,
618 settingsCopy,
619 *subgraph,
620 errMessages);
621 if (reassignmentResult.m_Error)
622 {
623 // Failed to re-assign one of the remaining backends to each layer of the sub-graph
624 result.m_Error = true;
625 return result;
626 }
Matteo Martincighadddddb2019-01-24 14:06:23 +0000627 }
Matteo Martincigh49124022019-01-11 13:25:59 +0000628 }
629 }
630 }
631
632 return result;
633}
634
Derek Lamberti84da38b2019-06-13 11:40:08 +0100635bool RequiresCopy(ITensorHandleFactory::FactoryId src,
636 ITensorHandleFactory::FactoryId dst,
637 TensorHandleFactoryRegistry& registry)
638{
639 if (src != dst)
640 {
641 ITensorHandleFactory* srcFactory = registry.GetFactory(src);
642 ITensorHandleFactory* dstFactory = registry.GetFactory(dst);
643
Matteo Martincigha6539ed2019-08-27 13:43:32 +0100644 if (srcFactory && dstFactory &&
645 (srcFactory->GetExportFlags() & dstFactory->GetImportFlags()) != 0)
Derek Lamberti84da38b2019-06-13 11:40:08 +0100646 {
647 return false;
648 }
649 return true;
650 }
651 return false;
652}
653
654// Find the handle factory for the input layer which results in fewest required copies.
655ITensorHandleFactory::FactoryId CalculateSlotOptionForInput(BackendsMap& backends,
656 OutputSlot& slot,
657 TensorHandleFactoryRegistry& registry)
658{
659 Layer& layer = slot.GetOwningLayer();
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +0100660 ARMNN_ASSERT(layer.GetType() == LayerType::Input);
Derek Lamberti84da38b2019-06-13 11:40:08 +0100661
662 // Explicitly select the tensorhandle factory for InputLayer because the rules for it are slightly different. It
663 // doesn't matter which backend it is assigned to because they all use the same implementation, which
664 // requires Map/Unmap support. This means that, so long as the handle type supports map/unmap semantics, we can
665 // select a factory with maximum compatibility with the layers connected to the InputLayer.
666
667 // First ensure the from backends can support the TensorHandeAPI
668 auto frmBackend = backends.find(layer.GetBackendId());
669 if (frmBackend == backends.end() ||
670 !frmBackend->second->SupportsTensorAllocatorAPI())
671 {
672 return ITensorHandleFactory::LegacyFactoryId;
673 }
674
675 // Go through all connections to the output slot and determine the TensorHandleFactory which results in the
676 // fewest copies.
677 std::map<ITensorHandleFactory::FactoryId, int> factoryScores;
678 int topScore = 0;
679 ITensorHandleFactory::FactoryId topChoice = ITensorHandleFactory::LegacyFactoryId;
680
681 for (auto&& connection : slot.GetConnections())
682 {
683 const Layer& connectedLayer = connection->GetOwningLayer();
684
685 auto toBackend = backends.find(connectedLayer.GetBackendId());
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +0100686 ARMNN_ASSERT_MSG(toBackend != backends.end(), "Backend id not found for the connected layer");
Derek Lamberti84da38b2019-06-13 11:40:08 +0100687
688 if (!toBackend->second.get()->SupportsTensorAllocatorAPI())
689 {
690 // The destination backend does not support the tensor allocator API, move to the next one
691 continue;
692 }
693
694 auto dstPrefs = toBackend->second.get()->GetHandleFactoryPreferences();
695 for (auto&& dst : dstPrefs)
696 {
Derek Lambertif674aa02019-08-01 15:56:25 +0100697 // Input layers use the mem copy workload or import, so the selected factory must
698 // support either the map/unmap API or Import API
Derek Lamberti84da38b2019-06-13 11:40:08 +0100699 ITensorHandleFactory* factory = registry.GetFactory(dst);
Derek Lambertif674aa02019-08-01 15:56:25 +0100700 if (!factory->SupportsMapUnmap() &&
701 !CheckFlag(factory->GetImportFlags(), MemorySource::Malloc)) // Just support cpu mem imports for now
Derek Lamberti84da38b2019-06-13 11:40:08 +0100702 {
Derek Lambertif674aa02019-08-01 15:56:25 +0100703 // The current tensor handle factory does not support the map/unmap or import
704 // strategy, move to the next one
Derek Lamberti84da38b2019-06-13 11:40:08 +0100705 continue;
706 }
707
708 auto it = factoryScores.find(dst);
709 if (it == factoryScores.end())
710 {
711 // Add new score to the table
712 factoryScores[dst] = 0;
713 if (topChoice == ITensorHandleFactory::LegacyFactoryId)
714 {
715 topChoice = dst;
716 }
717 }
718 else
719 {
720 // Increase the score
721 factoryScores[dst]++;
722
723 // Track the best option
724 if (factoryScores[dst] > topScore)
725 {
726 topScore = factoryScores[dst];
727 topChoice = dst;
728 }
729 }
730 }
731 }
732
733 return topChoice;
734}
735
736// Find the handle factory for the output layer which results in fewest required copies.
737ITensorHandleFactory::FactoryId CalculateSlotOptionForOutput(BackendsMap& backends,
738 OutputSlot& slot,
739 TensorHandleFactoryRegistry& registry)
740{
Jan Eilers8eb25602020-03-09 12:13:48 +0000741 IgnoreUnused(backends, slot, registry);
Derek Lamberti94a88d22019-12-10 21:12:59 +0000742 return ITensorHandleFactory::DeferredFactoryId;
Derek Lamberti84da38b2019-06-13 11:40:08 +0100743}
744
745// For all handle factories supported on the source backend, we wish to find the one which requires the fewest copies
746// when considering all connections.
747ITensorHandleFactory::FactoryId CalculateSlotOption(BackendsMap& backends,
748 OutputSlot& outputSlot,
749 TensorHandleFactoryRegistry& registry)
750{
751 // First ensure the from backends can support the TensorHandeAPI
752 Layer& layer = outputSlot.GetOwningLayer();
753 auto frmBackend = backends.find(layer.GetBackendId());
754 if (frmBackend == backends.end() ||
755 !frmBackend->second->SupportsTensorAllocatorAPI())
756 {
757 return ITensorHandleFactory::LegacyFactoryId;
758 }
759
760 // Connections to Output Layers requires support for map/unmap on the TensorHandle.
761 bool requiresMapUnmap = false;
762 for (auto&& connection : outputSlot.GetConnections())
763 {
764 const Layer& connectedLayer = connection->GetOwningLayer();
765 if (connectedLayer.GetType() == LayerType::Output)
766 {
767 requiresMapUnmap = true;
768 }
769 }
770
771 IBackendInternal* srcBackend = frmBackend->second.get();
772 auto srcPrefs = srcBackend->GetHandleFactoryPreferences();
773
774 // Initialize the scores
775 std::map<ITensorHandleFactory::FactoryId, int> factoryScores;
776 for (auto&& pref : srcPrefs)
777 {
778 if (requiresMapUnmap) // Only consider factories that support map/unmap if required
779 {
780 ITensorHandleFactory* factory = registry.GetFactory(pref);
781 if (!factory->SupportsMapUnmap())
782 {
783 // The current tensor handle factory does not support the map/unmap strategy, move to the next one
784 continue;
785 }
786 }
787
788 auto it = factoryScores.find(pref);
789 if (it == factoryScores.end())
790 {
791 // Add new score to the table
792 factoryScores[pref] = 0;
793 }
794 }
795
796 // Score each handle factory based on how many times it requires copies on the slot connections
797 for (auto&& connection : outputSlot.GetConnections())
798 {
799 const Layer& connectedLayer = connection->GetOwningLayer();
800
801 auto toBackend = backends.find(connectedLayer.GetBackendId());
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +0100802 ARMNN_ASSERT_MSG(toBackend != backends.end(), "Backend id not found for the connected layer");
Derek Lamberti84da38b2019-06-13 11:40:08 +0100803
804 auto dstPrefs = toBackend->second.get()->GetHandleFactoryPreferences();
805 for (auto&& src : srcPrefs)
806 {
807 if (factoryScores.find(src) == factoryScores.end()) // Don't consider excluded factories
808 {
809 continue;
810 }
811
812 for (auto&& dst : dstPrefs)
813 {
814 if (RequiresCopy(src, dst, registry))
815 {
816 // Copy avoided, increase the score
817 factoryScores[src]++;
818 break;
819 }
820 }
821 }
822 }
823
824 // Find the lowest score
825 int minScore = std::numeric_limits<int>::max();
826 for (auto it : factoryScores)
827 {
828 minScore = std::min(minScore, it.second);
829 }
830
831 // Collect factories matching the best(lowest) score
832 std::vector<ITensorHandleFactory::FactoryId> optimalFactories;
833 for (auto it : factoryScores)
834 {
835 if (it.second == minScore)
836 {
837 optimalFactories.push_back(it.first);
838 }
839 }
840
841 // For all compatible Factories matching the best score, find the preferred one for the current layer.
842 for (auto&& srcPref : srcPrefs)
843 {
844 for (auto&& comp : optimalFactories)
845 {
846 if (comp == srcPref)
847 {
848 return comp;
849 }
850 }
851 }
852
853 return ITensorHandleFactory::LegacyFactoryId;
854}
855
Derek Lambertif674aa02019-08-01 15:56:25 +0100856EdgeStrategy CalculateEdgeStrategy(BackendsMap& backends,
857 ITensorHandleFactory::FactoryId srcFactoryId,
858 const Layer& layer,
859 const Layer& connectedLayer,
Narumol Prangnawarata2493a02020-08-19 14:39:07 +0100860 TensorHandleFactoryRegistry& registry,
861 bool importEnabled)
Derek Lamberti84da38b2019-06-13 11:40:08 +0100862{
863 auto toBackend = backends.find(connectedLayer.GetBackendId());
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +0100864 ARMNN_ASSERT_MSG(toBackend != backends.end(), "Backend id not found for the connected layer");
Derek Lamberti84da38b2019-06-13 11:40:08 +0100865
866 auto dstPrefs = toBackend->second.get()->GetHandleFactoryPreferences();
867
868 // Legacy API check for backward compatibility
869 if (srcFactoryId == ITensorHandleFactory::LegacyFactoryId || dstPrefs.empty())
870 {
871 if (layer.GetBackendId() != connectedLayer.GetBackendId())
872 {
Derek Lambertif674aa02019-08-01 15:56:25 +0100873 return EdgeStrategy::CopyToTarget;
Derek Lamberti84da38b2019-06-13 11:40:08 +0100874 }
875 else
876 {
Derek Lambertif674aa02019-08-01 15:56:25 +0100877 return EdgeStrategy::DirectCompatibility;
Derek Lamberti84da38b2019-06-13 11:40:08 +0100878 }
879 }
880
881 // TensorHandleFactory API present, so perform more sophisticated strategies.
Derek Lambertif674aa02019-08-01 15:56:25 +0100882 // Dst Output layers don't require copy because they use import or map/unmap
Derek Lamberti84da38b2019-06-13 11:40:08 +0100883 if (connectedLayer.GetType() == LayerType::Output)
884 {
Derek Lambertif674aa02019-08-01 15:56:25 +0100885 return EdgeStrategy::DirectCompatibility;
Derek Lamberti84da38b2019-06-13 11:40:08 +0100886 }
887
888 // Search for direct match in prefs
889 for (auto&& pref : dstPrefs)
890 {
891 if (pref == srcFactoryId)
892 {
Derek Lambertif674aa02019-08-01 15:56:25 +0100893 return EdgeStrategy::DirectCompatibility;
Derek Lamberti84da38b2019-06-13 11:40:08 +0100894 }
895 }
896
897 // Search for export/import options
898 ITensorHandleFactory* srcFactory = registry.GetFactory(srcFactoryId);
Narumol Prangnawarata2493a02020-08-19 14:39:07 +0100899 if (srcFactory->GetExportFlags() != 0 && importEnabled)
Derek Lamberti84da38b2019-06-13 11:40:08 +0100900 {
901 for (auto&& pref : dstPrefs)
902 {
903 ITensorHandleFactory* dstFactory = registry.GetFactory(pref);
James Conroyffab16f2019-11-07 14:37:09 +0000904
James Conroy47e863d2019-11-18 17:07:43 +0000905 // Handles cases when a destPref is not listed in TensorHandleFactoryRegistry
James Conroyffab16f2019-11-07 14:37:09 +0000906 if (!dstFactory) {
James Conroy47e863d2019-11-18 17:07:43 +0000907 continue;
James Conroyffab16f2019-11-07 14:37:09 +0000908 }
909
Derek Lambertif674aa02019-08-01 15:56:25 +0100910 if ((dstFactory->GetImportFlags() & srcFactory->GetExportFlags()) != 0)
Derek Lamberti84da38b2019-06-13 11:40:08 +0100911 {
Narumol Prangnawaratb8d771a2020-08-14 11:51:12 +0100912 auto srcCapability = srcFactory->GetCapabilities(&layer, &layer, CapabilityClass::PaddingRequired);
913 auto dstCapability = dstFactory->GetCapabilities(&connectedLayer,
914 &connectedLayer,
915 CapabilityClass::PaddingRequired);
916 // Do not require memory copy if the source and destination do not require padding.
917 if (srcCapability.empty() && dstCapability.empty())
918 {
919 return EdgeStrategy::ExportToTarget;
920 }
Derek Lamberti84da38b2019-06-13 11:40:08 +0100921 }
922 }
923 }
924
925 // Search for copy options via map/unmap
926 if (srcFactory->SupportsMapUnmap())
927 {
928 for (auto&& pref : dstPrefs)
929 {
930 ITensorHandleFactory* dstFactory = registry.GetFactory(pref);
James Conroy47e863d2019-11-18 17:07:43 +0000931 if (dstFactory && dstFactory->SupportsMapUnmap())
Derek Lamberti84da38b2019-06-13 11:40:08 +0100932 {
Derek Lambertif674aa02019-08-01 15:56:25 +0100933 return EdgeStrategy::CopyToTarget;
Derek Lamberti84da38b2019-06-13 11:40:08 +0100934 }
935 }
936 }
937
Derek Lambertif674aa02019-08-01 15:56:25 +0100938 return EdgeStrategy::Undefined;
Derek Lamberti84da38b2019-06-13 11:40:08 +0100939}
940
941// Select the TensorHandleFactories and the corresponding memory strategy
942OptimizationResult SelectTensorHandleStrategy(Graph& optGraph,
943 BackendsMap& backends,
944 TensorHandleFactoryRegistry& registry,
Narumol Prangnawarata2493a02020-08-19 14:39:07 +0100945 bool importEnabled,
Derek Lamberti84da38b2019-06-13 11:40:08 +0100946 Optional<std::vector<std::string>&> errMessages)
947{
948 OptimizationResult result;
949
Narumol Prangnawarata2493a02020-08-19 14:39:07 +0100950 optGraph.ForEachLayer([&backends, &registry, &result, &errMessages, importEnabled](Layer* layer)
Derek Lamberti84da38b2019-06-13 11:40:08 +0100951 {
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +0100952 ARMNN_ASSERT(layer);
Derek Lamberti84da38b2019-06-13 11:40:08 +0100953
954 // Lets make sure the backend is in our list of supported backends. Something went wrong during backend
955 // assignment if this check fails
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +0100956 ARMNN_ASSERT(backends.find(layer->GetBackendId()) != backends.end());
Derek Lamberti84da38b2019-06-13 11:40:08 +0100957
958 // Check each output separately
959 for (unsigned int slotIdx = 0; slotIdx < layer->GetNumOutputSlots(); slotIdx++)
960 {
961 OutputSlot& outputSlot = layer->GetOutputSlot(slotIdx);
962
963 ITensorHandleFactory::FactoryId slotOption = ITensorHandleFactory::LegacyFactoryId;
964
965 // Calculate the factory to use which results in the fewest copies being made.
966 switch(layer->GetType())
967 {
968 case LayerType::Input:
969 slotOption = CalculateSlotOptionForInput(backends, outputSlot, registry);
970 break;
971 case LayerType::Output:
972 slotOption = CalculateSlotOptionForOutput(backends, outputSlot, registry);
973 break;
974 default:
975 slotOption = CalculateSlotOption(backends, outputSlot, registry);
976 break;
977 }
978 outputSlot.SetTensorHandleFactory(slotOption);
979
Derek Lambertif674aa02019-08-01 15:56:25 +0100980 // Now determine the "best" edge strategy for each connection given the slotOption.
Derek Lamberti84da38b2019-06-13 11:40:08 +0100981 unsigned int connectionIdx = 0;
982 for (auto&& connection : outputSlot.GetConnections())
983 {
984 const Layer& connectedLayer = connection->GetOwningLayer();
985
Narumol Prangnawarata2493a02020-08-19 14:39:07 +0100986 EdgeStrategy strategy = CalculateEdgeStrategy(backends, slotOption, *layer, connectedLayer,
987 registry, importEnabled);
Derek Lamberti84da38b2019-06-13 11:40:08 +0100988
Derek Lambertif674aa02019-08-01 15:56:25 +0100989 if (strategy == EdgeStrategy::Undefined)
Derek Lamberti84da38b2019-06-13 11:40:08 +0100990 {
991 result.m_Error = true;
992 if (errMessages)
993 {
994 errMessages.value().emplace_back("Could not find valid strategy required for compatibility"
995 " between backends.");
996 }
997 return;
998 }
999
Derek Lambertif674aa02019-08-01 15:56:25 +01001000 outputSlot.SetEdgeStrategy(connectionIdx, strategy);
Derek Lamberti84da38b2019-06-13 11:40:08 +01001001
1002 connectionIdx++;
1003 }
1004 }
1005 });
1006
1007 return result;
1008}
1009
Matteo Martincigh49124022019-01-11 13:25:59 +00001010IOptimizedNetworkPtr Optimize(const INetwork& inNetwork,
1011 const std::vector<BackendId>& backendPreferences,
1012 const IDeviceSpec& deviceSpec,
1013 const OptimizerOptions& options,
Rob Hughes23214432019-11-05 11:27:36 +00001014 Optional<std::vector<std::string>&> messages)
Matteo Martincigh49124022019-01-11 13:25:59 +00001015{
1016 if (backendPreferences.empty())
1017 {
Mike Kelly3a613cc2020-09-29 20:50:35 +01001018 throw InvalidArgumentException("Invoked Optimize with no backends specified");
Matteo Martincigh49124022019-01-11 13:25:59 +00001019 }
1020
Narumol Prangnawaratbc7ffb52020-03-20 15:01:01 +00001021 if (options.m_ReduceFp32ToFp16 && options.m_ReduceFp32ToBf16)
1022 {
1023 throw InvalidArgumentException("BFloat16 and Float16 optimization cannot be enabled at the same time.");
1024 }
1025
Jan Eilersbb446e52020-04-02 13:56:54 +01001026 const Network& network = *PolymorphicDowncast<const Network*>(&inNetwork);
Matteo Martincigh49124022019-01-11 13:25:59 +00001027 std::unique_ptr<Graph> graph = std::make_unique<Graph>(network.GetGraph());
1028
Sadik Armagan045f6be2020-09-10 13:37:32 +01001029 auto optNet = IOptimizedNetworkPtr(new OptimizedNetwork(std::move(graph), options.m_ModelOptions),
1030 &IOptimizedNetwork::Destroy);
Matteo Martincigh49124022019-01-11 13:25:59 +00001031
Jan Eilersbb446e52020-04-02 13:56:54 +01001032 OptimizedNetwork* optNetObjPtr = PolymorphicDowncast<OptimizedNetwork*>(optNet.get());
Matteo Martincigh49124022019-01-11 13:25:59 +00001033
Matteo Martincighadddddb2019-01-24 14:06:23 +00001034 // Get the optimized graph
1035 Graph& optGraph = optNetObjPtr->GetGraph();
1036
Narumol Prangnawarat16f82f92020-09-14 16:12:44 +01001037 // Perform AddBroadcastReshapeLayer optimisation
1038 using namespace optimizations;
1039 Optimizer::Pass(optGraph, MakeOptimizations(AddBroadcastReshapeLayer()));
1040
Narumol Prangnawaratbbf71a62020-09-07 14:05:22 +01001041 // Infer the tensor infos for all output slots. Throws an exception on failure
1042 optGraph.InferTensorInfos();
1043
Matteo Martincigh49124022019-01-11 13:25:59 +00001044 // Perform optimisation passes
Matteo Martincighadddddb2019-01-24 14:06:23 +00001045 Optimizer::Pass(optGraph, MakeOptimizations(SquashEqualPermuteSiblings(),
Mike Kelly490b7be2020-03-03 12:39:09 +00001046 SquashEqualTransposeSiblings(),
Matteo Martincighadddddb2019-01-24 14:06:23 +00001047 SquashEqualReshapeSiblings(),
1048 OptimizeInversePermutes(),
Mike Kelly490b7be2020-03-03 12:39:09 +00001049 OptimizeInverseTransposes(),
Matteo Martincighadddddb2019-01-24 14:06:23 +00001050 MovePermuteUp(),
Mike Kelly490b7be2020-03-03 12:39:09 +00001051 MoveTransposeUp(),
Matteo Martincighadddddb2019-01-24 14:06:23 +00001052 PermuteAsReshape(),
Mike Kelly490b7be2020-03-03 12:39:09 +00001053 TransposeAsReshape(),
Nina Drozd861985f2019-04-18 14:48:51 +01001054 OptimizeConsecutiveReshapes(),
Rob Hughes3a7d3a72019-09-24 16:59:56 +01001055 FoldPadIntoConvolution2d(),
Mike Kelly490b7be2020-03-03 12:39:09 +00001056 PermuteAndBatchToSpaceAsDepthToSpace(),
Teresa Charlin06e03002020-10-15 13:16:07 +01001057 TransposeAndBatchToSpaceAsDepthToSpace(),
Mike Kelly90231b82020-11-05 15:44:56 +00001058 FuseBatchNormIntoConvolution2DFloat32(),
1059 FuseBatchNormIntoConvolution2DFloat16(),
1060 FuseBatchNormIntoDepthwiseConvolution2DFloat32(),
1061 FuseBatchNormIntoDepthwiseConvolution2DFloat16()));
Matteo Martincigh49124022019-01-11 13:25:59 +00001062
Matteo Martincigh49124022019-01-11 13:25:59 +00001063 // If Fp32 to Fp16 optimization is set convert Fp32 network to Fp16
1064 if (options.m_ReduceFp32ToFp16)
1065 {
Matteo Martincighadddddb2019-01-24 14:06:23 +00001066 Optimizer::Pass(optGraph, MakeOptimizations(Fp32NetworkToFp16Converter()));
Derek Lambertidd6804b2019-11-27 09:29:57 +00001067 Optimizer::Pass(optGraph, MakeOptimizations(ConvertConstantsFloatToHalf()));
Matteo Martincigh49124022019-01-11 13:25:59 +00001068 }
1069
Narumol Prangnawaratbc7ffb52020-03-20 15:01:01 +00001070 // If Fp32 to Bf16 optimization is set convert Fp32 network to Bf16
Narumol Prangnawarat57ef0082020-03-26 09:20:43 +00001071 // Convert input of Convolution2d and FullyConnected from Fp32 to Bf16
1072 // Only Constant weight of Convolution2d and FullyConnected are converted from Fp32 to Bf16
Narumol Prangnawaratbc7ffb52020-03-20 15:01:01 +00001073 if (options.m_ReduceFp32ToBf16)
1074 {
1075 Optimizer::Pass(optGraph, MakeOptimizations(Fp32NetworkToBf16Converter()));
Narumol Prangnawaratbc7ffb52020-03-20 15:01:01 +00001076 }
1077
Matteo Martincigh49124022019-01-11 13:25:59 +00001078 // Initialize backend settings
1079 BackendSettings backendSettings(backendPreferences, deviceSpec);
1080 if (backendSettings.GetAvailablePreferredBackends().empty())
1081 {
1082 std::stringstream failureMsg;
1083 failureMsg << "None of the preferred backends " << backendPreferences
1084 << " are supported. Current platform provides " << backendSettings.m_SupportedBackends;
Rob Hughes23214432019-11-05 11:27:36 +00001085 ReportError(failureMsg.str(), messages);
Mike Kelly3a613cc2020-09-29 20:50:35 +01001086 throw InvalidArgumentException(failureMsg.str());
Matteo Martincigh49124022019-01-11 13:25:59 +00001087 }
1088
Derek Lamberti84da38b2019-06-13 11:40:08 +01001089 // Create a map to temporarily hold initialized backend objects
1090 TensorHandleFactoryRegistry tensorHandleFactoryRegistry;
1091 BackendsMap backends = CreateSupportedBackends(tensorHandleFactoryRegistry, backendSettings);
1092
Matteo Martincigh49124022019-01-11 13:25:59 +00001093 // Assign an available backend to each layer
Matteo Martincighadddddb2019-01-24 14:06:23 +00001094 Graph::Iterator firstLayer = optGraph.begin();
1095 Graph::Iterator lastLayer = optGraph.end();
Derek Lamberti84da38b2019-06-13 11:40:08 +01001096 OptimizationResult assignBackendsResult = AssignBackends(optNetObjPtr,
1097 backendSettings,
1098 firstLayer,
1099 lastLayer,
Rob Hughes23214432019-11-05 11:27:36 +00001100 messages);
Derek Lamberti84da38b2019-06-13 11:40:08 +01001101 if (assignBackendsResult.m_Error)
Matteo Martincigh49124022019-01-11 13:25:59 +00001102 {
1103 // Failed to assign a backend to each layer
Mike Kelly3a613cc2020-09-29 20:50:35 +01001104 throw InvalidArgumentException("Failed to assign a backend to each layer");
jimfly016b0b53d2018-10-08 14:43:01 +01001105 }
telsoa01c577f2c2018-08-31 09:22:23 +01001106
Matteo Martincighadddddb2019-01-24 14:06:23 +00001107 Optimizer::Pass(optGraph, MakeOptimizations(OptimizeInverseConversionsFp16(),
1108 OptimizeInverseConversionsFp32()));
telsoa01c577f2c2018-08-31 09:22:23 +01001109
Matteo Martincighadddddb2019-01-24 14:06:23 +00001110 // Apply the backend-specific optimizations
1111 OptimizationResult backendOptimizationResult = ApplyBackendOptimizations(optNetObjPtr,
1112 backendSettings,
Derek Lamberti84da38b2019-06-13 11:40:08 +01001113 backends,
Rob Hughes23214432019-11-05 11:27:36 +00001114 messages);
Matteo Martincighadddddb2019-01-24 14:06:23 +00001115 if (backendOptimizationResult.m_Error)
Matteo Martincigh49124022019-01-11 13:25:59 +00001116 {
Matteo Martincighadddddb2019-01-24 14:06:23 +00001117 // Failed to apply the backend-specific optimizations
Mike Kelly3a613cc2020-09-29 20:50:35 +01001118 throw InvalidArgumentException("Failed to apply the backend-specific optimizations");
Matteo Martincigh49124022019-01-11 13:25:59 +00001119 }
1120
Matteo Martincighadddddb2019-01-24 14:06:23 +00001121 // If the debug flag is set, then insert a DebugLayer after each layer
1122 // Doing this after applying the backend optimizations as they might have changed some layers
1123 if (options.m_Debug)
1124 {
1125 Optimizer::Pass(optGraph, MakeOptimizations(InsertDebugLayer()));
1126 }
1127
Derek Lamberti84da38b2019-06-13 11:40:08 +01001128 // Calculate the compatibility strategies for tensor handles
1129 OptimizationResult strategyResult = SelectTensorHandleStrategy(optGraph,
1130 backends,
1131 tensorHandleFactoryRegistry,
Narumol Prangnawarata2493a02020-08-19 14:39:07 +01001132 options.m_ImportEnabled,
Rob Hughes23214432019-11-05 11:27:36 +00001133 messages);
Derek Lamberti84da38b2019-06-13 11:40:08 +01001134 if (strategyResult.m_Error)
1135 {
1136 // Failed to apply the backend-specific optimizations
1137 return IOptimizedNetworkPtr(nullptr, &IOptimizedNetwork::Destroy);
1138 }
1139
1140 // Based on the tensor handle strategy determined above, insert copy layers where required.
Derek Lambertif674aa02019-08-01 15:56:25 +01001141 optGraph.AddCompatibilityLayers(backends, tensorHandleFactoryRegistry);
telsoa01c577f2c2018-08-31 09:22:23 +01001142
1143 // Convert constants
Matteo Martincighadddddb2019-01-24 14:06:23 +00001144 Optimizer::Pass(optGraph, MakeOptimizations(ConvertConstantsFloatToHalf()));
1145 Optimizer::Pass(optGraph, MakeOptimizations(ConvertConstantsHalfToFloat()));
telsoa01c577f2c2018-08-31 09:22:23 +01001146
Derek Lamberti84da38b2019-06-13 11:40:08 +01001147 // Run backend specific optimizations (deprecated)
Matteo Martincigh49124022019-01-11 13:25:59 +00001148 for (auto&& chosenBackend : backendSettings.m_SelectedBackends)
David Beck263e3492018-11-09 14:46:40 +00001149 {
1150 auto factoryFun = BackendRegistryInstance().GetFactory(chosenBackend);
1151 auto backendPtr = factoryFun();
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +01001152 ARMNN_ASSERT(backendPtr.get() != nullptr);
David Beck263e3492018-11-09 14:46:40 +00001153
Matteo Martincighed735042019-05-22 09:42:43 +01001154 ARMNN_NO_DEPRECATE_WARN_BEGIN
David Beck263e3492018-11-09 14:46:40 +00001155 auto backendSpecificOptimizations = backendPtr->GetOptimizations();
Matteo Martincighed735042019-05-22 09:42:43 +01001156 ARMNN_NO_DEPRECATE_WARN_END
1157
David Beck263e3492018-11-09 14:46:40 +00001158 if (!backendSpecificOptimizations.empty())
1159 {
1160 Optimizer::Pass(optNetObjPtr->GetGraph(), backendSpecificOptimizations);
1161 }
1162 }
1163
telsoa01c577f2c2018-08-31 09:22:23 +01001164 return optNet;
telsoa014fcda012018-03-09 14:13:49 +00001165}
Finn Williamsf24effa2020-07-03 10:12:03 +01001166bool Network::GetShapeInferenceMethod()
telsoa014fcda012018-03-09 14:13:49 +00001167{
Finn Williamsf24effa2020-07-03 10:12:03 +01001168 if (m_NetworkOptions.size() > 0 && m_NetworkOptions[0].GetBackendId().Get() == "ShapeInferenceMethod")
1169 {
1170 return m_NetworkOptions[0].GetOption(0).GetValue().AsBool();
1171 }
1172
1173 return false;
telsoa014fcda012018-03-09 14:13:49 +00001174}
Finn Williamsf24effa2020-07-03 10:12:03 +01001175Network::Network(NetworkOptions networkOptions)
1176: m_NetworkOptions(networkOptions),
1177 m_Graph(std::make_unique<Graph>(GetShapeInferenceMethod()))
1178{}
telsoa014fcda012018-03-09 14:13:49 +00001179
1180Network::~Network()
1181{
1182}
1183
Jan Eilers99d9d4a2019-11-06 10:02:16 +00001184Status Network::PrintGraph()
1185{
1186 m_Graph->Print();
1187 return Status::Success;
1188}
1189
telsoa014fcda012018-03-09 14:13:49 +00001190IConnectableLayer* Network::AddInputLayer(LayerBindingId id, const char* name)
1191{
1192 return m_Graph->AddLayer<InputLayer>(id, name);
1193}
1194
Éanna Ó Catháin4e1e1362018-11-12 11:36:34 +00001195IConnectableLayer* Network::AddBatchToSpaceNdLayer(const BatchToSpaceNdDescriptor& batchToSpaceNdDescriptor,
1196 const char* name)
1197{
1198 return m_Graph->AddLayer<BatchToSpaceNdLayer>(batchToSpaceNdDescriptor, name);
1199}
1200
Aron Virginas-Tar77bfb5e2019-10-16 17:45:38 +01001201IConnectableLayer* Network::AddComparisonLayer(const ComparisonDescriptor& comparisonDescriptor,
1202 const char* name)
1203{
1204 return m_Graph->AddLayer<ComparisonLayer>(comparisonDescriptor, name);
1205}
1206
josh minor4a3c6102020-01-06 16:40:46 -06001207IConnectableLayer* Network::AddElementwiseUnaryLayer(const ElementwiseUnaryDescriptor& elementwiseUnaryDescriptor,
1208 const char* name)
1209{
1210 return m_Graph->AddLayer<ElementwiseUnaryLayer>(elementwiseUnaryDescriptor, name);
1211}
1212
Ryan OSheaec6c6802020-06-05 17:17:06 +01001213IConnectableLayer* Network::AddFillLayer(const FillDescriptor& fillDescriptor,
1214 const char* name)
1215{
1216 return m_Graph->AddLayer<FillLayer>(fillDescriptor, name);
1217}
1218
telsoa014fcda012018-03-09 14:13:49 +00001219IConnectableLayer* Network::AddFullyConnectedLayerImpl(const FullyConnectedDescriptor& fullyConnectedDescriptor,
telsoa01c577f2c2018-08-31 09:22:23 +01001220 const ConstTensor& weights,
Aron Virginas-Tarad402702019-02-22 17:03:44 +00001221 const Optional<ConstTensor>& biases,
telsoa01c577f2c2018-08-31 09:22:23 +01001222 const char* name)
telsoa014fcda012018-03-09 14:13:49 +00001223{
Aron Virginas-Tarad402702019-02-22 17:03:44 +00001224 if (fullyConnectedDescriptor.m_BiasEnabled && !biases.has_value())
telsoa014fcda012018-03-09 14:13:49 +00001225 {
Aron Virginas-Tarad402702019-02-22 17:03:44 +00001226 throw InvalidArgumentException("AddFullyConnectedLayer: biases cannot be empty");
telsoa014fcda012018-03-09 14:13:49 +00001227 }
1228
1229 const auto layer = m_Graph->AddLayer<FullyConnectedLayer>(fullyConnectedDescriptor, name);
1230
1231 layer->m_Weight = std::make_unique<ScopedCpuTensorHandle>(weights);
1232
1233 if (fullyConnectedDescriptor.m_BiasEnabled)
1234 {
Aron Virginas-Tarad402702019-02-22 17:03:44 +00001235 layer->m_Bias = std::make_unique<ScopedCpuTensorHandle>(biases.value());
telsoa014fcda012018-03-09 14:13:49 +00001236 }
1237
1238 return layer;
1239}
1240
1241IConnectableLayer* Network::AddFullyConnectedLayer(const FullyConnectedDescriptor& fullyConnectedDescriptor,
telsoa01c577f2c2018-08-31 09:22:23 +01001242 const ConstTensor& weights,
Aron Virginas-Tarad402702019-02-22 17:03:44 +00001243 const Optional<ConstTensor>& biases,
telsoa01c577f2c2018-08-31 09:22:23 +01001244 const char* name)
telsoa014fcda012018-03-09 14:13:49 +00001245{
Aron Virginas-Tarad402702019-02-22 17:03:44 +00001246 return AddFullyConnectedLayerImpl(fullyConnectedDescriptor, weights, biases, name);
telsoa014fcda012018-03-09 14:13:49 +00001247}
1248
Aron Virginas-Tarad402702019-02-22 17:03:44 +00001249IConnectableLayer* Network::AddFullyConnectedLayer(const FullyConnectedDescriptor& fullyConnectedDescriptor,
1250 const ConstTensor& weights,
1251 const char* name)
1252{
Matteo Martincighfc598e12019-05-14 10:36:13 +01001253 Optional<ConstTensor> biases;
Aron Virginas-Tarad402702019-02-22 17:03:44 +00001254 return AddFullyConnectedLayerImpl(fullyConnectedDescriptor, weights, biases, name);
1255}
1256
telsoa014fcda012018-03-09 14:13:49 +00001257IConnectableLayer* Network::AddFullyConnectedLayer(const FullyConnectedDescriptor& fullyConnectedDescriptor,
telsoa01c577f2c2018-08-31 09:22:23 +01001258 const ConstTensor& weights,
1259 const ConstTensor& biases,
1260 const char* name)
telsoa014fcda012018-03-09 14:13:49 +00001261{
Aron Virginas-Tarad402702019-02-22 17:03:44 +00001262 Optional<ConstTensor> optionalBiases(biases);
1263 return AddFullyConnectedLayerImpl(fullyConnectedDescriptor, weights, optionalBiases, name);
telsoa014fcda012018-03-09 14:13:49 +00001264}
1265
Jim Flynne242f2d2019-05-22 14:24:13 +01001266IConnectableLayer* Network::AddConcatLayer(const ConcatDescriptor& concatDescriptor,
Jim Flynn906f9462019-05-10 13:55:21 +01001267 const char* name)
1268{
Jim Flynne242f2d2019-05-22 14:24:13 +01001269 return m_Graph->AddLayer<ConcatLayer>(concatDescriptor, name);
Jim Flynn906f9462019-05-10 13:55:21 +01001270}
1271
telsoa014fcda012018-03-09 14:13:49 +00001272IConnectableLayer* Network::AddConvolution2dLayerImpl(const Convolution2dDescriptor& convolution2dDescriptor,
telsoa01c577f2c2018-08-31 09:22:23 +01001273 const ConstTensor& weights,
Aron Virginas-Tarad402702019-02-22 17:03:44 +00001274 const Optional<ConstTensor>& biases,
telsoa01c577f2c2018-08-31 09:22:23 +01001275 const char* name)
telsoa014fcda012018-03-09 14:13:49 +00001276{
Aron Virginas-Tarad402702019-02-22 17:03:44 +00001277 if (convolution2dDescriptor.m_BiasEnabled && !biases.has_value())
telsoa014fcda012018-03-09 14:13:49 +00001278 {
Aron Virginas-Tarad402702019-02-22 17:03:44 +00001279 throw InvalidArgumentException("AddConvolution2dLayer: biases cannot be empty");
telsoa014fcda012018-03-09 14:13:49 +00001280 }
1281
1282 const auto layer = m_Graph->AddLayer<Convolution2dLayer>(convolution2dDescriptor, name);
1283
1284 layer->m_Weight = std::make_unique<ScopedCpuTensorHandle>(weights);
1285
1286 if (convolution2dDescriptor.m_BiasEnabled)
1287 {
Aron Virginas-Tarad402702019-02-22 17:03:44 +00001288 layer->m_Bias = std::make_unique<ScopedCpuTensorHandle>(biases.value());
telsoa014fcda012018-03-09 14:13:49 +00001289 }
1290
1291 return layer;
1292}
1293
1294IConnectableLayer* Network::AddConvolution2dLayer(const Convolution2dDescriptor& convolution2dDescriptor,
telsoa01c577f2c2018-08-31 09:22:23 +01001295 const ConstTensor& weights,
Aron Virginas-Tarad402702019-02-22 17:03:44 +00001296 const Optional<ConstTensor>& biases,
telsoa01c577f2c2018-08-31 09:22:23 +01001297 const char* name)
telsoa014fcda012018-03-09 14:13:49 +00001298{
Aron Virginas-Tarad402702019-02-22 17:03:44 +00001299 return AddConvolution2dLayerImpl(convolution2dDescriptor, weights, biases, name);
telsoa014fcda012018-03-09 14:13:49 +00001300}
Aron Virginas-Tarad402702019-02-22 17:03:44 +00001301
Aron Virginas-Tarad402702019-02-22 17:03:44 +00001302IConnectableLayer* Network::AddConvolution2dLayer(const Convolution2dDescriptor& convolution2dDescriptor,
1303 const ConstTensor& weights,
1304 const char* name)
1305{
Matteo Martincighfc598e12019-05-14 10:36:13 +01001306 Optional<ConstTensor> biases;
Aron Virginas-Tarad402702019-02-22 17:03:44 +00001307 return AddConvolution2dLayerImpl(convolution2dDescriptor, weights, biases, name);
1308}
1309
telsoa014fcda012018-03-09 14:13:49 +00001310IConnectableLayer* Network::AddConvolution2dLayer(const Convolution2dDescriptor& convolution2dDescriptor,
telsoa01c577f2c2018-08-31 09:22:23 +01001311 const ConstTensor& weights,
1312 const ConstTensor& biases,
1313 const char* name)
telsoa014fcda012018-03-09 14:13:49 +00001314{
Aron Virginas-Tarad402702019-02-22 17:03:44 +00001315 Optional<ConstTensor> optionalBiases(biases);
1316 return AddConvolution2dLayerImpl(convolution2dDescriptor, weights, optionalBiases, name);
telsoa014fcda012018-03-09 14:13:49 +00001317}
1318
1319IConnectableLayer* Network::AddDepthwiseConvolution2dLayerImpl(
1320 const DepthwiseConvolution2dDescriptor& convolution2dDescriptor,
1321 const ConstTensor& weights,
Aron Virginas-Tarad402702019-02-22 17:03:44 +00001322 const Optional<ConstTensor>& biases,
telsoa014fcda012018-03-09 14:13:49 +00001323 const char* name)
1324{
Aron Virginas-Tarad402702019-02-22 17:03:44 +00001325 if (convolution2dDescriptor.m_BiasEnabled && !biases.has_value())
telsoa014fcda012018-03-09 14:13:49 +00001326 {
Aron Virginas-Tarad402702019-02-22 17:03:44 +00001327 throw InvalidArgumentException("AddDepthwiseConvolution2dLayer: biases cannot be empty");
telsoa014fcda012018-03-09 14:13:49 +00001328 }
1329
Matteo Martincigh3d6898c2019-01-15 16:11:44 +00001330 const auto layer = m_Graph->AddLayer<DepthwiseConvolution2dLayer>(convolution2dDescriptor, name);
telsoa014fcda012018-03-09 14:13:49 +00001331
1332 layer->m_Weight = std::make_unique<ScopedCpuTensorHandle>(weights);
1333
1334 if (convolution2dDescriptor.m_BiasEnabled)
1335 {
Aron Virginas-Tarad402702019-02-22 17:03:44 +00001336 layer->m_Bias = std::make_unique<ScopedCpuTensorHandle>(biases.value());
telsoa014fcda012018-03-09 14:13:49 +00001337 }
1338
1339 return layer;
1340}
1341
Aron Virginas-Tardd6247f2019-09-19 14:31:17 +01001342IConnectableLayer* Network::AddDepthToSpaceLayer(const DepthToSpaceDescriptor& depthToSpaceDescriptor,
1343 const char* name)
1344{
1345 return m_Graph->AddLayer<DepthToSpaceLayer>(depthToSpaceDescriptor, name);
1346}
1347
telsoa014fcda012018-03-09 14:13:49 +00001348IConnectableLayer* Network::AddDepthwiseConvolution2dLayer(
Aron Virginas-Tarad402702019-02-22 17:03:44 +00001349 const DepthwiseConvolution2dDescriptor& convolution2dDescriptor,
1350 const ConstTensor& weights,
1351 const Optional<ConstTensor>& biases,
1352 const char* name)
1353{
1354 return AddDepthwiseConvolution2dLayerImpl(convolution2dDescriptor, weights, biases, name);
1355}
1356
Aron Virginas-Tarad402702019-02-22 17:03:44 +00001357IConnectableLayer* Network::AddDepthwiseConvolution2dLayer(
telsoa014fcda012018-03-09 14:13:49 +00001358 const DepthwiseConvolution2dDescriptor& convolution2dDescriptor,
1359 const ConstTensor& weights,
1360 const char* name)
1361{
Matteo Martincighfc598e12019-05-14 10:36:13 +01001362 Optional<ConstTensor> biases;
Aron Virginas-Tarad402702019-02-22 17:03:44 +00001363 return AddDepthwiseConvolution2dLayerImpl(convolution2dDescriptor, weights, biases, name);
telsoa014fcda012018-03-09 14:13:49 +00001364}
Aron Virginas-Tarad402702019-02-22 17:03:44 +00001365
telsoa014fcda012018-03-09 14:13:49 +00001366IConnectableLayer* Network::AddDepthwiseConvolution2dLayer(
1367 const DepthwiseConvolution2dDescriptor& convolution2dDescriptor,
1368 const ConstTensor& weights,
1369 const ConstTensor& biases,
1370 const char* name)
1371{
Aron Virginas-Tarad402702019-02-22 17:03:44 +00001372 Optional<ConstTensor> optionalBiases(biases);
1373 return AddDepthwiseConvolution2dLayerImpl(convolution2dDescriptor, weights, optionalBiases, name);
telsoa014fcda012018-03-09 14:13:49 +00001374}
1375
Narumol Prangnawarat94dd5d82019-01-23 18:06:26 +00001376IConnectableLayer* Network::AddDetectionPostProcessLayer(const armnn::DetectionPostProcessDescriptor& descriptor,
Narumol Prangnawarat6d302bf2019-02-04 11:46:26 +00001377 const ConstTensor& anchors, const char* name)
Narumol Prangnawarat94dd5d82019-01-23 18:06:26 +00001378{
Narumol Prangnawarat6d302bf2019-02-04 11:46:26 +00001379 const auto layer = m_Graph->AddLayer<DetectionPostProcessLayer>(descriptor, name);
1380
1381 layer->m_Anchors = std::make_unique<ScopedCpuTensorHandle>(anchors);
1382
1383 return layer;
Narumol Prangnawarat94dd5d82019-01-23 18:06:26 +00001384}
1385
telsoa014fcda012018-03-09 14:13:49 +00001386IConnectableLayer* Network::AddPermuteLayer(const PermuteDescriptor& permuteDescriptor,
1387 const char* name)
1388{
1389 return m_Graph->AddLayer<PermuteLayer>(permuteDescriptor, name);
1390}
1391
1392IConnectableLayer* Network::AddPooling2dLayer(const Pooling2dDescriptor& pooling2dDescriptor,
1393 const char* name)
1394{
1395 return m_Graph->AddLayer<Pooling2dLayer>(pooling2dDescriptor, name);
1396}
1397
1398IConnectableLayer* Network::AddActivationLayer(const ActivationDescriptor& activationDescriptor,
1399 const char* name)
1400{
1401 return m_Graph->AddLayer<ActivationLayer>(activationDescriptor, name);
1402}
1403
Nikhil Rajee391d52019-09-05 17:50:44 +01001404IConnectableLayer* Network::AddArgMinMaxLayer(const ArgMinMaxDescriptor& argMinMaxDescriptor,
1405 const char* name)
1406{
1407 return m_Graph->AddLayer<ArgMinMaxLayer>(argMinMaxDescriptor, name);
1408}
1409
telsoa01c577f2c2018-08-31 09:22:23 +01001410IConnectableLayer* Network::AddNormalizationLayer(const NormalizationDescriptor&
1411normalizationDescriptor,
telsoa014fcda012018-03-09 14:13:49 +00001412 const char* name)
1413{
1414 return m_Graph->AddLayer<NormalizationLayer>(normalizationDescriptor, name);
1415}
1416
Aron Virginas-Tar636ab402019-09-16 14:27:45 +01001417IConnectableLayer* Network::AddSliceLayer(const SliceDescriptor& sliceDescriptor, const char* name)
1418{
1419 return m_Graph->AddLayer<SliceLayer>(sliceDescriptor, name);
1420}
1421
telsoa014fcda012018-03-09 14:13:49 +00001422IConnectableLayer* Network::AddSoftmaxLayer(const SoftmaxDescriptor& softmaxDescriptor,
1423 const char* name)
1424{
1425 return m_Graph->AddLayer<SoftmaxLayer>(softmaxDescriptor, name);
1426}
1427
1428IConnectableLayer* Network::AddSplitterLayer(const ViewsDescriptor& splitterDescriptor,
1429 const char* name)
1430{
1431 return m_Graph->AddLayer<SplitterLayer>(splitterDescriptor, name);
1432}
1433
Nattapat Chaimanowong5a4304a2018-11-28 10:44:37 +00001434IConnectableLayer* Network::AddMaximumLayer(const char* name)
1435{
1436 return m_Graph->AddLayer<MaximumLayer>(name);
1437}
1438
Éanna Ó Catháin20e58802018-12-04 10:29:06 +00001439IConnectableLayer* Network::AddMinimumLayer(const char* name)
1440{
1441 return m_Graph->AddLayer<MinimumLayer>(name);
1442}
1443
Jim Flynne242f2d2019-05-22 14:24:13 +01001444IConnectableLayer* Network::AddMergerLayer(const MergerDescriptor& mergerDescriptor,
Jim Flynn906f9462019-05-10 13:55:21 +01001445 const char* name)
telsoa014fcda012018-03-09 14:13:49 +00001446{
Jim Flynne242f2d2019-05-22 14:24:13 +01001447 return AddConcatLayer(mergerDescriptor, name);
telsoa014fcda012018-03-09 14:13:49 +00001448}
1449
Kevin May868eb142019-09-04 17:29:31 +01001450IConnectableLayer* Network::AddAbsLayer(const char * name)
1451{
josh minor4a3c6102020-01-06 16:40:46 -06001452 return AddElementwiseUnaryLayer(ElementwiseUnaryDescriptor(UnaryOperation::Abs), name);
Kevin May868eb142019-09-04 17:29:31 +01001453}
1454
telsoa014fcda012018-03-09 14:13:49 +00001455IConnectableLayer* Network::AddAdditionLayer(const char* name)
1456{
1457 return m_Graph->AddLayer<AdditionLayer>(name);
1458}
1459
1460IConnectableLayer* Network::AddMultiplicationLayer(const char* name)
1461{
1462 return m_Graph->AddLayer<MultiplicationLayer>(name);
1463}
1464
1465IConnectableLayer* Network::AddOutputLayer(LayerBindingId id, const char* name)
1466{
1467 return m_Graph->AddLayer<OutputLayer>(id, name);
1468}
1469
1470IConnectableLayer* Network::AddBatchNormalizationLayer(const BatchNormalizationDescriptor& desc,
1471 const ConstTensor& mean,
1472 const ConstTensor& variance,
1473 const ConstTensor& beta,
1474 const ConstTensor& gamma,
1475 const char* name)
1476{
1477 const auto layer = m_Graph->AddLayer<BatchNormalizationLayer>(desc, name);
1478
1479 layer->m_Mean = std::make_unique<ScopedCpuTensorHandle>(mean);
1480 layer->m_Variance = std::make_unique<ScopedCpuTensorHandle>(variance);
1481 layer->m_Beta = std::make_unique<ScopedCpuTensorHandle>(beta);
1482 layer->m_Gamma = std::make_unique<ScopedCpuTensorHandle>(gamma);
1483
1484 return layer;
1485}
1486
Finn Williams2605b232020-06-10 15:53:46 +01001487IConnectableLayer* Network::AddRankLayer(const char* name)
1488{
1489 return m_Graph->AddLayer<RankLayer>(name);
1490}
1491
Aron Virginas-Tar169d2f12019-07-01 19:01:44 +01001492IConnectableLayer* Network::AddResizeBilinearLayer(const ResizeBilinearDescriptor& descriptor,
1493 const char* name)
telsoa014fcda012018-03-09 14:13:49 +00001494{
Aron Virginas-Tar169d2f12019-07-01 19:01:44 +01001495 ResizeDescriptor resizeDescriptor;
David Monahan4a0c9b92020-05-30 09:48:39 +01001496 resizeDescriptor.m_Method = ResizeMethod::Bilinear;
1497 resizeDescriptor.m_DataLayout = descriptor.m_DataLayout;
1498 resizeDescriptor.m_TargetWidth = descriptor.m_TargetWidth;
1499 resizeDescriptor.m_TargetHeight = descriptor.m_TargetHeight;
1500 resizeDescriptor.m_AlignCorners = descriptor.m_AlignCorners;
1501 resizeDescriptor.m_HalfPixelCenters = descriptor.m_HalfPixelCenters;
Aron Virginas-Tar169d2f12019-07-01 19:01:44 +01001502
1503 return m_Graph->AddLayer<ResizeLayer>(resizeDescriptor, name);
telsoa014fcda012018-03-09 14:13:49 +00001504}
1505
Teresa Charlina9075df2019-06-27 15:41:57 +01001506IConnectableLayer* Network::AddResizeLayer(const ResizeDescriptor&
1507resizeDescriptor, const char* name)
1508{
Aron Virginas-Tar169d2f12019-07-01 19:01:44 +01001509 return m_Graph->AddLayer<ResizeLayer>(resizeDescriptor, name);
Teresa Charlina9075df2019-06-27 15:41:57 +01001510}
1511
Kevin Mayce5045a2019-10-02 14:07:47 +01001512IConnectableLayer* Network::AddInstanceNormalizationLayer(const InstanceNormalizationDescriptor& desc,
1513 const char* name)
1514{
1515 return m_Graph->AddLayer<InstanceNormalizationLayer>(desc, name);
1516}
1517
Matteo Martincighbcd3c852018-09-28 14:14:12 +01001518IConnectableLayer* Network::AddL2NormalizationLayer(const L2NormalizationDescriptor& desc,
1519 const char* name)
telsoa014fcda012018-03-09 14:13:49 +00001520{
Matteo Martincighbcd3c852018-09-28 14:14:12 +01001521 return m_Graph->AddLayer<L2NormalizationLayer>(desc, name);
telsoa014fcda012018-03-09 14:13:49 +00001522}
1523
Aron Virginas-Tarf982dea2019-10-11 14:07:53 +01001524IConnectableLayer* Network::AddLogSoftmaxLayer(const LogSoftmaxDescriptor& desc,
1525 const char* name)
1526{
1527 return m_Graph->AddLayer<LogSoftmaxLayer>(desc, name);
1528}
1529
telsoa014fcda012018-03-09 14:13:49 +00001530IConnectableLayer* Network::AddConstantLayer(const ConstTensor& input, const char* name)
1531{
telsoa01c577f2c2018-08-31 09:22:23 +01001532 auto layer = m_Graph->AddLayer<ConstantLayer>(name);
1533
1534 layer->m_LayerOutput = std::make_unique<ScopedCpuTensorHandle>(input);
1535
1536 return layer;
telsoa014fcda012018-03-09 14:13:49 +00001537}
1538
telsoa01c577f2c2018-08-31 09:22:23 +01001539IConnectableLayer* Network::AddReshapeLayer(const ReshapeDescriptor& reshapeDescriptor,
1540 const char* name)
telsoa014fcda012018-03-09 14:13:49 +00001541{
1542 return m_Graph->AddLayer<ReshapeLayer>(reshapeDescriptor, name);
1543}
1544
Nattapat Chaimanowong207ef9a2018-11-02 10:57:25 +00001545IConnectableLayer* Network::AddSpaceToBatchNdLayer(const SpaceToBatchNdDescriptor& spaceToBatchNdDescriptor,
1546 const char* name)
1547{
1548 return m_Graph->AddLayer<SpaceToBatchNdLayer>(spaceToBatchNdDescriptor, name);
1549}
1550
Aron Virginas-Tar972af152019-06-11 14:14:03 +01001551IConnectableLayer* Network::AddSpaceToDepthLayer(const SpaceToDepthDescriptor& spaceToDepthDescriptor,
1552 const char* name)
1553{
1554 return m_Graph->AddLayer<SpaceToDepthLayer>(spaceToDepthDescriptor, name);
1555}
1556
telsoa014fcda012018-03-09 14:13:49 +00001557IConnectableLayer* Network::AddFloorLayer(const char* name)
1558{
1559 return m_Graph->AddLayer<FloorLayer>(name);
1560}
1561
telsoa01c577f2c2018-08-31 09:22:23 +01001562IConnectableLayer* Network::AddLstmLayer(const LstmDescriptor& descriptor,
1563 const LstmInputParams& params,
1564 const char* name)
1565{
1566 const auto layer = m_Graph->AddLayer<LstmLayer>(descriptor, name);
1567
1568 //Lstm Basic Parameters
1569 layer->m_BasicParameters.m_InputToForgetWeights =
1570 std::make_unique<ScopedCpuTensorHandle>(*(params.m_InputToForgetWeights));
1571 layer->m_BasicParameters.m_InputToCellWeights =
1572 std::make_unique<ScopedCpuTensorHandle>(*(params.m_InputToCellWeights));
1573 layer->m_BasicParameters.m_InputToOutputWeights =
1574 std::make_unique<ScopedCpuTensorHandle>(*(params.m_InputToOutputWeights));
1575 layer->m_BasicParameters.m_RecurrentToForgetWeights =
1576 std::make_unique<ScopedCpuTensorHandle>(*(params.m_RecurrentToForgetWeights));
1577 layer->m_BasicParameters.m_RecurrentToCellWeights =
1578 std::make_unique<ScopedCpuTensorHandle>(*(params.m_RecurrentToCellWeights));
1579 layer->m_BasicParameters.m_RecurrentToOutputWeights =
1580 std::make_unique<ScopedCpuTensorHandle>(*(params.m_RecurrentToOutputWeights));
1581 layer->m_BasicParameters.m_ForgetGateBias =
1582 std::make_unique<ScopedCpuTensorHandle>(*(params.m_ForgetGateBias));
1583 layer->m_BasicParameters.m_CellBias =
1584 std::make_unique<ScopedCpuTensorHandle>(*(params.m_CellBias));
1585 layer->m_BasicParameters.m_OutputGateBias =
1586 std::make_unique<ScopedCpuTensorHandle>(*(params.m_OutputGateBias));
1587
1588 //Lstm Cifg parameters
1589 if(!descriptor.m_CifgEnabled)
1590 {
1591 if(params.m_InputToInputWeights == nullptr)
1592 {
Jan Eilerse2062cd2020-03-30 15:07:45 +01001593 throw InvalidArgumentException("AddLstmLayer: Input To Input Weights cannot be NULL "
1594 "when CIFG is disabled.");
telsoa01c577f2c2018-08-31 09:22:23 +01001595 }
1596 if(params.m_RecurrentToInputWeights == nullptr)
1597 {
1598 throw InvalidArgumentException(
Jan Eilerse2062cd2020-03-30 15:07:45 +01001599 "AddLstmLayer: Recurrent To Input Weights cannot be NULL "
1600 "when CIFG is disabled.");
telsoa01c577f2c2018-08-31 09:22:23 +01001601 }
1602 if(params.m_InputGateBias == nullptr)
1603 {
Jan Eilerse2062cd2020-03-30 15:07:45 +01001604 throw InvalidArgumentException("AddLstmLayer: Input Gate Bias cannot be NULL "
1605 "when CIFG is disabled.");
telsoa01c577f2c2018-08-31 09:22:23 +01001606 }
1607 layer->m_CifgParameters.m_InputToInputWeights =
1608 std::make_unique<ScopedCpuTensorHandle>(*(params.m_InputToInputWeights));
1609 layer->m_CifgParameters.m_RecurrentToInputWeights =
1610 std::make_unique<ScopedCpuTensorHandle>(*(params.m_RecurrentToInputWeights));
telsoa01c577f2c2018-08-31 09:22:23 +01001611 layer->m_CifgParameters.m_InputGateBias =
1612 std::make_unique<ScopedCpuTensorHandle>(*(params.m_InputGateBias));
1613 }
1614
1615 //Lstm projection parameters
1616 if(descriptor.m_ProjectionEnabled)
1617 {
1618 if(params.m_ProjectionWeights == nullptr)
1619 {
Jan Eilerse2062cd2020-03-30 15:07:45 +01001620 throw InvalidArgumentException("AddLstmLayer: Projection Weights cannot be NULL "
1621 "when projection is enabled.");
telsoa01c577f2c2018-08-31 09:22:23 +01001622 }
1623 layer->m_ProjectionParameters.m_ProjectionWeights =
1624 std::make_unique<ScopedCpuTensorHandle>(*(params.m_ProjectionWeights));
1625 if(params.m_ProjectionBias != nullptr)
1626 {
1627 layer->m_ProjectionParameters.m_ProjectionBias =
1628 std::make_unique<ScopedCpuTensorHandle>(*(params.m_ProjectionBias));
1629 }
1630 }
1631
1632 //Lstm Peephole params
1633 if(descriptor.m_PeepholeEnabled)
1634 {
Jan Eilerse2062cd2020-03-30 15:07:45 +01001635 if(!descriptor.m_CifgEnabled)
1636 {
1637 if(params.m_CellToInputWeights == nullptr)
1638 {
1639 throw InvalidArgumentException("AddLstmLayer: Cell To Input Weights cannot be NULL "
1640 "when Peephole is enabled and CIFG disabled.");
1641 }
1642
1643 layer->m_PeepholeParameters.m_CellToInputWeights =
1644 std::make_unique<ScopedCpuTensorHandle>(*(params.m_CellToInputWeights));
1645 }
1646
telsoa01c577f2c2018-08-31 09:22:23 +01001647 if(params.m_CellToForgetWeights == nullptr)
1648 {
Jan Eilerse2062cd2020-03-30 15:07:45 +01001649 throw InvalidArgumentException("AddLstmLayer: Cell To Forget Weights cannot be NULL "
1650 "when Peephole is enabled.");
telsoa01c577f2c2018-08-31 09:22:23 +01001651 }
1652 if(params.m_CellToOutputWeights == nullptr)
1653 {
Jan Eilerse2062cd2020-03-30 15:07:45 +01001654 throw InvalidArgumentException("AddLstmLayer: Cell To Output Weights cannot be NULL "
1655 "when Peephole is enabled.");
telsoa01c577f2c2018-08-31 09:22:23 +01001656 }
Jan Eilerse2062cd2020-03-30 15:07:45 +01001657
telsoa01c577f2c2018-08-31 09:22:23 +01001658 layer->m_PeepholeParameters.m_CellToForgetWeights =
1659 std::make_unique<ScopedCpuTensorHandle>(*(params.m_CellToForgetWeights));
1660 layer->m_PeepholeParameters.m_CellToOutputWeights =
1661 std::make_unique<ScopedCpuTensorHandle>(*(params.m_CellToOutputWeights));
1662 }
Jan Eilersf8c62972019-07-17 11:07:49 +01001663
1664 //Lstm Layer Normalization params
1665 if(descriptor.m_LayerNormEnabled)
1666 {
1667 if(!descriptor.m_CifgEnabled)
1668 {
1669 if(params.m_InputLayerNormWeights == nullptr)
1670 {
Jan Eilerse2062cd2020-03-30 15:07:45 +01001671 throw InvalidArgumentException("AddLstmLayer: Input layer normalization weights cannot be NULL "
1672 "when layer normalization is enabled and CIFG disabled.");
Jan Eilersf8c62972019-07-17 11:07:49 +01001673 }
1674 layer->m_LayerNormParameters.m_InputLayerNormWeights =
1675 std::make_unique<ScopedCpuTensorHandle>(*(params.m_InputLayerNormWeights));
1676 }
1677
1678 if(params.m_ForgetLayerNormWeights == nullptr)
1679 {
Jan Eilerse2062cd2020-03-30 15:07:45 +01001680 throw InvalidArgumentException("AddLstmLayer: Forget layer normalization weights cannot be NULL "
1681 "when layer normalization is enabled.");
Jan Eilersf8c62972019-07-17 11:07:49 +01001682 }
1683 if(params.m_CellLayerNormWeights == nullptr)
1684 {
Jan Eilerse2062cd2020-03-30 15:07:45 +01001685 throw InvalidArgumentException("AddLstmLayer: Cell layer normalization weights cannot be NULL "
1686 "when layer normalization is enabled.");
Jan Eilersf8c62972019-07-17 11:07:49 +01001687 }
1688 if(params.m_OutputLayerNormWeights == nullptr)
1689 {
Jan Eilerse2062cd2020-03-30 15:07:45 +01001690 throw InvalidArgumentException("AddLstmLayer: Output layer normalization weights cannot be NULL "
1691 "when layer normalization is enabled.");
Jan Eilersf8c62972019-07-17 11:07:49 +01001692 }
1693 layer->m_LayerNormParameters.m_ForgetLayerNormWeights =
1694 std::make_unique<ScopedCpuTensorHandle>(*(params.m_ForgetLayerNormWeights));
1695 layer->m_LayerNormParameters.m_CellLayerNormWeights =
1696 std::make_unique<ScopedCpuTensorHandle>(*(params.m_CellLayerNormWeights));
1697 layer->m_LayerNormParameters.m_OutputLayerNormWeights =
1698 std::make_unique<ScopedCpuTensorHandle>(*(params.m_OutputLayerNormWeights));
1699 }
telsoa01c577f2c2018-08-31 09:22:23 +01001700 return layer;
1701}
1702
Francis Murtaghe7a86a42018-08-29 12:42:10 +01001703IConnectableLayer* Network::AddDivisionLayer(const char* name)
1704{
1705 return m_Graph->AddLayer<DivisionLayer>(name);
1706}
1707
David Beck19526222018-09-12 16:00:08 +01001708IConnectableLayer* Network::AddSubtractionLayer(const char* name)
1709{
1710 return m_Graph->AddLayer<SubtractionLayer>(name);
1711}
1712
narpra0132b90462018-09-13 11:07:48 +01001713IConnectableLayer* Network::AddMeanLayer(const MeanDescriptor& meanDescriptor, const char* name)
1714{
1715 return m_Graph->AddLayer<MeanLayer>(meanDescriptor,name);
1716}
1717
Mohamed Nour Abouelseoud5662c202018-09-24 13:30:09 +01001718IConnectableLayer* Network::AddPadLayer(const PadDescriptor& padDescriptor, const char* name)
1719{
1720 return m_Graph->AddLayer<PadLayer>(padDescriptor,name);
1721}
1722
Derek Lambertia9cca6a2019-03-25 15:41:58 +00001723IConnectableLayer *Network::AddQuantizeLayer(const char *name)
1724{
1725 return m_Graph->AddLayer<QuantizeLayer>(name);
1726}
1727
Nattapat Chaimanowonge4294fd2019-03-28 09:56:53 +00001728IConnectableLayer* Network::AddDequantizeLayer(const char* name)
1729{
1730 return m_Graph->AddLayer<DequantizeLayer>(name);
1731}
1732
Conor Kennedy430b5d82018-11-14 15:28:28 +00001733IConnectableLayer* Network::AddStridedSliceLayer(const StridedSliceDescriptor& stridedSliceDescriptor,
1734 const char* name)
1735{
1736 return m_Graph->AddLayer<StridedSliceLayer>(stridedSliceDescriptor, name);
1737}
1738
Matteo Martincigh59a950c2018-12-13 12:48:25 +00001739IConnectableLayer* Network::AddGreaterLayer(const char* name)
1740{
Aron Virginas-Tar77bfb5e2019-10-16 17:45:38 +01001741 return AddComparisonLayer(ComparisonDescriptor(ComparisonOperation::Greater), name);
Matteo Martincigh59a950c2018-12-13 12:48:25 +00001742}
1743
FrancisMurtagh20995952018-12-17 12:11:36 +00001744IConnectableLayer* Network::AddEqualLayer(const char* name)
1745{
Aron Virginas-Tar77bfb5e2019-10-16 17:45:38 +01001746 return AddComparisonLayer(ComparisonDescriptor(ComparisonOperation::Equal), name);
FrancisMurtagh20995952018-12-17 12:11:36 +00001747}
1748
Mohamed Nour Abouelseouda1d3c6a2018-12-27 12:39:16 +00001749IConnectableLayer* Network::AddRsqrtLayer(const char * name)
1750{
josh minor4a3c6102020-01-06 16:40:46 -06001751 return AddElementwiseUnaryLayer(ElementwiseUnaryDescriptor(UnaryOperation::Rsqrt), name);
Mohamed Nour Abouelseouda1d3c6a2018-12-27 12:39:16 +00001752}
1753
narpra01b89b05f2019-01-16 09:53:09 +00001754IConnectableLayer* Network::AddGatherLayer(const char* name)
1755{
Teresa Charlin52664732020-06-29 16:27:03 +01001756 GatherDescriptor gatherDescriptor{};
1757 return AddGatherLayer(gatherDescriptor, name);
1758}
1759
1760IConnectableLayer* Network::AddGatherLayer(const GatherDescriptor& gatherDescriptor,
1761 const char* name)
1762{
1763 return m_Graph->AddLayer<GatherLayer>(gatherDescriptor, name);
narpra01b89b05f2019-01-16 09:53:09 +00001764}
1765
Nattapat Chaimanowong1f886302019-04-05 13:37:19 +01001766IConnectableLayer* Network::AddMergeLayer(const char* name)
1767{
1768 return m_Graph->AddLayer<MergeLayer>(name);
1769}
1770
Sadik Armaganeff363d2019-04-05 15:25:46 +01001771IConnectableLayer* Network::AddSwitchLayer(const char* name)
1772{
1773 return m_Graph->AddLayer<SwitchLayer>(name);
1774}
1775
Matteo Martincigh0e406ee2019-06-12 15:42:18 +01001776IConnectableLayer* Network::AddPreluLayer(const char* name)
1777{
1778 return m_Graph->AddLayer<PreluLayer>(name);
1779}
1780
Aron Virginas-Tar639fb042019-06-20 14:28:19 +01001781IConnectableLayer* Network::AddTransposeConvolution2dLayer(const TransposeConvolution2dDescriptor& descriptor,
1782 const ConstTensor& weights,
1783 const Optional<ConstTensor>& biases,
1784 const char* name)
1785{
1786 if (descriptor.m_BiasEnabled && !biases.has_value())
1787 {
1788 throw InvalidArgumentException("AddTransposeConvolution2dLayer: Biases cannot be empty");
1789 }
1790
1791 const auto layer = m_Graph->AddLayer<TransposeConvolution2dLayer>(descriptor, name);
1792
1793 layer->m_Weight = std::make_unique<ScopedCpuTensorHandle>(weights);
1794
1795 if (descriptor.m_BiasEnabled)
1796 {
1797 layer->m_Bias = std::make_unique<ScopedCpuTensorHandle>(biases.value());
1798 }
1799
1800 return layer;
1801}
1802
Mike Kellyc9ea45a2020-02-28 18:11:58 +00001803IConnectableLayer* Network::AddTransposeLayer(const TransposeDescriptor& transposeDescriptor,
1804 const char* name)
1805{
1806 return m_Graph->AddLayer<TransposeLayer>(transposeDescriptor, name);
1807}
1808
Matthew Jackson2b8c1da2019-07-04 14:59:16 +01001809IConnectableLayer* Network::AddStackLayer(const StackDescriptor& stackDescriptor,
1810 const char* name)
1811{
1812 return m_Graph->AddLayer<StackLayer>(stackDescriptor, name);
1813}
1814
Derek Lamberti013c3902019-10-21 10:46:16 +01001815
1816IConnectableLayer* Network::AddStandInLayer(const StandInDescriptor& desc,
1817 const char* name)
1818{
1819 return m_Graph->AddLayer<StandInLayer>(desc, name);
1820}
1821
James Conroyee18dc82019-07-17 11:27:46 +01001822IConnectableLayer* Network::AddQuantizedLstmLayer(const QuantizedLstmInputParams& params,
1823 const char* name)
1824{
1825 const auto layer = m_Graph->AddLayer<QuantizedLstmLayer>(name);
1826
1827 // InputToX weights
1828 layer->m_QuantizedLstmParameters.m_InputToInputWeights =
Francis Murtaghbb590b42019-08-14 09:51:36 +01001829 std::make_unique<ScopedCpuTensorHandle>(params.GetInputToInputWeights());
James Conroyee18dc82019-07-17 11:27:46 +01001830 layer->m_QuantizedLstmParameters.m_InputToForgetWeights =
Francis Murtaghbb590b42019-08-14 09:51:36 +01001831 std::make_unique<ScopedCpuTensorHandle>(params.GetInputToForgetWeights());
James Conroyee18dc82019-07-17 11:27:46 +01001832 layer->m_QuantizedLstmParameters.m_InputToCellWeights =
Francis Murtaghbb590b42019-08-14 09:51:36 +01001833 std::make_unique<ScopedCpuTensorHandle>(params.GetInputToCellWeights());
James Conroyee18dc82019-07-17 11:27:46 +01001834 layer->m_QuantizedLstmParameters.m_InputToOutputWeights =
Francis Murtaghbb590b42019-08-14 09:51:36 +01001835 std::make_unique<ScopedCpuTensorHandle>(params.GetInputToOutputWeights());
James Conroyee18dc82019-07-17 11:27:46 +01001836
1837 // RecurrentToX weights
1838 layer->m_QuantizedLstmParameters.m_RecurrentToInputWeights =
Francis Murtaghbb590b42019-08-14 09:51:36 +01001839 std::make_unique<ScopedCpuTensorHandle>(params.GetRecurrentToInputWeights());
James Conroyee18dc82019-07-17 11:27:46 +01001840 layer->m_QuantizedLstmParameters.m_RecurrentToForgetWeights =
Francis Murtaghbb590b42019-08-14 09:51:36 +01001841 std::make_unique<ScopedCpuTensorHandle>(params.GetRecurrentToForgetWeights());
James Conroyee18dc82019-07-17 11:27:46 +01001842 layer->m_QuantizedLstmParameters.m_RecurrentToCellWeights =
Francis Murtaghbb590b42019-08-14 09:51:36 +01001843 std::make_unique<ScopedCpuTensorHandle>(params.GetRecurrentToCellWeights());
James Conroyee18dc82019-07-17 11:27:46 +01001844 layer->m_QuantizedLstmParameters.m_RecurrentToOutputWeights =
Francis Murtaghbb590b42019-08-14 09:51:36 +01001845 std::make_unique<ScopedCpuTensorHandle>(params.GetRecurrentToOutputWeights());
James Conroyee18dc82019-07-17 11:27:46 +01001846
1847 // Bias
1848 layer->m_QuantizedLstmParameters.m_InputGateBias =
Francis Murtaghbb590b42019-08-14 09:51:36 +01001849 std::make_unique<ScopedCpuTensorHandle>(params.GetInputGateBias());
James Conroyee18dc82019-07-17 11:27:46 +01001850 layer->m_QuantizedLstmParameters.m_ForgetGateBias =
Francis Murtaghbb590b42019-08-14 09:51:36 +01001851 std::make_unique<ScopedCpuTensorHandle>(params.GetForgetGateBias());
James Conroyee18dc82019-07-17 11:27:46 +01001852 layer->m_QuantizedLstmParameters.m_CellBias =
Francis Murtaghbb590b42019-08-14 09:51:36 +01001853 std::make_unique<ScopedCpuTensorHandle>(params.GetCellBias());
James Conroyee18dc82019-07-17 11:27:46 +01001854 layer->m_QuantizedLstmParameters.m_OutputGateBias =
Francis Murtaghbb590b42019-08-14 09:51:36 +01001855 std::make_unique<ScopedCpuTensorHandle>(params.GetOutputGateBias());
James Conroyee18dc82019-07-17 11:27:46 +01001856
1857 return layer;
1858}
1859
James Conroy586a9aa2020-03-20 08:49:33 +00001860IConnectableLayer* Network::AddQLstmLayer(const QLstmDescriptor& descriptor,
1861 const LstmInputParams& params,
1862 const char* name)
1863{
1864 const auto layer = m_Graph->AddLayer<QLstmLayer>(descriptor, name);
1865
1866 // QLstm Basic Parameters
1867 layer->m_BasicParameters.m_InputToForgetWeights =
1868 std::make_unique<ScopedCpuTensorHandle>(*(params.m_InputToForgetWeights));
1869 layer->m_BasicParameters.m_InputToCellWeights =
1870 std::make_unique<ScopedCpuTensorHandle>(*(params.m_InputToCellWeights));
1871 layer->m_BasicParameters.m_InputToOutputWeights =
1872 std::make_unique<ScopedCpuTensorHandle>(*(params.m_InputToOutputWeights));
1873 layer->m_BasicParameters.m_RecurrentToForgetWeights =
1874 std::make_unique<ScopedCpuTensorHandle>(*(params.m_RecurrentToForgetWeights));
1875 layer->m_BasicParameters.m_RecurrentToCellWeights =
1876 std::make_unique<ScopedCpuTensorHandle>(*(params.m_RecurrentToCellWeights));
1877 layer->m_BasicParameters.m_RecurrentToOutputWeights =
1878 std::make_unique<ScopedCpuTensorHandle>(*(params.m_RecurrentToOutputWeights));
1879 layer->m_BasicParameters.m_ForgetGateBias =
1880 std::make_unique<ScopedCpuTensorHandle>(*(params.m_ForgetGateBias));
1881 layer->m_BasicParameters.m_CellBias =
1882 std::make_unique<ScopedCpuTensorHandle>(*(params.m_CellBias));
1883 layer->m_BasicParameters.m_OutputGateBias =
1884 std::make_unique<ScopedCpuTensorHandle>(*(params.m_OutputGateBias));
1885
1886 // QLstm Cifg parameters
1887 if(!descriptor.m_CifgEnabled)
1888 {
1889 if(params.m_InputToInputWeights == nullptr)
1890 {
1891 throw InvalidArgumentException("AddQLstmLayer: Input To Input Weights cannot be NULL");
1892 }
1893
1894 if(params.m_RecurrentToInputWeights == nullptr)
1895 {
1896 throw InvalidArgumentException(
1897 "AddQLstmLayer: Recurrent To Input Weights cannot be NULL");
1898 }
1899
1900 if(params.m_InputGateBias == nullptr)
1901 {
1902 throw InvalidArgumentException("AddQLstmLayer: Input Gate Bias cannot be NULL");
1903 }
1904
1905 layer->m_CifgParameters.m_InputToInputWeights =
1906 std::make_unique<ScopedCpuTensorHandle>(*(params.m_InputToInputWeights));
1907 layer->m_CifgParameters.m_RecurrentToInputWeights =
1908 std::make_unique<ScopedCpuTensorHandle>(*(params.m_RecurrentToInputWeights));
1909 layer->m_CifgParameters.m_InputGateBias =
1910 std::make_unique<ScopedCpuTensorHandle>(*(params.m_InputGateBias));
1911 }
1912
1913 // QLstm Projection parameters
1914 if(descriptor.m_ProjectionEnabled)
1915 {
1916 if(params.m_ProjectionWeights == nullptr)
1917 {
1918 throw InvalidArgumentException("AddQLstmLayer: Projection Weights cannot be NULL");
1919 }
1920
James Conroy586a9aa2020-03-20 08:49:33 +00001921 layer->m_ProjectionParameters.m_ProjectionWeights =
1922 std::make_unique<ScopedCpuTensorHandle>(*(params.m_ProjectionWeights));
James Conroyed324052020-05-18 15:16:42 +01001923
1924 // Projection bias is optional even if projection is enabled
1925 if(params.m_ProjectionWeights != nullptr)
1926 {
1927 layer->m_ProjectionParameters.m_ProjectionBias =
1928 std::make_unique<ScopedCpuTensorHandle>(*(params.m_ProjectionBias));
1929 }
1930
James Conroy586a9aa2020-03-20 08:49:33 +00001931 }
1932
1933 // QLstm Peephole params
1934 if(descriptor.m_PeepholeEnabled)
1935 {
1936 if(params.m_CellToForgetWeights == nullptr)
1937 {
1938 throw InvalidArgumentException("AddQLstmLayer: Cell To Forget Weights cannot be NULL");
1939 }
1940
1941 if(params.m_CellToOutputWeights == nullptr)
1942 {
1943 throw InvalidArgumentException("AddQLstmLayer: Cell To Output Weights cannot be NULL");
1944 }
1945
1946 if(!descriptor.m_CifgEnabled)
1947 {
1948 if(params.m_CellToInputWeights == nullptr)
1949 {
1950 throw InvalidArgumentException("AddQLstmLayer: Cell To Input Weights cannot be NULL");
1951 }
1952
1953 layer->m_PeepholeParameters.m_CellToInputWeights =
1954 std::make_unique<ScopedCpuTensorHandle>(*(params.m_CellToInputWeights));
1955 }
1956
1957 layer->m_PeepholeParameters.m_CellToForgetWeights =
1958 std::make_unique<ScopedCpuTensorHandle>(*(params.m_CellToForgetWeights));
1959 layer->m_PeepholeParameters.m_CellToOutputWeights =
1960 std::make_unique<ScopedCpuTensorHandle>(*(params.m_CellToOutputWeights));
1961 }
1962
1963 // QLstm Layer Normalization params
1964 if(descriptor.m_LayerNormEnabled)
1965 {
1966 if(params.m_ForgetLayerNormWeights == nullptr)
1967 {
1968 throw InvalidArgumentException("AddQLstmLayer: Forget layer normalization weights cannot be NULL");
1969 }
1970
1971 if(params.m_CellLayerNormWeights == nullptr)
1972 {
1973 throw InvalidArgumentException("AddQLstmLayer: Cell layer normalization weights cannot be NULL");
1974 }
1975
1976 if(params.m_OutputLayerNormWeights == nullptr)
1977 {
1978 throw InvalidArgumentException("AddQLstmLayer: Output layer normalization weights cannot be NULL");
1979 }
1980
1981 if(!descriptor.m_CifgEnabled)
1982 {
1983 if(params.m_InputLayerNormWeights == nullptr)
1984 {
1985 throw InvalidArgumentException("AddQLstmLayer: Input layer normalization weights cannot be NULL");
1986 }
1987
1988 layer->m_LayerNormParameters.m_InputLayerNormWeights =
1989 std::make_unique<ScopedCpuTensorHandle>(*(params.m_InputLayerNormWeights));
1990 }
1991
1992 layer->m_LayerNormParameters.m_ForgetLayerNormWeights =
1993 std::make_unique<ScopedCpuTensorHandle>(*(params.m_ForgetLayerNormWeights));
1994 layer->m_LayerNormParameters.m_CellLayerNormWeights =
1995 std::make_unique<ScopedCpuTensorHandle>(*(params.m_CellLayerNormWeights));
1996 layer->m_LayerNormParameters.m_OutputLayerNormWeights =
1997 std::make_unique<ScopedCpuTensorHandle>(*(params.m_OutputLayerNormWeights));
1998 }
1999 return layer;
2000}
2001
Mike Kelly8c1701a2019-02-11 17:01:27 +00002002void Network::Accept(ILayerVisitor& visitor) const
2003{
2004 for (auto layer : GetGraph())
2005 {
2006 layer->Accept(visitor);
2007 };
2008}
2009
telsoa014fcda012018-03-09 14:13:49 +00002010OptimizedNetwork::OptimizedNetwork(std::unique_ptr<Graph> graph)
Sadik Armagan3184c902020-03-18 10:57:30 +00002011 : m_Graph(std::move(graph)), m_Guid(profiling::ProfilingService::GetNextGuid())
telsoa014fcda012018-03-09 14:13:49 +00002012{
2013}
2014
Sadik Armagan045f6be2020-09-10 13:37:32 +01002015OptimizedNetwork::OptimizedNetwork(std::unique_ptr<Graph> graph, const ModelOptions& modelOptions)
2016 : m_Graph(std::move(graph)), m_Guid(profiling::ProfilingService::GetNextGuid()), m_ModelOptions(modelOptions)
2017{
2018}
2019
telsoa014fcda012018-03-09 14:13:49 +00002020OptimizedNetwork::~OptimizedNetwork()
2021{
2022}
2023
2024} // namespace armnn