blob: 171d8e2b5dd9c779ce98605ca594e36674f3d452 [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/ArmNN.hpp>
7#include <armnn/backends/ICustomAllocator.hpp>
8
9#include <arm_compute/core/CL/CLKernelLibrary.h>
10#include <arm_compute/runtime/CL/CLScheduler.h>
11
12#include <iostream>
13
14/** Sample implementation of ICustomAllocator for use with the ClBackend.
15 * Note: any memory allocated must be host addressable with write access
16 * in order for ArmNN to be able to properly use it. */
17class SampleClBackendCustomAllocator : public armnn::ICustomAllocator
18{
19public:
20 SampleClBackendCustomAllocator() = default;
21
Francis Murtaghe8d7ccb2021-10-14 17:30:24 +010022 void* allocate(size_t size, size_t alignment) override
Jan Eilersc1c872f2021-07-22 13:17:04 +010023 {
24 // If alignment is 0 just use the CL_DEVICE_GLOBAL_MEM_CACHELINE_SIZE for alignment
25 if (alignment == 0)
26 {
27 alignment = arm_compute::CLKernelLibrary::get().get_device().getInfo<CL_DEVICE_GLOBAL_MEM_CACHELINE_SIZE>();
28 }
29 size_t space = size + alignment + alignment;
30 auto allocatedMemPtr = std::malloc(space * sizeof(size_t));
31
32 if (std::align(alignment, size, allocatedMemPtr, space) == nullptr)
33 {
34 throw armnn::Exception("SampleClBackendCustomAllocator::Alignment failed");
35 }
36 return allocatedMemPtr;
37 }
David Monahan6642b8a2021-11-04 16:31:46 +000038
39 void free(void* ptr) override
40 {
41 std::free(ptr);
42 }
43
44 armnn::MemorySource GetMemorySourceType() override
45 {
46 return armnn::MemorySource::Malloc;
47 }
Jan Eilersc1c872f2021-07-22 13:17:04 +010048};
49
50
51// A simple example application to show the usage of a custom memory allocator. In this sample, the users single
52// input number is multiplied by 1.0f using a fully connected layer with a single neuron to produce an output
53// number that is the same as the input. All memory required to execute this mini network is allocated with
54// the provided custom allocator.
55//
56// Using a Custom Allocator is required for use with Protected Mode and Protected Memory.
57// This example is provided using only unprotected malloc as Protected Memory is platform
58// and implementation specific.
59//
60// Note: This example is similar to the SimpleSample application that can also be found in armnn/samples.
61// The differences are in the use of a custom allocator, the backend is GpuAcc, and the inputs/outputs
62// are being imported instead of copied. (Import must be enabled when using a Custom Allocator)
63// You might find this useful for comparison.
64int main()
65{
66 using namespace armnn;
67
68 float number;
69 std::cout << "Please enter a number: " << std::endl;
70 std::cin >> number;
71
72 // Turn on logging to standard output
73 // This is useful in this sample so that users can learn more about what is going on
74 armnn::ConfigureLogging(true, false, LogSeverity::Info);
75
76 // Construct ArmNN network
77 armnn::NetworkId networkIdentifier;
78 INetworkPtr myNetwork = INetwork::Create();
79 armnn::FullyConnectedDescriptor fullyConnectedDesc;
80 float weightsData[] = {1.0f}; // Identity
81 TensorInfo weightsInfo(TensorShape({1, 1}), DataType::Float32);
82 weightsInfo.SetConstant(true);
83 armnn::ConstTensor weights(weightsInfo, weightsData);
84 ARMNN_NO_DEPRECATE_WARN_BEGIN
85 IConnectableLayer *fullyConnected = myNetwork->AddFullyConnectedLayer(fullyConnectedDesc,
86 weights,
87 EmptyOptional(),
88 "fully connected");
89 ARMNN_NO_DEPRECATE_WARN_END
90 IConnectableLayer *InputLayer = myNetwork->AddInputLayer(0);
91 IConnectableLayer *OutputLayer = myNetwork->AddOutputLayer(0);
92 InputLayer->GetOutputSlot(0).Connect(fullyConnected->GetInputSlot(0));
93 fullyConnected->GetOutputSlot(0).Connect(OutputLayer->GetInputSlot(0));
94
95 // Create ArmNN runtime:
96 //
97 // This is the interesting bit when executing a model with a custom allocator.
98 // You can have different allocators for different backends. To support this
99 // the runtime creation option has a map that takes a BackendId and the corresponding
100 // allocator that should be used for that backend.
101 // Only GpuAcc supports a Custom Allocator for now
102 //
103 // Note: This is not covered in this example but if you want to run a model on
104 // protected memory a custom allocator needs to be provided that supports
105 // protected memory allocations and the MemorySource of that allocator is
106 // set to MemorySource::DmaBufProtected
107 IRuntime::CreationOptions options;
108 auto customAllocator = std::make_shared<SampleClBackendCustomAllocator>();
109 options.m_CustomAllocatorMap = {{"GpuAcc", std::move(customAllocator)}};
110 IRuntimePtr runtime = IRuntime::Create(options);
111
112 //Set the tensors in the network.
113 TensorInfo inputTensorInfo(TensorShape({1, 1}), DataType::Float32);
114 InputLayer->GetOutputSlot(0).SetTensorInfo(inputTensorInfo);
115
116 unsigned int numElements = inputTensorInfo.GetNumElements();
117 size_t totalBytes = numElements * sizeof(float);
118
119 TensorInfo outputTensorInfo(TensorShape({1, 1}), DataType::Float32);
120 fullyConnected->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
121
122 // Optimise ArmNN network
123 OptimizerOptions optOptions;
124 optOptions.m_ImportEnabled = true;
125 armnn::IOptimizedNetworkPtr optNet =
126 Optimize(*myNetwork, {"GpuAcc"}, runtime->GetDeviceSpec(), optOptions);
127 if (!optNet)
128 {
129 // This shouldn't happen for this simple sample, with GpuAcc backend.
130 // But in general usage Optimize could fail if the backend at runtime cannot
131 // support the model that has been provided.
132 std::cerr << "Error: Failed to optimise the input network." << std::endl;
133 return 1;
134 }
135
136 // Load graph into runtime
137 std::string ignoredErrorMessage;
138 INetworkProperties networkProperties(false, MemorySource::Malloc, MemorySource::Malloc);
139 runtime->LoadNetwork(networkIdentifier, std::move(optNet), ignoredErrorMessage, networkProperties);
140
141 // Creates structures for input & output
142 const size_t alignment =
143 arm_compute::CLKernelLibrary::get().get_device().getInfo<CL_DEVICE_GLOBAL_MEM_CACHELINE_SIZE>();
144
145 void* alignedInputPtr = options.m_CustomAllocatorMap["GpuAcc"]->allocate(totalBytes, alignment);
146
147 // Input with negative values
148 auto* inputPtr = reinterpret_cast<float*>(alignedInputPtr);
149 std::fill_n(inputPtr, numElements, number);
150
151 void* alignedOutputPtr = options.m_CustomAllocatorMap["GpuAcc"]->allocate(totalBytes, alignment);
152 auto* outputPtr = reinterpret_cast<float*>(alignedOutputPtr);
153 std::fill_n(outputPtr, numElements, -10.0f);
154
155
156 armnn::InputTensors inputTensors
157 {
158 {0, armnn::ConstTensor(runtime->GetInputTensorInfo(networkIdentifier, 0), alignedInputPtr)},
159 };
160 armnn::OutputTensors outputTensors
161 {
162 {0, armnn::Tensor(runtime->GetOutputTensorInfo(networkIdentifier, 0), alignedOutputPtr)}
163 };
164
165 // Execute network
166 runtime->EnqueueWorkload(networkIdentifier, inputTensors, outputTensors);
167
168 // Tell the CLBackend to sync memory so we can read the output.
169 arm_compute::CLScheduler::get().sync();
170 auto* outputResult = reinterpret_cast<float*>(alignedOutputPtr);
171 std::cout << "Your number was " << outputResult[0] << std::endl;
172 runtime->UnloadNetwork(networkIdentifier);
173 return 0;
174
175}