blob: 60145139ff0aff9d95716ada516033019f339156 [file] [log] [blame]
Jan Eilersc1c872f2021-07-22 13:17:04 +01001//
2// Copyright © 2021 Arm Ltd and Contributors. All rights reserved.
3// SPDX-License-Identifier: MIT
4//
5
6#include <armnn/backends/ICustomAllocator.hpp>
7#include <armnn/Descriptors.hpp>
8#include <armnn/Exceptions.hpp>
9#include <armnn/INetwork.hpp>
10#include <armnn/IRuntime.hpp>
11#include <armnn/Utils.hpp>
12#include <armnn/BackendRegistry.hpp>
Francis Murtaghe8d7ccb2021-10-14 17:30:24 +010013
Jan Eilersc1c872f2021-07-22 13:17:04 +010014#include <cl/ClBackend.hpp>
Francis Murtaghb80eaff2021-08-16 11:59:53 +010015#if defined(ARMCOMPUTENEON_ENABLED)
16#include <neon/NeonBackend.hpp>
17#endif
Jan Eilersc1c872f2021-07-22 13:17:04 +010018#include <doctest/doctest.h>
Francis Murtaghe8d7ccb2021-10-14 17:30:24 +010019#include <armnn/utility/IgnoreUnused.hpp>
Jan Eilersc1c872f2021-07-22 13:17:04 +010020// Contains the OpenCl interfaces for mapping memory in the Gpu Page Tables
21// Requires the OpenCl backend to be included (GpuAcc)
22#include <arm_compute/core/CL/CLKernelLibrary.h>
23#include <CL/cl_ext.h>
24#include <arm_compute/runtime/CL/CLScheduler.h>
25
Jan Eilersc1c872f2021-07-22 13:17:04 +010026/** Sample implementation of ICustomAllocator for use with the ClBackend.
27 * Note: any memory allocated must be host accessible with write access to allow for weights and biases
28 * to be passed in. Read access is not required.. */
29class SampleClBackendCustomAllocator : public armnn::ICustomAllocator
30{
31public:
32 SampleClBackendCustomAllocator() = default;
33
Francis Murtaghe8d7ccb2021-10-14 17:30:24 +010034 void* allocate(size_t size, size_t alignment) override
Jan Eilersc1c872f2021-07-22 13:17:04 +010035 {
36 // If alignment is 0 just use the CL_DEVICE_GLOBAL_MEM_CACHELINE_SIZE for alignment
37 if (alignment == 0)
38 {
39 alignment = arm_compute::CLKernelLibrary::get().get_device().getInfo<CL_DEVICE_GLOBAL_MEM_CACHELINE_SIZE>();
40 }
41 size_t space = size + alignment + alignment;
42 auto allocatedMemPtr = std::malloc(space * sizeof(size_t));
43
44 if (std::align(alignment, size, allocatedMemPtr, space) == nullptr)
45 {
46 throw armnn::Exception("SampleClBackendCustomAllocator::Alignment failed");
47 }
48 return allocatedMemPtr;
49 }
50
51 /** Interface to be implemented by the child class to free the allocated tensor */
Francis Murtaghe8d7ccb2021-10-14 17:30:24 +010052 void free(void* ptr) override
Jan Eilersc1c872f2021-07-22 13:17:04 +010053 {
54 std::free(ptr);
55 }
56
Francis Murtaghe8d7ccb2021-10-14 17:30:24 +010057 armnn::MemorySource GetMemorySourceType() override
Jan Eilersc1c872f2021-07-22 13:17:04 +010058 {
59 return armnn::MemorySource::Malloc;
60 }
61};
62
Francis Murtagh62573b62021-08-12 11:55:21 +010063armnn::INetworkPtr CreateTestNetwork(armnn::TensorInfo& inputTensorInfo)
Jan Eilersc1c872f2021-07-22 13:17:04 +010064{
65 using namespace armnn;
Jan Eilersc1c872f2021-07-22 13:17:04 +010066 INetworkPtr myNetwork = INetwork::Create();
67
68 armnn::FullyConnectedDescriptor fullyConnectedDesc;
69 float weightsData[] = {1.0f}; // Identity
70 TensorInfo weightsInfo(TensorShape({1, 1}), DataType::Float32);
71 weightsInfo.SetConstant(true);
72 armnn::ConstTensor weights(weightsInfo, weightsData);
73
74 ARMNN_NO_DEPRECATE_WARN_BEGIN
75 IConnectableLayer* fullyConnected = myNetwork->AddFullyConnectedLayer(fullyConnectedDesc,
76 weights,
77 EmptyOptional(),
78 "fully connected");
79 ARMNN_NO_DEPRECATE_WARN_END
80 IConnectableLayer* InputLayer = myNetwork->AddInputLayer(0);
81 IConnectableLayer* OutputLayer = myNetwork->AddOutputLayer(0);
82 InputLayer->GetOutputSlot(0).Connect(fullyConnected->GetInputSlot(0));
83 fullyConnected->GetOutputSlot(0).Connect(OutputLayer->GetInputSlot(0));
84
Francis Murtagh62573b62021-08-12 11:55:21 +010085 //Set the tensors in the network.
86
87 InputLayer->GetOutputSlot(0).SetTensorInfo(inputTensorInfo);
88
89 TensorInfo outputTensorInfo(TensorShape({1, 1}), DataType::Float32);
90 fullyConnected->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
91
92 return myNetwork;
93}
94
95TEST_SUITE("ClCustomAllocatorTests")
96{
97
98// This is a copy of the SimpleSample app modified to use a custom
99// allocator for the clbackend. It creates a FullyConnected network with a single layer
100// taking a single number as an input
101TEST_CASE("ClCustomAllocatorTest")
102{
103 using namespace armnn;
104
105 float number = 3;
106
107 // Construct ArmNN network
108 armnn::NetworkId networkIdentifier;
109
110 TensorInfo inputTensorInfo(TensorShape({1, 1}), DataType::Float32);
111
112 INetworkPtr myNetwork = CreateTestNetwork(inputTensorInfo);
Jan Eilersc1c872f2021-07-22 13:17:04 +0100113
114 // Create ArmNN runtime
115 IRuntime::CreationOptions options; // default options
116 auto customAllocator = std::make_shared<SampleClBackendCustomAllocator>();
117 options.m_CustomAllocatorMap = {{"GpuAcc", std::move(customAllocator)}};
118 IRuntimePtr run = IRuntime::Create(options);
119
Jan Eilersc1c872f2021-07-22 13:17:04 +0100120 // Optimise ArmNN network
121 OptimizerOptions optOptions;
122 optOptions.m_ImportEnabled = true;
123 armnn::IOptimizedNetworkPtr optNet = Optimize(*myNetwork, {"GpuAcc"}, run->GetDeviceSpec(), optOptions);
124 CHECK(optNet);
125
126 // Load graph into runtime
127 std::string ignoredErrorMessage;
128 INetworkProperties networkProperties(false, MemorySource::Malloc, MemorySource::Malloc);
129 run->LoadNetwork(networkIdentifier, std::move(optNet), ignoredErrorMessage, networkProperties);
130
131 // Creates structures for input & output
132 unsigned int numElements = inputTensorInfo.GetNumElements();
133 size_t totalBytes = numElements * sizeof(float);
134
135 const size_t alignment =
136 arm_compute::CLKernelLibrary::get().get_device().getInfo<CL_DEVICE_GLOBAL_MEM_CACHELINE_SIZE>();
137
138 void* alignedInputPtr = options.m_CustomAllocatorMap["GpuAcc"]->allocate(totalBytes, alignment);
139
140 // Input with negative values
141 auto* inputPtr = reinterpret_cast<float*>(alignedInputPtr);
142 std::fill_n(inputPtr, numElements, number);
143
144 void* alignedOutputPtr = options.m_CustomAllocatorMap["GpuAcc"]->allocate(totalBytes, alignment);
145 auto* outputPtr = reinterpret_cast<float*>(alignedOutputPtr);
146 std::fill_n(outputPtr, numElements, -10.0f);
147
148 armnn::InputTensors inputTensors
149 {
150 {0, armnn::ConstTensor(run->GetInputTensorInfo(networkIdentifier, 0), alignedInputPtr)},
151 };
152 armnn::OutputTensors outputTensors
153 {
154 {0, armnn::Tensor(run->GetOutputTensorInfo(networkIdentifier, 0), alignedOutputPtr)}
155 };
156
157 // Execute network
158 run->EnqueueWorkload(networkIdentifier, inputTensors, outputTensors);
159 run->UnloadNetwork(networkIdentifier);
160
161
162 // Tell the CLBackend to sync memory so we can read the output.
163 arm_compute::CLScheduler::get().sync();
164 auto* outputResult = reinterpret_cast<float*>(alignedOutputPtr);
165
166 run->UnloadNetwork(networkIdentifier);
167 CHECK(outputResult[0] == number);
168 auto& backendRegistry = armnn::BackendRegistryInstance();
169 backendRegistry.DeregisterAllocator(ClBackend::GetIdStatic());
170}
171
Francis Murtaghb80eaff2021-08-16 11:59:53 +0100172// Only run this test if NEON is enabled
173#if defined(ARMCOMPUTENEON_ENABLED)
174
Francis Murtagh62573b62021-08-12 11:55:21 +0100175TEST_CASE("ClCustomAllocatorCpuAccNegativeTest")
176{
177 using namespace armnn;
178
179 // Create ArmNN runtime
180 IRuntime::CreationOptions options; // default options
181 auto customAllocator = std::make_shared<SampleClBackendCustomAllocator>();
182 options.m_CustomAllocatorMap = {{"CpuAcc", std::move(customAllocator)}};
183 IRuntimePtr run = IRuntime::Create(options);
Francis Murtagh62573b62021-08-12 11:55:21 +0100184 TensorInfo inputTensorInfo(TensorShape({1, 1}), DataType::Float32);
185 INetworkPtr myNetwork = CreateTestNetwork(inputTensorInfo);
186
187 // Optimise ArmNN network
188 OptimizerOptions optOptions;
189 optOptions.m_ImportEnabled = true;
190 IOptimizedNetworkPtr optNet(nullptr, nullptr);
191 std::vector<std::string> errMessages;
192
Colm Donelan380c1a02021-08-17 00:52:23 +0100193 CHECK_THROWS_AS_MESSAGE(Optimize(*myNetwork, {"CpuAcc"}, run->GetDeviceSpec(), optOptions, errMessages),
194 armnn::InvalidArgumentException,
195 "Expected an exception as GetAvailablePreferredBackends() should be empty in Optimize().");
Francis Murtagh62573b62021-08-12 11:55:21 +0100196
197 auto& backendRegistry = armnn::BackendRegistryInstance();
Francis Murtaghb80eaff2021-08-16 11:59:53 +0100198 backendRegistry.DeregisterAllocator(NeonBackend::GetIdStatic());
Francis Murtagh62573b62021-08-12 11:55:21 +0100199}
200
Francis Murtaghb80eaff2021-08-16 11:59:53 +0100201#endif
Francis Murtagh62573b62021-08-12 11:55:21 +0100202
Colm Donelan380c1a02021-08-17 00:52:23 +0100203TEST_CASE("ClCustomAllocatorGpuAccNullptrTest")
204{
205 using namespace armnn;
206
207 // Create ArmNN runtime
208 IRuntime::CreationOptions options; // default options
209 auto customAllocator = std::make_shared<SampleClBackendCustomAllocator>();
210 options.m_CustomAllocatorMap = {{"GpuAcc", nullptr}};
211
212 CHECK_THROWS_AS_MESSAGE(IRuntimePtr run = IRuntime::Create(options),
213 armnn::Exception,
214 "Expected exception in RuntimeImpl::RuntimeImpl() as allocator was nullptr.");
215}
216
Jan Eilersc1c872f2021-07-22 13:17:04 +0100217} // test suite ClCustomAllocatorTests