Conversion between float and F16
Hi, When using F16, what is the best way to convert between F16 and float?
Hi, if you are asking the data conversion in NEON, you can use vcvt to convert between half and single precision. If you are asking the depth conversion of the tensor class in arm compute library, it is not supported yet.
@steniu01 I would like to use CL... functions to run computations on GPU. I will need to assign values from CPU memory (floats) to half precision CLTensors. Vice versa, after computation, I will need to get values out of half precision CLTensors. How can I do that? There is no builtin type of 2-byte floating numbers in c++, so I 'm wondering how can I convert a float (in CPU) into a F16 in CLTensor (GPU memory).
Hi, you can use OpenCL vload_halfN vstore_halfN to convert between half and float. You would also need CL convert_half(). https://www.khronos.org/registry/OpenCL/sdk/1.0/docs/man/xhtml/vectorDataLoadandStoreFunctions.html Make sure you have "#pragma OPENCL EXTENSION cl_khr_fp16 : enable" in the kernel.
So You need to create a float input CLTensor to copy the data from CPU memory to GPU memory. Inside the GPU kernel, you do the conversion. Does it solve your problem?
It notes that for now, you need to copy from the CPU memory to GPU memory to allow GPU could access the data. In the future, we will consider adding support of zero copy so that the GPU can access the CPU memory directly without copy, provided that the CPU memory is backed by dma_buf.
In the meantime you can use a C++ half-float library such as this one to convert values on the CPU side
@AnthonyARM To use the library you mentioned, does the code below look good (to assign random values to a CLTensor that has been mapped):
execute_window_loop(wWindow, [&](const Coordinates &id){
float val = float(rand()) / RAND_MAX - 0.5;
half val_half(val);
*reinterpret_cast<uint16_t*>(wIt.ptr()) = *reinterpret_cast<uint16_t*>(&val_half);
}, wIt);
@steniu01 Your approach seems to suggest creating a F32 CLTensor as input, and do conversion in GPU. Does it make sense to create a F16 CLTensor directly, and do the conversion in CPU before dumping data into the CLTensor's mapped buffer?
@kindloaf , do you need CL code(GPU) access the data (like pictures, neural network weights) which was stored on CPU memory before ( this is what I originally thought) or you just need CLTensor hold random initialised fp16 data? From the example you gave to Anthony, it looks like actually the later case?
@steniu01 I need to store real data into CLTensor. The code example is just for simplicity.
I guess for real data, I can just replace the assignment with something like float val = image[id.x()][id.y()][id.z()];
Okey, get it. Since currently you need to copy from CPU to GPU memory anyway, it makes sense to have a fp16 CLTensor as input and do the conversion at CPU side while you move the data to GPU. You can use half float library as AnthonyARM suggested.
Cool. Thanks @steniu01