C++ AMP

At the AMD Fusion Developer Summit 2011 in June, Microsoft announced C++ Accelerated Massive Parallelism (C++ AMP), an extension to C++ for parallel programming of GPU’s.  This extension, included in Visual Studio 11, would allow developers to program the GPU with language features that are arguably much more powerful than either CUDA or OpenCL.  In comparison, CUDA and OpenCL seem more like stone knives and bearskins. After what seemed like an long three-month wait, Microsoft has finally released the Visual Studio 11 Developer Preview, which contains C++ Accelerated Massive Parallelism (C++ AMP), Microsoft’s vision of GPU programming.  Was it worth the wait?

Introduction to C++ AMP

Microsoft’s C++ AMP is important because it tackles the gap between PRAM algorithms and how they are implemented on the GPU.  But surprisingly, only a few additional features were needed to implement parallel programming in C++ AMP; there are minimal syntax changes.  In order to run C++ AMP, the only requirement is that a DirectX11 card be installed on a Windows 7 or later system.  If it is not, then code running C++ AMP is run sequentially on the CPU.

C++ AMP contains the following, contained in the namespace concurrency:

  • accelerator/accelerator_view: Wrappers for the GPU.
  • array/array_view: Wrappers for GPU and CPU memory.
  • index/grid/extent: Wrappers for index spaces.
  • lamda functions: For specifying kernel code.
  • parallel_for_each.  With this function, you specify kernel code and grid for code to be run on the GPU.
  • math/atomic/synchronization functions for kernel code.

An accelerator class is a wrapper for the GPU and CPU. (NB: You must be running Windows 8 if you are trying to run parallel_for_each.)  The accelerator class contains methods and properties to determine the size of local memory associated with the accelerator, whether it is associated with a display, the path of the device, the name of the device, and whether it is emulated in the CPU.  An accelerator_view is a wrapper for allowing multiple threads to share an accelerator.

An array class is a wrapper for memory on the GPU or CPU.  The data structure can be used to represent a dense N-dimensional matrix.  The class array_view is similar to array, but data is cached in the GPU on demand. Data is copied from the GPU to CPU when variables of either class are destructed.  Alternatively, the user can call array_view.synchronize() to explicitly copy the data.

Lambda functions were introduced in Visual C++ 2010, but their real power can only be exploited and appreciated with C++ AMP, especially to the developer who has experience using CUDA or OpenCL.  The best feature of lambda functions is the capture clause.  This allows the program to pass parameters to the kernel without declaring and passing formal parameters.  For example,

int main()
{
   // Create a vector object that contains 10 elements.
   vector v;
   for (int i = 0; i < 10; ++i)
   {
      v.push_back(i);
   }

   // Count the number of even numbers in the vector by
   // using the for_each function and a lambda expression.
   int evenCount = 0;
   for_each(v.begin(), v.end(), [&evenCount] (int n) {
      cout << n;

      if (n % 2 == 0)
      {
         cout << " is even " << endl;

         // Increment the counter.
         evenCount++;
      }
      else
      {
         cout << " is odd " << endl;
      }
   });

   // Print the count of even numbers to the console.
   cout << "There are " << evenCount
        << " even numbers in the vector." << endl;
}

In this code, the capture clause “[&evenCount]” specifies that evenCount is passed to the lambda function via call-by-reference.  A capture clause “[=]” specifies all variables referenced in the lambda function to be passed by call-by-value.

The parallel_for_each function calls kernel code (specified by the lambda function) on the GPU.  Parameters to the function include a grid and tile, which correspond naturally to GPU concepts.

In order to understand how PRAM algorithms are implemented in C++ AMP, and to compare the performance of C++ AMP with OpenCL and CUDA, I decided to implement matrix multiplication using C++ AMP, CUDA and OpenCL and compare the solutions.

Matrix multiplication

I started first with Daniel Moth’s blog on matrix multiplication.  In that implementation, Moth uses std:vector’s to represent the data in a matrix.  Unfortunately, in this and many other implementations, the elements of a matrix is disconnected from the dimensions of the matrix, which I never liked.  In a previous post, I presented a solution for matrix multiplication in CUDA using a templated class which fixes this problem.  However, in order to compare the performance of C++ AMP, CUDA, and OpenCL, the solution that I now present uses a C struct to represent a matrix because that is supported in all three platforms, C++ AMP, CUDA and OpenCL.

typedef struct {
    int rows;
    int cols;
    float _data[];
} Matrix;

Why?  Although C++ AMP and CUDA implement templated classes, OpenCL is C99 based, and so cannot.  In each solution, I provide a functions to encapsulate access to the matrix: Data(), which returns a pointer to the data elements contained in an array; Create_Matrix(), which creates the struct of the appropriate size to contain all the data elements; Multiply_Serial(), a function to multiply two matrices on the CPU in a sequential manner, and return the result in a pre-allocated matrix.  Since C++ is only available in Visual Studio 11, and CUDA only available in Visual Studio 2010, the implementations for each platform must be separated into different programs.  Note, each must be built for “Release” mode; C++ AMP cannot be debugged easily as explained here.

One PRAM algorithm for matrix multiplication is given below (adapted from 1):

MultiplySimple(C, A, B)
    parallel for (p = 0; p < C.rows * C.columns; p += 1)
        r = p / C.rows;
        c = p % C.rows;
        sum = 0;
        for (k = 0; k < A.columns; ++k)
            sum += A[r, k] * B[k, c];
        C[r, c] = sum;

In essence, a thread is created for each element for the result matrix C[r, c]; each thread computes the sum of the product of element A[r, k] * B[k, c].

The implementation of this algorithm in C++ AMP is shown below, lines 73-115.  The implementation selects the first accelerator (i.e., a GPU) from the list of available accelerators on the computer, then uses it to compute the product.  Three array_view‘s are declared for GPU memory, one for each matrix (A, B, and C).  The values of the elements of each matrix are copied on demand when the kernel (lines 101-110) are executed on the GPU.  The result of the parallel_for_loop (lines 99-111) is stored in matrix C.  Another implementation that uses an explicit tile of 16 by 16 elements is provided (lines 117-159).

The CUDA and OpenCL implementations are given below.  These implementations are straight forward, except that a tile must be chosen for CUDA and OpenCL implementations.

The run time for each were computed (ten runs with first one thrown out, standard error for sample), and a summary of these data are contained in the table below.

Implementation Sequential Implicit
(unspecified tile)
Explicit
(16 x 16 tile)
Shared mem
(16 x 16 tile)
C++ AMP 1.317 ± 0.006 s 0.035 ± 0.008 s 0.030 ± 0.001 s 0.015 ± 0.002 s
CUDA 1.454 ± 0.008 s n.a. 0.046 ± 0.001 s 0.0150 ± 0.0003 s
OpenCL 1.448 ± 0.003 s n.a. 0.061 ± 0.002 s 0.033 ± 0.002 s

(Random matrices A (480 x 640) x B (640 x 960) = C (480 x 960) single prec. floats. Environment: NVIDIA GeForce GTX 470, an ATI Radeon HD 6450 (not used), and an Intel Q6600 @ 2.51 Ghz (overclocked), 4 G RAM, run on the Windows 7 64-bit OS. 10 runs, first run thrown out (for total of 9). Average ± S.E. of sample.)

In this problem, the C++ AMP implementation is faster than either CUDA or OpenCL.  This is a surprise, because CUDA and OpenCL are lower level abstractions than C++ AMP.  The “Implicit” run is a C++ AMP implementation that does not specify the tile.  When run on the GPU (GTX 470), a tile size is set by C++ AMP implicitly.  OpenCL seems to be slower than either C++ AMP or CUDA.

Implementation in C++ AMP

#include <stdio.h>
#include <stddef.h>
#include <malloc.h>
#include <amp.h>
#include <sys/timeb.h>
#include <time.h>
#include <iostream>

typedef struct {
    int rows;
    int cols;
    float data[];
} Matrix;

float * Data(Matrix * matrix)
{
    return (float*)&matrix->data;
}

Matrix * Create_Matrix(int rows, int cols)
{
    Matrix * ret = (Matrix*)malloc(2 * sizeof(int) + rows * cols * sizeof(float));
    ret->rows = rows;
    ret->cols = cols;
    for (int i = 0; i < rows * cols; ++i)
        Data(ret)[i] = 0;
    return ret;
}

void MultiplySerial(Matrix * C, Matrix * A, Matrix * B)
{
    struct _timeb  t1;
    struct _timeb  t2;
    std::cout << "Starting serial... ";
    _ftime_s(&t1);
    int wA = A->cols;
    int hA = A->rows;
    int wB = B->cols;
    int hB = B->rows;
    int wC = C->cols;
    int hC = C->rows;
    for (int gr = 0; gr < hA; ++gr) // row
        for (int gc = 0; gc < wB; ++gc) { // col
            float sum = 0;
            for (int k = 0; k < hB; ++k) {
                float a = Data(A)[gr * wA + k];
                float b = Data(B)[k * wB + gc];
                sum += a * b;
            }
            Data(C)[gr * wC + gc] = sum;
        }
    _ftime(&t2);
    std::cout << (double)(t2.time - t1.time + ((double)(t2.millitm - t1.millitm))/1000) << " s.\n";
}

#define MYSIZE 2000
char buffer[MYSIZE];
CHAR* wtoc(const WCHAR* Source)
{
    for (int j = 0; j < MYSIZE; ++j)
        buffer[j] = 0;
    int i = 0;
    while(Source[i] != '\0')
    {
        buffer[i] = (CHAR)Source[i];
        ++i;
        if (i > 2000)
            break;
    }
    return buffer;
}

void MultiplySimple(Matrix * C, Matrix * A, Matrix * B)
{
    int wA = A->cols;
    int hA = A->rows;
    int wB = B->cols;
    int hB = B->rows;
    int wC = C->cols;
    int hC = C->rows;
    struct _timeb  t1;
    struct _timeb  t2;
    std::vector<concurrency::accelerator> accelerators = concurrency::get_accelerators();
    std::vector<concurrency::accelerator>::iterator it;
    for (it = accelerators.begin(); it != accelerators.end(); ++it)
    {
        if ((*it).get_has_display() == false)
            continue;
        break;
    }
    {
        std::cout << "Starting simple... ";
        _ftime_s(&t1);
        concurrency::array_view<const float,1> a(hA * wA, Data(A));
        concurrency::array_view<const float,1> b(hB * wB, Data(B));
        concurrency::array_view<concurrency::writeonly<float>,1> c(hC * wC, Data(C));
        concurrency::extent<2> e(hC, wC);
        concurrency::grid<2> g(e);
        concurrency::parallel_for_each(*it, g,
            [=](concurrency::index<2> idx) restrict(direct3d) {
            int gr = idx[0];
            int gc = idx[1];
            float sum = 0.0f;
            for(int k = 0; k < hB; k++)
            {
                float aa = a[gr * wA + k];
                float bb = b[k * wB + gc];
                sum += aa * bb;
            }
            c[gr * wC + gc] = sum;
        });
    }
    _ftime(&t2);
    std::cout << (double)(t2.time - t1.time + ((double)(t2.millitm - t1.millitm))/1000) << " s.\n";
}

void MultiplyExplicitSimple(Matrix * C, Matrix * A, Matrix * B)
{
    static const int TS = 16;
    int wA = A->cols;
    int hA = A->rows;
    int wB = B->cols;
    int hB = B->rows;
    int wC = C->cols;
    int hC = C->rows;
    struct _timeb  t1;
    struct _timeb  t2;
    std::vector<concurrency::accelerator> accelerators = concurrency::get_accelerators();
    std::vector<concurrency::accelerator>::iterator it;
    for (it = accelerators.begin(); it != accelerators.end(); ++it)
    {
        if ((*it).get_has_display() == false)
            continue;
        break;
    }
    {
        std::cout << "Starting explicit... ";
        _ftime_s(&t1);
        concurrency::array_view<const float,1> a(hA * wA, Data(A));
        concurrency::array_view<const float,1> b(hB * wB, Data(B));
        concurrency::array_view<concurrency::writeonly<float>,1> c(hC * wC, Data(C));
        concurrency::extent<2> e(hC, wC);
        concurrency::grid<2> g(e);
        concurrency::parallel_for_each(*it, g.tile<TS,TS>(),
            [=](concurrency::tiled_index<TS,TS> idx) restrict(direct3d) {
            int gr = idx.global[0]; int gc = idx.global[1];
            float sum = 0.0f;
            for(int k = 0; k < hB; k++)
            {
                float aa = a[gr * wA + k];
                float bb = b[k * wB + gc];
                sum += aa * bb;
            }
            c[gr * wC + gc] = sum;
        });
    }
    _ftime(&t2);
    std::cout << (double)(t2.time - t1.time + ((double)(t2.millitm - t1.millitm))/1000) << " s.\n";
}

void MultiplyTile(Matrix * C, Matrix * A, Matrix * B)
{
    static const int TS = 16;
    int wA = A->cols;
    int hA = A->rows;
    int wB = B->cols;
    int hB = B->rows;
    int wC = C->cols;
    int hC = C->rows;
    struct _timeb  t1;
    struct _timeb  t2;
    std::cout << "Starting tile... ";
    _ftime_s(&t1);
    std::vector<concurrency::accelerator> accelerators = concurrency::get_accelerators();
    std::vector<concurrency::accelerator>::iterator it;
    for (it = accelerators.begin(); it != accelerators.end(); ++it)
    {
        if ((*it).get_has_display() == false)
            continue;
        break;
    }
    {
        concurrency::array_view<const float,1> a(hA * wA, Data(A));
        concurrency::array_view<const float,1> b(hB * wB, Data(B));
        concurrency::array_view<concurrency::writeonly<float>,1> c(hC * wC, Data(C));
        concurrency::extent<2> e(hC, wC);
        concurrency::grid<2> g(e);
        concurrency::parallel_for_each(*it, g.tile<TS,TS>(),
            [=](concurrency::tiled_index<TS,TS> idx) restrict(direct3d) {
            int lr = idx.local[0]; int lc = idx.local[1];
            int gr = idx.global[0]; int gc = idx.global[1];

            float sum = 0.0f;
            for (int i = 0; i < hB; i += TS) {
                tile_static float locA[TS][TS], locB[TS][TS];
                locA[lr][lc] = a[gr * wA + lc + i];
                locB[lr][lc] = b[(lr + i) * wB + gc];
                idx.barrier.wait();

                for (int k = 0; k < TS; k++)
                    sum += locA[lr][k] * locB[k][lc];
                idx.barrier.wait();
            }
            c[gr * wC + gc] = sum;
        });
    }
    _ftime(&t2);
    std::cout << (double)(t2.time - t1.time + ((double)(t2.millitm - t1.millitm))/1000) << " s.\n";
}

int main()
{
    Matrix * A = Create_Matrix(16*30, 16*40);
    Matrix * B = Create_Matrix(16*40, 16*60);
    Matrix * C = Create_Matrix(A->rows, B->cols);
    Matrix * C2 = Create_Matrix(A->rows, B->cols);
    Matrix * C3 = Create_Matrix(A->rows, B->cols);
    Matrix * C4 = Create_Matrix(A->rows, B->cols);

    for (int i = 0; i < 10; ++i)
    {
        for (int i = 0; i < A->rows * A->cols; ++i) Data(A)[i] = rand() % 10;
        for (int i = 0; i < B->rows * B->cols; ++i) Data(B)[i] = rand() % 10;
        for (int i = 0; i < C->rows * C->cols; ++i) Data(C)[i] = rand() % 10;
        for (int i = 0; i < C2->rows * C2->cols; ++i) Data(C2)[i] = rand() % 10;
        for (int i = 0; i < C3->rows * C3->cols; ++i) Data(C3)[i] = rand() % 10;
        for (int i = 0; i < C4->rows * C4->cols; ++i) Data(C4)[i] = rand() % 10;
        MultiplySerial(C, A, B);
        MultiplySimple(C2, A, B);
        MultiplyExplicitSimple(C3, A, B);
        MultiplyTile(C4, A, B);
        for (int i = 0; i < C->rows * C->cols; ++i)
            if (fabs(Data(C)[i] - Data(C2)[i]) > 0.0001)
            { std::cout << "diff C2\n";
                break;
            }
        for (int i = 0; i < C3->rows * C3->cols; ++i)
            if (fabs(Data(C3)[i] - Data(C3)[i]) > 0.0001)
            { std::cout << "diff C4\n";
                break;
            }
        for (int i = 0; i < C4->rows * C4->cols; ++i)
            if (fabs(Data(C)[i] - Data(C4)[i]) > 0.0001)
            { std::cout << "diff C4\n";
                break;
            }
    }

    return 0;
}

Implementation in CUDA

#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <cl/cl.h>
#include <string.h>
#include <stdlib.h>
#include <sys/timeb.h>
#include <time.h>
#include <iostream>
#include <iomanip>
#include <fstream>

typedef struct {
    int rows;
    int cols;
    float _data;
} Matrix;

__device__ __host__ float * Data(Matrix * matrix)
{
    return (float*)&matrix->_data;
}

Matrix * Create_Matrix(int rows, int cols)
{
    Matrix * ret = (Matrix*)malloc(2 * sizeof(int) + rows * cols * sizeof(float));
    ret->rows = rows;
    ret->cols = cols;
    for (int i = 0; i < rows * cols; ++i)
        Data(ret)[i] = 0;
    return ret;
}

void MultiplySerial(Matrix * C, Matrix * A, Matrix * B)
{
    struct _timeb  t1;
    struct _timeb  t2;
    std::cout << "Starting serial... ";
    _ftime_s(&t1);
    int wA = A->cols;
    int hA = A->rows;
    int wB = B->cols;
    int hB = B->rows;
    int wC = C->cols;
    int hC = C->rows;
    for (int gr = 0; gr < hA; ++gr) // row
        for (int gc = 0; gc < wB; ++gc) { // col
            float sum = 0;
            for (int k = 0; k < hB; ++k) {
                float a = Data(A)[gr * wA + k];
                float b = Data(B)[k * wB + gc];
                sum += a * b;
            }
            Data(C)[gr * wC + gc] = sum;
        }
    _ftime(&t2);
    std::cout << (double)(t2.time - t1.time + ((double)(t2.millitm - t1.millitm))/1000) << " s.\n";
}

void Check(bool OK)
{
    if (! OK)
    {
        printf("error\n");
        throw;
    }
}

__global__ void kernelSimpleTile(Matrix * C, Matrix * A, Matrix * B)
{
    int gr = threadIdx.x + blockIdx.x * blockDim.x;
    int gc = threadIdx.y + blockIdx.y * blockDim.y;

    int hA = A->rows;
    int wA = A->cols;
    int wB = B->cols;
    int wC = C->cols;

    float sum = 0.0;
    for (int k = 0; k < wA; ++k)
    {
        float a = Data(A)[gr * wA + k];
        float b = Data(B)[k * wB + gc];
        sum += a * b;
    }
    Data(C)[gr * wC + gc] = sum;
}

void MultiplyExplicitSimple(Matrix * C, Matrix * A, Matrix * B)
{
    int wTile = 16;
    int hTile = 16;

    int wA = A->cols;
    int hA = A->rows;
    int wB = B->cols;
    int hB = B->rows;
    int wC = C->cols;
    int hC = C->rows;

    struct _timeb  t1;
    struct _timeb  t2;
    std::cout << "Starting CUDA simple tile... ";
    _ftime_s(&t1);

    cudaError_t errcode;
    Matrix * d_A;
    Matrix * d_B;
    Matrix * d_C;
    errcode = cudaMalloc((void**) &d_C, 2 * sizeof(int) + C->cols * C->rows * sizeof(float));
    Check(errcode == cudaSuccess);
    errcode = cudaMalloc((void**) &d_A, 2 * sizeof(int) + A->cols * A->rows * sizeof(float));
    Check(errcode == cudaSuccess);
    errcode = cudaMalloc((void**) &d_B, 2 * sizeof(int) + B->cols * B->rows * sizeof(float));
    Check(errcode == cudaSuccess);

    errcode = cudaMemcpy((void*)d_C, C, 2 * sizeof(int) + C->cols * C->rows * sizeof(float), cudaMemcpyHostToDevice);
    Check(errcode == cudaSuccess);
    errcode = cudaMemcpy((void*)d_A, A, 2 * sizeof(int) + A->cols * A->rows * sizeof(float), cudaMemcpyHostToDevice);
    Check(errcode == cudaSuccess);
    errcode = cudaMemcpy((void*)d_B, B, 2 * sizeof(int) + B->cols * B->rows * sizeof(float), cudaMemcpyHostToDevice);
    Check(errcode == cudaSuccess);

    dim3 threads(hTile, wTile);
    dim3 grid(hC / hTile, wC / wTile);

    kernelSimpleTile<<<grid, threads>>>(d_C, d_A, d_B);
    cudaThreadSynchronize();
    errcode = cudaGetLastError();
    Check(errcode == cudaSuccess);

    errcode = cudaMemcpy(C, d_C, 2 * sizeof(int) + C->cols * C->rows * sizeof(float), cudaMemcpyDeviceToHost);
    Check(errcode == cudaSuccess);

    cudaFree(d_A);
    cudaFree(d_B);
    cudaFree(d_C);

    _ftime_s(&t2);
    std::cout << (double)(t2.time - t1.time + ((double)(t2.millitm - t1.millitm))/1000) << " s.\n";
}

__global__ void kernelTile(Matrix * C, Matrix * A, Matrix * B)
{

    int TS = blockDim.x;
    int wA = A->cols;
    int hA = A->rows;
    int wB = B->cols;
    int hB = B->rows;
    int wC = C->cols;
    int hC = C->rows;
#define AS(i, j) As[i][j]
#define BS(i, j) Bs[i][j]

    int gr = threadIdx.x + blockIdx.x * blockDim.x;
    int gc = threadIdx.y + blockIdx.y * blockDim.y;
    int lr = threadIdx.x;
    int lc = threadIdx.y;

    float sum = 0;
    for (int i = 0; i < hB; i += TS)
    {

#define MAX_BLOCK_SIZE 30
        __shared__ float As[MAX_BLOCK_SIZE][MAX_BLOCK_SIZE];
        __shared__ float Bs[MAX_BLOCK_SIZE][MAX_BLOCK_SIZE];

        AS(lr, lc) = Data(A)[gr * wA + lc + i];
        BS(lr, lc) = Data(B)[(lr + i) * wB + gc];
        __syncthreads();

        for (int k = 0; k < TS; k++)
            sum += AS(lr, k) * BS(k, lc);
        __syncthreads();
    }
    Data(C)[gr * wC + gc] = sum;
};

void MultiplyTile(Matrix * C, Matrix * A, Matrix * B)
{
    int wTile = 16;
    int hTile = 16;
    int wA = A->cols;
    int hA = A->rows;
    int wB = B->cols;
    int hB = wA;
    int wC = wB;
    int hC = hA;

    struct _timeb  t1;
    struct _timeb  t2;
    std::cout << "Starting CUDA tile... ";
    _ftime_s(&t1);

    cudaError_t errcode;
    Matrix * d_A;
    Matrix * d_B;
    Matrix * d_C;
    errcode = cudaMalloc((void**) &d_C, 2 * sizeof(int) + C->cols * C->rows * sizeof(float));
    Check(errcode == cudaSuccess);
    errcode = cudaMalloc((void**) &d_A, 2 * sizeof(int) + A->cols * A->rows * sizeof(float));
    Check(errcode == cudaSuccess);
    errcode = cudaMalloc((void**) &d_B, 2 * sizeof(int) + B->cols * B->rows * sizeof(float));
    Check(errcode == cudaSuccess);

    errcode = cudaMemcpy((void*)d_C, C, 2 * sizeof(int) + C->cols * C->rows * sizeof(float), cudaMemcpyHostToDevice);
    Check(errcode == cudaSuccess);
    errcode = cudaMemcpy((void*)d_A, A, 2 * sizeof(int) + A->cols * A->rows * sizeof(float), cudaMemcpyHostToDevice);
    Check(errcode == cudaSuccess);
    errcode = cudaMemcpy((void*)d_B, B, 2 * sizeof(int) + B->cols * B->rows * sizeof(float), cudaMemcpyHostToDevice);
    Check(errcode == cudaSuccess);

    dim3 threads(hTile, wTile);
    dim3 grid(hC / hTile, wC / wTile);

    kernelTile<<<grid, threads>>>(d_C, d_A, d_B);
    cudaThreadSynchronize();
    errcode = cudaGetLastError();
    Check(errcode == cudaSuccess);

    errcode = cudaMemcpy(C, d_C, 2 * sizeof(int) + C->cols * C->rows * sizeof(float), cudaMemcpyDeviceToHost);
    Check(errcode == cudaSuccess);

    cudaFree(d_A);
    cudaFree(d_B);
    cudaFree(d_C);

    _ftime_s(&t2);
    std::cout << (double)(t2.time - t1.time + ((double)(t2.millitm - t1.millitm))/1000) << " s.\n";
}

int main(int argc, char * argv[])
{
    Matrix * A = Create_Matrix(16*30, 16*40);
    Matrix * B = Create_Matrix(16*40, 16*60);
    Matrix * C = Create_Matrix(A->rows, B->cols);
    Matrix * C2 = Create_Matrix(A->rows, B->cols);
    Matrix * C3 = Create_Matrix(A->rows, B->cols);

    for (int i = 0; i < 10; ++i)
    {
        for (int i = 0; i < A->rows * A->cols; ++i) Data(A)[i] = rand() % 10;
        for (int i = 0; i < B->rows * B->cols; ++i) Data(B)[i] = rand() % 10;
        for (int i = 0; i < C->rows * C->cols; ++i) Data(C)[i] = rand() % 10;
        for (int i = 0; i < C2->rows * C2->cols; ++i) Data(C2)[i] = rand() % 10;
        for (int i = 0; i < C3->rows * C3->cols; ++i) Data(C3)[i] = rand() % 10;
        MultiplySerial(C, A, B);
        MultiplyExplicitSimple(C2, A, B);
        MultiplyTile(C3, A, B);
        for (int i = 0; i < C->rows * C->cols; ++i)
            if (fabs(Data(C)[i] - Data(C2)[i]) > 0.0001)
            { std::cout << "diff\n";
                break;
            }
        for (int i = 0; i < C->rows * C->cols; ++i)
            if (fabs(Data(C)[i] - Data(C3)[i]) > 0.0001)
            { std::cout << "diff\n";
                break;
            }
    }

    return 0;
}

Implementation in OpenCL

// kernel.cl
// Multiply two matrices A * B = C
// Device code.

typedef struct {
    int rows;
    int cols;
    float _data[];
} Matrix;

__global float * Data(__global Matrix * matrix)
{
    return (__global float*)&matrix->_data;
}

__kernel void kernelSimple(__global Matrix* C, __global Matrix* A, __global Matrix* B)
{
    int i = get_global_id(0);
    int j = get_global_id(1);
    int hA = A->rows;
    int wA = A->cols;
    int wB = B->cols;
    int wC = C->cols;
    float sum = 0.0;
    for (int k = 0; k < wA; ++k)
    {
        float a = Data(A)[i * wA + k];
        float b = Data(B)[k * wB + j];
        sum += a * b;
    }
    Data(C)[i * wC + j] = sum;
}

__kernel void kernelTile(__global Matrix * C, __global Matrix * A, __global Matrix * B)
{

    int TS = get_local_size(0);
    int wA = A->cols;
    int hA = A->rows;
    int wB = B->cols;
    int hB = B->rows;
    int wC = C->cols;
    int hC = C->rows;
#define AS(i, j) As[i][j]
#define BS(i, j) Bs[i][j]

    int gr = get_global_id(0);
    int gc = get_global_id(1);
    int lr = get_local_id(0);
    int lc = get_local_id(1);

    float sum = 0.0;
    for (int i = 0; i < hB; i += TS)
    {

#define MAX_BLOCK_SIZE 30
        __local float As[MAX_BLOCK_SIZE][MAX_BLOCK_SIZE];
        __local float Bs[MAX_BLOCK_SIZE][MAX_BLOCK_SIZE];

        AS(lr, lc) = Data(A)[gr * wA + lc + i];
        BS(lr, lc) = Data(B)[(lr + i) * wB + gc];
        barrier(CLK_LOCAL_MEM_FENCE);

        for (int k = 0; k < TS; k++)
            sum += AS(lr, k) * BS(k, lc);
        barrier(CLK_LOCAL_MEM_FENCE);
    }
    Data(C)[gr * wC + gc] = sum;
};
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <cl/cl.h>
#include <string.h>
#include <stdlib.h>
#include <sys/timeb.h>
#include <time.h>
#include <iostream>
#include <iomanip>
#include <fstream>

typedef struct {
    int rows;
    int cols;
    float _data[];
} Matrix;

float * Data(Matrix * matrix)
{
    return (float*)&matrix->_data;
}

Matrix * Create_Matrix(int rows, int cols)
{
    Matrix * ret = (Matrix*)malloc(2 * sizeof(int) + rows * cols * sizeof(float));
    ret->rows = rows;
    ret->cols = cols;
    for (int i = 0; i < rows * cols; ++i)
        Data(ret)[i] = 0;
    return ret;
}

void MultiplySerial(Matrix * C, Matrix * A, Matrix * B)
{
    struct _timeb  t1;
    struct _timeb  t2;
    std::cout << "Starting serial... ";
    _ftime_s(&t1);
    int wA = A->cols;
    int hA = A->rows;
    int wB = B->cols;
    int hB = B->rows;
    int wC = C->cols;
    int hC = C->rows;
    for (int gr = 0; gr < hA; ++gr) // row
        for (int gc = 0; gc < wB; ++gc) { // col
            float sum = 0;
            for (int k = 0; k < hB; ++k) {
                float a = Data(A)[gr * wA + k];
                float b = Data(B)[k * wB + gc];
                sum += a * b;
            }
            Data(C)[gr * wC + gc] = sum;
        }
    _ftime(&t2);
    std::cout << (double)(t2.time - t1.time + ((double)(t2.millitm - t1.millitm))/1000) << " s.\n";
}

void Check(bool OK)
{
    if (! OK)
    {
        printf("error\n");
        throw;
    }
}

void get_device_info(cl_device_id device_id, cl_device_info device_info, std::string* value, cl_int * err)
{
    size_t size = 0;

    //  Get all params for the given platform id, first query their size, then get the actual data
    *err = clGetDeviceInfo(device_id, device_info, 0, NULL, &size);
    value->resize(size);
    *err = clGetDeviceInfo(device_id, device_info, size, &((*value)[0]), NULL);
}

void get_platform_info(cl_platform_id platform_id, cl_platform_info platform_info, std::string* value, cl_int * err)
{
    ::size_t size = 0;

    //  Get all params for the given platform id, first query their size, then get the actual data
    *err = clGetPlatformInfo(platform_id, platform_info, 0, NULL, &size);
    value->resize(size);
    *err = clGetPlatformInfo(platform_id, platform_info, size, &((*value)[0]), NULL);
}

std::string LoadProgram(char * file_name)
{
    std::ifstream input_file;
    input_file.open (file_name, std::ios::binary | std::ios::in);
    if (! input_file.is_open())
        return 0;

    //  Read contents
    std::istreambuf_iterator<char> begin(input_file.rdbuf());
    std::istreambuf_iterator<char> end;

    //  Store in std::string object
    std::string file_content(begin, end);

    //  Save source of program.
    return file_content;
}

void MultiplyExplicitSimple(Matrix * C, Matrix * A, Matrix * B)
{
    cl_context clGPUContext;
    cl_command_queue clCommandQue;
    cl_program clProgram;
    cl_kernel clKernel;

    size_t dataBytes;
    size_t kernelLength;
    cl_int errcode;

    cl_mem d_A;
    cl_mem d_B;
    cl_mem d_C;

    cl_int err = NULL;
    cl_platform_id plat_id[20];
    cl_uint num;

    err = clGetPlatformIDs(20, plat_id, &num);
    Check(err == 0);

    for (int p = 0; p < num; ++p)
    {
        cl_platform_id platform = plat_id[p];

        cl_context_properties props[4];
        props[0] = CL_CONTEXT_PLATFORM;
        props[1] = (cl_context_properties)platform;
        props[2] = 0;
        clGPUContext = clCreateContextFromType(props, CL_DEVICE_TYPE_GPU, NULL, NULL, &errcode);
        Check(errcode == CL_SUCCESS);

        errcode = clGetContextInfo(clGPUContext, CL_CONTEXT_DEVICES, 0, NULL, &dataBytes);
        cl_device_id * clDevices = (cl_device_id *)malloc(dataBytes);
        errcode |= clGetContextInfo(clGPUContext, CL_CONTEXT_DEVICES, dataBytes, clDevices, NULL);
        Check(errcode == CL_SUCCESS);

        for (int d = 0; d < dataBytes; ++d)
        {
            struct _timeb  t1;
            struct _timeb  t2;
            std::cout << "Starting explicit simple... ";
            _ftime_s(&t1);

            clCommandQue = clCreateCommandQueue(clGPUContext, clDevices[d], 0, &errcode);
            Check(errcode == CL_SUCCESS);

            d_C = clCreateBuffer(clGPUContext, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR, 2 * sizeof(int) + C->cols * C->rows * sizeof(float), C, &errcode);
            Check(errcode == CL_SUCCESS);
            d_A = clCreateBuffer(clGPUContext, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR, 2 * sizeof(int) + A->cols * A->rows * sizeof(float), A, &errcode);
            Check(errcode == CL_SUCCESS);
            d_B = clCreateBuffer(clGPUContext, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR, 2 * sizeof(int) + B->cols * B->rows * sizeof(float), B, &errcode);
            Check(errcode == CL_SUCCESS);

            std::string clMatrixMul = LoadProgram("kernel.cl");
            Check(clMatrixMul.c_str() != NULL);
            char * kernel_code = (char*)clMatrixMul.c_str();

            clProgram = clCreateProgramWithSource(clGPUContext, 1, (const char **)&kernel_code, 0, &errcode);
            Check(errcode == CL_SUCCESS);

            errcode = clBuildProgram(clProgram, 0, NULL, NULL, NULL, NULL);
            Check(errcode == CL_SUCCESS);

            clKernel = clCreateKernel(clProgram, "kernelSimple", &errcode);
            Check(errcode == CL_SUCCESS);

            size_t localWorkSize[2], globalWorkSize[2];

            errcode = clSetKernelArg(clKernel, 0, sizeof(cl_mem), (void *)&d_C);
            errcode |= clSetKernelArg(clKernel, 1, sizeof(cl_mem), (void *)&d_A);
            errcode |= clSetKernelArg(clKernel, 2, sizeof(cl_mem), (void *)&d_B);
            Check(errcode == CL_SUCCESS);

            localWorkSize[0] = 16;
            localWorkSize[1] = 16;
            globalWorkSize[0] = C->rows;
            globalWorkSize[1] = C->cols;

            errcode = clEnqueueNDRangeKernel(clCommandQue, clKernel, 2, NULL, globalWorkSize, localWorkSize, 0, NULL, NULL);
            Check(errcode == CL_SUCCESS);

            errcode = clEnqueueReadBuffer(clCommandQue, d_C, CL_TRUE, 0, 2 * sizeof(int) + C->cols * C->rows * sizeof(float), C, 0, NULL, NULL);
            Check(errcode == CL_SUCCESS);

            clReleaseMemObject(d_A);
            clReleaseMemObject(d_C);
            clReleaseMemObject(d_B);

            free(clDevices);
            clReleaseContext(clGPUContext);
            clReleaseKernel(clKernel);
            clReleaseProgram(clProgram);
            clReleaseCommandQueue(clCommandQue);

            _ftime_s(&t2);
            std::cout << (double)(t2.time - t1.time + ((double)(t2.millitm - t1.millitm))/1000) << " s.\n";

            return;
        }
    }
}

void MultiplyTile(Matrix * C, Matrix * A, Matrix * B)
{
    cl_context clGPUContext;
    cl_command_queue clCommandQue;
    cl_program clProgram;
    cl_kernel clKernel;

    size_t dataBytes;
    size_t kernelLength;
    cl_int errcode;

    cl_mem d_A;
    cl_mem d_B;
    cl_mem d_C;

    cl_int err = NULL;
    cl_platform_id plat_id[20];
    cl_uint num;

    err = clGetPlatformIDs(20, plat_id, &num);
    Check(err == 0);

    for (int p = 0; p < num; ++p)
    {
        cl_platform_id platform = plat_id[p];

        cl_context_properties props[4];
        props[0] = CL_CONTEXT_PLATFORM;
        props[1] = (cl_context_properties)platform;
        props[2] = 0;
        clGPUContext = clCreateContextFromType(props, CL_DEVICE_TYPE_GPU, NULL, NULL, &errcode);
        Check(errcode == CL_SUCCESS);

        errcode = clGetContextInfo(clGPUContext, CL_CONTEXT_DEVICES, 0, NULL, &dataBytes);
        cl_device_id * clDevices = (cl_device_id *)malloc(dataBytes);
        errcode |= clGetContextInfo(clGPUContext, CL_CONTEXT_DEVICES, dataBytes, clDevices, NULL);
        Check(errcode == CL_SUCCESS);

        for (int d = 0; d < dataBytes; ++d)
        {
            struct _timeb  t1;
            struct _timeb  t2;
            std::cout << "Starting tile... ";
            _ftime_s(&t1);

            clCommandQue = clCreateCommandQueue(clGPUContext, clDevices[d], 0, &errcode);
            Check(errcode == CL_SUCCESS);

            d_C = clCreateBuffer(clGPUContext, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR, 2 * sizeof(int) + C->cols * C->rows * sizeof(float), C, &errcode);
            Check(errcode == CL_SUCCESS);
            d_A = clCreateBuffer(clGPUContext, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR, 2 * sizeof(int) + A->cols * A->rows * sizeof(float), A, &errcode);
            Check(errcode == CL_SUCCESS);
            d_B = clCreateBuffer(clGPUContext, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR, 2 * sizeof(int) + B->cols * B->rows * sizeof(float), B, &errcode);
            Check(errcode == CL_SUCCESS);

            std::string clMatrixMul = LoadProgram("kernel.cl");
            Check(clMatrixMul.c_str() != NULL);
            char * kernel_code = (char*)clMatrixMul.c_str();

            clProgram = clCreateProgramWithSource(clGPUContext, 1, (const char **)&kernel_code, 0, &errcode);
            Check(errcode == CL_SUCCESS);

            errcode = clBuildProgram(clProgram, 0, NULL, NULL, NULL, NULL);
            Check(errcode == CL_SUCCESS);

            clKernel = clCreateKernel(clProgram, "kernelTile", &errcode);
            Check(errcode == CL_SUCCESS);

            size_t localWorkSize[2], globalWorkSize[2];

            errcode = clSetKernelArg(clKernel, 0, sizeof(cl_mem), (void *)&d_C);
            errcode |= clSetKernelArg(clKernel, 1, sizeof(cl_mem), (void *)&d_A);
            errcode |= clSetKernelArg(clKernel, 2, sizeof(cl_mem), (void *)&d_B);
            Check(errcode == CL_SUCCESS);

            localWorkSize[0] = 16;
            localWorkSize[1] = 16;
            globalWorkSize[0] = C->rows;
            globalWorkSize[1] = C->cols;

            errcode = clEnqueueNDRangeKernel(clCommandQue, clKernel, 2, NULL, globalWorkSize, localWorkSize, 0, NULL, NULL);
            Check(errcode == CL_SUCCESS);

            errcode = clEnqueueReadBuffer(clCommandQue, d_C, CL_TRUE, 0, 2 * sizeof(int) + C->cols * C->rows * sizeof(float), C, 0, NULL, NULL);
            Check(errcode == CL_SUCCESS);

            clReleaseMemObject(d_A);
            clReleaseMemObject(d_C);
            clReleaseMemObject(d_B);

            free(clDevices);
            clReleaseContext(clGPUContext);
            clReleaseKernel(clKernel);
            clReleaseProgram(clProgram);
            clReleaseCommandQueue(clCommandQue);

            _ftime_s(&t2);
            std::cout << (double)(t2.time - t1.time + ((double)(t2.millitm - t1.millitm))/1000) << " s.\n";

            return;
        }
    }
}

int
main(int argc, char** argv)
{
    Matrix * A = Create_Matrix(16*30, 16*40);
    Matrix * B = Create_Matrix(16*40, 16*60);
    Matrix * C = Create_Matrix(A->rows, B->cols);
    Matrix * C2 = Create_Matrix(A->rows, B->cols);
    Matrix * C4 = Create_Matrix(A->rows, B->cols);

    for (int i = 0; i < 10; ++i)
    {
        for (int i = 0; i < A->rows * A->cols; ++i) Data(A)[i] = rand() % 10;
        for (int i = 0; i < B->rows * B->cols; ++i) Data(B)[i] = rand() % 10;
        for (int i = 0; i < C->rows * C->cols; ++i) Data(C)[i] = rand() % 10;
        for (int i = 0; i < C2->rows * C2->cols; ++i) Data(C2)[i] = rand() % 10;
        for (int i = 0; i < C4->rows * C4->cols; ++i) Data(C4)[i] = rand() % 10;
        MultiplySerial(C, A, B);
        MultiplyExplicitSimple(C2, A, B);
        MultiplyTile(C4, A, B);
        for (int i = 0; i < C->rows * C->cols; ++i)
            if (fabs(Data(C)[i] - Data(C2)[i]) > 0.0001)
            { std::cout << "diff C2\n";
                break;
            }
        for (int i = 0; i < C->rows * C->cols; ++i)
            if (fabs(Data(C)[i] - Data(C4)[i]) > 0.0001)
            { std::cout << "diff C4\n";
                break;
            }
    }
    return 0;
}

 

Bitonic sort

A second problem I chose for comparison was bitonic sort of an integer array.  An in-place, power of 2 sequential solution is outlined in Gedik et al., but I did not choose that as a starting point.  While there is a CUDA implementation available in the public domain by NVIDIA, that solution is difficult to understand, and the implementation changes the algorithm used based on the size of the array.  My implementation is based on the description in Peters et al.  The C++ AMP and CUDA implementations are presented below.

Both solutions performs a sequence of parallel computations of groups of comparisons and swaps of a uni-directional (also known as “normalized”) sorting network.  An example of this network is displayed in the figure below, for an array of 16 elements (figure from Wikipedia).

For the sort, each group of vertically oriented swaps in the network are parallelized.  As shown in the figure above, each blue box is labelled with a phase, and each red box is labelled with a level.  (The red boxes in each phase is also known as a bitonic merge, because that portion of the network merges two bitonic sequences into one bitonic sequence.)  Orange boxes are unlabeled because there is only one per blue box.  (The orange box is also know as a bitonic split, because it creates two bitonic sequences.)  Swaps proceed in a left to right fashion, first with the orange box of Phase 1, then the orange box of Phase 2, then the red box of Phase 2, and so on.

In the C++ AMP implementation, swaps in blue box are computed in lines 77-99.  For each blue box, the orange box is computed (lines 78-86), followed by a number of red boxes (lines 88-99).  In this solution, the size of the tile is TS.  The length of the array must be a power of 2, and the length must be divisible by the size of the tile.

The run time for each were computed (nine runs, standard error for sample), and a summary of these data are contained in the table below.

Implementation Sequential Parallel (1024 threads per tile)
C++ AMP 12.5 ± 0.4 s 0.41 ± 0.04 s
CUDA 12.6 ± 0.01 s 0.372 ± 0.002 s

(Array of length 1024 * 32 * 16 * 16 = 8388608, of integers. Environment: NVIDIA GeForce GTX 470, an ATI Radeon HD 6450 (not used), and an Intel Q6600 @ 2.51 Ghz (overclocked), 4 G RAM, run on the Windows 7 64-bit OS. 10 runs, first run thrown out (for total of 9). Average ± S.E. of sample.)

For this problem, the C++ AMP implementation is on par with the CUDA implementation (if slightly slower than the CUDA implementation).

The naive bitionic sort implementation performs one comparison per thread.  Each thread loads the two elements to compare, then swaps the values if they are out of order.   However, global memory is accessed quite often with this implementation because the same elements are loaded from global memory over and over, between levels of the bitonic merge.  For example, element 0 of the array is loaded three times in the bitonic merge in phase 3: the first comparisons of level 2, 1, and 0.

An improved implementation is possible by using fewer threads, with each thread doing more work.  Each thread works on a partition of comparisons of the bitionic merge portion of the network.  The partition is defined so that it does not overlap with other threads working on the same levels of a phase.  Partitions that involve n levels of a merge are known as partitions with degree n.  The figure below shows two partitions.  One partition works with comparisons labelled with red lines; a second partition works with comparisons labelled with green lines.  Both partitions have degree 2 because they involve only two levels of the merge.

For comparison, I implemented bitonic sort with partitions of degree 5 (see Peters paper).  The runtimes for C++ AMP and CUDA showed an improvement, particularly with the CUDA implementation.

Implementation Naive parallel (512 threads per tile) Degree-5 parallel (512 threads per tile)
C++ AMP 0.285 ± 0.4 s 0.239 ± 0.001 s
CUDA 0.280 ± 0.001 s 0.187 ± 0.001 s

What is particularly interesting is that, while the C++ AMP implementation is slower than the CUDA implementation, the C++ AMP implementation with degree-5 merges performed better than its naive implementation.  Why?  In C++ AMP, there is no way for the programmer to choose a register representation of variables.  However, the compiler chose a register representation none the less.  It it hadn’t, the the implementation would have been slower than the naive implementation, which is was not.

Implementation in CUDA

#include <fstream>
#include <iomanip>
#include <iostream>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/timeb.h>
#include <time.h>

void exchange(int & i, int & j)
{
    int t = i;
    i = j;
    j = t;
}

void bitonicSortSequentialGedik(int * a, int length)
{
    struct _timeb  t1;
    struct _timeb  t2;
    std::cout << "Starting sequential (Gedik)... ";
    _ftime_s(&t1);
    int i,j,k;
    for (k = 2; k <= length; k = 2*k)
    {
        for (j = k >> 1; j > 0; j = j>>1)
        {
            for (i=0; i < length; i++)
            {
                int ixj = i ^ j;
                if (ixj > i)
                {
                    if ((i & k) == 0 && a[i] > a[ixj])
                        exchange(a[i], a[ixj]);
                    if ((i & k) != 0 && a[i] < a[ixj])
                        exchange(a[i], a[ixj]);
                }
            }
        }
    }
    _ftime(&t2);
    std::cout << (double)(t2.time - t1.time + ((double)(t2.millitm - t1.millitm))/1000) << " s.\n";
}

//__device__ __host__ inline void swap(int & a, int & b)
//{
//    if (a < b)
//        return;
//    int tmp = a;
//    a = b;
//    b = tmp;
//}
//__device__ __host__ inline void swap(int & a, int & b)
//{
//    if (a > b) {
//        int tmp = a;
//        a = b;
//        b = tmp;
//    }
//}

__device__ __host__ inline void swap(int & a, int & b)
{
    if (a > b) {
        a ^= b;
        b ^= a;
        a ^= b;
    }
}

unsigned int mylog2(unsigned int v)
{
    unsigned int x = 0;
    while ((v = (v >> 1)) != 0)
    {
        x++;
    }
    return x;
}

unsigned int pow2(int e)
{
    unsigned int x = 1;
    for (int i = 0; i < e; ++i)
        x *= 2;
    return x;
}

__device__ __host__ inline void orange_box(int i, int p2, int & cross, int & pair)
{
    int imp2 = i % p2;
    int j = imp2 + 2 * p2 * (int)(i / p2);
    cross = j;
    pair = -1 - imp2 + 2 * p2 * (int)((i+p2)/p2);
}

__device__ __host__ inline void red_box(int i, int p2, int & cross, int & pair)
{
    int imp2 = i % p2;
    int j = imp2 + 2 * p2 * (int)(i / p2);
    cross = j;
    pair = j + p2;
}

void bitonicSortSequential(int * data, int length)
{
    unsigned int log2length = mylog2(length);
    unsigned int checklength = pow2(log2length);
    if (length != checklength)
    {
        std::cout << "Length not a power of 2.\n";
        throw;
    }
    struct _timeb  t1;
    struct _timeb  t2;
    std::cout << "Starting sequential... ";
    _ftime_s(&t1);

    {
        for (int phase = 0; phase < log2length; ++phase)
        {
            int compares = length / 2;
            unsigned int phase2 = pow2((unsigned int)phase);
            for (int ig = 0; ig < compares; ++ig) {
                int cross;
                int paired;
                orange_box(ig, phase2, cross, paired);
                swap(data[cross], data[paired]);
            }
            for (int level = phase-1; level >= 0; --level)
            {
                unsigned int level2 = pow2((unsigned int)level);
                for (int ig = 0; ig < compares; ++ig) {
                    int cross;
                    int paired;
                    red_box(ig, level2, cross, paired);
                    swap(data[cross], data[paired]);
                }
            }
        }
    }
    _ftime(&t2);
    std::cout << (double)(t2.time - t1.time + ((double)(t2.millitm - t1.millitm))/1000) << " s.\n";
}

void Check(bool OK)
{
    if (! OK)
    {
        printf("error\n");
        throw;
    }
}

__global__ void Kernel1(int * a, int length, int phase2)
{
    int ig = threadIdx.x
            + blockDim.x * blockIdx.x
            + blockDim.x * gridDim.x * blockDim.y * blockIdx.y
            + blockDim.x * gridDim.x * threadIdx.y;
    if (ig < 0)
        return;
    if (ig >= length)
        return;
    int cross;
    int paired;
    orange_box(ig, phase2, cross, paired);
    swap(a[cross], a[paired]);
}

__global__ void Kernel2(int * a, int length, int phase2)
{
    int ig = threadIdx.x
            + blockDim.x * blockIdx.x
            + blockDim.x * gridDim.x * blockDim.y * blockIdx.y
            + blockDim.x * gridDim.x * threadIdx.y;
    if (ig < 0)
        return;
    if (ig >= length)
        return;
    int cross;
    int paired;
    red_box(ig, phase2, cross, paired);
    swap(a[cross], a[paired]);
}

void bitonicSortExplicitSimple(int * data, int length)
{
    unsigned int log2length = mylog2(length);
    unsigned int checklength = pow2(log2length);
    if (length != checklength)
    {
        std::cout << "Length not a power of 2.\n";
        throw;
    }
    struct _timeb  t1;
    struct _timeb  t2;
    std::cout << "Starting explicit simple... ";
    _ftime_s(&t1);

    {
        static const int TS = 512;
        cudaError_t errcode;
        int * a;
        errcode = cudaMalloc((void**) &a, length * sizeof(int));
        Check(errcode == cudaSuccess);

        errcode = cudaMemcpy((void*)a, data, length * sizeof(int), cudaMemcpyHostToDevice);
        Check(errcode == cudaSuccess);

        for (int phase = 0; phase < log2length; ++phase)
        {
            int threads = length / 2;
            unsigned int phase2 = pow2((unsigned int)phase);

            dim3 th(TS);
            dim3 gr(threads / TS, 1);

            Kernel1<<<gr, th>>>(a, length, phase2);
            cudaThreadSynchronize();
            errcode = cudaGetLastError();
            Check(errcode == cudaSuccess);

            for (int level = phase-1; level >= 0; --level)
            {
                unsigned int level2 = pow2((unsigned int)level);
                Kernel2<<<gr, th>>>(a, length, level2);
                cudaThreadSynchronize();
                errcode = cudaGetLastError();
                Check(errcode == cudaSuccess);
            }
        }
        errcode = cudaMemcpy((void**)data, a, length * sizeof(int), cudaMemcpyDeviceToHost);
        Check(errcode == cudaSuccess);
        cudaFree(a);
    }

    _ftime(&t2);
    std::cout << (double)(t2.time - t1.time + ((double)(t2.millitm - t1.millitm))/1000) << " s.\n";
}

void PrecomputePartition(int phase, int level, int degree, int ** _memory, int ** _compares, int ** _normalized_compares, int ** _levels, int * _msize, int * _csize, int * _threads, int * _block_size)
{
    //std::cout << "\nPartitioning with phase " << phase << ", level " << level << ", degree " << degree << "\n";
    if (degree == 3)
    {
        const int msize = 8;
        const int csize = 24;
        static int normalized_compares[csize] = {0, 4, 1, 5, 2, 6, 3, 7,
                                                 0, 2, 1, 3, 4, 6, 5, 7,
                                                 0, 1, 2, 3, 4, 5, 6, 7};
        static int memory[msize];
        for (int i = 0; i < msize; ++i)
            memory[i] = i * pow2(level + 1 - degree);
        static int levels[csize];
        for (int i = 0; i < csize; ++i)
            levels[i] = level - i / degree;
        static int compares[csize];
        for (int i = 0; i < csize; ++i)
            compares[i] = memory[normalized_compares[i]];
        int threads = memory[1];
        int block_size = memory[1] * msize;

        *_msize = msize;
        *_csize = csize;
        *_normalized_compares = normalized_compares;
        *_memory = memory;
        *_levels = levels;
        *_compares = compares;
        *_threads = threads;
        *_block_size = block_size;
    } else if (degree == 5)
    {
        const int msize = 32;
        const int csize = 160;
        static int normalized_compares[csize] = {
    0, 16, 1, 17, 2, 18, 3, 19, 4, 20,  5, 21,  6, 22,  7, 23,  8, 24,  9, 25, 10, 26, 11, 27, 12, 28, 13, 29, 14, 30, 15, 31,
    0,  8, 1,  9, 2, 10, 3, 11, 4, 12,  5, 13,  6, 14,  7, 15, 16, 24, 17, 25, 18, 26, 19, 27, 20, 28, 21, 29, 22, 30, 23, 31,
    0,  4, 1,  5, 2,  6, 3,  7, 8, 12,  9, 13, 10, 14, 11, 15, 16, 20, 17, 21, 18, 22, 19, 23, 24, 28, 25, 29, 26, 30, 27, 31,
    0,  2, 1,  3, 4,  6, 5,  7, 8, 10,  9, 11, 12, 14, 13, 15, 16, 18, 17, 19, 20, 22, 21, 23, 24, 26, 25, 27, 28, 30, 29, 31,
    0,  1, 2,  3, 4,  5, 6,  7, 8,  9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31};
        static int memory[msize];
        for (int i = 0; i < msize; ++i)
            memory[i] = i * pow2(level + 1 - degree);
        static int levels[csize];
        for (int i = 0; i < csize; ++i)
            levels[i] = level - i / degree;
        static int compares[csize];
        for (int i = 0; i < csize; ++i)
            compares[i] = memory[normalized_compares[i]];
        int threads = memory[1];
        int block_size = memory[1] * msize;

    }
}

__constant__ const int normalized_compares[160] = {
    0, 16, 1, 17, 2, 18, 3, 19, 4, 20,  5, 21,  6, 22,  7, 23,  8, 24,  9, 25, 10, 26, 11, 27, 12, 28, 13, 29, 14, 30, 15, 31,
    0,  8, 1,  9, 2, 10, 3, 11, 4, 12,  5, 13,  6, 14,  7, 15, 16, 24, 17, 25, 18, 26, 19, 27, 20, 28, 21, 29, 22, 30, 23, 31,
    0,  4, 1,  5, 2,  6, 3,  7, 8, 12,  9, 13, 10, 14, 11, 15, 16, 20, 17, 21, 18, 22, 19, 23, 24, 28, 25, 29, 26, 30, 27, 31,
    0,  2, 1,  3, 4,  6, 5,  7, 8, 10,  9, 11, 12, 14, 13, 15, 16, 18, 17, 19, 20, 22, 21, 23, 24, 26, 25, 27, 28, 30, 29, 31,
    0,  1, 2,  3, 4,  5, 6,  7, 8,  9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31};

__global__ void Kernel3(int * a, int length, int phase, int level, int level2)
{
    int ig = threadIdx.x
            + blockDim.x * blockIdx.x
            + blockDim.x * gridDim.x * blockDim.y * blockIdx.y
            + blockDim.x * gridDim.x * threadIdx.y;
    if (ig < 0)
        return;
    if (ig >= length)
        return;
    const int degree = 5;
    const int msize = 32;
    const int csize = 160;
    int memory[msize];
    for (int i = 0; i < msize; ++i)
        memory[i] = i * level2;
    int threads = memory[1];
    int block_size = memory[1] * msize;
    int base = ig % threads + block_size * (int)(ig / threads);
    int mm[msize];
    #pragma unroll
    for (int i = 0; i < msize; ++i)
    {
        mm[i] = a[base + memory[i]];
    }

//#define SCREW_YOU
#ifdef SCREW_YOU
    #pragma unroll
    for (int i = 0; i < csize; i += 2)
    {
        int cross = normalized_compares[i];
        int paired = normalized_compares[i+1];
        swap(mm[cross], mm[paired]);
    }
#else
    swap(mm[0], mm[16]);
    swap(mm[1], mm[17]);
    swap(mm[2], mm[18]);
    swap(mm[3], mm[19]);
    swap(mm[4], mm[20]);
    swap(mm[5], mm[21]);
    swap(mm[6], mm[22]);
    swap(mm[7], mm[23]);
    swap(mm[8], mm[24]);
    swap(mm[9], mm[25]);
    swap(mm[10], mm[26]);
    swap(mm[11], mm[27]);
    swap(mm[12], mm[28]);
    swap(mm[13], mm[29]);
    swap(mm[14], mm[30]);
    swap(mm[15], mm[31]);

    swap(mm[0], mm[8]);
    swap(mm[1], mm[9]);
    swap(mm[2], mm[10]);
    swap(mm[3], mm[11]);
    swap(mm[4], mm[12]);
    swap(mm[5], mm[13]);
    swap(mm[6], mm[14]);
    swap(mm[7], mm[15]);
    swap(mm[16], mm[24]);
    swap(mm[17], mm[25]);
    swap(mm[18], mm[26]);
    swap(mm[19], mm[27]);
    swap(mm[20], mm[28]);
    swap(mm[21], mm[29]);
    swap(mm[22], mm[30]);
    swap(mm[23], mm[31]);

    swap(mm[0], mm[4]);
    swap(mm[1], mm[5]);
    swap(mm[2], mm[6]);
    swap(mm[3], mm[7]);
    swap(mm[8], mm[12]);
    swap(mm[9], mm[13]);
    swap(mm[10], mm[14]);
    swap(mm[11], mm[15]);
    swap(mm[16], mm[20]);
    swap(mm[17], mm[21]);
    swap(mm[18], mm[22]);
    swap(mm[19], mm[23]);
    swap(mm[24], mm[28]);
    swap(mm[25], mm[29]);
    swap(mm[26], mm[30]);
    swap(mm[27], mm[31]);

    swap(mm[0], mm[2]);
    swap(mm[1], mm[3]);
    swap(mm[4], mm[6]);
    swap(mm[5], mm[7]);
    swap(mm[8], mm[10]);
    swap(mm[9], mm[11]);
    swap(mm[12], mm[14]);
    swap(mm[13], mm[15]);
    swap(mm[16], mm[18]);
    swap(mm[17], mm[19]);
    swap(mm[20], mm[22]);
    swap(mm[21], mm[23]);
    swap(mm[24], mm[26]);
    swap(mm[25], mm[27]);
    swap(mm[28], mm[30]);
    swap(mm[29], mm[31]);

    swap(mm[0], mm[1]);
    swap(mm[2], mm[3]);
    swap(mm[4], mm[5]);
    swap(mm[6], mm[7]);
    swap(mm[8], mm[9]);
    swap(mm[10], mm[11]);
    swap(mm[12], mm[13]);
    swap(mm[14], mm[15]);
    swap(mm[16], mm[17]);
    swap(mm[18], mm[19]);
    swap(mm[20], mm[21]);
    swap(mm[22], mm[23]);
    swap(mm[24], mm[25]);
    swap(mm[26], mm[27]);
    swap(mm[28], mm[29]);
    swap(mm[30], mm[31]);
#endif

    #pragma unroll
    for (int i = 0; i < msize; ++i)
    {
        a[base + memory[i]] = mm[i];
    }
}

void bitonicSortWithDegree(int * data, int length)
{
    unsigned int log2length = mylog2(length);
    unsigned int checklength = pow2(log2length);
    if (length != checklength)
    {
        std::cout << "Length not a power of 2.\n";
        throw;
    }
    struct _timeb  t1;
    struct _timeb  t2;
    std::cout << "Starting with degree... ";
    _ftime_s(&t1);
    {
        static const int TS = 512;
        cudaError_t errcode;
        int * a;
        errcode = cudaMalloc((void**) &a, length * sizeof(int));
        Check(errcode == cudaSuccess);

        errcode = cudaMemcpy((void*)a, data, length * sizeof(int), cudaMemcpyHostToDevice);
        Check(errcode == cudaSuccess);

        for (int phase = 0; phase < log2length; ++phase)
        {
            int threads = length / 2;
            unsigned int phase2 = pow2((unsigned int)phase);

            dim3 th(TS);
            dim3 gr(threads / TS, 1);

            Kernel1<<<gr, th>>>(a, length, phase2);
            cudaThreadSynchronize();
            errcode = cudaGetLastError();
            Check(errcode == cudaSuccess);

            for (int level = phase-1; level >= 0; )
            {
                if (level > 6)
                {
                    const int degree = 5;
                    const int msize = 32;
                    const int csize = 160;
                    static int memory[msize];
                    for (int i = 0; i < 2; ++i)
                        memory[i] = i * pow2(level + 1 - degree);
                    int threads = memory[1];
                    int block_size = memory[1] * msize;

                    // The size of each block is
                    int ncompares = threads * (length / block_size);

                    dim3 th(TS);
                    if (ncompares < TS)
                    throw;
                    dim3 gr(ncompares / TS, 1);
                    int l2 = pow2(level + 1 - degree);
                    Kernel3<<<gr, th>>>(a, length, phase, level, l2);
                    cudaThreadSynchronize();
                    errcode = cudaGetLastError();
                    Check(errcode == cudaSuccess);

                    level -= 5;
                }
                else
                {
                    unsigned int level2 = pow2((unsigned int)level);
                    Kernel2<<<gr, th>>>(a, length, level2);
                    cudaThreadSynchronize();
                    errcode = cudaGetLastError();
                    Check(errcode == cudaSuccess);
                    level -= 1;
                }
            }
        }
        errcode = cudaMemcpy((void**)data, a, length * sizeof(int), cudaMemcpyDeviceToHost);
        Check(errcode == cudaSuccess);
        cudaFree(a);
    }
    _ftime(&t2);
    std::cout << (double)(t2.time - t1.time + ((double)(t2.millitm - t1.millitm))/1000) << " s.\n";
}

int main()
{
    int size = 1024 * 32 * 16 * 16;
    int * A = (int*)malloc(size * sizeof(int));
    int * A2 = (int*)malloc(size * sizeof(int));
    int * A3 = (int*)malloc(size * sizeof(int));
    int * A4 = (int*)malloc(size * sizeof(int));
    for (int j = 0; j < 10; ++j)
    {
        for (int i = 0; i < size; ++i) A[i] = (size - i);
        for (int i = 0; i < size; ++i) A2[i] = A[i];
        for (int i = 0; i < size; ++i) A3[i] = A[i];
        for (int i = 0; i < size; ++i) A4[i] = A[i];
        bitonicSortSequentialGedik(A, size);
        bitonicSortSequential(A2, size);
        bitonicSortExplicitSimple(A3, size);
        bitonicSortWithDegree(A4, size);
        for (int i = 0; i < size; ++i)
            if (A[i] != A2[i])
            {
                std::cout << "diff A2.\n";
                break;
            }
        for (int i = 0; i < size; ++i)
            if (A[i] != A3[i])
            {
                std::cout << "diff A3.\n";
                break;
            }
        for (int i = 0; i < size; ++i)
            if (A[i] != A4[i])
            {
                std::cout << "diff A4.\n";
                break;
            }
    }
    return 0;
}

Implementation in C++ AMP

#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <amp.h>
#include <sys/timeb.h>
#include <time.h>
#include <stack>
#include <list>

using namespace concurrency;

void exchange(int & i, int & j)
{
    int t = i;
    i = j;
    j = t;
}

void bitonicSortSequentialGedik(int * a, int length)
{
    struct _timeb  t1;
    struct _timeb  t2;
    std::cout << "Starting sequential (Gedik)... ";
    _ftime_s(&t1);
    int i,j,k;
    for (k = 2; k <= length; k = 2*k)
    {
        for (j = k >> 1; j > 0; j = j>>1)
        {
            for (i=0; i < length; i++)
            {
                int ixj = i ^ j;
                if (ixj > i)
                {
                    if ((i & k) == 0 && a[i] > a[ixj])
                        exchange(a[i], a[ixj]);
                    if ((i & k) != 0 && a[i] < a[ixj])
                        exchange(a[i], a[ixj]);
                }
            }
        }
    }
    _ftime(&t2);
    std::cout << (double)(t2.time - t1.time + ((double)(t2.millitm - t1.millitm))/1000) << " s.\n";
}

inline void swap(int & a, int & b) restrict(direct3d, cpu)
{
    if (a < b)
        return;
    int tmp = a;
    a = b;
    b = tmp;
}

unsigned int log2(unsigned int v)
{
    unsigned int x = 0;
    while ((v = (v >> 1)) != 0)
    {
        x++;
    }
    return x;
}

unsigned int pow2(int e) restrict(direct3d, cpu)
{
    unsigned int x = 1;
    for (int i = 0; i < e; ++i)
        x *= 2;
    return x;
}

inline void orange_box(int i, int p2, int & cross, int & pair) restrict(direct3d, cpu)
{
    int imp2 = i % p2;
    int j = imp2 + 2 * p2 * (int)(i / p2);
    cross = j;
    pair = -1 - imp2 + 2 * p2 * (int)((i+p2)/p2);
}

inline void orange_box_phase(int i, int phase, int & cross, int & pair) restrict(direct3d, cpu)
{
    int p2 = pow2(phase);
    int imp2 = i % p2;
    int j = imp2 + 2 * p2 * (int)(i / p2);
    cross = j;
    pair = -1 - imp2 + 2 * p2 * (int)((i+p2)/p2);
}

inline void red_box(int i, int p2, int & cross, int & pair) restrict(direct3d, cpu)
{
    int imp2 = i % p2;
    int j = imp2 + 2 * p2 * (int)(i / p2);
    cross = j;
    pair = j + p2;
}

inline void red_box_level(int i, int level, int & cross, int & pair) restrict(direct3d, cpu)
{
    int p2 = pow2(level);
    int imp2 = i % p2;
    int j = imp2 + 2 * p2 * (int)(i / p2);
    cross = j;
    pair = j + p2;
}

// compute the COEX index for the index of the element in the array.
int reverse_red_box(int level, int element)
{
    int a = pow2(level);
    int b = element % a;
    int c = a * (int)(element / (2 * a));
    return b + c;
}

// Return the COEX of an index into the array.
int reverse_orange_box(int phase, int element)
{
    phase++;
    int c = element % pow2(phase-1);
    int d = (int)(abs((int)((element + pow2(phase-1))/pow2(phase-1))));
    int e = d % 2;
    int f = (d - 1) % 2;
    int g = (int)(abs((int)((element + pow2(phase))/pow2(phase))));
    int h = (g-1)*pow2(phase-1);
    int i = pow2(phase-1) - 1 - element % pow2(phase-1);
    int j = e*c+f*i;
    int k = j+h;
    return k;
}

void bitonicSortSequential(int * data, int length)
{
    unsigned int log2length = log2(length);
    unsigned int checklength = pow2(log2length);
    if (length != checklength)
    {
        std::cout << "Length not a power of 2.\n";
        throw;
    }
    struct _timeb  t1;
    struct _timeb  t2;
    std::cout << "Starting sequential... ";
    _ftime_s(&t1);

    {
        for (int phase = 0; phase < log2length; ++phase)
        {
            int compares = length / 2;
            unsigned int phase2 = pow2((unsigned int)phase);
            for (int ig = 0; ig < compares; ++ig) {
                int cross;
                int paired;
                orange_box(ig, phase2, cross, paired);
                swap(data[cross], data[paired]);
            }
            for (int level = phase-1; level >= 0; --level)
            {
                unsigned int level2 = pow2((unsigned int)level);
                for (int ig = 0; ig < compares; ++ig) {
                    int cross;
                    int paired;
                    red_box(ig, level2, cross, paired);
                    swap(data[cross], data[paired]);
                }
            }
        }
    }
    _ftime(&t2);
    std::cout << (double)(t2.time - t1.time + ((double)(t2.millitm - t1.millitm))/1000) << " s.\n";
}

void bitonicSortWithDegree(int * data, int length)
{
    unsigned int log2length = log2(length);
    unsigned int checklength = pow2(log2length);
    if (length != checklength)
    {
        std::cout << "Length not a power of 2.\n";
        throw;
    }
    struct _timeb  t1;
    struct _timeb  t2;
    std::cout << "Starting with degree... ";
    _ftime_s(&t1);
    std::vector<accelerator> accelerators = get_accelerators();
    std::vector<accelerator>::iterator it;
    for (it = accelerators.begin(); it != accelerators.end(); ++it)
    {
        if ((*it).get_has_display() == false)
            continue;
        break;
    }
    {
        static const int TS = 512;
        array_view<int,1> a(length, data);

        for (int phase = 0; phase < log2length; ++phase)
        {
            int compares = length / 2;
            extent<1> e(compares);
            grid<1> g(e);

            unsigned int phase2 = pow2((unsigned int)phase);
            parallel_for_each(*it, g.tile<TS>(),
                [phase2, a](tiled_index<TS> idx) restrict(direct3d) {
                int ig = idx.global[0];
                int cross;
                int paired;
                orange_box(ig, phase2, cross, paired);
                swap(a[cross], a[paired]);
            });

            for (int level = phase-1; level >= 0; )
            {
                if (level > 6)
                {
                    const int degree = 5;
                    const int msize = 32;
                    const int csize = 160;
                    static int memory[msize];
                    for (int i = 0; i < 2; ++i)
                        memory[i] = i * pow2(level + 1 - degree);
                    int threads = memory[1];
                    int block_size = memory[1] * msize;
                    int ncompares = threads * (length / block_size);
                    int l2 = pow2(level + 1 - degree);
                    extent<1> e(ncompares);
                    grid<1> g(e);
                    parallel_for_each(*it, g.tile<TS>(),
                        [a, length, phase, level, l2](tiled_index<TS> idx) restrict(direct3d)
                    {
                        int ig = idx.global[0];
                        const int degree = 5;
                        const int msize = 32;
                        const int csize = 160;
                        int memory[msize];
                        for (int i = 0; i < msize; ++i)
                            memory[i] = i * l2;
                        int threads = memory[1];
                        int block_size = memory[1] * msize;
                        int base = ig % threads + block_size * (int)(ig / threads);
                        int mm[msize];
                        for (int i = 0; i < msize; ++i)
                        {
                            mm[i] = a[base + memory[i]];
                        }
#define XXX
#ifdef XXX
 int normalized_compares[160] = {
    0, 16, 1, 17, 2, 18, 3, 19, 4, 20,  5, 21,  6, 22,  7, 23,  8, 24,  9, 25, 10, 26, 11, 27, 12, 28, 13, 29, 14, 30, 15, 31,
    0,  8, 1,  9, 2, 10, 3, 11, 4, 12,  5, 13,  6, 14,  7, 15, 16, 24, 17, 25, 18, 26, 19, 27, 20, 28, 21, 29, 22, 30, 23, 31,
    0,  4, 1,  5, 2,  6, 3,  7, 8, 12,  9, 13, 10, 14, 11, 15, 16, 20, 17, 21, 18, 22, 19, 23, 24, 28, 25, 29, 26, 30, 27, 31,
    0,  2, 1,  3, 4,  6, 5,  7, 8, 10,  9, 11, 12, 14, 13, 15, 16, 18, 17, 19, 20, 22, 21, 23, 24, 26, 25, 27, 28, 30, 29, 31,
    0,  1, 2,  3, 4,  5, 6,  7, 8,  9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31};

                        for (int i = 0; i < csize; i += 2)
                        {
                            int cross = normalized_compares[i];
                            int paired = normalized_compares[i+1];
                            swap(mm[cross], mm[paired]);
                        }
#else
                        swap(mm[0], mm[16]);
                        swap(mm[1], mm[17]);
                        swap(mm[2], mm[18]);
                        swap(mm[3], mm[19]);
                        swap(mm[4], mm[20]);
                        swap(mm[5], mm[21]);
                        swap(mm[6], mm[22]);
                        swap(mm[7], mm[23]);
                        swap(mm[8], mm[24]);
                        swap(mm[9], mm[25]);
                        swap(mm[10], mm[26]);
                        swap(mm[11], mm[27]);
                        swap(mm[12], mm[28]);
                        swap(mm[13], mm[29]);
                        swap(mm[14], mm[30]);
                        swap(mm[15], mm[31]);

                        swap(mm[0], mm[8]);
                        swap(mm[1], mm[9]);
                        swap(mm[2], mm[10]);
                        swap(mm[3], mm[11]);
                        swap(mm[4], mm[12]);
                        swap(mm[5], mm[13]);
                        swap(mm[6], mm[14]);
                        swap(mm[7], mm[15]);
                        swap(mm[16], mm[24]);
                        swap(mm[17], mm[25]);
                        swap(mm[18], mm[26]);
                        swap(mm[19], mm[27]);
                        swap(mm[20], mm[28]);
                        swap(mm[21], mm[29]);
                        swap(mm[22], mm[30]);
                        swap(mm[23], mm[31]);

                        swap(mm[0], mm[4]);
                        swap(mm[1], mm[5]);
                        swap(mm[2], mm[6]);
                        swap(mm[3], mm[7]);
                        swap(mm[8], mm[12]);
                        swap(mm[9], mm[13]);
                        swap(mm[10], mm[14]);
                        swap(mm[11], mm[15]);
                        swap(mm[16], mm[20]);
                        swap(mm[17], mm[21]);
                        swap(mm[18], mm[22]);
                        swap(mm[19], mm[23]);
                        swap(mm[24], mm[28]);
                        swap(mm[25], mm[29]);
                        swap(mm[26], mm[30]);
                        swap(mm[27], mm[31]);

                        swap(mm[0], mm[2]);
                        swap(mm[1], mm[3]);
                        swap(mm[4], mm[6]);
                        swap(mm[5], mm[7]);
                        swap(mm[8], mm[10]);
                        swap(mm[9], mm[11]);
                        swap(mm[12], mm[14]);
                        swap(mm[13], mm[15]);
                        swap(mm[16], mm[18]);
                        swap(mm[17], mm[19]);
                        swap(mm[20], mm[22]);
                        swap(mm[21], mm[23]);
                        swap(mm[24], mm[26]);
                        swap(mm[25], mm[27]);
                        swap(mm[28], mm[30]);
                        swap(mm[29], mm[31]);

                        swap(mm[0], mm[1]);
                        swap(mm[2], mm[3]);
                        swap(mm[4], mm[5]);
                        swap(mm[6], mm[7]);
                        swap(mm[8], mm[9]);
                        swap(mm[10], mm[11]);
                        swap(mm[12], mm[13]);
                        swap(mm[14], mm[15]);
                        swap(mm[16], mm[17]);
                        swap(mm[18], mm[19]);
                        swap(mm[20], mm[21]);
                        swap(mm[22], mm[23]);
                        swap(mm[24], mm[25]);
                        swap(mm[26], mm[27]);
                        swap(mm[28], mm[29]);
                        swap(mm[30], mm[31]);
#endif
                        for (int i = 0; i < msize; ++i)
                            a[base + memory[i]] = mm[i];

                    });
                    level -= degree;
                }
                else
                {
                    unsigned int level2 = pow2((unsigned int)level);
                    parallel_for_each(*it, g.tile<TS>(),
                        [level2, a](tiled_index<TS> idx) restrict(direct3d) {
                        int ig = idx.global[0];
                        int cross;
                        int paired;
                        red_box(ig, level2, cross, paired);
                        swap(a[cross], a[paired]);
                    });
                    level -= 1;
                }
            }
        }
    }
    _ftime(&t2);
    std::cout << (double)(t2.time - t1.time + ((double)(t2.millitm - t1.millitm))/1000) << " s.\n";
}

void bitonicSortSimple(int * data, int length)
{
    unsigned int log2length = log2(length);
    unsigned int checklength = pow2(log2length);
    if (length != checklength)
    {
        std::cout << "Length not a power of 2.\n";
        throw;
    }
    struct _timeb  t1;
    struct _timeb  t2;
    std::cout << "Starting simple... ";
    _ftime_s(&t1);
    std::vector<accelerator> accelerators = get_accelerators();
    std::vector<accelerator>::iterator it;
    for (it = accelerators.begin(); it != accelerators.end(); ++it)
    {
        if ((*it).get_has_display() == false)
            continue;
        break;
    }
    {
        array_view<int,1> a(length, data);

        for (int phase = 0; phase < log2length; ++phase)
        {
            int compares = length / 2;
            extent<1> e(compares);
            grid<1> g(e);

            unsigned int phase2 = pow2((unsigned int)phase);
            parallel_for_each(*it, g,
                [phase2, a](index<1> idx) restrict(direct3d) {
                int ig = idx[0];
                int cross;
                int paired;
                orange_box(ig, phase2, cross, paired);
                swap(a[cross], a[paired]);
            });

            for (int level = phase-1; level >= 0; --level)
            {
                unsigned int level2 = pow2((unsigned int)level);
                parallel_for_each(*it, g,
                    [level2, a](index<1> idx) restrict(direct3d) {
                    int ig = idx[0];
                    int cross;
                    int paired;
                    red_box(ig, level2, cross, paired);
                    swap(a[cross], a[paired]);
                });
            }
        }
    }
    _ftime(&t2);
    std::cout << (double)(t2.time - t1.time + ((double)(t2.millitm - t1.millitm))/1000) << " s.\n";
}

void bitonicSortSimpleAcceleratorView(int * data, int length)
{
    unsigned int log2length = log2(length);
    unsigned int checklength = pow2(log2length);
    if (length != checklength)
    {
        std::cout << "Length not a power of 2.\n";
        throw;
    }
    struct _timeb  t1;
    struct _timeb  t2;
    std::cout << "Starting simple acc view... ";
    _ftime_s(&t1);
    std::vector<accelerator> accelerators = get_accelerators();
    std::vector<accelerator>::iterator it;
    for (it = accelerators.begin(); it != accelerators.end(); ++it)
    {
        if ((*it).get_has_display() == false)
            continue;
        break;
    }
    {
        accelerator_view av = it->create_view(queuing_mode::deferred);

        array_view<int,1> a(length, data);

        for (int phase = 0; phase < log2length; ++phase)
        {
            int compares = length / 2;
            extent<1> e(compares);
            grid<1> g(e);

            unsigned int phase2 = pow2((unsigned int)phase);
            parallel_for_each(av, g,
                [phase2, a](index<1> idx) restrict(direct3d) {
                int ig = idx[0];
                int cross;
                int paired;
                orange_box(ig, phase2, cross, paired);
                swap(a[cross], a[paired]);
            });

            for (int level = phase-1; level >= 0; --level)
            {
                unsigned int level2 = pow2((unsigned int)level);
                parallel_for_each(av, g,
                    [level2, a](index<1> idx) restrict(direct3d) {
                    int ig = idx[0];
                    int cross;
                    int paired;
                    red_box(ig, level2, cross, paired);
                    swap(a[cross], a[paired]);
                });
            }
        }
    }
    _ftime(&t2);
    std::cout << (double)(t2.time - t1.time + ((double)(t2.millitm - t1.millitm))/1000) << " s.\n";
}

void bitonicSortSimpleMixed(int * data, int length)
{
    unsigned int log2length = log2(length);
    unsigned int checklength = pow2(log2length);
    if (length != checklength)
    {
        std::cout << "Length not a power of 2.\n";
        throw;
    }
    struct _timeb  t1;
    struct _timeb  t2;
    std::cout << "Starting simple mixed... ";
    _ftime_s(&t1);
    std::vector<accelerator> accelerators = get_accelerators();
    std::vector<accelerator>::iterator it;
    for (it = accelerators.begin(); it != accelerators.end(); ++it)
    {
        if ((*it).get_has_display() == false)
            continue;
        break;
    }
    {
        accelerator_view av = it->create_view(queuing_mode::deferred);

        array_view<int,1> a(length, data);

        for (int phase = 0; phase < log2length; ++phase)
        {
            int compares = length / 2;
            extent<1> e(compares);
            grid<1> g(e);

            unsigned int phase2 = pow2((unsigned int)phase);
            parallel_for_each(av, g,
                [phase2, a](index<1> idx) restrict(direct3d) {
                int ig = idx[0];
                int cross;
                int paired;
                orange_box(ig, phase2, cross, paired);
                swap(a[cross], a[paired]);
            });

            for (int level = phase-1; level >= 0; --level)
            {
                unsigned int level2 = pow2((unsigned int)level);
                parallel_for_each(*it, g,                                // BOGUS! SHOULD USE "av"
                    [level2, a](index<1> idx) restrict(direct3d) {
                    int ig = idx[0];
                    int cross;
                    int paired;
                    red_box(ig, level2, cross, paired);
                    swap(a[cross], a[paired]);
                });
            }
        }
    }
    _ftime(&t2);
    std::cout << (double)(t2.time - t1.time + ((double)(t2.millitm - t1.millitm))/1000) << " s.\n";
}

void bitonicSortExplicitSimple(int * data, int length)
{
    unsigned int log2length = log2(length);
    unsigned int checklength = pow2(log2length);
    if (length != checklength)
    {
        std::cout << "Length not a power of 2.\n";
        throw;
    }
    struct _timeb  t1;
    struct _timeb  t2;
    std::cout << "Starting explicit simple... ";
    _ftime_s(&t1);
    std::vector<accelerator> accelerators = get_accelerators();
    std::vector<accelerator>::iterator it;
    for (it = accelerators.begin(); it != accelerators.end(); ++it)
    {
        if ((*it).get_has_display() == false)
            continue;
        break;
    }
    {
        static const int TS = 512;
        array_view<int,1> a(length, data);

        for (int phase = 0; phase < log2length; ++phase)
        {
            int compares = length / 2;
            extent<1> e(compares);
            grid<1> g(e);

            unsigned int phase2 = pow2((unsigned int)phase);
            parallel_for_each(*it, g.tile<TS>(),
                [phase2, a](tiled_index<TS> idx) restrict(direct3d) {
                int ig = idx.global[0];
                int cross;
                int paired;
                orange_box(ig, phase2, cross, paired);
                swap(a[cross], a[paired]);
            });

            for (int level = phase-1; level >= 0; --level)
            {
                unsigned int level2 = pow2((unsigned int)level);
                parallel_for_each(*it, g.tile<TS>(),
                    [level2, a](tiled_index<TS> idx) restrict(direct3d) {
                    int ig = idx.global[0];
                    int cross;
                    int paired;
                    red_box(ig, level2, cross, paired);
                    swap(a[cross], a[paired]);
                });
            }
        }
    }
    _ftime(&t2);
    std::cout << (double)(t2.time - t1.time + ((double)(t2.millitm - t1.millitm))/1000) << " s.\n";
}

void Diff(int * A, int * A2, int size, std::string name)
{
    for (int i = 0; i < size; ++i)
        if (A[i] != A2[i])
        {
            std::cout << "diff " << name << "\n";
            break;
        }
}

int main()
{
    int size = 1024 * 32 * 16 * 16;
    int * A = (int*)malloc(size * sizeof(int));
    int * A2 = (int*)malloc(size * sizeof(int));
    int * A3 = (int*)malloc(size * sizeof(int));
    int * A4 = (int*)malloc(size * sizeof(int));
    int * A5 = (int*)malloc(size * sizeof(int));
    int * A6 = (int*)malloc(size * sizeof(int));
    for (int j = 0; j < 10; ++j)
    {
        for (int i = 0; i < size; ++i) A[i] = (size - i);
        for (int i = 0; i < size; ++i) A2[i] = A[i];
        for (int i = 0; i < size; ++i) A3[i] = A[i];
        for (int i = 0; i < size; ++i) A4[i] = A[i];
        for (int i = 0; i < size; ++i) A5[i] = A[i];
        for (int i = 0; i < size; ++i) A6[i] = A[i];
        bitonicSortSequentialGedik(A, size);
        bitonicSortSequential(A2, size);
        bitonicSortSimple(A3, size);
        bitonicSortSimpleAcceleratorView(A4, size);
        bitonicSortWithDegree(A5, size);
        bitonicSortExplicitSimple(A6, size);
        Diff(A, A2, size, "A2");
        Diff(A, A3, size, "A3");
        Diff(A, A4, size, "A4");
        Diff(A, A5, size, "A5");
        Diff(A, A6, size, "A6");
    }
    return 0;
}

Conclusions

C++ AMP is a new, high-level extension of the C++ language for solving problems using parallelism on GPU’s.  Two problems were examined, with implementations in C++ AMP, CUDA, and OpenCL for comparison.  C++ AMP provides higher level abstractions for the GPU and its memory.  Much of the details of the GPU, however, are hidden from the programmer, which is exactly how programmers get the most out of the GPU.  While the extension looks promising, it is not clear if one trades lower performance for the higher-level abstraction.  Further investigations are needed.

Source code

Matrix multiplication: C++AMP  CUDA  OpenCL

Bitonic sort:  C++AMP  CUDA

Meetup presentation (http://www.meetup.com/HPC-GPU-Supercomputing-Group-of-Boston/events/28657211/): PPT

References

Gedik, B., R. R. Bordawekar, et al. (2007). CellSort: high performance sorting on the cell processor, VLDB Endowment.

Peters, H., O. Schulz-Hildebrandt, et al. (2010). Fast In-Place Sorting with CUDA Based on Bitonic Sort. Parallel Processing and Applied Mathematics. R. Wyrzykowski, J. Dongarra, K. Karczewski and J. Wasniewski, Springer Berlin / Heidelberg. 6067: 403-410.