main.cpp 32.7 KB
Newer Older
Gaurav Khanna's avatar
Gaurav Khanna committed
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
//
// File:       main.cpp
//
// Version:    <1.0>
//
// Disclaimer: IMPORTANT:  This Apple software is supplied to you by Apple Inc. ("Apple")
//             in consideration of your agreement to the following terms, and your use,
//             installation, modification or redistribution of this Apple software
//             constitutes acceptance of these terms.  If you do not agree with these
//             terms, please do not use, install, modify or redistribute this Apple
//             software.
//
//             In consideration of your agreement to abide by the following terms, and
//             subject to these terms, Apple grants you a personal, non - exclusive
//             license, under Apple's copyrights in this original Apple software ( the
//             "Apple Software" ), to use, reproduce, modify and redistribute the Apple
//             Software, with or without modifications, in source and / or binary forms;
//             provided that if you redistribute the Apple Software in its entirety and
//             without modifications, you must retain this notice and the following text
//             and disclaimers in all such redistributions of the Apple Software. Neither
//             the name, trademarks, service marks or logos of Apple Inc. may be used to
//             endorse or promote products derived from the Apple Software without specific
//             prior written permission from Apple.  Except as expressly stated in this
//             notice, no other rights or licenses, express or implied, are granted by
//             Apple herein, including but not limited to any patent rights that may be
//             infringed by your derivative works or by other works in which the Apple
//             Software may be incorporated.
//
//             The Apple Software is provided by Apple on an "AS IS" basis.  APPLE MAKES NO
//             WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED
//             WARRANTIES OF NON - INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A
//             PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION
//             ALONE OR IN COMBINATION WITH YOUR PRODUCTS.
//
//             IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR
//             CONSEQUENTIAL DAMAGES ( INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
//             SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
//             INTERRUPTION ) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION
//             AND / OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER
//             UNDER THEORY OF CONTRACT, TORT ( INCLUDING NEGLIGENCE ), STRICT LIABILITY OR
//             OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright ( C ) 2008 Apple Inc. All Rights Reserved.
//
////////////////////////////////////////////////////////////////////////////////////////////////////
Gaurav Khanna's avatar
Gaurav Khanna committed
47
48


49
50
51
52
#include <string.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
53
54
55
56
57
58
59
60
#ifdef __APPLE__
    #include <OpenCL/cl.h>
    #include <mach/mach_time.h>
    #include <Accelerate/Accelerate.h>
#else
    #include <CL/cl.h>
#endif
#include <clFFT.h>
61
62
63
64
65
#include "procs.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <stdint.h>
#include <float.h>
Gaurav Khanna's avatar
Gaurav Khanna committed
66

67
#define eps_avg 10.0
Gaurav Khanna's avatar
Gaurav Khanna committed
68

Oliver Bock's avatar
Oliver Bock committed
69
#define MAX( _a, _b)    ((_a)>(_b)?(_a) : (_b))
Gaurav Khanna's avatar
Gaurav Khanna committed
70

71
typedef enum {
Oliver Bock's avatar
Oliver Bock committed
72
73
    clFFT_OUT_OF_PLACE,
    clFFT_IN_PLACE,
74
}clFFT_TestType;
75

76
77
typedef struct
{
Oliver Bock's avatar
Oliver Bock committed
78
79
    double real;
    double imag;
80
}clFFT_ComplexDouble;
Oliver Bock's avatar
Oliver Bock committed
81

82
83
typedef struct
{
Oliver Bock's avatar
Oliver Bock committed
84
85
    double *real;
    double *imag;
86
87
88
89
90
91
}clFFT_SplitComplexDouble;

cl_device_id     device_id;
cl_context       context;
cl_command_queue queue;

92
#ifdef __APPLE__
93
94
95
96
double subtractTimes( uint64_t endTime, uint64_t startTime )
{
    uint64_t difference = endTime - startTime;
    static double conversion = 0.0;
Oliver Bock's avatar
Oliver Bock committed
97

98
99
100
101
    if( conversion == 0.0 )
    {
        mach_timebase_info_data_t info;
        kern_return_t err = mach_timebase_info( &info );
Oliver Bock's avatar
Oliver Bock committed
102

Oliver Bock's avatar
Oliver Bock committed
103
        //Convert the timebase into seconds
104
        if( err == 0  )
Oliver Bock's avatar
Oliver Bock committed
105
            conversion = 1e-9 * (double) info.numer / (double) info.denom;
106
    }
Oliver Bock's avatar
Oliver Bock committed
107

108
109
    return conversion * (double) difference;
}
110
#endif
111

112
#ifdef __APPLE__
Oliver Bock's avatar
Oliver Bock committed
113
void computeReferenceF(clFFT_SplitComplex *out, clFFT_Dim3 n,
Oliver Bock's avatar
Oliver Bock committed
114
                      unsigned int batchSize, clFFT_Dimension dim, clFFT_Direction dir)
115
{
Oliver Bock's avatar
Oliver Bock committed
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
    FFTSetup plan_vdsp;
    DSPSplitComplex out_vdsp;
    FFTDirection dir_vdsp = dir == clFFT_Forward ? FFT_FORWARD : FFT_INVERSE;

    unsigned int i, j, k;
    unsigned int stride;
    unsigned int log2Nx = (unsigned int) log2(n.x);
    unsigned int log2Ny = (unsigned int) log2(n.y);
    unsigned int log2Nz = (unsigned int) log2(n.z);
    unsigned int log2N;

    log2N = log2Nx;
    log2N = log2N > log2Ny ? log2N : log2Ny;
    log2N = log2N > log2Nz ? log2N : log2Nz;

    plan_vdsp = vDSP_create_fftsetup(log2N, 2);

    switch(dim)
    {
        case clFFT_1D:

            for(i = 0; i < batchSize; i++)
            {
                stride = i * n.x;
                out_vdsp.realp  = out->real  + stride;
                out_vdsp.imagp  = out->imag  + stride;

                vDSP_fft_zip(plan_vdsp, &out_vdsp, 1, log2Nx, dir_vdsp);
            }
            break;

        case clFFT_2D:

            for(i = 0; i < batchSize; i++)
            {
                for(j = 0; j < n.y; j++)
                {
                    stride = j * n.x + i * n.x * n.y;
                    out_vdsp.realp = out->real + stride;
                    out_vdsp.imagp = out->imag + stride;

                    vDSP_fft_zip(plan_vdsp, &out_vdsp, 1, log2Nx, dir_vdsp);
                }
            }
            for(i = 0; i < batchSize; i++)
            {
                for(j = 0; j < n.x; j++)
                {
                    stride = j + i * n.x  * n.y;
                    out_vdsp.realp = out->real + stride;
                    out_vdsp.imagp = out->imag + stride;

                    vDSP_fft_zip(plan_vdsp, &out_vdsp, n.x, log2Ny, dir_vdsp);
                }
            }
            break;

        case clFFT_3D:

            for(i = 0; i < batchSize; i++)
            {
                for(j = 0; j < n.z; j++)
                {
                    for(k = 0; k < n.y; k++)
                    {
                        stride = k * n.x + j * n.x * n.y + i * n.x * n.y * n.z;
                        out_vdsp.realp = out->real + stride;
                        out_vdsp.imagp = out->imag + stride;

                        vDSP_fft_zip(plan_vdsp, &out_vdsp, 1, log2Nx, dir_vdsp);
                    }
                }
            }
            for(i = 0; i < batchSize; i++)
            {
                for(j = 0; j < n.z; j++)
                {
                    for(k = 0; k < n.x; k++)
                    {
                        stride = k + j * n.x * n.y + i * n.x * n.y * n.z;
                        out_vdsp.realp = out->real + stride;
                        out_vdsp.imagp = out->imag + stride;

                        vDSP_fft_zip(plan_vdsp, &out_vdsp, n.x, log2Ny, dir_vdsp);
                    }
                }
            }
            for(i = 0; i < batchSize; i++)
            {
                for(j = 0; j < n.y; j++)
                {
                    for(k = 0; k < n.x; k++)
                    {
                        stride = k + j * n.x + i * n.x * n.y * n.z;
                        out_vdsp.realp = out->real + stride;
                        out_vdsp.imagp = out->imag + stride;

                        vDSP_fft_zip(plan_vdsp, &out_vdsp, n.x*n.y, log2Nz, dir_vdsp);
                    }
                }
            }
            break;
    }

    vDSP_destroy_fftsetup(plan_vdsp);
221
}
222
#endif
223

224
#ifdef __APPLE__
Oliver Bock's avatar
Oliver Bock committed
225
void computeReferenceD(clFFT_SplitComplexDouble *out, clFFT_Dim3 n,
Oliver Bock's avatar
Oliver Bock committed
226
                      unsigned int batchSize, clFFT_Dimension dim, clFFT_Direction dir)
227
{
Oliver Bock's avatar
Oliver Bock committed
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
    FFTSetupD plan_vdsp;
    DSPDoubleSplitComplex out_vdsp;
    FFTDirection dir_vdsp = dir == clFFT_Forward ? FFT_FORWARD : FFT_INVERSE;

    unsigned int i, j, k;
    unsigned int stride;
    unsigned int log2Nx = (int) log2(n.x);
    unsigned int log2Ny = (int) log2(n.y);
    unsigned int log2Nz = (int) log2(n.z);
    unsigned int log2N;

    log2N = log2Nx;
    log2N = log2N > log2Ny ? log2N : log2Ny;
    log2N = log2N > log2Nz ? log2N : log2Nz;

    plan_vdsp = vDSP_create_fftsetupD(log2N, 2);

    switch(dim)
    {
        case clFFT_1D:

            for(i = 0; i < batchSize; i++)
            {
                stride = i * n.x;
                out_vdsp.realp  = out->real  + stride;
                out_vdsp.imagp  = out->imag  + stride;

                vDSP_fft_zipD(plan_vdsp, &out_vdsp, 1, log2Nx, dir_vdsp);
            }
            break;

        case clFFT_2D:

            for(i = 0; i < batchSize; i++)
            {
                for(j = 0; j < n.y; j++)
                {
                    stride = j * n.x + i * n.x * n.y;
                    out_vdsp.realp = out->real + stride;
                    out_vdsp.imagp = out->imag + stride;

                    vDSP_fft_zipD(plan_vdsp, &out_vdsp, 1, log2Nx, dir_vdsp);
                }
            }
            for(i = 0; i < batchSize; i++)
            {
                for(j = 0; j < n.x; j++)
                {
                    stride = j + i * n.x  * n.y;
                    out_vdsp.realp = out->real + stride;
                    out_vdsp.imagp = out->imag + stride;

                    vDSP_fft_zipD(plan_vdsp, &out_vdsp, n.x, log2Ny, dir_vdsp);
                }
            }
            break;

        case clFFT_3D:

            for(i = 0; i < batchSize; i++)
            {
                for(j = 0; j < n.z; j++)
                {
                    for(k = 0; k < n.y; k++)
                    {
                        stride = k * n.x + j * n.x * n.y + i * n.x * n.y * n.z;
                        out_vdsp.realp = out->real + stride;
                        out_vdsp.imagp = out->imag + stride;

                        vDSP_fft_zipD(plan_vdsp, &out_vdsp, 1, log2Nx, dir_vdsp);
                    }
                }
            }
            for(i = 0; i < batchSize; i++)
            {
                for(j = 0; j < n.z; j++)
                {
                    for(k = 0; k < n.x; k++)
                    {
                        stride = k + j * n.x * n.y + i * n.x * n.y * n.z;
                        out_vdsp.realp = out->real + stride;
                        out_vdsp.imagp = out->imag + stride;

                        vDSP_fft_zipD(plan_vdsp, &out_vdsp, n.x, log2Ny, dir_vdsp);
                    }
                }
            }
            for(i = 0; i < batchSize; i++)
            {
                for(j = 0; j < n.y; j++)
                {
                    for(k = 0; k < n.x; k++)
                    {
                        stride = k + j * n.x + i * n.x * n.y * n.z;
                        out_vdsp.realp = out->real + stride;
                        out_vdsp.imagp = out->imag + stride;

                        vDSP_fft_zipD(plan_vdsp, &out_vdsp, n.x*n.y, log2Nz, dir_vdsp);
                    }
                }
            }
            break;
    }

    vDSP_destroy_fftsetupD(plan_vdsp);
333
}
334
#endif
335
336
337

double complexNormSq(clFFT_ComplexDouble a)
{
Oliver Bock's avatar
Oliver Bock committed
338
    return (a.real * a.real + a.imag * a.imag);
339
340
341
342
}

double computeL2Error(clFFT_SplitComplex *data, clFFT_SplitComplexDouble *data_ref, int n, int batchSize, double *max_diff, double *min_diff)
{
Oliver Bock's avatar
Oliver Bock committed
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
    int i, j;
    double avg_norm = 0.0;
    *max_diff = 0.0;
    *min_diff = 0x1.0p1000;

    for(j = 0; j < batchSize; j++)
    {
        double norm_ref = 0.0;
        double norm = 0.0;
        for(i = 0; i < n; i++)
        {
            int index = j * n + i;
            clFFT_ComplexDouble diff = (clFFT_ComplexDouble) { data_ref->real[index] - data->real[index], data_ref->imag[index] - data->imag[index] };
            double norm_tmp = complexNormSq(diff);
            norm += norm_tmp;
            norm_ref += (data_ref->real[index] * data_ref->real[index] + data_ref->imag[index] * data_ref->imag[index]);
        }
        double curr_norm = sqrt( norm / norm_ref ) / FLT_EPSILON;
        avg_norm += curr_norm;
        *max_diff = *max_diff < curr_norm ? curr_norm : *max_diff;
        *min_diff = *min_diff > curr_norm ? curr_norm : *min_diff;
    }

    return avg_norm / batchSize;
367
368
369
370
}

void convertInterleavedToSplit(clFFT_SplitComplex *result_split, clFFT_Complex *data_cl, int length)
{
Oliver Bock's avatar
Oliver Bock committed
371
372
373
374
375
    int i;
    for(i = 0; i < length; i++) {
        result_split->real[i] = data_cl[i].real;
        result_split->imag[i] = data_cl[i].imag;
    }
376
377
}

Oliver Bock's avatar
Oliver Bock committed
378
int runTest(clFFT_Dim3 n, int batchSize, clFFT_Direction dir, clFFT_Dimension dim,
Oliver Bock's avatar
Oliver Bock committed
379
            clFFT_DataFormat dataFormat, int numIter, clFFT_TestType testType)
Oliver Bock's avatar
Oliver Bock committed
380
{
Oliver Bock's avatar
Oliver Bock committed
381
382
    cl_int err = CL_SUCCESS;
    int iter;
383
384

#ifdef __APPLE__
Oliver Bock's avatar
Oliver Bock committed
385
386
    double t;
    uint64_t t0, t1;
387

Oliver Bock's avatar
Oliver Bock committed
388
389
390
    int mx = log2(n.x);
    int my = log2(n.y);
    int mz = log2(n.z);
391

Oliver Bock's avatar
Oliver Bock committed
392
    double gflops = 5e-9 * ((double)mx + (double)my + (double)mz) * (double)n.x * (double)n.y * (double)n.z * (double)batchSize * (double)numIter;
393
394
#endif

Oliver Bock's avatar
Oliver Bock committed
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
    int length = n.x * n.y * n.z * batchSize;

    clFFT_SplitComplex data_i_split = (clFFT_SplitComplex) { NULL, NULL };
    clFFT_SplitComplex data_cl_split = (clFFT_SplitComplex) { NULL, NULL };
    clFFT_Complex *data_i = NULL;
    clFFT_Complex *data_cl = NULL;
    clFFT_SplitComplexDouble data_iref = (clFFT_SplitComplexDouble) { NULL, NULL };
    clFFT_SplitComplexDouble data_oref = (clFFT_SplitComplexDouble) { NULL, NULL };

    clFFT_Plan plan = NULL;
    cl_mem data_in = NULL;
    cl_mem data_out = NULL;
    cl_mem data_in_real = NULL;
    cl_mem data_in_imag = NULL;
    cl_mem data_out_real = NULL;
    cl_mem data_out_imag = NULL;

    if(dataFormat == clFFT_SplitComplexFormat) {
        data_i_split.real     = (float *) malloc(sizeof(float) * length);
        data_i_split.imag     = (float *) malloc(sizeof(float) * length);
        data_cl_split.real    = (float *) malloc(sizeof(float) * length);
        data_cl_split.imag    = (float *) malloc(sizeof(float) * length);
        if(!data_i_split.real || !data_i_split.imag || !data_cl_split.real || !data_cl_split.imag)
        {
            err = -1;
            log_error("Out-of-Resources\n");
            goto cleanup;
        }
    }
    else {
        data_i  = (clFFT_Complex *) malloc(sizeof(clFFT_Complex)*length);
        data_cl = (clFFT_Complex *) malloc(sizeof(clFFT_Complex)*length);
        if(!data_i || !data_cl)
        {
            err = -2;
            log_error("Out-of-Resouces\n");
            goto cleanup;
        }
    }

    data_iref.real   = (double *) malloc(sizeof(double) * length);
    data_iref.imag   = (double *) malloc(sizeof(double) * length);
    data_oref.real   = (double *) malloc(sizeof(double) * length);
    data_oref.imag   = (double *) malloc(sizeof(double) * length);
    if(!data_iref.real || !data_iref.imag || !data_oref.real || !data_oref.imag)
    {
        err = -3;
        log_error("Out-of-Resources\n");
        goto cleanup;
    }

    int i;
    if(dataFormat == clFFT_SplitComplexFormat) {
        for(i = 0; i < length; i++)
        {
            data_i_split.real[i] = 2.0f * (float) rand() / (float) RAND_MAX - 1.0f;
            data_i_split.imag[i] = 2.0f * (float) rand() / (float) RAND_MAX - 1.0f;
            data_cl_split.real[i] = 0.0f;
            data_cl_split.imag[i] = 0.0f;
            data_iref.real[i] = data_i_split.real[i];
            data_iref.imag[i] = data_i_split.imag[i];
            data_oref.real[i] = data_iref.real[i];
            data_oref.imag[i] = data_iref.imag[i];
        }
    }
    else {
        for(i = 0; i < length; i++)
        {
            data_i[i].real = 2.0f * (float) rand() / (float) RAND_MAX - 1.0f;
            data_i[i].imag = 2.0f * (float) rand() / (float) RAND_MAX - 1.0f;
            data_cl[i].real = 0.0f;
            data_cl[i].imag = 0.0f;
            data_iref.real[i] = data_i[i].real;
            data_iref.imag[i] = data_i[i].imag;
            data_oref.real[i] = data_iref.real[i];
            data_oref.imag[i] = data_iref.imag[i];
        }
    }

    plan = clFFT_CreatePlan( context, n, dim, dataFormat, &err );
    if(!plan || err)
    {
        log_error("clFFT_CreatePlan failed\n");
        goto cleanup;
    }

    //clFFT_DumpPlan(plan, stdout);

    if(dataFormat == clFFT_SplitComplexFormat)
    {
        data_in_real = clCreateBuffer(context, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR, length*sizeof(float), data_i_split.real, &err);
        if(!data_in_real || err)
        {
            log_error("clCreateBuffer failed\n");
            goto cleanup;
        }

        data_in_imag = clCreateBuffer(context, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR, length*sizeof(float), data_i_split.imag, &err);
        if(!data_in_imag || err)
        {
            log_error("clCreateBuffer failed\n");
            goto cleanup;
        }

        if(testType == clFFT_OUT_OF_PLACE)
        {
            data_out_real = clCreateBuffer(context, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR, length*sizeof(float), data_cl_split.real, &err);
            if(!data_out_real || err)
            {
                log_error("clCreateBuffer failed\n");
                goto cleanup;
            }

            data_out_imag = clCreateBuffer(context, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR, length*sizeof(float), data_cl_split.imag, &err);
            if(!data_out_imag || err)
            {
                log_error("clCreateBuffer failed\n");
                goto cleanup;
            }
        }
        else
        {
            data_out_real = data_in_real;
            data_out_imag = data_in_imag;
        }
    }
    else
    {
        data_in = clCreateBuffer(context, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR, length*sizeof(float)*2, data_i, &err);
        if(!data_in)
        {
            log_error("clCreateBuffer failed\n");
            goto cleanup;
        }
        if(testType == clFFT_OUT_OF_PLACE)
        {
            data_out = clCreateBuffer(context, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR, length*sizeof(float)*2, data_cl, &err);
            if(!data_out)
            {
                log_error("clCreateBuffer failed\n");
                goto cleanup;
            }
        }
        else
            data_out = data_in;
    }


    err = CL_SUCCESS;
544
545

#ifdef __APPLE__
Oliver Bock's avatar
Oliver Bock committed
546
    t0 = mach_absolute_time();
547
#endif
Oliver Bock's avatar
Oliver Bock committed
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
    if(dataFormat == clFFT_SplitComplexFormat)
    {
        for(iter = 0; iter < numIter; iter++)
            err |= clFFT_ExecutePlannar(queue, plan, batchSize, dir, data_in_real, data_in_imag, data_out_real, data_out_imag, 0, NULL, NULL);
    }
    else
    {
        for(iter = 0; iter < numIter; iter++)
            err |= clFFT_ExecuteInterleaved(queue, plan, batchSize, dir, data_in, data_out, 0, NULL, NULL);
    }

    err |= clFinish(queue);

    if(err)
    {
        log_error("clFFT_Execute\n");
        goto cleanup;
    }
566
567

#ifdef __APPLE__
Oliver Bock's avatar
Oliver Bock committed
568
569
570
571
572
    t1 = mach_absolute_time();
    t = subtractTimes(t1, t0);
    char temp[100];
    sprintf(temp, "GFlops achieved for n = (%d, %d, %d), batchsize = %d", n.x, n.y, n.z, batchSize);
    log_perf(gflops / (float) t, 1, "GFlops/s", "%s", temp);
573
#endif
574

Oliver Bock's avatar
Oliver Bock committed
575
576
577
578
579
580
581
582
583
584
585
586
587
    if(dataFormat == clFFT_SplitComplexFormat)
    {
        err |= clEnqueueReadBuffer(queue, data_out_real, CL_TRUE, 0, length*sizeof(float), data_cl_split.real, 0, NULL, NULL);
        err |= clEnqueueReadBuffer(queue, data_out_imag, CL_TRUE, 0, length*sizeof(float), data_cl_split.imag, 0, NULL, NULL);
    }
    else
    {
        err |= clEnqueueReadBuffer(queue, data_out, CL_TRUE, 0, length*sizeof(float)*2, data_cl, 0, NULL, NULL);
    }

    if(err)
    {
        log_error("clEnqueueReadBuffer failed\n");
588
        goto cleanup;
Oliver Bock's avatar
Oliver Bock committed
589
    }
590

591
#ifdef __APPLE__
Oliver Bock's avatar
Oliver Bock committed
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
    computeReferenceD(&data_oref, n, batchSize, dim, dir);

    double diff_avg, diff_max, diff_min;
    if(dataFormat == clFFT_SplitComplexFormat) {
        diff_avg = computeL2Error(&data_cl_split, &data_oref, n.x*n.y*n.z, batchSize, &diff_max, &diff_min);
        if(diff_avg > eps_avg)
            log_error("Test failed (n=(%d, %d, %d), batchsize=%d): %s Test: rel. L2-error = %f eps (max=%f eps, min=%f eps)\n", n.x, n.y, n.z, batchSize, (testType == clFFT_OUT_OF_PLACE) ? "out-of-place" : "in-place", diff_avg, diff_max, diff_min);
        else
            log_info("Test passed (n=(%d, %d, %d), batchsize=%d): %s Test: rel. L2-error = %f eps (max=%f eps, min=%f eps)\n", n.x, n.y, n.z, batchSize, (testType == clFFT_OUT_OF_PLACE) ? "out-of-place" : "in-place", diff_avg, diff_max, diff_min);
    }
    else {
        clFFT_SplitComplex result_split;
        result_split.real = (float *) malloc(length*sizeof(float));
        result_split.imag = (float *) malloc(length*sizeof(float));
        convertInterleavedToSplit(&result_split, data_cl, length);
        diff_avg = computeL2Error(&result_split, &data_oref, n.x*n.y*n.z, batchSize, &diff_max, &diff_min);

        if(diff_avg > eps_avg)
            log_error("Test failed (n=(%d, %d, %d), batchsize=%d): %s Test: rel. L2-error = %f eps (max=%f eps, min=%f eps)\n", n.x, n.y, n.z, batchSize, (testType == clFFT_OUT_OF_PLACE) ? "out-of-place" : "in-place", diff_avg, diff_max, diff_min);
        else
            log_info("Test passed (n=(%d, %d, %d), batchsize=%d): %s Test: rel. L2-error = %f eps (max=%f eps, min=%f eps)\n", n.x, n.y, n.z, batchSize, (testType == clFFT_OUT_OF_PLACE) ? "out-of-place" : "in-place", diff_avg, diff_max, diff_min);
        free(result_split.real);
        free(result_split.imag);
    }
616
617
#endif

618
cleanup:
Oliver Bock's avatar
Oliver Bock committed
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
    clFFT_DestroyPlan(plan);
    if(dataFormat == clFFT_SplitComplexFormat)
    {
        if(data_i_split.real)
            free(data_i_split.real);
        if(data_i_split.imag)
            free(data_i_split.imag);
        if(data_cl_split.real)
            free(data_cl_split.real);
        if(data_cl_split.imag)
            free(data_cl_split.imag);

        if(data_in_real)
            clReleaseMemObject(data_in_real);
        if(data_in_imag)
            clReleaseMemObject(data_in_imag);
        if(data_out_real && testType == clFFT_OUT_OF_PLACE)
            clReleaseMemObject(data_out_real);
        if(data_out_imag && clFFT_OUT_OF_PLACE)
            clReleaseMemObject(data_out_imag);
    }
    else
    {
        if(data_i)
            free(data_i);
        if(data_cl)
            free(data_cl);

        if(data_in)
            clReleaseMemObject(data_in);
        if(data_out && testType == clFFT_OUT_OF_PLACE)
            clReleaseMemObject(data_out);
    }

    if(data_iref.real)
        free(data_iref.real);
    if(data_iref.imag)
        free(data_iref.imag);
    if(data_oref.real)
        free(data_oref.real);
    if(data_oref.imag)
        free(data_oref.imag);

    return err;
663
664
665
}

bool ifLineCommented(const char *line) {
Oliver Bock's avatar
Oliver Bock committed
666
667
668
669
670
671
672
    const char *Line = line;
    while(*Line != '\0')
        if((*Line == '/') && (*(Line + 1) == '/'))
            return true;
        else
            Line++;
    return false;
673
674
675
676
}

cl_device_type getGlobalDeviceType()
{
Oliver Bock's avatar
Oliver Bock committed
677
678
679
680
681
682
683
684
685
686
687
688
689
690
    char *force_cpu = getenv( "CL_DEVICE_TYPE" );
    if( force_cpu != NULL )
    {
        if( strcmp( force_cpu, "gpu" ) == 0 || strcmp( force_cpu, "CL_DEVICE_TYPE_GPU" ) == 0 )
            return CL_DEVICE_TYPE_GPU;
        else if( strcmp( force_cpu, "cpu" ) == 0 || strcmp( force_cpu, "CL_DEVICE_TYPE_CPU" ) == 0 )
            return CL_DEVICE_TYPE_CPU;
        else if( strcmp( force_cpu, "accelerator" ) == 0 || strcmp( force_cpu, "CL_DEVICE_TYPE_ACCELERATOR" ) == 0 )
            return CL_DEVICE_TYPE_ACCELERATOR;
        else if( strcmp( force_cpu, "CL_DEVICE_TYPE_DEFAULT" ) == 0 )
            return CL_DEVICE_TYPE_DEFAULT;
    }
    // default
    return CL_DEVICE_TYPE_GPU;
691
692
}

Oliver Bock's avatar
Oliver Bock committed
693
void
694
695
notify_callback(const char *errinfo, const void *private_info, size_t cb, void *user_data)
{
696
    printf( "ERROR: %s\n", errinfo );
697
}
698

699
700
701
int
checkMemRequirements(clFFT_Dim3 n, int batchSize, clFFT_TestType testType, cl_ulong gMemSize)
{
Oliver Bock's avatar
Oliver Bock committed
702
703
704
705
706
707
    cl_ulong memReq = (testType == clFFT_OUT_OF_PLACE) ? 3 : 2;
    memReq *= n.x*n.y*n.z*sizeof(clFFT_Complex)*batchSize;
    memReq = memReq/1024/1024;
    if(memReq >= gMemSize)
        return -1;
    return 0;
708
}
Gaurav Khanna's avatar
Gaurav Khanna committed
709

710
int main (int argc, char * const argv[]) {
Oliver Bock's avatar
Oliver Bock committed
711

Oliver Bock's avatar
Oliver Bock committed
712
713
714
715
716
717
718
719
720
721
722
723
724
725
    test_start();

    cl_ulong gMemSize;
    clFFT_Direction dir = clFFT_Forward;
    int numIter = 1;
    clFFT_Dim3 n = { 1024, 1, 1 };
    int batchSize = 1;
    clFFT_DataFormat dataFormat = clFFT_SplitComplexFormat;
    clFFT_Dimension dim = clFFT_1D;
    clFFT_TestType testType = clFFT_OUT_OF_PLACE;
    cl_device_id device_ids[16];

    FILE *paramFile;

726
    cl_int err, status;
Oliver Bock's avatar
Oliver Bock committed
727
728
729
730
731
732
733
734
735
736
    unsigned int num_devices;

    cl_device_type device_type = getGlobalDeviceType();
    if(device_type != CL_DEVICE_TYPE_GPU)
    {
        log_info("Test only supported on DEVICE_TYPE_GPU\n");
        test_finish();
        exit(0);
    }

737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
    cl_uint numPlatforms;
    cl_platform_id platform = NULL;
    status = clGetPlatformIDs(0, NULL, &numPlatforms);
    if(CL_SUCCESS != status) {
        printf("ERROR: clGetPlatformIDs failed with error: %d\n", status);
        return -1;
    }
    if (0 < numPlatforms) {
        cl_platform_id* platforms = new cl_platform_id[numPlatforms];
        status = clGetPlatformIDs(numPlatforms, platforms, NULL);
        if(CL_SUCCESS != status) {
            printf("ERROR: clGetPlatformIDs failed with error: %d\n", status);
            return -1;
        }

        for (unsigned i = 0; i < numPlatforms; ++i) 
        {
            char profile[32] = {0};;
            status = clGetPlatformInfo(platforms[i],
                                       CL_PLATFORM_PROFILE,
                                       sizeof(profile),
                                       profile,
                                       NULL);
            if(CL_SUCCESS != status) {
                printf("ERROR: clGetPlatformInfo failed with error: %d\n", status);
                return -1;
            }

            if (!strcmp(profile, "FULL_PROFILE"))
            {
                platform = platforms[i];
                break;
            }
        }
        delete[] platforms;
    }

    if( NULL == platform) {
        log_error("No valid OpenCL platform found!\n");
        return -1;
    }

    char vendor[128] = {0};
    status = clGetPlatformInfo(platform,
                               CL_PLATFORM_VENDOR,
                               sizeof(vendor),
                               vendor,
                               NULL);
    if(CL_SUCCESS != status) {
        printf("WARN: clGetPlatformInfo failed with error: %d\n", status);
    }
    else {
        printf("INFO: Using OpenCL platform provided by: %s\n", vendor);
    }

    err = clGetDeviceIDs(platform, device_type, sizeof(device_ids), device_ids, &num_devices);
Oliver Bock's avatar
Oliver Bock committed
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
    if(err)
    {
        printf("ERROR: clGetDeviceIDs failed with error: %d\n", err);
        test_finish();
        return -1;
    }

    device_id = NULL;
    unsigned int i = 0;

    if (argc == 3) {
        cl_bool available;
        err = clGetDeviceInfo(device_ids[atoi(argv[2])], CL_DEVICE_AVAILABLE, sizeof(cl_bool), &available, NULL);
        if(err) {
            printf("ERROR: Cannot check device availability of device # %d\n", atoi(argv[2]));
808
                return -1;
Oliver Bock's avatar
Oliver Bock committed
809
810
811
812
813
814
815
816
817
818
        }

        if(available) {
            device_id = device_ids[atoi(argv[2])];
        }
        else {
            char name[200];
            err = clGetDeviceInfo(device_ids[i], CL_DEVICE_NAME, sizeof(name), name, NULL);
            if(err == CL_SUCCESS) {
                printf("ERROR: Device %s not available for compute\n", name);
819
            }
Oliver Bock's avatar
Oliver Bock committed
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
            else {
                printf("ERROR: Device # %d not available for compute\n", atoi(argv[2]));
            }
            return -1;
            }
    }
    else {
        for(i = 0; i < num_devices; i++)
        {
            cl_bool available;
            err = clGetDeviceInfo(device_ids[i], CL_DEVICE_AVAILABLE, sizeof(cl_bool), &available, NULL);
            if(err) {
                printf("ERROR: Cannot check device availability of device # %d. Continuing with next available device...\n", i);
                continue;
            }

            if(available) {
                device_id = device_ids[i];
                break;
            }
            else {
                char name[200];
                err = clGetDeviceInfo(device_ids[i], CL_DEVICE_NAME, sizeof(name), name, NULL);
                if(err == CL_SUCCESS) {
                    printf("INFO: Device %s not available for compute\n", name);
                }
                else {
                    printf("INFO: Device # %d not available for compute\n", i);
                }
            }
        }
    }

    if(!device_id) {
        log_error("None of the devices available for compute ... aborting test\n");
        test_finish();
        return -1;
    }
    else {
        char name[200];
        err = clGetDeviceInfo(device_id, CL_DEVICE_NAME, sizeof(name), name, NULL);
        if(err == CL_SUCCESS) {
            printf("INFO: Using device %s...\n", name);
        }
        else {
            printf("INFO: Using device # %d...\n", i);
        }
    }

869
870
871
    cl_context_properties ctxProps[3] = {CL_CONTEXT_PLATFORM, (cl_context_properties) platform, 0};

    context = clCreateContext(ctxProps, 1, &device_id, NULL, NULL, &err);
Oliver Bock's avatar
Oliver Bock committed
872
873
874
875
876
877
    if(!context || err)
    {
        log_error("clCreateContext failed\n");
        test_finish();
        return -1;
    }
Oliver Bock's avatar
Oliver Bock committed
878

879
880
    queue = clCreateCommandQueue(context, device_id, 0, &err);
    if(!queue || err)
Oliver Bock's avatar
Oliver Bock committed
881
    {
882
        log_error("clCreateCommandQueue() failed.\n");
Oliver Bock's avatar
Oliver Bock committed
883
        clReleaseContext(context);
884
885
        test_finish();
        return -1;
Oliver Bock's avatar
Oliver Bock committed
886
887
    }

Oliver Bock's avatar
Oliver Bock committed
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
    err = clGetDeviceInfo(device_id, CL_DEVICE_GLOBAL_MEM_SIZE, sizeof(cl_ulong), &gMemSize, NULL);
    if(err)
    {
        log_error("Failed to get global mem size\n");
        clReleaseContext(context);
        clReleaseCommandQueue(queue);
        test_finish();
        return -2;
    }

    gMemSize /= (1024*1024);

    char delim[] = " \n";
    char tmpStr[100];
    char line[200];
    char *param, *val;
    int total_errors = 0;
    if(argc == 1) {
        log_error("Need file name with list of parameters to run the test\n");
        test_finish();
        return -1;
    }

    if(argc >= 2) { // arguments are supplied in a file with arguments for a single run are all on the same line
        paramFile = fopen(argv[1], "r");
        if(!paramFile) {
            log_error("Cannot open the parameter file\n");
            clReleaseContext(context);
            clReleaseCommandQueue(queue);
            test_finish();
            return -3;
        }
        while(fgets(line, 199, paramFile)) {
            if(!strcmp(line, "") || !strcmp(line, "\n") || ifLineCommented(line))
                continue;
            param = strtok(line, delim);
            while(param) {
                val = strtok(NULL, delim);
                if(!strcmp(param, "-n")) {
                    sscanf(val, "%d", &n.x);
                    val = strtok(NULL, delim);
                    sscanf(val, "%d", &n.y);
                    val = strtok(NULL, delim);
                    sscanf(val, "%d", &n.z);
                }
                else if(!strcmp(param, "-batchsize"))
                    sscanf(val, "%d", &batchSize);
                else if(!strcmp(param, "-dir")) {
                    sscanf(val, "%s", tmpStr);
                    if(!strcmp(tmpStr, "forward"))
                        dir = clFFT_Forward;
                    else if(!strcmp(tmpStr, "inverse"))
                        dir = clFFT_Inverse;
                }
                else if(!strcmp(param, "-dim")) {
                    sscanf(val, "%s", tmpStr);
                    if(!strcmp(tmpStr, "1D"))
                        dim = clFFT_1D;
                    else if(!strcmp(tmpStr, "2D"))
                        dim = clFFT_2D;
                    else if(!strcmp(tmpStr, "3D"))
                        dim = clFFT_3D;
                }
                else if(!strcmp(param, "-format")) {
                    sscanf(val, "%s", tmpStr);
                    if(!strcmp(tmpStr, "plannar"))
                        dataFormat = clFFT_SplitComplexFormat;
                    else if(!strcmp(tmpStr, "interleaved"))
                        dataFormat = clFFT_InterleavedComplexFormat;
                }
                else if(!strcmp(param, "-numiter"))
                    sscanf(val, "%d", &numIter);
                else if(!strcmp(param, "-testtype")) {
                    sscanf(val, "%s", tmpStr);
                    if(!strcmp(tmpStr, "out-of-place"))
                        testType = clFFT_OUT_OF_PLACE;
                    else if(!strcmp(tmpStr, "in-place"))
                        testType = clFFT_IN_PLACE;
                }
                param = strtok(NULL, delim);
            }

            if(checkMemRequirements(n, batchSize, testType, gMemSize)) {
                log_info("This test cannot run because memory requirements canot be met by the available device\n");
                continue;
            }

            err = runTest(n, batchSize, dir, dim, dataFormat, numIter, testType);
            if (err)
                total_errors++;
        }
    }

    clReleaseContext(context);
    clReleaseCommandQueue(queue);

    test_finish();
    return total_errors;
986
}