This example is basically a copy of the SimpleSample example. But it makes use of a CustomAllocator to allocate memory for the inputs, outputs and inter layer memory.
#include <arm_compute/core/CL/CLKernelLibrary.h>
#include <arm_compute/runtime/CL/CLScheduler.h>
#include <iostream>
{
public:
SampleClBackendCustomAllocator() = default;
void*
allocate(
size_t size,
size_t alignment)
{
if (alignment == 0)
{
alignment = arm_compute::CLKernelLibrary::get().get_device().getInfo<CL_DEVICE_GLOBAL_MEM_CACHELINE_SIZE>();
}
size_t space = size + alignment + alignment;
auto allocatedMemPtr = std::malloc(space * sizeof(size_t));
if (std::align(alignment, size, allocatedMemPtr, space) == nullptr)
{
}
return allocatedMemPtr;
}
{
std::free(ptr);
}
{
}
};
{
float number;
std::cout << "Please enter a number: " << std::endl;
std::cin >> number;
float weightsData[] = {1.0f};
IConnectableLayer *fullyConnected = myNetwork->AddFullyConnectedLayer(fullyConnectedDesc,
weights,
"fully connected");
fullyConnected->GetOutputSlot(0).Connect(OutputLayer->
GetInputSlot(0));
auto customAllocator = std::make_shared<SampleClBackendCustomAllocator>();
InputLayer->GetOutputSlot(0).SetTensorInfo(inputTensorInfo);
size_t totalBytes = numElements * sizeof(float);
fullyConnected->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
Optimize(*myNetwork, {
"GpuAcc"}, runtime->GetDeviceSpec(), optOptions);
if (!optNet)
{
std::cerr << "Error: Failed to optimise the input network." << std::endl;
return 1;
}
std::string ignoredErrorMessage;
runtime->LoadNetwork(networkIdentifier, std::move(optNet), ignoredErrorMessage, networkProperties);
const size_t alignment =
arm_compute::CLKernelLibrary::get().get_device().getInfo<CL_DEVICE_GLOBAL_MEM_CACHELINE_SIZE>();
auto* inputPtr = reinterpret_cast<float*>(alignedInputPtr);
std::fill_n(inputPtr, numElements, number);
auto* outputPtr = reinterpret_cast<float*>(alignedOutputPtr);
std::fill_n(outputPtr, numElements, -10.0f);
{
{0,
armnn::ConstTensor(runtime->GetInputTensorInfo(networkIdentifier, 0), alignedInputPtr)},
};
{
{0,
armnn::Tensor(runtime->GetOutputTensorInfo(networkIdentifier, 0), alignedOutputPtr)}
};
runtime->EnqueueWorkload(networkIdentifier, inputTensors, outputTensors);
arm_compute::CLScheduler::get().sync();
auto* outputResult = reinterpret_cast<float*>(alignedOutputPtr);
std::cout << "Your number was " << outputResult[0] << std::endl;
runtime->UnloadNetwork(networkIdentifier);
return 0;
}