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)
override
{
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;
}
void free(
void* ptr)
override
{
std::free(ptr);
}
{
}
};
{
float number;
std::cout << "Please enter a number: " << std::endl;
std::cin >> number;
float weightsData[] = {1.0f};
weightsInfo.SetConstant(true);
network->AddFullyConnectedLayer(fullyConnectedDesc, "fully connected");
auto customAllocator = std::make_shared<SampleClBackendCustomAllocator>();
unsigned int numElements = inputTensorInfo.GetNumElements();
size_t totalBytes = numElements * sizeof(float);
Optimize(*network, {
"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);
inputTensorInfo = runtime->GetInputTensorInfo(networkIdentifier, 0);
inputTensorInfo.SetConstant(true);
{
};
{
{0,
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;
}