summaryrefslogtreecommitdiff
path: root/external/clBLAS/src/library/blas/generic/solution_seq.c
blob: cc52c425baf5e071eeb532e14a8f13ab692eb12c (plain)
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
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
221
222
223
224
225
226
227
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
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
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
/* ************************************************************************
 * Copyright 2013 Advanced Micro Devices, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ************************************************************************/


#include <stdlib.h>
#include <string.h>
#include <clblas_stddef.h>

#include "matrix_dims.h"
#include "problem_iter.h"
#include "solution_assert.h"
#include "solution_seq.h"

bool VISIBILITY_HIDDEN isMatrixInImage(MemoryPattern *pattern, MatrixRole mrole);
void VISIBILITY_HIDDEN releaseStepImgs(SolutionStep *step);

static cl_int
enqueueKernel(
    SolutionStep *step,
    const Kernel *kernel,
    cl_uint numEventsInWaitList,
    const cl_event *eventWaitList,
    cl_event *event);

static void
splitSolutionStep(
    SolutionStep *rem,
    SolutionStep *cut,
    SDimComponent component,
    size_t chunk,
    bool backward);

static cl_int
executeImageStep(
    SolutionStep *step,
    cl_uint numEventsInWaitList,
    const cl_event *eventWaitList,
    cl_event *event);

void
freeSolutionSeq(ListHead *seq)
{
    listDoForEachSafe(seq, freeSolutionStep);
    listInitHead(seq);
}

cl_int
executeSolutionSeq(const ListHead *seq)
{
    cl_int err = CL_SUCCESS;
    ListNode *i;
    SolutionStep *step;


    /* Enqueue computing kernels */
    for (i = listNodeFirst(seq); (i != seq) && (err == CL_SUCCESS);
         i = i->next) {

        step = container_of(i, node, SolutionStep);
        if (step->cmdQueue == NULL) {
            continue;
        }

        if (step->args.scimage[0]) {
            err = executeImageStep(step, step->numEventsInWaitList,
                                   step->eventWaitList, step->event);
        }
        else {
			#ifdef DEBUG_2
			printf("enqueueKernel from executreSolutionSeq...\n");
			#endif

            err = enqueueKernel(step,
                                step->kernels[CLBLAS_COMPUTING_KERNEL],
                                step->numEventsInWaitList, step->eventWaitList,
                                step->event);
        }
    }

    return err;
}

/* private functions */

void VISIBILITY_HIDDEN
freeSolutionStep(ListNode *node)
{
    SolutionStep *step = container_of(node, node, SolutionStep);
    int i;

    for (i = 0; i < MAX_CLBLAS_KERNELS_PER_STEP; i++) {
        if (step->kernels[i] != NULL) {
            putKernel(clblasKernelCache, step->kernels[i]);
        }
    }
    releaseStepImgs(step);
    free(step);
}

static cl_int
enqueueKernel(
    SolutionStep *step,
    const Kernel *kernel,
    cl_uint numEventsInWaitList,
    const cl_event *eventWaitList,
    cl_event *event)
{
    cl_int err;
    KernelDesc kernelDesc;
    KernelErrorInfo errInfo;
    MemoryPattern *pattern;
    const CLBLASKernExtra *kextra = (const CLBLASKernExtra*)kernel->extra;
    SubproblemDim subdims[MAX_SUBDIMS];

    step->args.kernType = kextra->kernType;
    pattern = &clblasSolvers[step->funcID].memPatterns[step->patternID];
    kernelDesc.workDim = step->pgran.wgDim;

    memcpy(subdims, step->subdims, sizeof(step->subdims));

    if(NULL==pattern->sops->calcThreads)
    {
        SubproblemDim globDim;
        const PGranularity *pgran;

        pgran = (pattern->nrLevels == 1) ? NULL : &step->pgran;
        kargsToProbDims(&globDim, step->funcID, &step->args, false);

        // fixup dimensions in respect with desired work dispatch order
        if ((step->pgran.wgDim == 2) && pattern->sops->innerDecompositionAxis) {
            if (pattern->sops->innerDecompositionAxis(&step->args) ==
                DECOMP_AXIS_X) {

                /*
                 * these dimensions will not used more anywhere, so we can
                 * just swap them
                 */
                swapDimXY(&subdims[0]);
                swapDimXY(&subdims[1]);
                swapDimXY(&globDim);
            }
        }

        calcGlobalThreads(kernelDesc.globalThreads, subdims,
                          pgran, globDim.y, globDim.x);
    }
    else
    {
		#ifdef DEBUG_2
		printf("calcThreads is defined\n");
		#endif

		pattern->sops->calcThreads(	kernelDesc.globalThreads,
									subdims,
									&step->pgran,
									&step->args,
									kextra);
    }

    //
    // Store the numWGSpawned for this kernel
    // This size can be used by sequence-steps down the line
    // e.g. Reduction of intermediate results of each work group
    //
    step->pgran.numWGSpawned[0] = kernelDesc.globalThreads[0] / step->pgran.wgSize[0];
    step->pgran.numWGSpawned[1] = kernelDesc.globalThreads[1] / step->pgran.wgSize[1];

    kernelDesc.localThreads[0] = step->pgran.wgSize[0];
    kernelDesc.localThreads[1] = step->pgran.wgSize[1];
    kernelDesc.workDim = step->pgran.wgDim;
    kernelDesc.waitListSize = numEventsInWaitList;
    kernelDesc.eventWaitList = eventWaitList;
    kernelDesc.nowait = 1;
    kernelDesc.event = event;
    kernelDesc.needExecTime = 0;

    memset(kernelDesc.args, 0, sizeof(KernelArg) * MAX_KERNEL_ARGS);
    pattern->sops->assignKargs(kernelDesc.args, (const void*)&(step->args),
                               kextra);

    errInfo.wrongArg = 0;
    errInfo.phase = 0;

    /*
     * TODO: log launchClKernel errors
     */
    dumpKernel(step, kextra->kernType);

    err = clCreateKernelsInProgram(kernel->program, 1, &kernelDesc.kernel,
                                   NULL);
    if (err == CL_SUCCESS) {
        err = launchClKernel(&kernelDesc, step->cmdQueue, &errInfo);
        clReleaseKernel(kernelDesc.kernel);
    }

    return err;
}

bool VISIBILITY_HIDDEN
isMatrixInImage(
    MemoryPattern *pattern,
    MatrixRole mrole)
{
    const CLBLASMpatExtra *extra = (const CLBLASMpatExtra*)pattern->extra;
    bool ret = false;

    if (extra != NULL) {
        switch (mrole) {
        case MATRIX_A:
            ret = (extra->mobjA == CLMEM_IMAGE);
            break;
        case MATRIX_B:
            ret = (extra->mobjB == CLMEM_IMAGE);
            break;
        default:
            break;
        }
    }

    return ret;
}

void VISIBILITY_HIDDEN
releaseStepImgs(SolutionStep *step)
{
    int i;
    cl_mem *imgs = step->args.scimage;
    cl_device_id devID = NULL;;

    for (i = 0; (i < 2) && (imgs[i] != NULL); i++) {
        if (devID == NULL) {
            getQueueDevice(step->cmdQueue, &devID);
        }
        putSCImage(devID, imgs[i]);
        imgs[i] = NULL; //to avoid double release
    }
}

static cl_int
executeImageStep(
    SolutionStep *step,
    cl_uint numEventsInWaitList,
    const cl_event *eventWaitList,
    cl_event *event)
{
    SolutionStep outerStep, innerStep, execStep;
    cl_int err = CL_SUCCESS;
    int currImg = 0;
    size_t imgWidth, imgHeight;
    size_t ha, hb;
    size_t maxPanels[MATRIX_ROLES_NUMBER], maxBlocks[MATRIX_ROLES_NUMBER];
    size_t off;
    SubproblemDim wholeDim;
    MatrixRole mrole;
    CLBlasKargs *kargs = &step->args;
    cl_mem *imgs = kargs->scimage;
    MemoryPattern *mempat = &clblasSolvers[step->funcID].memPatterns[step->patternID];
    ProblemIterator innerIter, outerIter;
    int oend = 0, iend;
    SDimComponent comp[2];
    bool backward;
    ListHead doneSteps;
    CLBlasKernelType ktype;

    kargsToProbDims(&wholeDim, step->funcID, kargs, false);
    memset(maxPanels, 0, sizeof(maxPanels));
    memset(maxBlocks, 0, sizeof(maxPanels));

    memcpy(&outerStep, step, sizeof(SolutionStep));
    memcpy(&execStep, step, sizeof(SolutionStep));
    listInitHead(&doneSteps);

    /*
     * Cover the whole problem with dimension which matrix blocks are
     * fitted to images at.
     */

    for (mrole = MATRIX_A; mrole < MATRIX_C; mrole++) {
        if (!isMatrixInImage(mempat, mrole)) {
            continue;
        }

        clGetImageInfo(imgs[currImg], CL_IMAGE_WIDTH, sizeof(imgWidth),
                       &imgWidth, NULL);
        clGetImageInfo(imgs[currImg], CL_IMAGE_HEIGHT, sizeof(imgHeight),
                       &imgHeight, NULL);

        if (step->funcID == CLBLAS_TRSM) {
            maxPanels[mrole] = 0;
            maxBlocks[mrole] = 0;
        } else {
            maxPanels[mrole] = imgHeight / matrBlockHeight(step->subdims, mrole,
                                                           clblasLeft);
        }
        currImg++;
    }

    /*
     * for GEMM function we can take both the matrices as outer, it depends on
     * their sizes and image sizes
     */
    if (step->funcID == CLBLAS_GEMM) {
        size_t dx, dy;

        // FIXME: check which of them use really an image

        ha = matrBlockHeight(&wholeDim, MATRIX_A, clblasLeft);
        hb = matrBlockHeight(&wholeDim, MATRIX_B, clblasLeft);

        dx = maxPanels[MATRIX_B] * matrBlockHeight(step->subdims, MATRIX_B,
                                                   clblasLeft);
        dy = maxPanels[MATRIX_A] * matrBlockHeight(step->subdims, MATRIX_A,
                                                   clblasLeft);

        // hb + (hb*ha)/dx < ha + (ha*hb)/dy
        if ((hb / ha) < (1 + hb / dy) / (1 + ha / dx)) {
            mrole = MATRIX_B;
        }
        else {
            mrole = MATRIX_A;
        }
    }
    else {
        mrole = MATRIX_B;
    }
    /*
     * Let's cover the whole image based step.
     * Pattern iterator is used for traversing
     */
    initProblemIterator(&outerIter, step->funcID, mrole, kargs,
                        maxPanels[mrole], maxBlocks[mrole], step->subdims);
    if (mrole == MATRIX_B) {
        comp[0] = SDIM_X;
        comp[1] = SDIM_Y;
        mrole = MATRIX_A;
    }
    else {
        comp[0] = SDIM_Y;
        comp[1] = SDIM_X;
        mrole = MATRIX_B;
    }
    initProblemIterator(&innerIter, step->funcID, mrole,
                        kargs, maxPanels[mrole], maxBlocks[mrole],
                        step->subdims);
    backward = isIterBackward(&innerIter);

    /*
     * Difference in overflowing checking in the outer and inner loops
     * is due to
     */
    do {
        iteratorReset(&innerIter);
        iend = 0;
        oend = iterateProblem(&outerIter);
        off = iterLastOffset(&outerIter);

        splitSolutionStep(&outerStep, &execStep, comp[0],
                                  off, false);
        if (execStep.funcID == CLBLAS_GEMM) {
            fixupGemmOffsets(&execStep.args, execStep.extraFlags, 0);
        }

        memcpy(&innerStep, &execStep, sizeof(SolutionStep));

        ktype = (comp[0] == SDIM_Y) ? CLBLAS_PREP_A_KERNEL :
                                      CLBLAS_PREP_B_KERNEL;

        if (execStep.kernels[ktype] != NULL) {
            err = enqueueKernel(&execStep, execStep.kernels[ktype],
                                numEventsInWaitList, eventWaitList, event);
            if (err != CL_SUCCESS) {
                 break;
            }
        }

        do {
            iend = iterateProblem(&innerIter);
            off = iterLastOffset(&innerIter);
            splitSolutionStep(&innerStep, &execStep,
                              comp[1], off, backward);
            if (execStep.funcID == CLBLAS_GEMM) {
                fixupGemmOffsets(&execStep.args, execStep.extraFlags, 0);
            }

            assertImageSubstep(step, &execStep, &doneSteps);

            ktype = (comp[1] == SDIM_Y) ? CLBLAS_PREP_A_KERNEL :
                                          CLBLAS_PREP_B_KERNEL;
            if (execStep.kernels[ktype] != NULL) {
                err = enqueueKernel(&execStep, execStep.kernels[ktype],
                                    numEventsInWaitList, eventWaitList, event);
            }
            if (err == CL_SUCCESS) {
                err = enqueueKernel(&execStep,
                                    execStep.kernels[CLBLAS_COMPUTING_KERNEL],
                                    numEventsInWaitList, eventWaitList,
                                    event);
            }
        } while (!iend && (err == CL_SUCCESS));
    } while (!oend && (err == CL_SUCCESS));

    if (err == CL_SUCCESS) {
        assertImageStep(step, &doneSteps);
    }
    releaseImageAssertion(&doneSteps);

    return err;
}

static void
splitSolutionStep(
    SolutionStep *rem,
    SolutionStep *cut,
    SDimComponent component,
    size_t chunk,
    bool backward)
{
    SubproblemDim remDim, cutDim;
    SubproblemDim remDimOff, cutDimOff;

    kargsToProbDims(&remDimOff, rem->funcID, &rem->args, true);
    kargsToProbDims(&remDim, rem->funcID, &rem->args, false);
    memcpy(&cutDim, &remDim, sizeof(SubproblemDim));
    memcpy(&cutDimOff, &remDimOff, sizeof(SubproblemDim));

    memcpy(cut, rem, sizeof(SolutionStep));
    if (component == SDIM_Y) {
        if (backward) {
            cutDimOff.y += remDim.y - chunk;
        }
        else {
            remDimOff.y += chunk;
        }
        cutDim.y = chunk;
        remDim.y -= chunk;
    }
    else {
        if (backward) {
            cutDimOff.x += remDim.x - chunk;
        }
        else {
            remDimOff.x += chunk;
        }
        cutDim.x = chunk;
        remDim.x -= chunk;
    }

    probDimsToKargs(&rem->args, rem->funcID, &remDimOff, true);
    probDimsToKargs(&rem->args, rem->funcID, &remDim, false);
    probDimsToKargs(&cut->args, cut->funcID, &cutDimOff, true);
    probDimsToKargs(&cut->args, cut->funcID, &cutDim, false);
}