GP-GPU Computing via C#

Nikolay Mozgovoy

Almost every year we increase the number of CPU cores in our devices to increase overall performance and user experience. Having an eight-core phone is not a big deal nowadays. Although there exists another kind of programmable unit that is usually ignored by most of the programmers. It has a multitude of computing cores, hundreds of them, and it is a GPU or graphics processing unit responsible for drawing the user interface and handling 3D experience in games. From the very beginning of its existence, it was a highly specialized device designed just for transforming and rendering the given data, and there was only one-way flow of data: from CPU to GPU.

However, since the arriving of Nvidia CUDA (Compute Unified Device Architecture) in 2007 and OpenCL (Open Computing Language) in 2009, the graphics processing units became accessible for general-purpose, bidirectional computations (called General-Purpose GPU Programming or simply GPGPU).

From my perspective as a .NET developer, it would be a great opportunity to have an access to a huge computational power of hundreds GPU cores, so I tried to figure out what is the current state of art in my domain.

First of all, what CUDA and OpenCL are and what are the differences between them?

 

CUDA vs OpenCL

Image 1. CUDA vs OpenCL

In general, they are APIs that allow a programmer to perform a specific set of computations on GPU (or even exotic devices like FPGA). It means that instead of rendering the result on display, the GPU will somehow return it to the API caller.

There are considerable differences between the two technologies.

Firstly, CUDA is a proprietary framework developed and supported only by Nvidia, while OpenCL is an open standard rather than a complete solution or concrete implementation. Therefore, CUDA is available only on Nvidia devices, while any manufacturer may support OpenCL (by the way, Nvidia chips support it as well).

Secondly, CUDA is a GPU-specific technology (at least now), while OpenCL interface may be implemented by various devices (CPU, GPU, FPGA, ALU, etc.).

These differences have obvious consequences:

  • CUDA is a little bit more performant than OpenCL on Nvidia chips;
  • You certainly can rely on consistence between CUDA documentation and implementation having a single manufacturer (Nvidia), which is not the case with OpenCL;
  • OpenCL is the only way to go if you have to support hardware other that Nvidia chips.

 

How it works

CUDA Processing Flow

Image 2. CUDA processing flow

Let us describe how GPGPU works with the scheme represented in Image 2:

  1. Form the data to be processed in RAM
  2. Copy processing data into video RAM
  3. Instruct GPU to process the data
  4. Execute in parallel on each core
  5. Copy the result back to RAM

It should be noted that this kind of general-purpose GPU computations is reasonably restricted:

  • they cannot perform any IO;
  • they cannot directly reference data in computer memory.

Even though it seems simple on general scheme, the computation model and API are not that intuitive, especially considering the fact that the native API itself is available only in C and C++.

Methinks it is the main reason why the GPGPU programming is not really widespread yet.

 

GPGPU on .NET platform

There is no native support of GPU programming on .NET platform yet, so we will have to rely on third party solutions. Moreover, there are not that many options to choose from, so let us briefly review available alternatives among actively developing projects. Interestingly, most of them focus on Nvidia CUDA rather than OpenCL.

 

Alea GPU by QuantAlea

Alea GPU is a proprietary CUDA-based library featuring free and commercial editions. Having even a free community edition allows you to produce commercial GPU-ready software for the consumer level graphics cards (which are Nvidia GeForce series).

The documentation is really nice, with the samples provided both in C# and F#, and it also features really nice supplemental images. I would say that Alea GPU is the most mature, well-documented and easy-to-use solution at the moment.

Also, it is cross-platform and compatible with .Net Framework and Mono.

 

Hybridizer by Atimesh

Hybridizer is another commercial CUDA-based library, but I would not say it is comparable with Alea GPU in the sense of usability. Firstly, it is free for educational purpose only (but requires having a license anyway). Secondly, the configuration of the application is really awkward, since it requires to have an additional C++ project containing the generated code, which can be compiled only by Visual Studio 2015.

 

ILGPU by Marcel Köster

ILGPU is an open source CUDA-based library featuring nice documentation and samples. It is not as abstract and easy-to-use as Alea GPU, but anyway it is an impressive and solid product even being developed by a single person.

Compatible with both .Net Framework and .Net Core.

 

Campy by Ken Domino

Campy is another example of an interesting open source library being developed by a single programmer. It is still in early beta, but promises to have a really high-level API. It is built upon .NET Core.

I tried to use each of the mentioned solutions, but Hybridizer appeared too awkward to configure, while Campy simply did not work on my hardware. Therefore, we will proceed our evaluation with Alea GPU and ILGPU libraries.

 

Evaluation

To have a taste of GPGPU programming on .NET, we will implement a simple app that will transform a set of images applying a simple filter to them.

There are going to be three implementations for comparison:

  1. Using standard Task Parallel Library of .NET Framework;
  2. Using Alea GPU;
  3. Using ILGPU.

Since both libraries use CUDA, we will have to have a Nvidia device. Fortunately, I’ve got one.

In general, my workstation is a mid-range PC with the following specs:

  • CPU: Intel Core i5-4460 (4 cores no Hyper-Threading, 3.20 GHz base clock speed);
  • GPU: Nvidia Geforce GTX 1050 Ti (768 CUDA Cores, 4 GB GDDR5 VRAM, 1290 MHz Clock base clock speed);
  • RAM: 32 GB DDR3;
  • Storage: Samsung SSD 850 EVO 250 GB (which is not really necessary);
  • OS: Windows 10 Pro;

Before we proceed, we will have to install the CUDA Toolkit (required by ILGPU, not AleaGPU) from the official web site: https://developer.nvidia.com/cuda-downloads

Both libraries are cross-platform, but since Alea GPU is not yet adapted for .NET Core, we will create a Windows-based console app using the last .Net Framework installed on my workstation (which is 4.7.1).

I will use the following Nuget packages:

  • Install-Package Alea - Version 3.0.4
  • Install-Package FSharp.Core - Version 4.5.0
  • Install-Package ILGPU - Version 0.3.0
  • Install-Package SixLabors.ImageSharp - Version 1.0.0-beta0004

FSharp.Core is required by Alea GPU, because it is built upon it.

ImageSharp is a nice cross-platform image processing library, which will simplify the process of reading and saving the image data for us.

 

General program flow

Our program is going to be quite straightforward consisting of the following steps:

  1. Load image using ImageSharp Image class;
  2. Get an array of pixels (represented by Rgba32 structure);
  3. Transform the array of pixels (inverse the colors);
  4. Reload them into Image object;
  5. Save result into output directory.

 

  1. Image<Rgba32> image = Image.Load(imagePath);
  2. Rgba32[] pixelArray = new Rgba32[image.Height * image.Width];
  3. image.SavePixelData(pixelArray);
  4. string imageTitle = Path.GetFileName(imagePath);
  5. Rgba32[] transformedPixels = transform(pixelArray);
  6. Image<Rgba32> res = Image.LoadPixelData(
  7.    config: Configuration.Default,
  8.    data: transformedPixels,
  9.    width: image.Width,
  10.    height: image.Height);
  11. res.Save(Path.Combine(outDir, $"{imageTitle}.{tech}.bmp"));

transform is the function of the following signature: Func<Rgba32[ ], Rgba32[ ]>

We are going to have a distinct implementation of this function for each chosen technology.

 

TPL implementation

The Task Parallel Library is a standard and friendly way of handling parallelism and concurrency in .NET framework. The code below, implementing out simple image filter, hardly requires any comments. I should only note that I do mutate the pixel array passed to Apply method to gain better performance, even though I discourage such functions.

  1. public static class TplImageFilter
  2. {
  3.    public static Rgba32[] Apply(Rgba32[] pixelArray, Func<Rgba32, Rgba32> filter)
  4.    {
  5.       Parallel.For(0, pixelArray.Length, i => pixelArray[i] = filter(pixelArray[i]));
  6.       return pixelArray;
  7.    }
  8.    public static Rgba32 Invert(Rgba32 color)
  9.    {
  10.       return new Rgba32(
  11.          r: (byte)~color.R,
  12.          g: (byte)~color.G,
  13.          b: (byte)~color.B,
  14.          a: (byte)~color.A);
  15.    }
  16. }

 

Alea GPU implementation

Considering the below filter implementation in Alea GPU, we should admit that there is no real difference with the previous TPL example. The only noticeable change is Invert method, where we had to use parameterless constructor for Rgba32 structure, this is the current limitation of the code run by Alea GPU.

  1. public class AleaGpuImageFilter
  2. {
  3.    public static Rgba32[] Apply(Rgba32[] pixelArray, Func<Rgba32, Rgba32> filter)
  4.    {
  5.       Gpu gpu = Gpu.Default;
  6.       gpu.For(0, pixelArray.Length, i => pixelArray[i] = filter(pixelArray[i]));
  7.       return pixelArray;
  8.     }
  9.    public static Rgba32 Invert(Rgba32 from)
  10.    {
  11.       /* Noticeable that Alea GPU only support parameterless constructors */
  12.       var to = new Rgba32
  13.       {
  14.          A = (byte)~from.A,
  15.          R = (byte)~from.R,
  16.          G = (byte)~from.G,
  17.          B = (byte)~from.B
  18.        };
  19.        return to;
  20.     }
  21. }

 

ILGPU implementation

ILGPU API is much less abstract compared to the previous ones. First of all, we have to explicitly select a processing accelerator. Secondly, we need to explicitly load a kernel, which is a static function that is going to be run by GPU cores in order to transform our data. The kernel function is very restricted: it cannot operate reference types and surely cannot perform IO. Thirdly, we need to allocate a memory in GPU RAM and load our data into it before starting the transformation process.

  1. public class IlGpuFilter : IDisposable
  2. {
  3.    private readonly Accelerator gpu;
  4.    private readonly Action<Index, ArrayView<Rgba32>> kernel;
  5.    public IlGpuFilter()
  6.    {
  7.       this.gpu = Accelerator.Create(
  8.          new Context(),
  9.          Accelerator.Accelerators.First(a => a.AcceleratorType == AcceleratorType.Cuda));
  10.       this.kernel =
  11.          this.gpu.LoadAutoGroupedStreamKernel<Index, ArrayView<Rgba32>>(ApplyKernel);
  12.    }
  13.    private static void ApplyKernel(
  14.       Index index, /* The global thread index (1D in this case) */
  15.       ArrayView<Rgba32> pixelArray /* A view to a chunk of memory (1D in this case)*/)
  16.    {
  17.       pixelArray[index] = Invert(pixelArray[index]);
  18.    }
  19.    public Rgba32[] Apply(Rgba32[] pixelArray, Func<Rgba32, Rgba32> filter)
  20.    {
  21.       using (MemoryBuffer<Rgba32> buffer = this.gpu.Allocate<Rgba32>(pixelArray.Length))
  22.       {
  23.          buffer.CopyFrom(pixelArray, 0, Index.Zero, pixelArray.Length);
  24.          this.kernel(buffer.Length, buffer.View);
  25.  
  26.          // Wait for the kernel to finish...
  27.          this.gpu.Synchronize();
  28.          return buffer.GetAsArray();
  29.        }
  30.    }
  31.    public static Rgba32 Invert(Rgba32 color)
  32.    {
  33.       return new Rgba32(
  34.          r: (byte)~color.R,
  35.          g: (byte)~color.G,
  36.          b: (byte)~color.B,
  37.          a: (byte)~color.A);
  38.    }
  39.    public void Dispose()
  40.    {
  41.       this.gpu?.Dispose();
  42.    }
  43. }

 

Simple performance test

Finally, we need to measure the speed of image transformations. In order to do that I will use a standard Stopwatch class:

  1. var stopwatch = new Stopwatch();
  2. foreach (string imagePath in imagePaths)
  3. {
  4.    /* Some Code */
  5.    stopwatch.Start( );
  6.    Rgba32[ ] transformedPixels = transform(pixelArray);
  7.    stopwatch.Stop( );
  8.    /* Some Code */
  9. }
  10. Console.WriteLine($"{tech}:\t\t{stopwatch.Elapsed}");

Note that to have a clean test, I only measured the time of transformation itself, not taking into account IO operations.

For the test data I used several high-resolution photos made by Hubble telescope.

 

Transformation Example

Image 3.  Transformation example

 

Running the program on my particular workstation, I’ve got the following average results:

  • TPL: 0.737472333 seconds
  • Alea GPU: 0.4567708 seconds
  • ILGPU: 0.410849867 seconds

So, in this particular case the least abstract approach provided by ILGP appeared to be the fastest one offering almost 80% win in performance.

So, what does it mean and is it even worth it?

On the one hand it isn’t that great win, although I am pretty sure, that my way of using the available API wasn’t optimal.

On the other hand, it is already great, considering that we did transform the images noticeably faster and our CPU remained free and available for another kind of work!

 

Conclusion

General-purpose GPU programming on a high-level language like C# is a real fun and I would highly suggest you to play around with the libraries like Alea GPU or ILGPU. I do believe that tomorrow many of us will program in heterogeneous computation environments consisting of different kind processing units, and we should learn how to utilize their powers.

I hope to have a native support of GPU programming in .NET somewhere in the future. It would be great if Microsoft makes TPL compatible with OpenCL standard. Another amazing option would be if Microsoft acquires Alea GPU like it did with Xamarin. Considering Nvidia Tesla GPUs in Azure it sounds reasonable.

All the source code is available at my GitHub: https://github.com/NicklausBrain/GpGpuViaCs-2018

Your comments and critics are welcome. Perhaps you can point at my misuse of the API, so that I can further improve the performance.

Need an innovative and reliable IT consultant?

Let's connect

Contact us

Thank you for reaching out to Sigma Software! Please fill the form below. Our team will contact you shortly.