blob: 0d06042abe5ed7e70bbd85339bbcee5c0595c025 [file] [log] [blame]
telsoa014fcda012018-03-09 14:13:49 +00001//
2// Copyright © 2017 Arm Ltd. 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>
David Beck263e3492018-11-09 14:46:40 +000017#include <backendsCommon/BackendRegistry.hpp>
18#include <backendsCommon/IBackendInternal.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>
telsoa014fcda012018-03-09 14:13:49 +000023
24#include <fcntl.h>
25#include <algorithm>
26#include <fstream>
27#include <memory>
telsoa01c577f2c2018-08-31 09:22:23 +010028#include <vector>
29#include <algorithm>
telsoa014fcda012018-03-09 14:13:49 +000030
31#include <boost/assert.hpp>
32#include <boost/format.hpp>
33#include <boost/log/trivial.hpp>
34#include <boost/numeric/conversion/converter_policies.hpp>
35#include <boost/cast.hpp>
36
37namespace armnn
38{
39
40armnn::INetwork* INetwork::CreateRaw()
41{
42 return new Network();
43}
44
45armnn::INetworkPtr INetwork::Create()
46{
47 return INetworkPtr(CreateRaw(), &INetwork::Destroy);
48}
49
50void INetwork::Destroy(INetwork* network)
51{
52 delete boost::polymorphic_downcast<Network*>(network);
53}
54
55Status Network::PrintGraph()
56{
57 m_Graph->Print();
58 return Status::Success;
59}
60
61void IOptimizedNetwork::Destroy(IOptimizedNetwork* network)
62{
63 delete boost::polymorphic_downcast<OptimizedNetwork*>(network);
64}
65
66Status OptimizedNetwork::PrintGraph()
67{
68 m_Graph->Print();
69 return Status::Success;
70}
71
surmeh01bceff2f2018-03-29 16:29:27 +010072Status OptimizedNetwork::SerializeToDot(std::ostream& stream) const
73{
74 return m_Graph->SerializeToDot(stream);
75}
76
Matteo Martincigh49124022019-01-11 13:25:59 +000077struct OptimizationResult
78{
79 bool m_Warning;
80 bool m_Error;
81
82 OptimizationResult()
83 : m_Warning(false)
84 , m_Error(false)
85 {}
86};
87
88void ReportError(const std::string& errorMessage,
89 Optional<std::vector<std::string>&> errorMessages)
90{
91 std::stringstream fullErrorMessage;
92 fullErrorMessage << "ERROR: " << errorMessage;
93 BOOST_LOG_TRIVIAL(warning) << fullErrorMessage.str();
94 if (errorMessages)
95 {
96 errorMessages.value().push_back(fullErrorMessage.str());
97 }
98}
99
100void ReportWarning(const std::string& warningMessage,
101 Optional<std::vector<std::string>&> warningMessages)
102{
103 std::stringstream fullWarningMessage;
104 fullWarningMessage << "WARNING: " << warningMessage;
105 BOOST_LOG_TRIVIAL(warning) << fullWarningMessage.str();
106 if (warningMessages)
107 {
108 warningMessages.value().push_back(fullWarningMessage.str());
109 }
110}
111
jimfly016b0b53d2018-10-08 14:43:01 +0100112bool CheckScaleSetOnQuantizedType(Layer* layer, Optional<std::vector<std::string>&> errMessages)
113{
114 bool noErrors = true;
115 unsigned int numOutputs = layer->GetNumOutputSlots();
116 for (unsigned int i = 0; i < numOutputs; i++) {
David Monahanb8554702019-04-25 16:03:38 +0100117 OutputSlot& outputSlot = layer->GetOutputSlot(i);
118 TensorInfo info = outputSlot.GetTensorInfo();
jimfly016b0b53d2018-10-08 14:43:01 +0100119 if (DataType::QuantisedAsymm8 == info.GetDataType()) {
120 if (0.f == info.GetQuantizationScale()) {
121 noErrors = false;
122 std::stringstream ss;
Matteo Martincigh49124022019-01-11 13:25:59 +0000123 ss << "output " << i << " of layer " << GetLayerTypeAsCString(layer->GetType())
jimfly016b0b53d2018-10-08 14:43:01 +0100124 << " (" << layer->GetNameStr() << ") is of type"
125 << " Quantized 8 bit but its scale parameter has not been set";
Matteo Martincigh49124022019-01-11 13:25:59 +0000126 ReportError(ss.str(), errMessages);
jimfly016b0b53d2018-10-08 14:43:01 +0100127 }
David Monahanb8554702019-04-25 16:03:38 +0100128 // Softmax under QuantisedAsymm8 must always be scale (1.0f/256.0f) and offset 0
129 if ((info.GetQuantizationScale() != (1.0f / 256.0f) ||
130 info.GetQuantizationOffset() != 0) &&
131 layer->GetType() == armnn::LayerType::Softmax)
132 {
133 std::stringstream ss;
134 ss << "Quantization parameters for Softmax layer (Scale: " <<
135 info.GetQuantizationScale() << " and Offset: " << info.GetQuantizationOffset() <<
136 ") are incorrect and have been updated to Scale: 0.00390625 and Offset: 0";
137 BOOST_LOG_TRIVIAL(warning) << ss.str();
138 info.SetQuantizationScale((1.0f /256.0f));
139 info.SetQuantizationOffset(0);
140 outputSlot.SetTensorInfo(info);
141 }
jimfly016b0b53d2018-10-08 14:43:01 +0100142 }
143 }
144 return noErrors;
145}
146
Matteo Martincigh49124022019-01-11 13:25:59 +0000147OptimizationResult AssignBackends(OptimizedNetwork* optNetObjPtr,
148 BackendSettings& backendSettings,
149 Graph::Iterator& firstLayer,
150 Graph::Iterator& lastLayer,
151 Optional<std::vector<std::string>&> errMessages)
telsoa014fcda012018-03-09 14:13:49 +0000152{
Matteo Martincigh49124022019-01-11 13:25:59 +0000153 OptimizationResult result;
telsoa014fcda012018-03-09 14:13:49 +0000154
Matteo Martincigh49124022019-01-11 13:25:59 +0000155 // Helper lambda to compose meaningful error message before returning with error
156 auto ReturnWithError = [&](const Layer* layer)
telsoa01c577f2c2018-08-31 09:22:23 +0100157 {
jimfly016b0b53d2018-10-08 14:43:01 +0100158 std::stringstream failureMsg;
Matteo Martincigh49124022019-01-11 13:25:59 +0000159 failureMsg << "Layer of type " << GetLayerTypeAsCString(layer->GetType())
160 << " is not supported on any preferred backend " << backendSettings.m_PreferredBackends;
161 ReportError(failureMsg.str(), errMessages);
162
163 result.m_Error = true;
164 return result;
telsoa01c577f2c2018-08-31 09:22:23 +0100165 };
166
Matteo Martincigh49124022019-01-11 13:25:59 +0000167 auto availablePreferredBackends = backendSettings.GetAvailablePreferredBackends();
168 if (availablePreferredBackends.empty())
telsoa01c577f2c2018-08-31 09:22:23 +0100169 {
Matteo Martincigh49124022019-01-11 13:25:59 +0000170 std::stringstream failureMsg;
171 failureMsg << "No preferred backends are available";
172 ReportError(failureMsg.str(), errMessages);
173
174 result.m_Error = true;
175 return result;
176 }
177
178 for (auto it = firstLayer; it != lastLayer; ++it)
179 {
180 auto layer = *it;
telsoa01c577f2c2018-08-31 09:22:23 +0100181 DataType dataType = layer->GetDataType();
182 std::string reasonIfUnsupported;
183 bool found = false;
jimfly016b0b53d2018-10-08 14:43:01 +0100184 if (!CheckScaleSetOnQuantizedType(layer, errMessages))
185 {
186 // don't bomb immediately, find all the quantized outputs
187 // which haven't had a scale set and report them all back.
Matteo Martincigh49124022019-01-11 13:25:59 +0000188 result.m_Error = true;
jimfly016b0b53d2018-10-08 14:43:01 +0100189 }
Matteo Martincigh49124022019-01-11 13:25:59 +0000190
David Beckf0b48452018-10-19 15:20:56 +0100191 for (const auto& backend : availablePreferredBackends)
telsoa01c577f2c2018-08-31 09:22:23 +0100192 {
193 // need to set the compute device on the layer
194 // before we can check if it is supported
David Beck33f0ae02018-10-18 15:13:56 +0100195 layer->SetBackendId(backend);
telsoa01c577f2c2018-08-31 09:22:23 +0100196 if (!IWorkloadFactory::IsLayerSupported(*layer, dataType, reasonIfUnsupported))
197 {
198 if (dataType == DataType::Float16)
199 {
200 if (IWorkloadFactory::IsLayerSupported(*layer, DataType::Float32, reasonIfUnsupported)
201 && layer->GetType() != LayerType::ConvertFp32ToFp16
202 && layer->GetType() != LayerType::ConvertFp16ToFp32)
203 {
204 // Insert FP16 -> FP32 conversion layer before current layer
205 std::vector<ConvertFp16ToFp32Layer*> convertFp16ToFp32Layers =
206 InsertConvertFp16ToFp32LayersBefore(optNetObjPtr->GetGraph(), *layer);
207
208 // Insert FP32 -> FP16 conversion layer after current layer
209 std::vector<ConvertFp32ToFp16Layer*> convertFp32ToFp16Layers =
210 InsertConvertFp32ToFp16LayersAfter(optNetObjPtr->GetGraph(), *layer);
211
212 // Assign a supported backend to the newly introduced conversion layers
David Beckf0b48452018-10-19 15:20:56 +0100213 auto AssignFirstSupportedBackend = [&](Layer* layer, BackendId preferredBackend)
telsoa01c577f2c2018-08-31 09:22:23 +0100214 {
215 bool supportedBackendFound = false;
216 std::string reasonIfUnsupported;
217
218 // Try preferred backend first
David Beck33f0ae02018-10-18 15:13:56 +0100219 layer->SetBackendId(preferredBackend);
David Beck29c75de2018-10-23 13:35:58 +0100220 if (IWorkloadFactory::IsLayerSupported(*layer,
221 EmptyOptional(),
222 reasonIfUnsupported))
telsoa01c577f2c2018-08-31 09:22:23 +0100223 {
224 supportedBackendFound = true;
225 }
226 else
227 {
David Beckf0b48452018-10-19 15:20:56 +0100228 for (const auto& backend : availablePreferredBackends)
telsoa01c577f2c2018-08-31 09:22:23 +0100229 {
230 // Skip preferred backend (we already determined that it is not supported)
231 if (backend == preferredBackend)
232 {
233 continue;
234 }
235
David Beck33f0ae02018-10-18 15:13:56 +0100236 layer->SetBackendId(backend);
David Beck29c75de2018-10-23 13:35:58 +0100237 if (IWorkloadFactory::IsLayerSupported(*layer,
238 EmptyOptional(),
239 reasonIfUnsupported))
telsoa01c577f2c2018-08-31 09:22:23 +0100240 {
241 supportedBackendFound = true;
242 break;
243 }
244 }
245 }
246
247 return supportedBackendFound;
248 };
249
250 for (ConvertFp16ToFp32Layer* convertLayer : convertFp16ToFp32Layers)
251 {
252 if (!AssignFirstSupportedBackend(convertLayer, backend))
253 {
254 return ReturnWithError(convertLayer);
255 }
256 }
257
258 for (ConvertFp32ToFp16Layer* convertLayer : convertFp32ToFp16Layers)
259 {
260 if (!AssignFirstSupportedBackend(convertLayer, backend))
261 {
262 return ReturnWithError(convertLayer);
263 }
264 }
265
266 found = true;
267 break;
268 }
269 }
jimfly016b0b53d2018-10-08 14:43:01 +0100270 std::stringstream warningMsg;
Matteo Martincigh49124022019-01-11 13:25:59 +0000271 warningMsg << "Layer of type " << GetLayerTypeAsCString(layer->GetType())
David Beck33f0ae02018-10-18 15:13:56 +0100272 << " is not supported on requested backend " << layer->GetBackendId().Get()
jimfly016b0b53d2018-10-08 14:43:01 +0100273 << " for data type " << GetDataTypeName(dataType)
274 << " (reason: " << reasonIfUnsupported
275 << "), falling back to the next backend.";
Matteo Martincigh49124022019-01-11 13:25:59 +0000276 ReportWarning(warningMsg.str(), errMessages);
telsoa01c577f2c2018-08-31 09:22:23 +0100277 }
278 else
279 {
280 found = true;
Matteo Martincigh49124022019-01-11 13:25:59 +0000281 backendSettings.m_SelectedBackends.insert(backend);
telsoa01c577f2c2018-08-31 09:22:23 +0100282 break;
283 }
284 }
285
286 // If the layer is unsupported by any devices, log and return a null network.
Matteo Martincigh49124022019-01-11 13:25:59 +0000287 if (!found)
288 {
telsoa01c577f2c2018-08-31 09:22:23 +0100289 // NOTE: if the layer is not an operation queue type AND we have not got CpuRef as a
290 // fallback we should set the compute device on the layer to CpuRef (these are not
291 // available as accelerated operations, or are only available under certain
292 // conditions, currently they comprise MemCopy, Constant, Permute)
293 armnn::LayerType layerType = layer->GetType();
Matteo Martincigh49124022019-01-11 13:25:59 +0000294 if (!backendSettings.IsCpuRefUsed() && (layerType == armnn::LayerType::MemCopy ||
295 layerType == armnn::LayerType::Constant ||
296 layerType == armnn::LayerType::Permute))
telsoa01c577f2c2018-08-31 09:22:23 +0100297 {
Matteo Martincigh49124022019-01-11 13:25:59 +0000298 BackendId cpuBackendId(armnn::Compute::CpuRef);
299 layer->SetBackendId(cpuBackendId);
300 backendSettings.m_SelectedBackends.insert(cpuBackendId);
telsoa01c577f2c2018-08-31 09:22:23 +0100301 }
302 else
303 {
304 return ReturnWithError(layer);
305 }
306 }
307 }
Matteo Martincigh49124022019-01-11 13:25:59 +0000308
309 return result;
310}
311
Matteo Martincighadddddb2019-01-24 14:06:23 +0000312OptimizationResult AssignBackends(OptimizedNetwork* optNetObjPtr,
313 BackendSettings& backendSettings,
Derek Lambertiff05cc52019-04-26 13:05:17 +0100314 SubgraphView& subgraph,
Matteo Martincighadddddb2019-01-24 14:06:23 +0000315 Optional<std::vector<std::string>&> errMessages)
Matteo Martincigh49124022019-01-11 13:25:59 +0000316{
Derek Lambertiff05cc52019-04-26 13:05:17 +0100317 Graph::Iterator firstLayer = subgraph.begin();
318 Graph::Iterator lastLayer = subgraph.end();
Matteo Martincighadddddb2019-01-24 14:06:23 +0000319 return AssignBackends(optNetObjPtr,
320 backendSettings,
321 firstLayer,
322 lastLayer,
323 errMessages);
324}
325
326OptimizationResult ApplyBackendOptimizations(OptimizedNetwork* optNetObjPtr,
327 BackendSettings& backendSettings,
328 Optional<std::vector<std::string>&> errMessages)
329{
330 BOOST_ASSERT(optNetObjPtr);
Matteo Martincigh49124022019-01-11 13:25:59 +0000331
332 OptimizationResult result;
333
Matteo Martincighadddddb2019-01-24 14:06:23 +0000334 // Get the optimized graph
335 Graph& optGraph = optNetObjPtr->GetGraph();
Matteo Martincigh49124022019-01-11 13:25:59 +0000336
Matteo Martincighadddddb2019-01-24 14:06:23 +0000337 // Run backend specific optimizations
338 auto const& backendRegistry = BackendRegistryInstance();
339 for (auto&& selectedBackend : backendSettings.m_SelectedBackends)
Matteo Martincigh49124022019-01-11 13:25:59 +0000340 {
Matteo Martincighadddddb2019-01-24 14:06:23 +0000341 auto backendFactory = backendRegistry.GetFactory(selectedBackend);
342 auto backendObjPtr = backendFactory();
343 BOOST_ASSERT(backendObjPtr);
344
345 // Select sub-graphs based on backend
Derek Lambertiff05cc52019-04-26 13:05:17 +0100346 SubgraphViewSelector::Subgraphs subgraphs =
Rob Hughes616acc62019-07-24 08:21:03 +0000347 SubgraphViewSelector::SelectSubgraphs(optGraph,
Matteo Martincigh602af092019-05-01 10:31:27 +0100348 // Select layers assigned to the requested backend
349 [&backendObjPtr](const Layer& layer)
350 {
351 return layer.GetType() != LayerType::Input &&
352 layer.GetType() != LayerType::Output &&
353 layer.GetBackendId() == backendObjPtr->GetId();
354 });
Derek Lambertiff05cc52019-04-26 13:05:17 +0100355 if (subgraphs.empty())
Matteo Martincigh49124022019-01-11 13:25:59 +0000356 {
Matteo Martincighadddddb2019-01-24 14:06:23 +0000357 // No sub-graphs found, try with next selected backend
358 continue;
Matteo Martincigh49124022019-01-11 13:25:59 +0000359 }
Matteo Martincighadddddb2019-01-24 14:06:23 +0000360
361 // Try to optimize each sub-graph
Derek Lambertiff05cc52019-04-26 13:05:17 +0100362 for (auto& subgraph : subgraphs)
Matteo Martincigh49124022019-01-11 13:25:59 +0000363 {
Matteo Martincighadddddb2019-01-24 14:06:23 +0000364 // Try to optimize the current sub-graph
Matteo Martincigh84924332019-05-09 12:46:16 +0100365 OptimizationViews optimizationViews = backendObjPtr->OptimizeSubgraphView(*subgraph);
366 BOOST_ASSERT(optimizationViews.Validate(*subgraph));
Matteo Martincighadddddb2019-01-24 14:06:23 +0000367
368 // Optimization attempted, check the resulting optimized sub-graph
Matteo Martincigh84924332019-05-09 12:46:16 +0100369 for (auto& substitution : optimizationViews.GetSubstitutions())
Matteo Martincighadddddb2019-01-24 14:06:23 +0000370 {
371 // Sub-graph optimized, substitute the sub-graph with the new optimized one in the main optimized graph
Matteo Martincigh84924332019-05-09 12:46:16 +0100372 SubgraphView& replacementSubgraph = substitution.m_ReplacementSubgraph;
373 SubgraphView& substitutableSubgraph = substitution.m_SubstitutableSubgraph;
374 optGraph.SubstituteSubgraph(substitutableSubgraph, replacementSubgraph);
Matteo Martincighadddddb2019-01-24 14:06:23 +0000375
376 // Assign the current backend to the optimized sub-graph
Matteo Martincigh84924332019-05-09 12:46:16 +0100377 std::for_each(replacementSubgraph.begin(), replacementSubgraph.end(), [&selectedBackend](Layer* l)
Derek Lambertic2fe5fb2019-05-08 10:23:08 +0100378 {
379 BOOST_ASSERT(l);
380 l->SetBackendId(selectedBackend);
381 });
Matteo Martincighadddddb2019-01-24 14:06:23 +0000382 }
Derek Lambertic2fe5fb2019-05-08 10:23:08 +0100383
Matteo Martincigh84924332019-05-09 12:46:16 +0100384 if (!optimizationViews.GetFailedSubgraphs().empty())
Matteo Martincighadddddb2019-01-24 14:06:23 +0000385 {
Matteo Martincighadddddb2019-01-24 14:06:23 +0000386 std::stringstream warningMsg;
Derek Lambertic2fe5fb2019-05-08 10:23:08 +0100387 warningMsg << "Some sub-graph(s) failed to optimized on " << backendObjPtr->GetId() << " backend.";
Matteo Martincighadddddb2019-01-24 14:06:23 +0000388 ReportWarning(warningMsg.str(), errMessages);
389
390 // Failed to optimize the given sub-graph, re-assign the sub-graph layers to other available backends
Derek Lambertic2fe5fb2019-05-08 10:23:08 +0100391 BackendSettings settingsCopy(backendSettings);
Matteo Martincighadddddb2019-01-24 14:06:23 +0000392 if (!backendObjPtr->GetId().IsCpuRef())
393 {
394 // Add the current backend to the list of backends to ignore
Derek Lambertic2fe5fb2019-05-08 10:23:08 +0100395 settingsCopy.m_IgnoredBackends.insert(backendObjPtr->GetId());
Matteo Martincighadddddb2019-01-24 14:06:23 +0000396 }
Derek Lambertic2fe5fb2019-05-08 10:23:08 +0100397
398 int count=0;
Matteo Martincigh84924332019-05-09 12:46:16 +0100399 for (auto& failedSubgraph : optimizationViews.GetFailedSubgraphs())
Matteo Martincighadddddb2019-01-24 14:06:23 +0000400 {
Derek Lambertic2fe5fb2019-05-08 10:23:08 +0100401 // An error occurred: the optimization was attempted but not performed, try different backends
402 std::stringstream subgraphMsg;
403 subgraphMsg << "Re-assigning backends to " << failedSubgraph.GetLayers().size()
404 << " layers inside sub-graph " << count++;
405 ReportWarning(warningMsg.str(), errMessages);
406
407 OptimizationResult reassignmentResult = AssignBackends(optNetObjPtr,
408 settingsCopy,
409 *subgraph,
410 errMessages);
411 if (reassignmentResult.m_Error)
412 {
413 // Failed to re-assign one of the remaining backends to each layer of the sub-graph
414 result.m_Error = true;
415 return result;
416 }
Matteo Martincighadddddb2019-01-24 14:06:23 +0000417 }
Matteo Martincigh49124022019-01-11 13:25:59 +0000418 }
419 }
420 }
421
422 return result;
423}
424
425IOptimizedNetworkPtr Optimize(const INetwork& inNetwork,
426 const std::vector<BackendId>& backendPreferences,
427 const IDeviceSpec& deviceSpec,
428 const OptimizerOptions& options,
429 Optional<std::vector<std::string>&> errMessages)
430{
431 if (backendPreferences.empty())
432 {
433 throw armnn::InvalidArgumentException("Invoked Optimize with no backends specified");
434 }
435
436 const Network& network = *boost::polymorphic_downcast<const Network*>(&inNetwork);
437 std::unique_ptr<Graph> graph = std::make_unique<Graph>(network.GetGraph());
438
439 auto optNet = IOptimizedNetworkPtr(new OptimizedNetwork(std::move(graph)), &IOptimizedNetwork::Destroy);
440
441 OptimizedNetwork* optNetObjPtr = boost::polymorphic_downcast<OptimizedNetwork*>(optNet.get());
442
Matteo Martincighadddddb2019-01-24 14:06:23 +0000443 // Get the optimized graph
444 Graph& optGraph = optNetObjPtr->GetGraph();
445
Matteo Martincigh49124022019-01-11 13:25:59 +0000446 // Perform optimisation passes
447 using namespace optimizations;
Matteo Martincighadddddb2019-01-24 14:06:23 +0000448 Optimizer::Pass(optGraph, MakeOptimizations(SquashEqualPermuteSiblings(),
449 SquashEqualReshapeSiblings(),
450 OptimizeInversePermutes(),
451 MovePermuteUp(),
452 PermuteAsReshape(),
Nina Drozd861985f2019-04-18 14:48:51 +0100453 OptimizeConsecutiveReshapes(),
454 FoldPadIntoConvolution2d()));
Matteo Martincigh49124022019-01-11 13:25:59 +0000455
Matteo Martincighadddddb2019-01-24 14:06:23 +0000456 // Infer the tensor infos for all output slots. Throws an exception on failure
457 optGraph.InferTensorInfos();
Matteo Martincigh49124022019-01-11 13:25:59 +0000458
459 // If Fp32 to Fp16 optimization is set convert Fp32 network to Fp16
460 if (options.m_ReduceFp32ToFp16)
461 {
Matteo Martincighadddddb2019-01-24 14:06:23 +0000462 Optimizer::Pass(optGraph, MakeOptimizations(Fp32NetworkToFp16Converter()));
Matteo Martincigh49124022019-01-11 13:25:59 +0000463 }
464
465 // Initialize backend settings
466 BackendSettings backendSettings(backendPreferences, deviceSpec);
467 if (backendSettings.GetAvailablePreferredBackends().empty())
468 {
469 std::stringstream failureMsg;
470 failureMsg << "None of the preferred backends " << backendPreferences
471 << " are supported. Current platform provides " << backendSettings.m_SupportedBackends;
472 ReportError(failureMsg.str(), errMessages);
473 return IOptimizedNetworkPtr(nullptr, &IOptimizedNetwork::Destroy);
474 }
475
476 // Assign an available backend to each layer
Matteo Martincighadddddb2019-01-24 14:06:23 +0000477 Graph::Iterator firstLayer = optGraph.begin();
478 Graph::Iterator lastLayer = optGraph.end();
Matteo Martincigh49124022019-01-11 13:25:59 +0000479 OptimizationResult assigBackendsResult = AssignBackends(optNetObjPtr,
480 backendSettings,
481 firstLayer,
482 lastLayer,
483 errMessages);
484 if (assigBackendsResult.m_Error)
485 {
486 // Failed to assign a backend to each layer
jimfly016b0b53d2018-10-08 14:43:01 +0100487 return IOptimizedNetworkPtr(nullptr, &IOptimizedNetwork::Destroy);
488 }
telsoa01c577f2c2018-08-31 09:22:23 +0100489
Matteo Martincighadddddb2019-01-24 14:06:23 +0000490 Optimizer::Pass(optGraph, MakeOptimizations(OptimizeInverseConversionsFp16(),
491 OptimizeInverseConversionsFp32()));
telsoa01c577f2c2018-08-31 09:22:23 +0100492
Matteo Martincighadddddb2019-01-24 14:06:23 +0000493 // Apply the backend-specific optimizations
494 OptimizationResult backendOptimizationResult = ApplyBackendOptimizations(optNetObjPtr,
495 backendSettings,
496 errMessages);
497 if (backendOptimizationResult.m_Error)
Matteo Martincigh49124022019-01-11 13:25:59 +0000498 {
Matteo Martincighadddddb2019-01-24 14:06:23 +0000499 // Failed to apply the backend-specific optimizations
500 return IOptimizedNetworkPtr(nullptr, &IOptimizedNetwork::Destroy);
Matteo Martincigh49124022019-01-11 13:25:59 +0000501 }
502
Matteo Martincighadddddb2019-01-24 14:06:23 +0000503 // If the debug flag is set, then insert a DebugLayer after each layer
504 // Doing this after applying the backend optimizations as they might have changed some layers
505 if (options.m_Debug)
506 {
507 Optimizer::Pass(optGraph, MakeOptimizations(InsertDebugLayer()));
508 }
509
510 optGraph.AddCopyLayers();
telsoa01c577f2c2018-08-31 09:22:23 +0100511
512 // Convert constants
Matteo Martincighadddddb2019-01-24 14:06:23 +0000513 Optimizer::Pass(optGraph, MakeOptimizations(ConvertConstantsFloatToHalf()));
514 Optimizer::Pass(optGraph, MakeOptimizations(ConvertConstantsHalfToFloat()));
telsoa01c577f2c2018-08-31 09:22:23 +0100515
David Beck263e3492018-11-09 14:46:40 +0000516 // Run backend specific optimizations
Matteo Martincigh49124022019-01-11 13:25:59 +0000517 for (auto&& chosenBackend : backendSettings.m_SelectedBackends)
David Beck263e3492018-11-09 14:46:40 +0000518 {
519 auto factoryFun = BackendRegistryInstance().GetFactory(chosenBackend);
520 auto backendPtr = factoryFun();
521 BOOST_ASSERT(backendPtr.get() != nullptr);
522
Matteo Martincighed735042019-05-22 09:42:43 +0100523 ARMNN_NO_DEPRECATE_WARN_BEGIN
David Beck263e3492018-11-09 14:46:40 +0000524 auto backendSpecificOptimizations = backendPtr->GetOptimizations();
Matteo Martincighed735042019-05-22 09:42:43 +0100525 ARMNN_NO_DEPRECATE_WARN_END
526
David Beck263e3492018-11-09 14:46:40 +0000527 if (!backendSpecificOptimizations.empty())
528 {
529 Optimizer::Pass(optNetObjPtr->GetGraph(), backendSpecificOptimizations);
530 }
531 }
532
telsoa01c577f2c2018-08-31 09:22:23 +0100533 return optNet;
telsoa014fcda012018-03-09 14:13:49 +0000534}
535
536Network::Network()
537: m_Graph(std::make_unique<Graph>())
538{
539}
540
541Network::~Network()
542{
543}
544
545IConnectableLayer* Network::AddInputLayer(LayerBindingId id, const char* name)
546{
547 return m_Graph->AddLayer<InputLayer>(id, name);
548}
549
Éanna Ó Catháin4e1e1362018-11-12 11:36:34 +0000550IConnectableLayer* Network::AddBatchToSpaceNdLayer(const BatchToSpaceNdDescriptor& batchToSpaceNdDescriptor,
551 const char* name)
552{
553 return m_Graph->AddLayer<BatchToSpaceNdLayer>(batchToSpaceNdDescriptor, name);
554}
555
telsoa014fcda012018-03-09 14:13:49 +0000556IConnectableLayer* Network::AddFullyConnectedLayerImpl(const FullyConnectedDescriptor& fullyConnectedDescriptor,
telsoa01c577f2c2018-08-31 09:22:23 +0100557 const ConstTensor& weights,
Aron Virginas-Tarad402702019-02-22 17:03:44 +0000558 const Optional<ConstTensor>& biases,
telsoa01c577f2c2018-08-31 09:22:23 +0100559 const char* name)
telsoa014fcda012018-03-09 14:13:49 +0000560{
Aron Virginas-Tarad402702019-02-22 17:03:44 +0000561 if (fullyConnectedDescriptor.m_BiasEnabled && !biases.has_value())
telsoa014fcda012018-03-09 14:13:49 +0000562 {
Aron Virginas-Tarad402702019-02-22 17:03:44 +0000563 throw InvalidArgumentException("AddFullyConnectedLayer: biases cannot be empty");
telsoa014fcda012018-03-09 14:13:49 +0000564 }
565
566 const auto layer = m_Graph->AddLayer<FullyConnectedLayer>(fullyConnectedDescriptor, name);
567
568 layer->m_Weight = std::make_unique<ScopedCpuTensorHandle>(weights);
569
570 if (fullyConnectedDescriptor.m_BiasEnabled)
571 {
Aron Virginas-Tarad402702019-02-22 17:03:44 +0000572 layer->m_Bias = std::make_unique<ScopedCpuTensorHandle>(biases.value());
telsoa014fcda012018-03-09 14:13:49 +0000573 }
574
575 return layer;
576}
577
578IConnectableLayer* Network::AddFullyConnectedLayer(const FullyConnectedDescriptor& fullyConnectedDescriptor,
telsoa01c577f2c2018-08-31 09:22:23 +0100579 const ConstTensor& weights,
Aron Virginas-Tarad402702019-02-22 17:03:44 +0000580 const Optional<ConstTensor>& biases,
telsoa01c577f2c2018-08-31 09:22:23 +0100581 const char* name)
telsoa014fcda012018-03-09 14:13:49 +0000582{
Aron Virginas-Tarad402702019-02-22 17:03:44 +0000583 return AddFullyConnectedLayerImpl(fullyConnectedDescriptor, weights, biases, name);
telsoa014fcda012018-03-09 14:13:49 +0000584}
585
Aron Virginas-Tarad402702019-02-22 17:03:44 +0000586IConnectableLayer* Network::AddFullyConnectedLayer(const FullyConnectedDescriptor& fullyConnectedDescriptor,
587 const ConstTensor& weights,
588 const char* name)
589{
Matteo Martincighfc598e12019-05-14 10:36:13 +0100590 Optional<ConstTensor> biases;
Aron Virginas-Tarad402702019-02-22 17:03:44 +0000591 return AddFullyConnectedLayerImpl(fullyConnectedDescriptor, weights, biases, name);
592}
593
telsoa014fcda012018-03-09 14:13:49 +0000594IConnectableLayer* Network::AddFullyConnectedLayer(const FullyConnectedDescriptor& fullyConnectedDescriptor,
telsoa01c577f2c2018-08-31 09:22:23 +0100595 const ConstTensor& weights,
596 const ConstTensor& biases,
597 const char* name)
telsoa014fcda012018-03-09 14:13:49 +0000598{
Aron Virginas-Tarad402702019-02-22 17:03:44 +0000599 Optional<ConstTensor> optionalBiases(biases);
600 return AddFullyConnectedLayerImpl(fullyConnectedDescriptor, weights, optionalBiases, name);
telsoa014fcda012018-03-09 14:13:49 +0000601}
602
Jim Flynn906f9462019-05-10 13:55:21 +0100603IConnectableLayer* Network::AddConcatLayer(const OriginsDescriptor& mergerDescriptor,
604 const char* name)
605{
606 ARMNN_NO_DEPRECATE_WARN_BEGIN
607 return AddMergerLayer(mergerDescriptor, name);
608 ARMNN_NO_DEPRECATE_WARN_END
609}
610
telsoa014fcda012018-03-09 14:13:49 +0000611IConnectableLayer* Network::AddConvolution2dLayerImpl(const Convolution2dDescriptor& convolution2dDescriptor,
telsoa01c577f2c2018-08-31 09:22:23 +0100612 const ConstTensor& weights,
Aron Virginas-Tarad402702019-02-22 17:03:44 +0000613 const Optional<ConstTensor>& biases,
telsoa01c577f2c2018-08-31 09:22:23 +0100614 const char* name)
telsoa014fcda012018-03-09 14:13:49 +0000615{
Aron Virginas-Tarad402702019-02-22 17:03:44 +0000616 if (convolution2dDescriptor.m_BiasEnabled && !biases.has_value())
telsoa014fcda012018-03-09 14:13:49 +0000617 {
Aron Virginas-Tarad402702019-02-22 17:03:44 +0000618 throw InvalidArgumentException("AddConvolution2dLayer: biases cannot be empty");
telsoa014fcda012018-03-09 14:13:49 +0000619 }
620
621 const auto layer = m_Graph->AddLayer<Convolution2dLayer>(convolution2dDescriptor, name);
622
623 layer->m_Weight = std::make_unique<ScopedCpuTensorHandle>(weights);
624
625 if (convolution2dDescriptor.m_BiasEnabled)
626 {
Aron Virginas-Tarad402702019-02-22 17:03:44 +0000627 layer->m_Bias = std::make_unique<ScopedCpuTensorHandle>(biases.value());
telsoa014fcda012018-03-09 14:13:49 +0000628 }
629
630 return layer;
631}
632
633IConnectableLayer* Network::AddConvolution2dLayer(const Convolution2dDescriptor& convolution2dDescriptor,
telsoa01c577f2c2018-08-31 09:22:23 +0100634 const ConstTensor& weights,
Aron Virginas-Tarad402702019-02-22 17:03:44 +0000635 const Optional<ConstTensor>& biases,
telsoa01c577f2c2018-08-31 09:22:23 +0100636 const char* name)
telsoa014fcda012018-03-09 14:13:49 +0000637{
Aron Virginas-Tarad402702019-02-22 17:03:44 +0000638 return AddConvolution2dLayerImpl(convolution2dDescriptor, weights, biases, name);
telsoa014fcda012018-03-09 14:13:49 +0000639}
Aron Virginas-Tarad402702019-02-22 17:03:44 +0000640
Aron Virginas-Tarad402702019-02-22 17:03:44 +0000641IConnectableLayer* Network::AddConvolution2dLayer(const Convolution2dDescriptor& convolution2dDescriptor,
642 const ConstTensor& weights,
643 const char* name)
644{
Matteo Martincighfc598e12019-05-14 10:36:13 +0100645 Optional<ConstTensor> biases;
Aron Virginas-Tarad402702019-02-22 17:03:44 +0000646 return AddConvolution2dLayerImpl(convolution2dDescriptor, weights, biases, name);
647}
648
telsoa014fcda012018-03-09 14:13:49 +0000649IConnectableLayer* Network::AddConvolution2dLayer(const Convolution2dDescriptor& convolution2dDescriptor,
telsoa01c577f2c2018-08-31 09:22:23 +0100650 const ConstTensor& weights,
651 const ConstTensor& biases,
652 const char* name)
telsoa014fcda012018-03-09 14:13:49 +0000653{
Aron Virginas-Tarad402702019-02-22 17:03:44 +0000654 Optional<ConstTensor> optionalBiases(biases);
655 return AddConvolution2dLayerImpl(convolution2dDescriptor, weights, optionalBiases, name);
telsoa014fcda012018-03-09 14:13:49 +0000656}
657
658IConnectableLayer* Network::AddDepthwiseConvolution2dLayerImpl(
659 const DepthwiseConvolution2dDescriptor& convolution2dDescriptor,
660 const ConstTensor& weights,
Aron Virginas-Tarad402702019-02-22 17:03:44 +0000661 const Optional<ConstTensor>& biases,
telsoa014fcda012018-03-09 14:13:49 +0000662 const char* name)
663{
Aron Virginas-Tarad402702019-02-22 17:03:44 +0000664 if (convolution2dDescriptor.m_BiasEnabled && !biases.has_value())
telsoa014fcda012018-03-09 14:13:49 +0000665 {
Aron Virginas-Tarad402702019-02-22 17:03:44 +0000666 throw InvalidArgumentException("AddDepthwiseConvolution2dLayer: biases cannot be empty");
telsoa014fcda012018-03-09 14:13:49 +0000667 }
668
Matteo Martincigh3d6898c2019-01-15 16:11:44 +0000669 const auto layer = m_Graph->AddLayer<DepthwiseConvolution2dLayer>(convolution2dDescriptor, name);
telsoa014fcda012018-03-09 14:13:49 +0000670
671 layer->m_Weight = std::make_unique<ScopedCpuTensorHandle>(weights);
672
673 if (convolution2dDescriptor.m_BiasEnabled)
674 {
Aron Virginas-Tarad402702019-02-22 17:03:44 +0000675 layer->m_Bias = std::make_unique<ScopedCpuTensorHandle>(biases.value());
telsoa014fcda012018-03-09 14:13:49 +0000676 }
677
678 return layer;
679}
680
681IConnectableLayer* Network::AddDepthwiseConvolution2dLayer(
Aron Virginas-Tarad402702019-02-22 17:03:44 +0000682 const DepthwiseConvolution2dDescriptor& convolution2dDescriptor,
683 const ConstTensor& weights,
684 const Optional<ConstTensor>& biases,
685 const char* name)
686{
687 return AddDepthwiseConvolution2dLayerImpl(convolution2dDescriptor, weights, biases, name);
688}
689
Aron Virginas-Tarad402702019-02-22 17:03:44 +0000690IConnectableLayer* Network::AddDepthwiseConvolution2dLayer(
telsoa014fcda012018-03-09 14:13:49 +0000691 const DepthwiseConvolution2dDescriptor& convolution2dDescriptor,
692 const ConstTensor& weights,
693 const char* name)
694{
Matteo Martincighfc598e12019-05-14 10:36:13 +0100695 Optional<ConstTensor> biases;
Aron Virginas-Tarad402702019-02-22 17:03:44 +0000696 return AddDepthwiseConvolution2dLayerImpl(convolution2dDescriptor, weights, biases, name);
telsoa014fcda012018-03-09 14:13:49 +0000697}
Aron Virginas-Tarad402702019-02-22 17:03:44 +0000698
telsoa014fcda012018-03-09 14:13:49 +0000699IConnectableLayer* Network::AddDepthwiseConvolution2dLayer(
700 const DepthwiseConvolution2dDescriptor& convolution2dDescriptor,
701 const ConstTensor& weights,
702 const ConstTensor& biases,
703 const char* name)
704{
Aron Virginas-Tarad402702019-02-22 17:03:44 +0000705 Optional<ConstTensor> optionalBiases(biases);
706 return AddDepthwiseConvolution2dLayerImpl(convolution2dDescriptor, weights, optionalBiases, name);
telsoa014fcda012018-03-09 14:13:49 +0000707}
708
Narumol Prangnawarat94dd5d82019-01-23 18:06:26 +0000709IConnectableLayer* Network::AddDetectionPostProcessLayer(const armnn::DetectionPostProcessDescriptor& descriptor,
Narumol Prangnawarat6d302bf2019-02-04 11:46:26 +0000710 const ConstTensor& anchors, const char* name)
Narumol Prangnawarat94dd5d82019-01-23 18:06:26 +0000711{
Narumol Prangnawarat6d302bf2019-02-04 11:46:26 +0000712 const auto layer = m_Graph->AddLayer<DetectionPostProcessLayer>(descriptor, name);
713
714 layer->m_Anchors = std::make_unique<ScopedCpuTensorHandle>(anchors);
715
716 return layer;
Narumol Prangnawarat94dd5d82019-01-23 18:06:26 +0000717}
718
telsoa014fcda012018-03-09 14:13:49 +0000719IConnectableLayer* Network::AddPermuteLayer(const PermuteDescriptor& permuteDescriptor,
720 const char* name)
721{
722 return m_Graph->AddLayer<PermuteLayer>(permuteDescriptor, name);
723}
724
725IConnectableLayer* Network::AddPooling2dLayer(const Pooling2dDescriptor& pooling2dDescriptor,
726 const char* name)
727{
728 return m_Graph->AddLayer<Pooling2dLayer>(pooling2dDescriptor, name);
729}
730
731IConnectableLayer* Network::AddActivationLayer(const ActivationDescriptor& activationDescriptor,
732 const char* name)
733{
734 return m_Graph->AddLayer<ActivationLayer>(activationDescriptor, name);
735}
736
telsoa01c577f2c2018-08-31 09:22:23 +0100737IConnectableLayer* Network::AddNormalizationLayer(const NormalizationDescriptor&
738normalizationDescriptor,
telsoa014fcda012018-03-09 14:13:49 +0000739 const char* name)
740{
741 return m_Graph->AddLayer<NormalizationLayer>(normalizationDescriptor, name);
742}
743
744IConnectableLayer* Network::AddSoftmaxLayer(const SoftmaxDescriptor& softmaxDescriptor,
745 const char* name)
746{
747 return m_Graph->AddLayer<SoftmaxLayer>(softmaxDescriptor, name);
748}
749
750IConnectableLayer* Network::AddSplitterLayer(const ViewsDescriptor& splitterDescriptor,
751 const char* name)
752{
753 return m_Graph->AddLayer<SplitterLayer>(splitterDescriptor, name);
754}
755
Nattapat Chaimanowong5a4304a2018-11-28 10:44:37 +0000756IConnectableLayer* Network::AddMaximumLayer(const char* name)
757{
758 return m_Graph->AddLayer<MaximumLayer>(name);
759}
760
Éanna Ó Catháin20e58802018-12-04 10:29:06 +0000761IConnectableLayer* Network::AddMinimumLayer(const char* name)
762{
763 return m_Graph->AddLayer<MinimumLayer>(name);
764}
765
telsoa014fcda012018-03-09 14:13:49 +0000766IConnectableLayer* Network::AddMergerLayer(const OriginsDescriptor& mergerDescriptor,
Jim Flynn906f9462019-05-10 13:55:21 +0100767 const char* name)
telsoa014fcda012018-03-09 14:13:49 +0000768{
769 return m_Graph->AddLayer<MergerLayer>(mergerDescriptor, name);
770}
771
772IConnectableLayer* Network::AddAdditionLayer(const char* name)
773{
774 return m_Graph->AddLayer<AdditionLayer>(name);
775}
776
777IConnectableLayer* Network::AddMultiplicationLayer(const char* name)
778{
779 return m_Graph->AddLayer<MultiplicationLayer>(name);
780}
781
782IConnectableLayer* Network::AddOutputLayer(LayerBindingId id, const char* name)
783{
784 return m_Graph->AddLayer<OutputLayer>(id, name);
785}
786
787IConnectableLayer* Network::AddBatchNormalizationLayer(const BatchNormalizationDescriptor& desc,
788 const ConstTensor& mean,
789 const ConstTensor& variance,
790 const ConstTensor& beta,
791 const ConstTensor& gamma,
792 const char* name)
793{
794 const auto layer = m_Graph->AddLayer<BatchNormalizationLayer>(desc, name);
795
796 layer->m_Mean = std::make_unique<ScopedCpuTensorHandle>(mean);
797 layer->m_Variance = std::make_unique<ScopedCpuTensorHandle>(variance);
798 layer->m_Beta = std::make_unique<ScopedCpuTensorHandle>(beta);
799 layer->m_Gamma = std::make_unique<ScopedCpuTensorHandle>(gamma);
800
801 return layer;
802}
803
telsoa01c577f2c2018-08-31 09:22:23 +0100804IConnectableLayer* Network::AddResizeBilinearLayer(const ResizeBilinearDescriptor&
805resizeDescriptor, const char* name)
telsoa014fcda012018-03-09 14:13:49 +0000806{
807 return m_Graph->AddLayer<ResizeBilinearLayer>(resizeDescriptor,name);
808}
809
Matteo Martincighbcd3c852018-09-28 14:14:12 +0100810IConnectableLayer* Network::AddL2NormalizationLayer(const L2NormalizationDescriptor& desc,
811 const char* name)
telsoa014fcda012018-03-09 14:13:49 +0000812{
Matteo Martincighbcd3c852018-09-28 14:14:12 +0100813 return m_Graph->AddLayer<L2NormalizationLayer>(desc, name);
telsoa014fcda012018-03-09 14:13:49 +0000814}
815
816IConnectableLayer* Network::AddConstantLayer(const ConstTensor& input, const char* name)
817{
telsoa01c577f2c2018-08-31 09:22:23 +0100818 auto layer = m_Graph->AddLayer<ConstantLayer>(name);
819
820 layer->m_LayerOutput = std::make_unique<ScopedCpuTensorHandle>(input);
821
822 return layer;
telsoa014fcda012018-03-09 14:13:49 +0000823}
824
telsoa01c577f2c2018-08-31 09:22:23 +0100825IConnectableLayer* Network::AddReshapeLayer(const ReshapeDescriptor& reshapeDescriptor,
826 const char* name)
telsoa014fcda012018-03-09 14:13:49 +0000827{
828 return m_Graph->AddLayer<ReshapeLayer>(reshapeDescriptor, name);
829}
830
Nattapat Chaimanowong207ef9a2018-11-02 10:57:25 +0000831IConnectableLayer* Network::AddSpaceToBatchNdLayer(const SpaceToBatchNdDescriptor& spaceToBatchNdDescriptor,
832 const char* name)
833{
834 return m_Graph->AddLayer<SpaceToBatchNdLayer>(spaceToBatchNdDescriptor, name);
835}
836
telsoa014fcda012018-03-09 14:13:49 +0000837IConnectableLayer* Network::AddFloorLayer(const char* name)
838{
839 return m_Graph->AddLayer<FloorLayer>(name);
840}
841
telsoa01c577f2c2018-08-31 09:22:23 +0100842IConnectableLayer* Network::AddLstmLayer(const LstmDescriptor& descriptor,
843 const LstmInputParams& params,
844 const char* name)
845{
846 const auto layer = m_Graph->AddLayer<LstmLayer>(descriptor, name);
847
848 //Lstm Basic Parameters
849 layer->m_BasicParameters.m_InputToForgetWeights =
850 std::make_unique<ScopedCpuTensorHandle>(*(params.m_InputToForgetWeights));
851 layer->m_BasicParameters.m_InputToCellWeights =
852 std::make_unique<ScopedCpuTensorHandle>(*(params.m_InputToCellWeights));
853 layer->m_BasicParameters.m_InputToOutputWeights =
854 std::make_unique<ScopedCpuTensorHandle>(*(params.m_InputToOutputWeights));
855 layer->m_BasicParameters.m_RecurrentToForgetWeights =
856 std::make_unique<ScopedCpuTensorHandle>(*(params.m_RecurrentToForgetWeights));
857 layer->m_BasicParameters.m_RecurrentToCellWeights =
858 std::make_unique<ScopedCpuTensorHandle>(*(params.m_RecurrentToCellWeights));
859 layer->m_BasicParameters.m_RecurrentToOutputWeights =
860 std::make_unique<ScopedCpuTensorHandle>(*(params.m_RecurrentToOutputWeights));
861 layer->m_BasicParameters.m_ForgetGateBias =
862 std::make_unique<ScopedCpuTensorHandle>(*(params.m_ForgetGateBias));
863 layer->m_BasicParameters.m_CellBias =
864 std::make_unique<ScopedCpuTensorHandle>(*(params.m_CellBias));
865 layer->m_BasicParameters.m_OutputGateBias =
866 std::make_unique<ScopedCpuTensorHandle>(*(params.m_OutputGateBias));
867
868 //Lstm Cifg parameters
869 if(!descriptor.m_CifgEnabled)
870 {
871 if(params.m_InputToInputWeights == nullptr)
872 {
873 throw InvalidArgumentException("AddLstmLayer: Input To Input Weights cannot be NULL");
874 }
875 if(params.m_RecurrentToInputWeights == nullptr)
876 {
877 throw InvalidArgumentException(
878 "AddLstmLayer: Recurrent To Input Weights cannot be NULL");
879 }
880 if(params.m_InputGateBias == nullptr)
881 {
882 throw InvalidArgumentException("AddLstmLayer: Input Gate Bias cannot be NULL");
883 }
884 layer->m_CifgParameters.m_InputToInputWeights =
885 std::make_unique<ScopedCpuTensorHandle>(*(params.m_InputToInputWeights));
886 layer->m_CifgParameters.m_RecurrentToInputWeights =
887 std::make_unique<ScopedCpuTensorHandle>(*(params.m_RecurrentToInputWeights));
888 // In the VTS tests, cell-to-input weights may be null, even if the other CIFG params are not.
889 if(params.m_CellToInputWeights != nullptr)
890 {
891 layer->m_CifgParameters.m_CellToInputWeights =
892 std::make_unique<ScopedCpuTensorHandle>(*(params.m_CellToInputWeights));
893 }
894 layer->m_CifgParameters.m_InputGateBias =
895 std::make_unique<ScopedCpuTensorHandle>(*(params.m_InputGateBias));
896 }
897
898 //Lstm projection parameters
899 if(descriptor.m_ProjectionEnabled)
900 {
901 if(params.m_ProjectionWeights == nullptr)
902 {
903 throw InvalidArgumentException("AddLstmLayer: Projection Weights cannot be NULL");
904 }
905 layer->m_ProjectionParameters.m_ProjectionWeights =
906 std::make_unique<ScopedCpuTensorHandle>(*(params.m_ProjectionWeights));
907 if(params.m_ProjectionBias != nullptr)
908 {
909 layer->m_ProjectionParameters.m_ProjectionBias =
910 std::make_unique<ScopedCpuTensorHandle>(*(params.m_ProjectionBias));
911 }
912 }
913
914 //Lstm Peephole params
915 if(descriptor.m_PeepholeEnabled)
916 {
917 if(params.m_CellToForgetWeights == nullptr)
918 {
919 throw InvalidArgumentException("AddLstmLayer: Cell To Forget Weights cannot be NULL");
920 }
921 if(params.m_CellToOutputWeights == nullptr)
922 {
923 throw InvalidArgumentException("AddLstmLayer: Cell To Output Weights cannot be NULL");
924 }
925 layer->m_PeepholeParameters.m_CellToForgetWeights =
926 std::make_unique<ScopedCpuTensorHandle>(*(params.m_CellToForgetWeights));
927 layer->m_PeepholeParameters.m_CellToOutputWeights =
928 std::make_unique<ScopedCpuTensorHandle>(*(params.m_CellToOutputWeights));
929 }
930 return layer;
931}
932
Francis Murtaghe7a86a42018-08-29 12:42:10 +0100933IConnectableLayer* Network::AddDivisionLayer(const char* name)
934{
935 return m_Graph->AddLayer<DivisionLayer>(name);
936}
937
David Beck19526222018-09-12 16:00:08 +0100938IConnectableLayer* Network::AddSubtractionLayer(const char* name)
939{
940 return m_Graph->AddLayer<SubtractionLayer>(name);
941}
942
narpra0132b90462018-09-13 11:07:48 +0100943IConnectableLayer* Network::AddMeanLayer(const MeanDescriptor& meanDescriptor, const char* name)
944{
945 return m_Graph->AddLayer<MeanLayer>(meanDescriptor,name);
946}
947
Mohamed Nour Abouelseoud5662c202018-09-24 13:30:09 +0100948IConnectableLayer* Network::AddPadLayer(const PadDescriptor& padDescriptor, const char* name)
949{
950 return m_Graph->AddLayer<PadLayer>(padDescriptor,name);
951}
952
Derek Lambertia9cca6a2019-03-25 15:41:58 +0000953IConnectableLayer *Network::AddQuantizeLayer(const char *name)
954{
955 return m_Graph->AddLayer<QuantizeLayer>(name);
956}
957
Nattapat Chaimanowonge4294fd2019-03-28 09:56:53 +0000958IConnectableLayer* Network::AddDequantizeLayer(const char* name)
959{
960 return m_Graph->AddLayer<DequantizeLayer>(name);
961}
962
Conor Kennedy430b5d82018-11-14 15:28:28 +0000963IConnectableLayer* Network::AddStridedSliceLayer(const StridedSliceDescriptor& stridedSliceDescriptor,
964 const char* name)
965{
966 return m_Graph->AddLayer<StridedSliceLayer>(stridedSliceDescriptor, name);
967}
968
Matteo Martincigh59a950c2018-12-13 12:48:25 +0000969IConnectableLayer* Network::AddGreaterLayer(const char* name)
970{
971 return m_Graph->AddLayer<GreaterLayer>(name);
972}
973
FrancisMurtagh20995952018-12-17 12:11:36 +0000974IConnectableLayer* Network::AddEqualLayer(const char* name)
975{
jimfly0184c70e62018-12-19 13:14:46 +0000976 return m_Graph->AddLayer<EqualLayer>(name);
FrancisMurtagh20995952018-12-17 12:11:36 +0000977}
978
Mohamed Nour Abouelseouda1d3c6a2018-12-27 12:39:16 +0000979IConnectableLayer* Network::AddRsqrtLayer(const char * name)
980{
981 return m_Graph->AddLayer<RsqrtLayer>(name);
982}
983
narpra01b89b05f2019-01-16 09:53:09 +0000984IConnectableLayer* Network::AddGatherLayer(const char* name)
985{
986 return m_Graph->AddLayer<GatherLayer>(name);
987}
988
Nattapat Chaimanowong1f886302019-04-05 13:37:19 +0100989IConnectableLayer* Network::AddMergeLayer(const char* name)
990{
991 return m_Graph->AddLayer<MergeLayer>(name);
992}
993
Sadik Armaganeff363d2019-04-05 15:25:46 +0100994IConnectableLayer* Network::AddSwitchLayer(const char* name)
995{
996 return m_Graph->AddLayer<SwitchLayer>(name);
997}
998
Mike Kelly8c1701a2019-02-11 17:01:27 +0000999void Network::Accept(ILayerVisitor& visitor) const
1000{
1001 for (auto layer : GetGraph())
1002 {
1003 layer->Accept(visitor);
1004 };
1005}
1006
telsoa014fcda012018-03-09 14:13:49 +00001007OptimizedNetwork::OptimizedNetwork(std::unique_ptr<Graph> graph)
1008 : m_Graph(std::move(graph))
1009{
1010}
1011
1012OptimizedNetwork::~OptimizedNetwork()
1013{
1014}
1015
1016} // namespace armnn