2 // Copyright © 2017 Arm Ltd and Contributors. All rights reserved.
3 // SPDX-License-Identifier: MIT
9 #include "DeviceSpec.hpp"
10 #include "Optimizer.hpp"
11 #include "SubgraphViewSelector.hpp"
12 #include "BackendSettings.hpp"
13 #include "optimizations/All.hpp"
15 #include <backendsCommon/CpuTensorHandle.hpp>
16 #include <backendsCommon/WorkloadFactory.hpp>
17 #include <armnn/backends/IBackendInternal.hpp>
18 #include <backendsCommon/TensorHandleFactoryRegistry.hpp>
20 #include <armnn/Exceptions.hpp>
21 #include <armnn/Utils.hpp>
22 #include <armnn/TypesUtils.hpp>
23 #include <armnn/BackendRegistry.hpp>
24 #include <armnn/Logging.hpp>
25 #include <armnn/utility/Assert.hpp>
26 #include <armnn/utility/IgnoreUnused.hpp>
27 #include <armnn/utility/PolymorphicDowncast.hpp>
29 #include <ProfilingService.hpp>
38 #include <boost/format.hpp>
39 #include <boost/numeric/conversion/converter_policies.hpp>
44 armnn::INetwork* INetwork::CreateRaw(NetworkOptions networkOptions)
46 return new Network(networkOptions);
49 armnn::INetworkPtr INetwork::Create(NetworkOptions networkOptions)
51 return INetworkPtr(CreateRaw(networkOptions), &INetwork::Destroy);
54 void INetwork::Destroy(INetwork* network)
56 delete PolymorphicDowncast<Network*>(network);
59 void IOptimizedNetwork::Destroy(IOptimizedNetwork* network)
61 delete PolymorphicDowncast<OptimizedNetwork*>(network);
64 Status OptimizedNetwork::PrintGraph()
67 return Status::Success;
70 Status OptimizedNetwork::SerializeToDot(std::ostream& stream) const
72 return m_Graph->SerializeToDot(stream);
75 void ReportError(const std::string& errorMessage,
76 Optional<std::vector<std::string>&> errorMessages)
78 std::stringstream fullErrorMessage;
79 fullErrorMessage << "ERROR: " << errorMessage;
80 ARMNN_LOG(warning) << fullErrorMessage.str();
83 errorMessages.value().push_back(fullErrorMessage.str());
87 void ReportWarning(const std::string& warningMessage,
88 Optional<std::vector<std::string>&> warningMessages)
90 std::stringstream fullWarningMessage;
91 fullWarningMessage << "WARNING: " << warningMessage;
92 ARMNN_LOG(warning) << fullWarningMessage.str();
95 warningMessages.value().push_back(fullWarningMessage.str());
99 OptimizationResult ReturnWithError(OptimizationResult res,
101 const BackendSettings& backendSettings,
102 Optional<std::vector<std::string>&> errMessages)
104 std::stringstream failureMsg;
105 failureMsg << "Layer of type " << GetLayerTypeAsCString(layer->GetType())
106 << " is not supported on any preferred backend " << backendSettings.m_PreferredBackends;
107 ReportError(failureMsg.str(), errMessages);
114 bool CheckScaleSetOnQuantizedType(Layer* layer, Optional<std::vector<std::string>&> errMessages)
116 bool noErrors = true;
117 unsigned int numOutputs = layer->GetNumOutputSlots();
118 for (unsigned int i = 0; i < numOutputs; i++) {
119 OutputSlot& outputSlot = layer->GetOutputSlot(i);
120 TensorInfo info = outputSlot.GetTensorInfo();
121 if (DataType::QAsymmU8 == info.GetDataType()) {
122 if (0.f == info.GetQuantizationScale()) {
124 std::stringstream ss;
125 ss << "output " << i << " of layer " << GetLayerTypeAsCString(layer->GetType())
126 << " (" << layer->GetNameStr() << ") is of type"
127 << " Quantized 8 bit but its scale parameter has not been set";
128 ReportError(ss.str(), errMessages);
130 // Softmax under QuantisedAsymm8 must always be scale (1.0f/256.0f) and offset 0
131 if ((info.GetQuantizationScale() != (1.0f / 256.0f) ||
132 info.GetQuantizationOffset() != 0) &&
133 layer->GetType() == armnn::LayerType::Softmax)
135 std::stringstream ss;
136 ss << "Quantization parameters for Softmax layer (Scale: " <<
137 info.GetQuantizationScale() << " and Offset: " << info.GetQuantizationOffset() <<
138 ") are incorrect and have been updated to Scale: 0.00390625 and Offset: 0";
139 ARMNN_LOG(warning) << ss.str();
140 info.SetQuantizationScale((1.0f /256.0f));
141 info.SetQuantizationOffset(0);
142 outputSlot.SetTensorInfo(info);
149 template <typename LayerT>
150 LayerT* ConvertBf16ToFp32Weight(Layer* l)
152 LayerT* layer = PolymorphicDowncast<LayerT*>(l);
153 if ((layer->GetType() == LayerType::Convolution2d || layer->GetType() == LayerType::FullyConnected)
156 const TensorInfo& info = layer->m_Weight->GetTensorInfo();
158 if (info.GetDataType() == DataType::BFloat16)
160 std::vector<float> newValues(info.GetNumElements());
162 armnnUtils::FloatingPointConverter::ConvertBFloat16ToFloat32(
163 layer->m_Weight->template GetTensor<armnn::BFloat16>(), info.GetNumElements(), newValues.data());
165 TensorInfo newInfo(info.GetShape(), DataType::Float32);
166 ConstTensor newInput(newInfo, newValues);
167 layer->m_Weight.reset(new ScopedCpuTensorHandle(newInput));
173 OptimizationResult AttemptBackendAssignment(BackendSettings& backendSettings,
178 DataType dataTypeOut,
179 const std::vector<BackendId>& availablePreferredBackends,
180 std::string& reasonIfUnsupported,
181 Optional<std::vector<std::string>&> errMessages)
183 OptimizationResult result;
185 // Helper lambda to compose meaningful error message before returning with error
186 auto ReturnError = [&](const Layer* layer)
188 return ReturnWithError(result, layer, backendSettings, errMessages);
191 // need to set the compute device on the layer
192 // before we can check if it is supported
193 layer->SetBackendId(backend);
194 if (!IWorkloadFactory::IsLayerSupported(*layer, EmptyOptional(), reasonIfUnsupported))
196 if (dataTypeIn == DataType::Float16 || dataTypeOut == DataType::Float16)
198 if (IWorkloadFactory::IsLayerSupported(*layer, DataType::Float32, reasonIfUnsupported)
199 && layer->GetType() != LayerType::ConvertFp32ToFp16
200 && layer->GetType() != LayerType::ConvertFp16ToFp32)
202 // Insert FP16 -> FP32 conversion layer before current layer
203 std::vector<ConvertFp16ToFp32Layer*> convertFp16ToFp32Layers;
204 if (dataTypeIn == DataType::Float16)
206 convertFp16ToFp32Layers =
207 InsertConvertFp16ToFp32LayersBefore(graph, *layer);
210 // Insert FP32 -> FP16 conversion layer after current layer
211 std::vector<ConvertFp32ToFp16Layer*> convertFp32ToFp16Layers;
212 if (dataTypeOut == DataType::Float16)
214 convertFp32ToFp16Layers =
215 InsertConvertFp32ToFp16LayersAfter(graph, *layer);
218 // Assign a supported backend to the newly introduced conversion layers
219 auto AssignFirstSupportedBackend = [&](Layer* layer, BackendId preferredBackend)
221 bool supportedBackendFound = false;
222 std::string reasonIfUnsupported;
224 // Try preferred backend first
225 layer->SetBackendId(preferredBackend);
226 if (IWorkloadFactory::IsLayerSupported(*layer,
228 reasonIfUnsupported))
230 supportedBackendFound = true;
234 for (const auto& backend : availablePreferredBackends)
236 // Skip preferred backend (we already determined that it is not supported)
237 if (backend == preferredBackend)
242 layer->SetBackendId(backend);
243 if (IWorkloadFactory::IsLayerSupported(*layer,
245 reasonIfUnsupported))
247 supportedBackendFound = true;
253 return supportedBackendFound;
256 for (ConvertFp16ToFp32Layer* convertLayer : convertFp16ToFp32Layers)
258 if (!AssignFirstSupportedBackend(convertLayer, backend))
260 return ReturnError(convertLayer);
264 for (ConvertFp32ToFp16Layer* convertLayer : convertFp32ToFp16Layers)
266 if (!AssignFirstSupportedBackend(convertLayer, backend))
268 return ReturnError(convertLayer);
275 else if (dataTypeIn == DataType::BFloat16 || dataTypeOut == DataType::BFloat16)
277 if (IWorkloadFactory::IsLayerSupported(*layer, DataType::Float32, reasonIfUnsupported)
278 && layer->GetType() != LayerType::ConvertFp32ToBf16
279 && layer->GetType() != LayerType::ConvertBf16ToFp32)
281 // Insert BF16 -> FP32 conversion layer before current layer
282 std::vector<ConvertBf16ToFp32Layer*> convertBf16ToFp32Layers;
283 if (dataTypeIn == DataType::BFloat16)
285 convertBf16ToFp32Layers =
286 InsertConvertBf16ToFp32LayersBefore(graph, *layer);
287 if (layer->GetType() == LayerType::Convolution2d)
289 ConvertBf16ToFp32Weight<Convolution2dLayer>(layer);
291 else if (layer->GetType() == LayerType::FullyConnected)
293 ConvertBf16ToFp32Weight<FullyConnectedLayer>(layer);
297 // Insert FP32 -> BF16 conversion layer after current layer
298 std::vector<ConvertFp32ToBf16Layer*> convertFp32ToBf16Layers;
299 if (dataTypeOut == DataType::BFloat16)
301 convertFp32ToBf16Layers =
302 InsertConvertFp32ToBf16LayersAfter(graph, *layer);
305 // Assign a supported backend to the newly introduced conversion layers
306 auto AssignFirstSupportedBackend = [&](Layer* layer, BackendId preferredBackend)
308 bool supportedBackendFound = false;
309 std::string reasonIfUnsupported;
311 // Try preferred backend first
312 layer->SetBackendId(preferredBackend);
313 if (IWorkloadFactory::IsLayerSupported(*layer,
315 reasonIfUnsupported))
317 supportedBackendFound = true;
321 for (const auto& backend : availablePreferredBackends)
323 // Skip preferred backend (we already determined that it is not supported)
324 if (backend == preferredBackend)
329 layer->SetBackendId(backend);
330 if (IWorkloadFactory::IsLayerSupported(*layer,
332 reasonIfUnsupported))
334 supportedBackendFound = true;
340 return supportedBackendFound;
343 for (ConvertBf16ToFp32Layer* convertLayer : convertBf16ToFp32Layers)
345 if (!AssignFirstSupportedBackend(convertLayer, backend))
347 return ReturnError(convertLayer);
351 for (ConvertFp32ToBf16Layer* convertLayer : convertFp32ToBf16Layers)
353 if (!AssignFirstSupportedBackend(convertLayer, backend))
355 return ReturnError(convertLayer);
363 std::stringstream warningMsg;
364 warningMsg << "Layer of type " << GetLayerTypeAsCString(layer->GetType())
365 << " is not supported on requested backend " << layer->GetBackendId().Get()
366 << " for input data type " << GetDataTypeName(dataTypeIn)
367 << " and output data type " << GetDataTypeName(dataTypeOut)
368 << " (reason: " << reasonIfUnsupported
369 << "), falling back to the next backend.";
370 ReportWarning(warningMsg.str(), errMessages);
372 return OptimizationResult(true, false);
381 OptimizationResult AssignBackends(OptimizedNetwork* optNetObjPtr,
382 BackendSettings& backendSettings,
383 Graph::Iterator& firstLayer,
384 Graph::Iterator& lastLayer,
385 Optional<std::vector<std::string>&> errMessages)
387 OptimizationResult result;
389 // Helper lambda to compose meaningful error message before returning with error
390 auto ReturnError = [&](const Layer* layer)
392 return ReturnWithError(result, layer, backendSettings, errMessages);
396 auto availablePreferredBackends = backendSettings.GetAvailablePreferredBackends();
397 if (availablePreferredBackends.empty())
399 std::stringstream failureMsg;
400 failureMsg << "No preferred backends are available";
401 ReportError(failureMsg.str(), errMessages);
403 result.m_Error = true;
407 for (auto it = firstLayer; it != lastLayer; ++it)
411 DataType dataTypeIn = layer->GetNumInputSlots() == 0 ? DataType::Float32 :
412 layer->GetInputSlot(0).GetConnectedOutputSlot()->GetTensorInfo().GetDataType();
413 DataType dataTypeOut = layer->GetNumOutputSlots() == 0 ? DataType::Float32 :
414 layer->GetOutputSlot(0).GetTensorInfo().GetDataType();
416 std::string reasonIfUnsupported;
418 if (!CheckScaleSetOnQuantizedType(layer, errMessages))
420 // don't bomb immediately, find all the quantized outputs
421 // which haven't had a scale set and report them all back.
422 result.m_Error = true;
425 // First try assign layer to hint backend
426 if (layer->GetBackendHint().has_value() &&
427 backendSettings.IsBackendSupported(layer->GetBackendHint().value()) &&
428 AttemptBackendAssignment(backendSettings,
429 optNetObjPtr->GetGraph(),
431 layer->GetBackendHint().value(),
434 availablePreferredBackends,
439 backendSettings.m_SelectedBackends.insert(layer->GetBackendHint().value());
443 // Try assign layer to prefered list of backends
444 for (const auto& backend : availablePreferredBackends)
446 if (layer->GetBackendHint().has_value() &&
447 layer->GetBackendHint().value() == backend)
449 continue; //Don't re-test the backend hint
452 OptimizationResult res = AttemptBackendAssignment(backendSettings,
453 optNetObjPtr->GetGraph(),
458 availablePreferredBackends,
465 backendSettings.m_SelectedBackends.insert(backend);
468 else if (res.IsError())
470 return res; // Cannot continue.
471 // Note: we don't need to log the error as it would already
472 // be logged in AttemptBackendAssignment().
476 ARMNN_ASSERT_MSG(res.IsWarningOnly(), "OptimizationResult in unexpected state.");
481 // If the layer is unsupported by any devices, log and return a null network.
484 // NOTE: if the layer is not an operation queue type AND we have not got CpuRef as a
485 // fallback we should set the compute device on the layer to CpuRef (these are not
486 // available as accelerated operations, or are only available under certain
487 // conditions, currently they comprise MemCopy, Constant, Permute)
488 armnn::LayerType layerType = layer->GetType();
489 if (!backendSettings.IsCpuRefUsed() && (layerType == armnn::LayerType::MemCopy ||
490 layerType == armnn::LayerType::Constant ||
491 layerType == armnn::LayerType::Permute))
493 BackendId cpuBackendId(armnn::Compute::CpuRef);
494 layer->SetBackendId(cpuBackendId);
495 backendSettings.m_SelectedBackends.insert(cpuBackendId);
499 return ReturnError(layer);
507 OptimizationResult AssignBackends(OptimizedNetwork* optNetObjPtr,
508 BackendSettings& backendSettings,
509 SubgraphView& subgraph,
510 Optional<std::vector<std::string>&> errMessages)
512 Graph::Iterator firstLayer = subgraph.begin();
513 Graph::Iterator lastLayer = subgraph.end();
514 return AssignBackends(optNetObjPtr,
521 BackendsMap CreateSupportedBackends(TensorHandleFactoryRegistry& handleFactoryRegistry,
522 BackendSettings& backendSettings)
524 BackendsMap backends;
525 auto const& backendRegistry = BackendRegistryInstance();
526 for (auto&& selectedBackend : backendSettings.m_SupportedBackends)
528 auto backendFactory = backendRegistry.GetFactory(selectedBackend);
529 auto backendObjPtr = backendFactory();
530 ARMNN_ASSERT(backendObjPtr);
532 backendObjPtr->RegisterTensorHandleFactories(handleFactoryRegistry);
534 backends[backendObjPtr->GetId()] = std::move(backendObjPtr);
540 OptimizationResult ApplyBackendOptimizations(OptimizedNetwork* optNetObjPtr,
541 BackendSettings& backendSettings,
542 BackendsMap& backends,
543 Optional<std::vector<std::string>&> errMessages)
545 ARMNN_ASSERT(optNetObjPtr);
547 OptimizationResult result;
549 // Get the optimized graph
550 Graph& optGraph = optNetObjPtr->GetGraph();
552 // Run backend specific optimizations
553 for (auto&& selectedBackend : backendSettings.m_SelectedBackends)
555 auto backendObjPtr = backends.find(selectedBackend)->second.get();
556 ARMNN_ASSERT(backendObjPtr);
558 // Select sub-graphs based on backend
559 SubgraphViewSelector::Subgraphs subgraphs =
560 SubgraphViewSelector::SelectSubgraphs(optGraph,
561 // Select layers assigned to the requested backend
562 [&backendObjPtr](const Layer& layer)
564 return layer.GetType() != LayerType::Input &&
565 layer.GetType() != LayerType::Output &&
566 layer.GetBackendId() == backendObjPtr->GetId();
568 if (subgraphs.empty())
570 // No sub-graphs found, try with next selected backend
574 // Try to optimize each sub-graph
575 for (auto& subgraph : subgraphs)
577 // Try to optimize the current sub-graph
578 OptimizationViews optimizationViews = backendObjPtr->OptimizeSubgraphView(*subgraph);
579 ARMNN_ASSERT(optimizationViews.Validate(*subgraph));
581 // Optimization attempted, check the resulting optimized sub-graph
582 for (auto& substitution : optimizationViews.GetSubstitutions())
584 // Sub-graph optimized, substitute the sub-graph with the new optimized one in the main optimized graph
585 SubgraphView& replacementSubgraph = substitution.m_ReplacementSubgraph;
586 SubgraphView& substitutableSubgraph = substitution.m_SubstitutableSubgraph;
587 optGraph.SubstituteSubgraph(substitutableSubgraph, replacementSubgraph);
589 // Assign the current backend to the optimized sub-graph
590 std::for_each(replacementSubgraph.begin(), replacementSubgraph.end(), [&selectedBackend](Layer* l)
593 l->SetBackendId(selectedBackend);
597 if (!optimizationViews.GetFailedSubgraphs().empty())
599 std::stringstream warningMsg;
600 warningMsg << "Some sub-graph(s) failed to optimized on " << backendObjPtr->GetId() << " backend.";
601 ReportWarning(warningMsg.str(), errMessages);
603 // Failed to optimize the given sub-graph, re-assign the sub-graph layers to other available backends
604 BackendSettings settingsCopy(backendSettings);
605 if (!backendObjPtr->GetId().IsCpuRef())
607 // Add the current backend to the list of backends to ignore
608 settingsCopy.m_IgnoredBackends.insert(backendObjPtr->GetId());
612 for (auto& failedSubgraph : optimizationViews.GetFailedSubgraphs())
614 // An error occurred: the optimization was attempted but not performed, try different backends
615 std::stringstream subgraphMsg;
616 subgraphMsg << "Re-assigning backends to " << failedSubgraph.GetLayers().size()
617 << " layers inside sub-graph " << count++;
618 ReportWarning(subgraphMsg.str(), errMessages);
620 OptimizationResult reassignmentResult = AssignBackends(optNetObjPtr,
624 if (reassignmentResult.m_Error)
626 // Failed to re-assign one of the remaining backends to each layer of the sub-graph
627 result.m_Error = true;
638 bool RequiresCopy(ITensorHandleFactory::FactoryId src,
639 ITensorHandleFactory::FactoryId dst,
640 TensorHandleFactoryRegistry& registry)
644 ITensorHandleFactory* srcFactory = registry.GetFactory(src);
645 ITensorHandleFactory* dstFactory = registry.GetFactory(dst);
647 if (srcFactory && dstFactory &&
648 (srcFactory->GetExportFlags() & dstFactory->GetImportFlags()) != 0)
657 // Find the handle factory for the input layer which results in fewest required copies.
658 ITensorHandleFactory::FactoryId CalculateSlotOptionForInput(BackendsMap& backends,
660 TensorHandleFactoryRegistry& registry)
662 Layer& layer = slot.GetOwningLayer();
663 ARMNN_ASSERT(layer.GetType() == LayerType::Input);
665 // Explicitly select the tensorhandle factory for InputLayer because the rules for it are slightly different. It
666 // doesn't matter which backend it is assigned to because they all use the same implementation, which
667 // requires Map/Unmap support. This means that, so long as the handle type supports map/unmap semantics, we can
668 // select a factory with maximum compatibility with the layers connected to the InputLayer.
670 // First ensure the from backends can support the TensorHandeAPI
671 auto frmBackend = backends.find(layer.GetBackendId());
672 if (frmBackend == backends.end() ||
673 !frmBackend->second->SupportsTensorAllocatorAPI())
675 return ITensorHandleFactory::LegacyFactoryId;
678 // Go through all connections to the output slot and determine the TensorHandleFactory which results in the
680 std::map<ITensorHandleFactory::FactoryId, int> factoryScores;
682 ITensorHandleFactory::FactoryId topChoice = ITensorHandleFactory::LegacyFactoryId;
684 for (auto&& connection : slot.GetConnections())
686 const Layer& connectedLayer = connection->GetOwningLayer();
688 auto toBackend = backends.find(connectedLayer.GetBackendId());
689 ARMNN_ASSERT_MSG(toBackend != backends.end(), "Backend id not found for the connected layer");
691 if (!toBackend->second.get()->SupportsTensorAllocatorAPI())
693 // The destination backend does not support the tensor allocator API, move to the next one
697 auto dstPrefs = toBackend->second.get()->GetHandleFactoryPreferences();
698 for (auto&& dst : dstPrefs)
700 // Input layers use the mem copy workload or import, so the selected factory must
701 // support either the map/unmap API or Import API
702 ITensorHandleFactory* factory = registry.GetFactory(dst);
703 if (!factory->SupportsMapUnmap() &&
704 !CheckFlag(factory->GetImportFlags(), MemorySource::Malloc)) // Just support cpu mem imports for now
706 // The current tensor handle factory does not support the map/unmap or import
707 // strategy, move to the next one
711 auto it = factoryScores.find(dst);
712 if (it == factoryScores.end())
714 // Add new score to the table
715 factoryScores[dst] = 0;
716 if (topChoice == ITensorHandleFactory::LegacyFactoryId)
723 // Increase the score
724 factoryScores[dst]++;
726 // Track the best option
727 if (factoryScores[dst] > topScore)
729 topScore = factoryScores[dst];
739 // Find the handle factory for the output layer which results in fewest required copies.
740 ITensorHandleFactory::FactoryId CalculateSlotOptionForOutput(BackendsMap& backends,
742 TensorHandleFactoryRegistry& registry)
744 IgnoreUnused(backends, slot, registry);
745 return ITensorHandleFactory::DeferredFactoryId;
748 // For all handle factories supported on the source backend, we wish to find the one which requires the fewest copies
749 // when considering all connections.
750 ITensorHandleFactory::FactoryId CalculateSlotOption(BackendsMap& backends,
751 OutputSlot& outputSlot,
752 TensorHandleFactoryRegistry& registry)
754 // First ensure the from backends can support the TensorHandeAPI
755 Layer& layer = outputSlot.GetOwningLayer();
756 auto frmBackend = backends.find(layer.GetBackendId());
757 if (frmBackend == backends.end() ||
758 !frmBackend->second->SupportsTensorAllocatorAPI())
760 return ITensorHandleFactory::LegacyFactoryId;
763 // Connections to Output Layers requires support for map/unmap on the TensorHandle.
764 bool requiresMapUnmap = false;
765 for (auto&& connection : outputSlot.GetConnections())
767 const Layer& connectedLayer = connection->GetOwningLayer();
768 if (connectedLayer.GetType() == LayerType::Output)
770 requiresMapUnmap = true;
774 IBackendInternal* srcBackend = frmBackend->second.get();
775 auto srcPrefs = srcBackend->GetHandleFactoryPreferences();
777 // Initialize the scores
778 std::map<ITensorHandleFactory::FactoryId, int> factoryScores;
779 for (auto&& pref : srcPrefs)
781 if (requiresMapUnmap) // Only consider factories that support map/unmap if required
783 ITensorHandleFactory* factory = registry.GetFactory(pref);
784 if (!factory->SupportsMapUnmap())
786 // The current tensor handle factory does not support the map/unmap strategy, move to the next one
791 auto it = factoryScores.find(pref);
792 if (it == factoryScores.end())
794 // Add new score to the table
795 factoryScores[pref] = 0;
799 // Score each handle factory based on how many times it requires copies on the slot connections
800 for (auto&& connection : outputSlot.GetConnections())
802 const Layer& connectedLayer = connection->GetOwningLayer();
804 auto toBackend = backends.find(connectedLayer.GetBackendId());
805 ARMNN_ASSERT_MSG(toBackend != backends.end(), "Backend id not found for the connected layer");
807 auto dstPrefs = toBackend->second.get()->GetHandleFactoryPreferences();
808 for (auto&& src : srcPrefs)
810 if (factoryScores.find(src) == factoryScores.end()) // Don't consider excluded factories
815 for (auto&& dst : dstPrefs)
817 if (RequiresCopy(src, dst, registry))
819 // Copy avoided, increase the score
820 factoryScores[src]++;
827 // Find the lowest score
828 int minScore = std::numeric_limits<int>::max();
829 for (auto it : factoryScores)
831 minScore = std::min(minScore, it.second);
834 // Collect factories matching the best(lowest) score
835 std::vector<ITensorHandleFactory::FactoryId> optimalFactories;
836 for (auto it : factoryScores)
838 if (it.second == minScore)
840 optimalFactories.push_back(it.first);
844 // For all compatible Factories matching the best score, find the preferred one for the current layer.
845 for (auto&& srcPref : srcPrefs)
847 for (auto&& comp : optimalFactories)
856 return ITensorHandleFactory::LegacyFactoryId;
859 EdgeStrategy CalculateEdgeStrategy(BackendsMap& backends,
860 ITensorHandleFactory::FactoryId srcFactoryId,
862 const Layer& connectedLayer,
863 TensorHandleFactoryRegistry& registry,
866 auto toBackend = backends.find(connectedLayer.GetBackendId());
867 ARMNN_ASSERT_MSG(toBackend != backends.end(), "Backend id not found for the connected layer");
869 auto dstPrefs = toBackend->second.get()->GetHandleFactoryPreferences();
871 // Legacy API check for backward compatibility
872 if (srcFactoryId == ITensorHandleFactory::LegacyFactoryId || dstPrefs.empty())
874 if (layer.GetBackendId() != connectedLayer.GetBackendId())
876 return EdgeStrategy::CopyToTarget;
880 return EdgeStrategy::DirectCompatibility;
884 // TensorHandleFactory API present, so perform more sophisticated strategies.
885 // Dst Output layers don't require copy because they use import or map/unmap
886 if (connectedLayer.GetType() == LayerType::Output)
888 return EdgeStrategy::DirectCompatibility;
891 // Search for direct match in prefs
892 for (auto&& pref : dstPrefs)
894 if (pref == srcFactoryId)
896 return EdgeStrategy::DirectCompatibility;
900 // Search for export/import options
901 ITensorHandleFactory* srcFactory = registry.GetFactory(srcFactoryId);
902 if (srcFactory->GetExportFlags() != 0 && importEnabled)
904 for (auto&& pref : dstPrefs)
906 ITensorHandleFactory* dstFactory = registry.GetFactory(pref);
908 // Handles cases when a destPref is not listed in TensorHandleFactoryRegistry
913 if ((dstFactory->GetImportFlags() & srcFactory->GetExportFlags()) != 0)
915 auto srcCapability = srcFactory->GetCapabilities(&layer, &layer, CapabilityClass::PaddingRequired);
916 auto dstCapability = dstFactory->GetCapabilities(&connectedLayer,
918 CapabilityClass::PaddingRequired);
919 // Do not require memory copy if the source and destination do not require padding.
920 if (srcCapability.empty() && dstCapability.empty())
922 return EdgeStrategy::ExportToTarget;
928 // Search for copy options via map/unmap
929 if (srcFactory->SupportsMapUnmap())
931 for (auto&& pref : dstPrefs)
933 ITensorHandleFactory* dstFactory = registry.GetFactory(pref);
934 if (dstFactory && dstFactory->SupportsMapUnmap())
936 return EdgeStrategy::CopyToTarget;
941 return EdgeStrategy::Undefined;
944 // Select the TensorHandleFactories and the corresponding memory strategy
945 OptimizationResult SelectTensorHandleStrategy(Graph& optGraph,
946 BackendsMap& backends,
947 TensorHandleFactoryRegistry& registry,
949 Optional<std::vector<std::string>&> errMessages)
951 OptimizationResult result;
953 optGraph.ForEachLayer([&backends, ®istry, &result, &errMessages, importEnabled](Layer* layer)
957 // Lets make sure the backend is in our list of supported backends. Something went wrong during backend
958 // assignment if this check fails
959 ARMNN_ASSERT(backends.find(layer->GetBackendId()) != backends.end());
961 // Check each output separately
962 for (unsigned int slotIdx = 0; slotIdx < layer->GetNumOutputSlots(); slotIdx++)
964 OutputSlot& outputSlot = layer->GetOutputSlot(slotIdx);
966 ITensorHandleFactory::FactoryId slotOption = ITensorHandleFactory::LegacyFactoryId;
968 // Calculate the factory to use which results in the fewest copies being made.
969 switch(layer->GetType())
971 case LayerType::Input:
972 slotOption = CalculateSlotOptionForInput(backends, outputSlot, registry);
974 case LayerType::Output:
975 slotOption = CalculateSlotOptionForOutput(backends, outputSlot, registry);
978 slotOption = CalculateSlotOption(backends, outputSlot, registry);
981 outputSlot.SetTensorHandleFactory(slotOption);
983 // Now determine the "best" edge strategy for each connection given the slotOption.
984 unsigned int connectionIdx = 0;
985 for (auto&& connection : outputSlot.GetConnections())
987 const Layer& connectedLayer = connection->GetOwningLayer();
989 EdgeStrategy strategy = CalculateEdgeStrategy(backends, slotOption, *layer, connectedLayer,
990 registry, importEnabled);
992 if (strategy == EdgeStrategy::Undefined)
994 result.m_Error = true;
997 errMessages.value().emplace_back("Could not find valid strategy required for compatibility"
998 " between backends.");
1003 outputSlot.SetEdgeStrategy(connectionIdx, strategy);
1013 IOptimizedNetworkPtr Optimize(const INetwork& inNetwork,
1014 const std::vector<BackendId>& backendPreferences,
1015 const IDeviceSpec& deviceSpec,
1016 const OptimizerOptions& options,
1017 Optional<std::vector<std::string>&> messages)
1019 if (backendPreferences.empty())
1021 throw InvalidArgumentException("Invoked Optimize with no backends specified");
1024 if (options.m_ReduceFp32ToFp16 && options.m_ReduceFp32ToBf16)
1026 throw InvalidArgumentException("BFloat16 and Float16 optimization cannot be enabled at the same time.");
1029 const Network& network = *PolymorphicDowncast<const Network*>(&inNetwork);
1030 std::unique_ptr<Graph> graph = std::make_unique<Graph>(network.GetGraph());
1032 auto optNet = IOptimizedNetworkPtr(new OptimizedNetwork(std::move(graph), options.m_ModelOptions),
1033 &IOptimizedNetwork::Destroy);
1035 OptimizedNetwork* optNetObjPtr = PolymorphicDowncast<OptimizedNetwork*>(optNet.get());
1037 // Get the optimized graph
1038 Graph& optGraph = optNetObjPtr->GetGraph();
1040 // Perform AddBroadcastReshapeLayer optimisation
1041 using namespace optimizations;
1042 Optimizer::Pass(optGraph, MakeOptimizations(AddBroadcastReshapeLayer()));
1044 // Infer the tensor infos for all output slots. Throws an exception on failure
1045 optGraph.InferTensorInfos();
1047 // Perform optimisation passes
1048 Optimizer::Pass(optGraph, MakeOptimizations(SquashEqualPermuteSiblings(),
1049 SquashEqualTransposeSiblings(),
1050 SquashEqualReshapeSiblings(),
1051 OptimizeInversePermutes(),
1052 OptimizeInverseTransposes(),
1056 TransposeAsReshape(),
1057 OptimizeConsecutiveReshapes(),
1058 FoldPadIntoConvolution2d(),
1059 PermuteAndBatchToSpaceAsDepthToSpace(),
1060 TransposeAndBatchToSpaceAsDepthToSpace()));
1062 // If Fp32 to Fp16 optimization is set convert Fp32 network to Fp16
1063 if (options.m_ReduceFp32ToFp16)
1065 Optimizer::Pass(optGraph, MakeOptimizations(Fp32NetworkToFp16Converter()));
1066 Optimizer::Pass(optGraph, MakeOptimizations(ConvertConstantsFloatToHalf()));
1069 // If Fp32 to Bf16 optimization is set convert Fp32 network to Bf16
1070 // Convert input of Convolution2d and FullyConnected from Fp32 to Bf16
1071 // Only Constant weight of Convolution2d and FullyConnected are converted from Fp32 to Bf16
1072 if (options.m_ReduceFp32ToBf16)
1074 Optimizer::Pass(optGraph, MakeOptimizations(Fp32NetworkToBf16Converter()));
1077 // Initialize backend settings
1078 BackendSettings backendSettings(backendPreferences, deviceSpec);
1079 if (backendSettings.GetAvailablePreferredBackends().empty())
1081 std::stringstream failureMsg;
1082 failureMsg << "None of the preferred backends " << backendPreferences
1083 << " are supported. Current platform provides " << backendSettings.m_SupportedBackends;
1084 ReportError(failureMsg.str(), messages);
1085 throw InvalidArgumentException(failureMsg.str());
1088 // Create a map to temporarily hold initialized backend objects
1089 TensorHandleFactoryRegistry tensorHandleFactoryRegistry;
1090 BackendsMap backends = CreateSupportedBackends(tensorHandleFactoryRegistry, backendSettings);
1092 // Assign an available backend to each layer
1093 Graph::Iterator firstLayer = optGraph.begin();
1094 Graph::Iterator lastLayer = optGraph.end();
1095 OptimizationResult assignBackendsResult = AssignBackends(optNetObjPtr,
1100 if (assignBackendsResult.m_Error)
1102 // Failed to assign a backend to each layer
1103 throw InvalidArgumentException("Failed to assign a backend to each layer");
1106 Optimizer::Pass(optGraph, MakeOptimizations(OptimizeInverseConversionsFp16(),
1107 OptimizeInverseConversionsFp32()));
1109 // Apply the backend-specific optimizations
1110 OptimizationResult backendOptimizationResult = ApplyBackendOptimizations(optNetObjPtr,
1114 if (backendOptimizationResult.m_Error)
1116 // Failed to apply the backend-specific optimizations
1117 throw InvalidArgumentException("Failed to apply the backend-specific optimizations");
1120 // If the debug flag is set, then insert a DebugLayer after each layer
1121 // Doing this after applying the backend optimizations as they might have changed some layers
1122 if (options.m_Debug)
1124 Optimizer::Pass(optGraph, MakeOptimizations(InsertDebugLayer()));
1127 // Calculate the compatibility strategies for tensor handles
1128 OptimizationResult strategyResult = SelectTensorHandleStrategy(optGraph,
1130 tensorHandleFactoryRegistry,
1131 options.m_ImportEnabled,
1133 if (strategyResult.m_Error)
1135 // Failed to apply the backend-specific optimizations
1136 return IOptimizedNetworkPtr(nullptr, &IOptimizedNetwork::Destroy);
1139 // Based on the tensor handle strategy determined above, insert copy layers where required.
1140 optGraph.AddCompatibilityLayers(backends, tensorHandleFactoryRegistry);
1142 // Convert constants
1143 Optimizer::Pass(optGraph, MakeOptimizations(ConvertConstantsFloatToHalf()));
1144 Optimizer::Pass(optGraph, MakeOptimizations(ConvertConstantsHalfToFloat()));
1146 // Run backend specific optimizations (deprecated)
1147 for (auto&& chosenBackend : backendSettings.m_SelectedBackends)
1149 auto factoryFun = BackendRegistryInstance().GetFactory(chosenBackend);
1150 auto backendPtr = factoryFun();
1151 ARMNN_ASSERT(backendPtr.get() != nullptr);
1153 ARMNN_NO_DEPRECATE_WARN_BEGIN
1154 auto backendSpecificOptimizations = backendPtr->GetOptimizations();
1155 ARMNN_NO_DEPRECATE_WARN_END
1157 if (!backendSpecificOptimizations.empty())
1159 Optimizer::Pass(optNetObjPtr->GetGraph(), backendSpecificOptimizations);
1165 bool Network::GetShapeInferenceMethod()
1167 if (m_NetworkOptions.size() > 0 && m_NetworkOptions[0].GetBackendId().Get() == "ShapeInferenceMethod")
1169 return m_NetworkOptions[0].GetOption(0).GetValue().AsBool();
1174 Network::Network(NetworkOptions networkOptions)
1175 : m_NetworkOptions(networkOptions),
1176 m_Graph(std::make_unique<Graph>(GetShapeInferenceMethod()))
1183 Status Network::PrintGraph()
1186 return Status::Success;
1189 IConnectableLayer* Network::AddInputLayer(LayerBindingId id, const char* name)
1191 return m_Graph->AddLayer<InputLayer>(id, name);
1194 IConnectableLayer* Network::AddBatchToSpaceNdLayer(const BatchToSpaceNdDescriptor& batchToSpaceNdDescriptor,
1197 return m_Graph->AddLayer<BatchToSpaceNdLayer>(batchToSpaceNdDescriptor, name);
1200 IConnectableLayer* Network::AddComparisonLayer(const ComparisonDescriptor& comparisonDescriptor,
1203 return m_Graph->AddLayer<ComparisonLayer>(comparisonDescriptor, name);
1206 IConnectableLayer* Network::AddElementwiseUnaryLayer(const ElementwiseUnaryDescriptor& elementwiseUnaryDescriptor,
1209 return m_Graph->AddLayer<ElementwiseUnaryLayer>(elementwiseUnaryDescriptor, name);
1212 IConnectableLayer* Network::AddFillLayer(const FillDescriptor& fillDescriptor,
1215 return m_Graph->AddLayer<FillLayer>(fillDescriptor, name);
1218 IConnectableLayer* Network::AddFullyConnectedLayerImpl(const FullyConnectedDescriptor& fullyConnectedDescriptor,
1219 const ConstTensor& weights,
1220 const Optional<ConstTensor>& biases,
1223 if (fullyConnectedDescriptor.m_BiasEnabled && !biases.has_value())
1225 throw InvalidArgumentException("AddFullyConnectedLayer: biases cannot be empty");
1228 const auto layer = m_Graph->AddLayer<FullyConnectedLayer>(fullyConnectedDescriptor, name);
1230 layer->m_Weight = std::make_unique<ScopedCpuTensorHandle>(weights);
1232 if (fullyConnectedDescriptor.m_BiasEnabled)
1234 layer->m_Bias = std::make_unique<ScopedCpuTensorHandle>(biases.value());
1240 IConnectableLayer* Network::AddFullyConnectedLayer(const FullyConnectedDescriptor& fullyConnectedDescriptor,
1241 const ConstTensor& weights,
1242 const Optional<ConstTensor>& biases,
1245 return AddFullyConnectedLayerImpl(fullyConnectedDescriptor, weights, biases, name);
1248 IConnectableLayer* Network::AddFullyConnectedLayer(const FullyConnectedDescriptor& fullyConnectedDescriptor,
1249 const ConstTensor& weights,
1252 Optional<ConstTensor> biases;
1253 return AddFullyConnectedLayerImpl(fullyConnectedDescriptor, weights, biases, name);
1256 IConnectableLayer* Network::AddFullyConnectedLayer(const FullyConnectedDescriptor& fullyConnectedDescriptor,
1257 const ConstTensor& weights,
1258 const ConstTensor& biases,
1261 Optional<ConstTensor> optionalBiases(biases);
1262 return AddFullyConnectedLayerImpl(fullyConnectedDescriptor, weights, optionalBiases, name);
1265 IConnectableLayer* Network::AddConcatLayer(const ConcatDescriptor& concatDescriptor,
1268 return m_Graph->AddLayer<ConcatLayer>(concatDescriptor, name);
1271 IConnectableLayer* Network::AddConvolution2dLayerImpl(const Convolution2dDescriptor& convolution2dDescriptor,
1272 const ConstTensor& weights,
1273 const Optional<ConstTensor>& biases,
1276 if (convolution2dDescriptor.m_BiasEnabled && !biases.has_value())
1278 throw InvalidArgumentException("AddConvolution2dLayer: biases cannot be empty");
1281 const auto layer = m_Graph->AddLayer<Convolution2dLayer>(convolution2dDescriptor, name);
1283 layer->m_Weight = std::make_unique<ScopedCpuTensorHandle>(weights);
1285 if (convolution2dDescriptor.m_BiasEnabled)
1287 layer->m_Bias = std::make_unique<ScopedCpuTensorHandle>(biases.value());
1293 IConnectableLayer* Network::AddConvolution2dLayer(const Convolution2dDescriptor& convolution2dDescriptor,
1294 const ConstTensor& weights,
1295 const Optional<ConstTensor>& biases,
1298 return AddConvolution2dLayerImpl(convolution2dDescriptor, weights, biases, name);
1301 IConnectableLayer* Network::AddConvolution2dLayer(const Convolution2dDescriptor& convolution2dDescriptor,
1302 const ConstTensor& weights,
1305 Optional<ConstTensor> biases;
1306 return AddConvolution2dLayerImpl(convolution2dDescriptor, weights, biases, name);
1309 IConnectableLayer* Network::AddConvolution2dLayer(const Convolution2dDescriptor& convolution2dDescriptor,
1310 const ConstTensor& weights,
1311 const ConstTensor& biases,
1314 Optional<ConstTensor> optionalBiases(biases);
1315 return AddConvolution2dLayerImpl(convolution2dDescriptor, weights, optionalBiases, name);
1318 IConnectableLayer* Network::AddDepthwiseConvolution2dLayerImpl(
1319 const DepthwiseConvolution2dDescriptor& convolution2dDescriptor,
1320 const ConstTensor& weights,
1321 const Optional<ConstTensor>& biases,
1324 if (convolution2dDescriptor.m_BiasEnabled && !biases.has_value())
1326 throw InvalidArgumentException("AddDepthwiseConvolution2dLayer: biases cannot be empty");
1329 const auto layer = m_Graph->AddLayer<DepthwiseConvolution2dLayer>(convolution2dDescriptor, name);
1331 layer->m_Weight = std::make_unique<ScopedCpuTensorHandle>(weights);
1333 if (convolution2dDescriptor.m_BiasEnabled)
1335 layer->m_Bias = std::make_unique<ScopedCpuTensorHandle>(biases.value());
1341 IConnectableLayer* Network::AddDepthToSpaceLayer(const DepthToSpaceDescriptor& depthToSpaceDescriptor,
1344 return m_Graph->AddLayer<DepthToSpaceLayer>(depthToSpaceDescriptor, name);
1347 IConnectableLayer* Network::AddDepthwiseConvolution2dLayer(
1348 const DepthwiseConvolution2dDescriptor& convolution2dDescriptor,
1349 const ConstTensor& weights,
1350 const Optional<ConstTensor>& biases,
1353 return AddDepthwiseConvolution2dLayerImpl(convolution2dDescriptor, weights, biases, name);
1356 IConnectableLayer* Network::AddDepthwiseConvolution2dLayer(
1357 const DepthwiseConvolution2dDescriptor& convolution2dDescriptor,
1358 const ConstTensor& weights,
1361 Optional<ConstTensor> biases;
1362 return AddDepthwiseConvolution2dLayerImpl(convolution2dDescriptor, weights, biases, name);
1365 IConnectableLayer* Network::AddDepthwiseConvolution2dLayer(
1366 const DepthwiseConvolution2dDescriptor& convolution2dDescriptor,
1367 const ConstTensor& weights,
1368 const ConstTensor& biases,
1371 Optional<ConstTensor> optionalBiases(biases);
1372 return AddDepthwiseConvolution2dLayerImpl(convolution2dDescriptor, weights, optionalBiases, name);
1375 IConnectableLayer* Network::AddDetectionPostProcessLayer(const armnn::DetectionPostProcessDescriptor& descriptor,
1376 const ConstTensor& anchors, const char* name)
1378 const auto layer = m_Graph->AddLayer<DetectionPostProcessLayer>(descriptor, name);
1380 layer->m_Anchors = std::make_unique<ScopedCpuTensorHandle>(anchors);
1385 IConnectableLayer* Network::AddPermuteLayer(const PermuteDescriptor& permuteDescriptor,
1388 return m_Graph->AddLayer<PermuteLayer>(permuteDescriptor, name);
1391 IConnectableLayer* Network::AddPooling2dLayer(const Pooling2dDescriptor& pooling2dDescriptor,
1394 return m_Graph->AddLayer<Pooling2dLayer>(pooling2dDescriptor, name);
1397 IConnectableLayer* Network::AddActivationLayer(const ActivationDescriptor& activationDescriptor,
1400 return m_Graph->AddLayer<ActivationLayer>(activationDescriptor, name);
1403 IConnectableLayer* Network::AddArgMinMaxLayer(const ArgMinMaxDescriptor& argMinMaxDescriptor,
1406 return m_Graph->AddLayer<ArgMinMaxLayer>(argMinMaxDescriptor, name);
1409 IConnectableLayer* Network::AddNormalizationLayer(const NormalizationDescriptor&
1410 normalizationDescriptor,
1413 return m_Graph->AddLayer<NormalizationLayer>(normalizationDescriptor, name);
1416 IConnectableLayer* Network::AddSliceLayer(const SliceDescriptor& sliceDescriptor, const char* name)
1418 return m_Graph->AddLayer<SliceLayer>(sliceDescriptor, name);
1421 IConnectableLayer* Network::AddSoftmaxLayer(const SoftmaxDescriptor& softmaxDescriptor,
1424 return m_Graph->AddLayer<SoftmaxLayer>(softmaxDescriptor, name);
1427 IConnectableLayer* Network::AddSplitterLayer(const ViewsDescriptor& splitterDescriptor,
1430 return m_Graph->AddLayer<SplitterLayer>(splitterDescriptor, name);
1433 IConnectableLayer* Network::AddMaximumLayer(const char* name)
1435 return m_Graph->AddLayer<MaximumLayer>(name);
1438 IConnectableLayer* Network::AddMinimumLayer(const char* name)
1440 return m_Graph->AddLayer<MinimumLayer>(name);
1443 IConnectableLayer* Network::AddMergerLayer(const MergerDescriptor& mergerDescriptor,
1446 return AddConcatLayer(mergerDescriptor, name);
1449 IConnectableLayer* Network::AddAbsLayer(const char * name)
1451 return AddElementwiseUnaryLayer(ElementwiseUnaryDescriptor(UnaryOperation::Abs), name);
1454 IConnectableLayer* Network::AddAdditionLayer(const char* name)
1456 return m_Graph->AddLayer<AdditionLayer>(name);
1459 IConnectableLayer* Network::AddMultiplicationLayer(const char* name)
1461 return m_Graph->AddLayer<MultiplicationLayer>(name);
1464 IConnectableLayer* Network::AddOutputLayer(LayerBindingId id, const char* name)
1466 return m_Graph->AddLayer<OutputLayer>(id, name);
1469 IConnectableLayer* Network::AddBatchNormalizationLayer(const BatchNormalizationDescriptor& desc,
1470 const ConstTensor& mean,
1471 const ConstTensor& variance,
1472 const ConstTensor& beta,
1473 const ConstTensor& gamma,
1476 const auto layer = m_Graph->AddLayer<BatchNormalizationLayer>(desc, name);
1478 layer->m_Mean = std::make_unique<ScopedCpuTensorHandle>(mean);
1479 layer->m_Variance = std::make_unique<ScopedCpuTensorHandle>(variance);
1480 layer->m_Beta = std::make_unique<ScopedCpuTensorHandle>(beta);
1481 layer->m_Gamma = std::make_unique<ScopedCpuTensorHandle>(gamma);
1486 IConnectableLayer* Network::AddRankLayer(const char* name)
1488 return m_Graph->AddLayer<RankLayer>(name);
1491 IConnectableLayer* Network::AddResizeBilinearLayer(const ResizeBilinearDescriptor& descriptor,
1494 ResizeDescriptor resizeDescriptor;
1495 resizeDescriptor.m_Method = ResizeMethod::Bilinear;
1496 resizeDescriptor.m_DataLayout = descriptor.m_DataLayout;
1497 resizeDescriptor.m_TargetWidth = descriptor.m_TargetWidth;
1498 resizeDescriptor.m_TargetHeight = descriptor.m_TargetHeight;
1499 resizeDescriptor.m_AlignCorners = descriptor.m_AlignCorners;
1500 resizeDescriptor.m_HalfPixelCenters = descriptor.m_HalfPixelCenters;
1502 return m_Graph->AddLayer<ResizeLayer>(resizeDescriptor, name);
1505 IConnectableLayer* Network::AddResizeLayer(const ResizeDescriptor&
1506 resizeDescriptor, const char* name)
1508 return m_Graph->AddLayer<ResizeLayer>(resizeDescriptor, name);
1511 IConnectableLayer* Network::AddInstanceNormalizationLayer(const InstanceNormalizationDescriptor& desc,
1514 return m_Graph->AddLayer<InstanceNormalizationLayer>(desc, name);
1517 IConnectableLayer* Network::AddL2NormalizationLayer(const L2NormalizationDescriptor& desc,
1520 return m_Graph->AddLayer<L2NormalizationLayer>(desc, name);
1523 IConnectableLayer* Network::AddLogSoftmaxLayer(const LogSoftmaxDescriptor& desc,
1526 return m_Graph->AddLayer<LogSoftmaxLayer>(desc, name);
1529 IConnectableLayer* Network::AddConstantLayer(const ConstTensor& input, const char* name)
1531 auto layer = m_Graph->AddLayer<ConstantLayer>(name);
1533 layer->m_LayerOutput = std::make_unique<ScopedCpuTensorHandle>(input);
1538 IConnectableLayer* Network::AddReshapeLayer(const ReshapeDescriptor& reshapeDescriptor,
1541 return m_Graph->AddLayer<ReshapeLayer>(reshapeDescriptor, name);
1544 IConnectableLayer* Network::AddSpaceToBatchNdLayer(const SpaceToBatchNdDescriptor& spaceToBatchNdDescriptor,
1547 return m_Graph->AddLayer<SpaceToBatchNdLayer>(spaceToBatchNdDescriptor, name);
1550 IConnectableLayer* Network::AddSpaceToDepthLayer(const SpaceToDepthDescriptor& spaceToDepthDescriptor,
1553 return m_Graph->AddLayer<SpaceToDepthLayer>(spaceToDepthDescriptor, name);
1556 IConnectableLayer* Network::AddFloorLayer(const char* name)
1558 return m_Graph->AddLayer<FloorLayer>(name);
1561 IConnectableLayer* Network::AddLstmLayer(const LstmDescriptor& descriptor,
1562 const LstmInputParams& params,
1565 const auto layer = m_Graph->AddLayer<LstmLayer>(descriptor, name);
1567 //Lstm Basic Parameters
1568 layer->m_BasicParameters.m_InputToForgetWeights =
1569 std::make_unique<ScopedCpuTensorHandle>(*(params.m_InputToForgetWeights));
1570 layer->m_BasicParameters.m_InputToCellWeights =
1571 std::make_unique<ScopedCpuTensorHandle>(*(params.m_InputToCellWeights));
1572 layer->m_BasicParameters.m_InputToOutputWeights =
1573 std::make_unique<ScopedCpuTensorHandle>(*(params.m_InputToOutputWeights));
1574 layer->m_BasicParameters.m_RecurrentToForgetWeights =
1575 std::make_unique<ScopedCpuTensorHandle>(*(params.m_RecurrentToForgetWeights));
1576 layer->m_BasicParameters.m_RecurrentToCellWeights =
1577 std::make_unique<ScopedCpuTensorHandle>(*(params.m_RecurrentToCellWeights));
1578 layer->m_BasicParameters.m_RecurrentToOutputWeights =
1579 std::make_unique<ScopedCpuTensorHandle>(*(params.m_RecurrentToOutputWeights));
1580 layer->m_BasicParameters.m_ForgetGateBias =
1581 std::make_unique<ScopedCpuTensorHandle>(*(params.m_ForgetGateBias));
1582 layer->m_BasicParameters.m_CellBias =
1583 std::make_unique<ScopedCpuTensorHandle>(*(params.m_CellBias));
1584 layer->m_BasicParameters.m_OutputGateBias =
1585 std::make_unique<ScopedCpuTensorHandle>(*(params.m_OutputGateBias));
1587 //Lstm Cifg parameters
1588 if(!descriptor.m_CifgEnabled)
1590 if(params.m_InputToInputWeights == nullptr)
1592 throw InvalidArgumentException("AddLstmLayer: Input To Input Weights cannot be NULL "
1593 "when CIFG is disabled.");
1595 if(params.m_RecurrentToInputWeights == nullptr)
1597 throw InvalidArgumentException(
1598 "AddLstmLayer: Recurrent To Input Weights cannot be NULL "
1599 "when CIFG is disabled.");
1601 if(params.m_InputGateBias == nullptr)
1603 throw InvalidArgumentException("AddLstmLayer: Input Gate Bias cannot be NULL "
1604 "when CIFG is disabled.");
1606 layer->m_CifgParameters.m_InputToInputWeights =
1607 std::make_unique<ScopedCpuTensorHandle>(*(params.m_InputToInputWeights));
1608 layer->m_CifgParameters.m_RecurrentToInputWeights =
1609 std::make_unique<ScopedCpuTensorHandle>(*(params.m_RecurrentToInputWeights));
1610 layer->m_CifgParameters.m_InputGateBias =
1611 std::make_unique<ScopedCpuTensorHandle>(*(params.m_InputGateBias));
1614 //Lstm projection parameters
1615 if(descriptor.m_ProjectionEnabled)
1617 if(params.m_ProjectionWeights == nullptr)
1619 throw InvalidArgumentException("AddLstmLayer: Projection Weights cannot be NULL "
1620 "when projection is enabled.");
1622 layer->m_ProjectionParameters.m_ProjectionWeights =
1623 std::make_unique<ScopedCpuTensorHandle>(*(params.m_ProjectionWeights));
1624 if(params.m_ProjectionBias != nullptr)
1626 layer->m_ProjectionParameters.m_ProjectionBias =
1627 std::make_unique<ScopedCpuTensorHandle>(*(params.m_ProjectionBias));
1631 //Lstm Peephole params
1632 if(descriptor.m_PeepholeEnabled)
1634 if(!descriptor.m_CifgEnabled)
1636 if(params.m_CellToInputWeights == nullptr)
1638 throw InvalidArgumentException("AddLstmLayer: Cell To Input Weights cannot be NULL "
1639 "when Peephole is enabled and CIFG disabled.");
1642 layer->m_PeepholeParameters.m_CellToInputWeights =
1643 std::make_unique<ScopedCpuTensorHandle>(*(params.m_CellToInputWeights));
1646 if(params.m_CellToForgetWeights == nullptr)
1648 throw InvalidArgumentException("AddLstmLayer: Cell To Forget Weights cannot be NULL "
1649 "when Peephole is enabled.");
1651 if(params.m_CellToOutputWeights == nullptr)
1653 throw InvalidArgumentException("AddLstmLayer: Cell To Output Weights cannot be NULL "
1654 "when Peephole is enabled.");
1657 layer->m_PeepholeParameters.m_CellToForgetWeights =
1658 std::make_unique<ScopedCpuTensorHandle>(*(params.m_CellToForgetWeights));
1659 layer->m_PeepholeParameters.m_CellToOutputWeights =
1660 std::make_unique<ScopedCpuTensorHandle>(*(params.m_CellToOutputWeights));
1663 //Lstm Layer Normalization params
1664 if(descriptor.m_LayerNormEnabled)
1666 if(!descriptor.m_CifgEnabled)
1668 if(params.m_InputLayerNormWeights == nullptr)
1670 throw InvalidArgumentException("AddLstmLayer: Input layer normalization weights cannot be NULL "
1671 "when layer normalization is enabled and CIFG disabled.");
1673 layer->m_LayerNormParameters.m_InputLayerNormWeights =
1674 std::make_unique<ScopedCpuTensorHandle>(*(params.m_InputLayerNormWeights));
1677 if(params.m_ForgetLayerNormWeights == nullptr)
1679 throw InvalidArgumentException("AddLstmLayer: Forget layer normalization weights cannot be NULL "
1680 "when layer normalization is enabled.");
1682 if(params.m_CellLayerNormWeights == nullptr)
1684 throw InvalidArgumentException("AddLstmLayer: Cell layer normalization weights cannot be NULL "
1685 "when layer normalization is enabled.");
1687 if(params.m_OutputLayerNormWeights == nullptr)
1689 throw InvalidArgumentException("AddLstmLayer: Output layer normalization weights cannot be NULL "
1690 "when layer normalization is enabled.");
1692 layer->m_LayerNormParameters.m_ForgetLayerNormWeights =
1693 std::make_unique<ScopedCpuTensorHandle>(*(params.m_ForgetLayerNormWeights));
1694 layer->m_LayerNormParameters.m_CellLayerNormWeights =
1695 std::make_unique<ScopedCpuTensorHandle>(*(params.m_CellLayerNormWeights));
1696 layer->m_LayerNormParameters.m_OutputLayerNormWeights =
1697 std::make_unique<ScopedCpuTensorHandle>(*(params.m_OutputLayerNormWeights));
1702 IConnectableLayer* Network::AddDivisionLayer(const char* name)
1704 return m_Graph->AddLayer<DivisionLayer>(name);
1707 IConnectableLayer* Network::AddSubtractionLayer(const char* name)
1709 return m_Graph->AddLayer<SubtractionLayer>(name);
1712 IConnectableLayer* Network::AddMeanLayer(const MeanDescriptor& meanDescriptor, const char* name)
1714 return m_Graph->AddLayer<MeanLayer>(meanDescriptor,name);
1717 IConnectableLayer* Network::AddPadLayer(const PadDescriptor& padDescriptor, const char* name)
1719 return m_Graph->AddLayer<PadLayer>(padDescriptor,name);
1722 IConnectableLayer *Network::AddQuantizeLayer(const char *name)
1724 return m_Graph->AddLayer<QuantizeLayer>(name);
1727 IConnectableLayer* Network::AddDequantizeLayer(const char* name)
1729 return m_Graph->AddLayer<DequantizeLayer>(name);
1732 IConnectableLayer* Network::AddStridedSliceLayer(const StridedSliceDescriptor& stridedSliceDescriptor,
1735 return m_Graph->AddLayer<StridedSliceLayer>(stridedSliceDescriptor, name);
1738 IConnectableLayer* Network::AddGreaterLayer(const char* name)
1740 return AddComparisonLayer(ComparisonDescriptor(ComparisonOperation::Greater), name);
1743 IConnectableLayer* Network::AddEqualLayer(const char* name)
1745 return AddComparisonLayer(ComparisonDescriptor(ComparisonOperation::Equal), name);
1748 IConnectableLayer* Network::AddRsqrtLayer(const char * name)
1750 return AddElementwiseUnaryLayer(ElementwiseUnaryDescriptor(UnaryOperation::Rsqrt), name);
1753 IConnectableLayer* Network::AddGatherLayer(const char* name)
1755 GatherDescriptor gatherDescriptor{};
1756 return AddGatherLayer(gatherDescriptor, name);
1759 IConnectableLayer* Network::AddGatherLayer(const GatherDescriptor& gatherDescriptor,
1762 return m_Graph->AddLayer<GatherLayer>(gatherDescriptor, name);
1765 IConnectableLayer* Network::AddMergeLayer(const char* name)
1767 return m_Graph->AddLayer<MergeLayer>(name);
1770 IConnectableLayer* Network::AddSwitchLayer(const char* name)
1772 return m_Graph->AddLayer<SwitchLayer>(name);
1775 IConnectableLayer* Network::AddPreluLayer(const char* name)
1777 return m_Graph->AddLayer<PreluLayer>(name);
1780 IConnectableLayer* Network::AddTransposeConvolution2dLayer(const TransposeConvolution2dDescriptor& descriptor,
1781 const ConstTensor& weights,
1782 const Optional<ConstTensor>& biases,
1785 if (descriptor.m_BiasEnabled && !biases.has_value())
1787 throw InvalidArgumentException("AddTransposeConvolution2dLayer: Biases cannot be empty");
1790 const auto layer = m_Graph->AddLayer<TransposeConvolution2dLayer>(descriptor, name);
1792 layer->m_Weight = std::make_unique<ScopedCpuTensorHandle>(weights);
1794 if (descriptor.m_BiasEnabled)
1796 layer->m_Bias = std::make_unique<ScopedCpuTensorHandle>(biases.value());
1802 IConnectableLayer* Network::AddTransposeLayer(const TransposeDescriptor& transposeDescriptor,
1805 return m_Graph->AddLayer<TransposeLayer>(transposeDescriptor, name);
1808 IConnectableLayer* Network::AddStackLayer(const StackDescriptor& stackDescriptor,
1811 return m_Graph->AddLayer<StackLayer>(stackDescriptor, name);
1815 IConnectableLayer* Network::AddStandInLayer(const StandInDescriptor& desc,
1818 return m_Graph->AddLayer<StandInLayer>(desc, name);
1821 IConnectableLayer* Network::AddQuantizedLstmLayer(const QuantizedLstmInputParams& params,
1824 const auto layer = m_Graph->AddLayer<QuantizedLstmLayer>(name);
1827 layer->m_QuantizedLstmParameters.m_InputToInputWeights =
1828 std::make_unique<ScopedCpuTensorHandle>(params.GetInputToInputWeights());
1829 layer->m_QuantizedLstmParameters.m_InputToForgetWeights =
1830 std::make_unique<ScopedCpuTensorHandle>(params.GetInputToForgetWeights());
1831 layer->m_QuantizedLstmParameters.m_InputToCellWeights =
1832 std::make_unique<ScopedCpuTensorHandle>(params.GetInputToCellWeights());
1833 layer->m_QuantizedLstmParameters.m_InputToOutputWeights =
1834 std::make_unique<ScopedCpuTensorHandle>(params.GetInputToOutputWeights());
1836 // RecurrentToX weights
1837 layer->m_QuantizedLstmParameters.m_RecurrentToInputWeights =
1838 std::make_unique<ScopedCpuTensorHandle>(params.GetRecurrentToInputWeights());
1839 layer->m_QuantizedLstmParameters.m_RecurrentToForgetWeights =
1840 std::make_unique<ScopedCpuTensorHandle>(params.GetRecurrentToForgetWeights());
1841 layer->m_QuantizedLstmParameters.m_RecurrentToCellWeights =
1842 std::make_unique<ScopedCpuTensorHandle>(params.GetRecurrentToCellWeights());
1843 layer->m_QuantizedLstmParameters.m_RecurrentToOutputWeights =
1844 std::make_unique<ScopedCpuTensorHandle>(params.GetRecurrentToOutputWeights());
1847 layer->m_QuantizedLstmParameters.m_InputGateBias =
1848 std::make_unique<ScopedCpuTensorHandle>(params.GetInputGateBias());
1849 layer->m_QuantizedLstmParameters.m_ForgetGateBias =
1850 std::make_unique<ScopedCpuTensorHandle>(params.GetForgetGateBias());
1851 layer->m_QuantizedLstmParameters.m_CellBias =
1852 std::make_unique<ScopedCpuTensorHandle>(params.GetCellBias());
1853 layer->m_QuantizedLstmParameters.m_OutputGateBias =
1854 std::make_unique<ScopedCpuTensorHandle>(params.GetOutputGateBias());
1859 IConnectableLayer* Network::AddQLstmLayer(const QLstmDescriptor& descriptor,
1860 const LstmInputParams& params,
1863 const auto layer = m_Graph->AddLayer<QLstmLayer>(descriptor, name);
1865 // QLstm Basic Parameters
1866 layer->m_BasicParameters.m_InputToForgetWeights =
1867 std::make_unique<ScopedCpuTensorHandle>(*(params.m_InputToForgetWeights));
1868 layer->m_BasicParameters.m_InputToCellWeights =
1869 std::make_unique<ScopedCpuTensorHandle>(*(params.m_InputToCellWeights));
1870 layer->m_BasicParameters.m_InputToOutputWeights =
1871 std::make_unique<ScopedCpuTensorHandle>(*(params.m_InputToOutputWeights));
1872 layer->m_BasicParameters.m_RecurrentToForgetWeights =
1873 std::make_unique<ScopedCpuTensorHandle>(*(params.m_RecurrentToForgetWeights));
1874 layer->m_BasicParameters.m_RecurrentToCellWeights =
1875 std::make_unique<ScopedCpuTensorHandle>(*(params.m_RecurrentToCellWeights));
1876 layer->m_BasicParameters.m_RecurrentToOutputWeights =
1877 std::make_unique<ScopedCpuTensorHandle>(*(params.m_RecurrentToOutputWeights));
1878 layer->m_BasicParameters.m_ForgetGateBias =
1879 std::make_unique<ScopedCpuTensorHandle>(*(params.m_ForgetGateBias));
1880 layer->m_BasicParameters.m_CellBias =
1881 std::make_unique<ScopedCpuTensorHandle>(*(params.m_CellBias));
1882 layer->m_BasicParameters.m_OutputGateBias =
1883 std::make_unique<ScopedCpuTensorHandle>(*(params.m_OutputGateBias));
1885 // QLstm Cifg parameters
1886 if(!descriptor.m_CifgEnabled)
1888 if(params.m_InputToInputWeights == nullptr)
1890 throw InvalidArgumentException("AddQLstmLayer: Input To Input Weights cannot be NULL");
1893 if(params.m_RecurrentToInputWeights == nullptr)
1895 throw InvalidArgumentException(
1896 "AddQLstmLayer: Recurrent To Input Weights cannot be NULL");
1899 if(params.m_InputGateBias == nullptr)
1901 throw InvalidArgumentException("AddQLstmLayer: Input Gate Bias cannot be NULL");
1904 layer->m_CifgParameters.m_InputToInputWeights =
1905 std::make_unique<ScopedCpuTensorHandle>(*(params.m_InputToInputWeights));
1906 layer->m_CifgParameters.m_RecurrentToInputWeights =
1907 std::make_unique<ScopedCpuTensorHandle>(*(params.m_RecurrentToInputWeights));
1908 layer->m_CifgParameters.m_InputGateBias =
1909 std::make_unique<ScopedCpuTensorHandle>(*(params.m_InputGateBias));
1912 // QLstm Projection parameters
1913 if(descriptor.m_ProjectionEnabled)
1915 if(params.m_ProjectionWeights == nullptr)
1917 throw InvalidArgumentException("AddQLstmLayer: Projection Weights cannot be NULL");
1920 layer->m_ProjectionParameters.m_ProjectionWeights =
1921 std::make_unique<ScopedCpuTensorHandle>(*(params.m_ProjectionWeights));
1923 // Projection bias is optional even if projection is enabled
1924 if(params.m_ProjectionWeights != nullptr)
1926 layer->m_ProjectionParameters.m_ProjectionBias =
1927 std::make_unique<ScopedCpuTensorHandle>(*(params.m_ProjectionBias));
1932 // QLstm Peephole params
1933 if(descriptor.m_PeepholeEnabled)
1935 if(params.m_CellToForgetWeights == nullptr)
1937 throw InvalidArgumentException("AddQLstmLayer: Cell To Forget Weights cannot be NULL");
1940 if(params.m_CellToOutputWeights == nullptr)
1942 throw InvalidArgumentException("AddQLstmLayer: Cell To Output Weights cannot be NULL");
1945 if(!descriptor.m_CifgEnabled)
1947 if(params.m_CellToInputWeights == nullptr)
1949 throw InvalidArgumentException("AddQLstmLayer: Cell To Input Weights cannot be NULL");
1952 layer->m_PeepholeParameters.m_CellToInputWeights =
1953 std::make_unique<ScopedCpuTensorHandle>(*(params.m_CellToInputWeights));
1956 layer->m_PeepholeParameters.m_CellToForgetWeights =
1957 std::make_unique<ScopedCpuTensorHandle>(*(params.m_CellToForgetWeights));
1958 layer->m_PeepholeParameters.m_CellToOutputWeights =
1959 std::make_unique<ScopedCpuTensorHandle>(*(params.m_CellToOutputWeights));
1962 // QLstm Layer Normalization params
1963 if(descriptor.m_LayerNormEnabled)
1965 if(params.m_ForgetLayerNormWeights == nullptr)
1967 throw InvalidArgumentException("AddQLstmLayer: Forget layer normalization weights cannot be NULL");
1970 if(params.m_CellLayerNormWeights == nullptr)
1972 throw InvalidArgumentException("AddQLstmLayer: Cell layer normalization weights cannot be NULL");
1975 if(params.m_OutputLayerNormWeights == nullptr)
1977 throw InvalidArgumentException("AddQLstmLayer: Output layer normalization weights cannot be NULL");
1980 if(!descriptor.m_CifgEnabled)
1982 if(params.m_InputLayerNormWeights == nullptr)
1984 throw InvalidArgumentException("AddQLstmLayer: Input layer normalization weights cannot be NULL");
1987 layer->m_LayerNormParameters.m_InputLayerNormWeights =
1988 std::make_unique<ScopedCpuTensorHandle>(*(params.m_InputLayerNormWeights));
1991 layer->m_LayerNormParameters.m_ForgetLayerNormWeights =
1992 std::make_unique<ScopedCpuTensorHandle>(*(params.m_ForgetLayerNormWeights));
1993 layer->m_LayerNormParameters.m_CellLayerNormWeights =
1994 std::make_unique<ScopedCpuTensorHandle>(*(params.m_CellLayerNormWeights));
1995 layer->m_LayerNormParameters.m_OutputLayerNormWeights =
1996 std::make_unique<ScopedCpuTensorHandle>(*(params.m_OutputLayerNormWeights));
2001 void Network::Accept(ILayerVisitor& visitor) const
2003 for (auto layer : GetGraph())
2005 layer->Accept(visitor);
2009 OptimizedNetwork::OptimizedNetwork(std::unique_ptr<Graph> graph)
2010 : m_Graph(std::move(graph)), m_Guid(profiling::ProfilingService::GetNextGuid())
2014 OptimizedNetwork::OptimizedNetwork(std::unique_ptr<Graph> graph, const ModelOptions& modelOptions)
2015 : m_Graph(std::move(graph)), m_Guid(profiling::ProfilingService::GetNextGuid()), m_ModelOptions(modelOptions)
2019 OptimizedNetwork::~OptimizedNetwork()
2023 } // namespace armnn