批改娘 10095. Matrix Calculator (OpenCL)

contents

  1. 1. 題目描述
    1. 1.1. sequence.c
  2. 2. 輸入格式
  3. 3. 輸出格式
  4. 4. 範例輸入 1
  5. 5. 範例輸出 1
  6. 6. 範例輸入 2
  7. 7. 範例輸出 2
  8. 8. 編譯參數
  9. 9. Solution
  10. 10. coarse grain 版本
    1. 10.1. main.c
    2. 10.2. matrix-lib.cl
  11. 11. 作弊版本
    1. 11.1. main.c
    2. 11.2. matrix-lib.cl

題目描述

小明的數學作業要計算方陣,現在請你幫幫他!

題目給定數個 $N \times N$ 的矩陣和 $2$ 小題。

  • $X = AB+CD$
  • $Y = ABE+CDF$

sequence.c

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
#include <stdio.h>
#include <stdint.h>
// #define DEBUG
#define UINT uint32_t
#define MAXN 1024
void multiply(int N, UINT A[][MAXN], UINT B[][MAXN], UINT C[][MAXN]) {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
UINT sum = 0; // overflow, let it go.
for (int k = 0; k < N; k++)
sum += A[i][k] * B[k][j];
C[i][j] = sum;
}
}
}
void add(int N, UINT A[][MAXN], UINT B[][MAXN], UINT C[][MAXN]) {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++)
C[i][j] = A[i][j] + B[i][j];
}
}
void rand_gen(UINT c, int N, UINT A[][MAXN]) {
UINT x = 2, n = N*N;
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
x = (x * x + c + i + j)%n;
A[i][j] = x;
}
}
}
void print_matrix(int N, UINT A[][MAXN]) {
for (int i = 0; i < N; i++) {
fprintf(stderr, "[");
for (int j = 0; j < N; j++)
fprintf(stderr, " %u", A[i][j]);
fprintf(stderr, " ]\n");
}
}
UINT signature(int N, UINT A[][MAXN]) {
UINT h = 0;
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++)
h = (h + A[i][j]) * 2654435761LU;
}
return h;
}
UINT IN[6][MAXN][MAXN], TMP[6][MAXN][MAXN];
int main() {
int N, S[6];
scanf("%d", &N);
for (int i = 0; i < 6; i++) {
scanf("%d", &S[i]);
rand_gen(S[i], N, IN[i]);
}
// AB
multiply(N, IN[0], IN[1], TMP[0]);
// CD
multiply(N, IN[2], IN[3], TMP[1]);
// AB+CD
add(N, TMP[0], TMP[1], TMP[2]);
printf("%u\n", signature(N, TMP[2]));
// ABE
multiply(N, TMP[0], IN[4], TMP[3]);
// CDF
multiply(N, TMP[1], IN[5], TMP[4]);
// ABE+CDF
add(N, TMP[3], TMP[4], TMP[5]);
printf("%u\n", signature(N, TMP[5]));
return 0;
}

輸入格式

測資只有一組,第一行會有一個整數 $N$,表示題目給定 $N \times N$ 矩陣,第二行上會有 $6$ 個整數,分別為矩陣 $A, B, C, D, E, F$ 的生成種子。

  • $1 \le N \le 1024$
  • $0 \le S_i \le 2^{31}$

輸出格式

輸出兩行 $X$ 和 $Y$ 的雜湊值,可參考 sequence.c 的流程。

範例輸入 1

1
2
2
0 1 2 3 4 5
$$A = \begin{bmatrix} 0 & 1\\ 2 & 2 \end{bmatrix}, B = \begin{bmatrix} 1 & 3\\ 3 & 0 \end{bmatrix}, C = \begin{bmatrix} 2 & 3\\ 0 & 0 \end{bmatrix}, D = \begin{bmatrix} 3 & 1\\ 1 & 2 \end{bmatrix}, E = \begin{bmatrix} 0 & 1\\ 2 & 2 \end{bmatrix}, F = \begin{bmatrix} 1 & 3\\ 3 & 0 \end{bmatrix}$$ $$AB = \begin{bmatrix} 3 & 0\\ 8 & 6 \end{bmatrix}, CD = \begin{bmatrix} 9 & 8\\ 0 & 0 \end{bmatrix}, AB+CD = \begin{bmatrix} 12 & 8\\ 8 & 6 \end{bmatrix}\\ ABE = \begin{bmatrix} 0 & 3\\ 12 & 20 \end{bmatrix}, CDF = \begin{bmatrix} 33 & 27\\ 0 & 0 \end{bmatrix}, ABE+CDF = \begin{bmatrix} 33 & 30\\ 12 & 20 \end{bmatrix}$$

範例輸出 1

1
2
2385860290
1374821695

範例輸入 2

1
2
10
0 1 2 3 4 5

範例輸出 2

1
2
617438354
1897844131

編譯參數

1
2
$ gcc -std=c99 -O2 main.c -lm -lOpenCL -fopenmp
$ ./main

Solution

這一題用來設計多個 device 共同合作計算一個矩陣表達式,通常會有兩個面向 fine-grain 或者是 coarse-grain,從 fine-grain 角度看來,只需要針對矩陣劃分成數個區塊,例如 device 0 計算 [0, B], device 1 計算 [B+1, 2B] 等方法。而 coarse-grain 則看起來會像是直接從表達式那裡拆分,有可能會重複計算相同的計算值,這裡就不特別消除。

雖然 OpenCL 提供多個 device 共同合作的平台,藉由 context 建立 buffer,但是他們傳輸還是得透過 CPU 控制,沒辦法直接存取另一個 GPU 的 global memory,但寫起來方便許多。

coarse grain 版本

這個版本會針對計算能力做 scheduling,兩個表達式 $X\;, Y$ 分別拆到兩個裝置上運行,重複計算就不理會。將計算量大的表達式丟到較高運算能力的 GPU 上執行。

main.c

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
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
#include <stdio.h>
#include <assert.h>
#include <inttypes.h>
#include <string.h>
#include <signal.h>
#include <unistd.h>
#include <CL/cl.h>
#include <omp.h>
#define MAXGPU 2
#define MAXN 1024
#define MAXM 26
#define GPULOCAL 64
#define MAXMID 20
uint32_t hostMtx[MAXM][MAXN*MAXN];
int N, binN, M, Q;
char expr[1024];
char clSrcFormat[32767] = "";
char clSrc[32767] = "";
// -- start working with OpenCL
const int clNeedDevCnt = 2;
cl_context clCtx[2];
cl_program clPrg[2];
cl_kernel clKrnAdd[2], clKrnMul[2];
cl_command_queue clQue[2];
cl_mem clMemIn[2][MAXM], clMemMid[2][MAXM*2];
typedef struct Node {
struct Node *l, *r;
int opcode;
uint32_t *hostV;
cl_mem clV;
cl_event event, *waitEvents;
int waitEventsN;
int pid, mid;
long long h;
} Node;
#define CheckFailAndExit(status) \
if (status != CL_SUCCESS) { \
fprintf(stderr, "Error %d: Line %u in file %s\n\n", status, __LINE__, __FILE__), \
destroyGPU(clCtx, clPrg, clKrnAdd, clKrnMul, clQue, clMemIn); \
}
#define clFuncArgs cl_context clCtx[], cl_program clPrg[], cl_kernel clKrnAdd[], \
cl_kernel clKrnMul[], cl_command_queue clQue[], cl_mem clMemIn[][MAXM]
#define clCallFunc clCtx, clPrg, clKrnAdd, clKrnMul, clQue, clMemIn
#define clCallFuncOuter clCtx, clPrg, clKrnAdd, clKrnMul, clQue, clMemIn
void assignGPU(Node *u, int gpuIdx) {
if (u == NULL) return ;
if (u->l == NULL) {
u->hostV = hostMtx[u->mid];
u->clV = clMemIn[gpuIdx][u->mid];
return ;
}
assignGPU(u->l, gpuIdx);
assignGPU(u->r, gpuIdx);
}
Node* parseExpr(int l, int r, char expr[], int procId, clFuncArgs) {
cl_int clStat;
Node *u = (Node *) calloc(1, sizeof(Node));
u->pid = procId;
if (l == r) {
int idx = expr[l] - 'A';
u->hostV = hostMtx[idx];
u->mid = idx;
u->h = 0;
return u;
}
int cnt = 0;
for (int i = l; i <= r; i++) {
if (expr[i] == '(') {
cnt++;
} else if (expr[i] == ')') {
cnt--;
} else if (expr[i] == '+' && cnt == 0) {
u->l = parseExpr(l, i-1, expr, procId, clCallFunc);
u->r = parseExpr(i+1, r, expr, procId, clCallFunc);
u->opcode = '+';
u->h = u->l->h + u->r->h + N;
return u;
}
}
for (int i = l; i <= r; i++) {
if (expr[i] == '(') {
if (cnt == 0 && i != l) {
u->l = parseExpr(l, i-1, expr, procId, clCallFunc);
u->r = parseExpr(i, r, expr, procId, clCallFunc);
u->opcode = '*';
u->h = u->l->h + u->r->h + N*N;
return u;
}
cnt++;
} else if (expr[i] == ')') {
cnt--;
} else if (expr[i] >= 'A' && expr[i] <= 'Z' && cnt == 0 && i != l) {
u->l = parseExpr(l, i-1, expr, procId, clCallFunc);
u->r = parseExpr(i, r, expr, procId, clCallFunc);
u->opcode = '*';
u->h = u->l->h + u->r->h + N*N;
return u;
}
}
free(u);
return parseExpr(l+1, r-1, expr, procId, clCallFunc);
}
uint32_t writeMatrixOut(int N, uint32_t *A) {
uint32_t h = 0;
for (int i = 0; i < N; i++)
for (int j = 0; j < N; j++)
h = (h + A[i*binN + j]) * 2654435761LU;
return h;
}
void destroyGPU(clFuncArgs) {
fprintf(stderr, "Starting Cleanup ...\n\n");
for (int i = 0; i < clNeedDevCnt; i++) {
for (int j = 0; j < M; j++) {
if (clMemIn[i][j])
clReleaseMemObject(clMemIn[i][j]);
}
}
for (int i = 0; i < clNeedDevCnt; i++) {
for (int j = 0; j < MAXMID; j++) {
if (clMemMid[i][j])
clReleaseMemObject(clMemMid[i][j]);
}
}
for (int i = 0; i < clNeedDevCnt; i++) {
if (clKrnAdd[i]) clReleaseKernel(clKrnAdd[i]);
if (clKrnMul[i]) clReleaseKernel(clKrnMul[i]);
if (clPrg[i]) clReleaseProgram(clPrg[i]);
}
for (int i = 0; i < clNeedDevCnt; i++) {
if (clQue[i])
clReleaseCommandQueue(clQue[i]);
}
for (int i = 0; i < clNeedDevCnt; i++) {
if (clCtx[i])
clReleaseContext(clCtx[i]);
}
exit(0);
}
int initAllGPU(char fileName[], clFuncArgs) {
// -- generate kernel code
FILE *codefin = fopen(fileName, "r");
assert(codefin != NULL);
assert(fread(clSrcFormat, 1, 32767, codefin) < 32767);
sprintf(clSrc, clSrcFormat, binN);
size_t clSrcLen = strlen(clSrc);
fclose(codefin);
cl_int clStat;
cl_uint clPlatN, clGPUN, clDevN;
cl_platform_id clPlatID;
cl_device_id clGPUID[MAXGPU];
const char *clSrcPtr = clSrc;
// -- basic OpenCL setup
clGetPlatformIDs(1, &clPlatID, &clPlatN);
clGetDeviceIDs(clPlatID, CL_DEVICE_TYPE_GPU, MAXGPU, clGPUID, &clDevN);
assert(clDevN >= clNeedDevCnt);
for (int i = 0; i < clNeedDevCnt; i++) {
clCtx[i] = clCreateContext(NULL, 1, clGPUID+i, NULL, NULL, &clStat);
CheckFailAndExit(clStat);
}
for (int i = 0; i < clNeedDevCnt; i++) {
clQue[i] = clCreateCommandQueue(clCtx[i], clGPUID[i],
CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE, &clStat);
CheckFailAndExit(clStat);
}
for (int i = 0; i < clNeedDevCnt; i++) {
clPrg[i] = clCreateProgramWithSource(clCtx[i], 1, &clSrcPtr, &clSrcLen, &clStat);
CheckFailAndExit(clStat);
clStat = clBuildProgram(clPrg[i], 1, clGPUID+i, NULL, NULL, NULL);
if (clStat != CL_SUCCESS) {
fprintf(stderr, "Error: Line %u in file %s\n\n", __LINE__, __FILE__);
size_t log_size;
clGetProgramBuildInfo(*clPrg, clGPUID[0],
CL_PROGRAM_BUILD_LOG, 0, NULL, &log_size);
char *program_log = (char *) calloc(log_size+1, sizeof(char));
clGetProgramBuildInfo(*clPrg, clGPUID[0],
CL_PROGRAM_BUILD_LOG, log_size+1, program_log, NULL);
printf("%s", program_log);
free(program_log);
CheckFailAndExit(CL_BUILD_PROGRAM_FAILURE);
}
clKrnAdd[i] = clCreateKernel(clPrg[i], "matrixAdd", &clStat);
CheckFailAndExit(clStat);
clKrnMul[i] = clCreateKernel(clPrg[i], "matrixMul", &clStat);
CheckFailAndExit(clStat);
}
// -- create all buffers
cl_mem_flags clInBuffFlag = CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR;
for (int d = 0; d < clNeedDevCnt; d++) {
for (int i = 0; i < M; i++) {
clMemIn[d][i] = clCreateBuffer(clCtx[d], clInBuffFlag, sizeof(uint32_t)*binN*binN,
hostMtx[i], &clStat);
CheckFailAndExit(clStat);
}
}
for (int d = 0; d < clNeedDevCnt; d++) {
for (int i = 0; i < MAXMID; i++) {
clMemMid[d][i] = clCreateBuffer(clCtx[d], CL_MEM_READ_WRITE,
sizeof(uint32_t)*binN*binN, NULL, &clStat);
CheckFailAndExit(clStat);
}
}
return 1;
}
void GPUmultiply(int N, Node *U, Node *L, Node *R, int devIdx, clFuncArgs) {
cl_int clStat;
size_t globalOffset[] = {0};
size_t globalSize[] = {binN};
size_t localSize[] = {GPULOCAL};
// -- set argument to kernel
clStat = clSetKernelArg(clKrnMul[devIdx], 0, sizeof(cl_mem), &(L->clV));
CheckFailAndExit(clStat);
clStat = clSetKernelArg(clKrnMul[devIdx], 1, sizeof(cl_mem), &(R->clV));
CheckFailAndExit(clStat);
clStat = clSetKernelArg(clKrnMul[devIdx], 2, sizeof(cl_mem), &(U->clV));
CheckFailAndExit(clStat);
// -- find wait events
int waitN = 0, waitCnt = 0;
if (L->event) waitCnt++;
if (R->event) waitCnt++;
cl_event *events = (cl_event*) malloc(sizeof(cl_event) * waitCnt);
if (L->event) events[waitN++] = L->event;
if (R->event) events[waitN++] = R->event;
U->waitEvents = events, U->waitEventsN = waitCnt;
// -- execute
clStat = clEnqueueNDRangeKernel(clQue[devIdx], clKrnMul[devIdx], 1, globalOffset,
globalSize, localSize, U->waitEventsN, U->waitEvents, &(U->event) );
CheckFailAndExit(clStat);
}
void GPUadd(int N, Node *U, Node *L, Node *R, int devIdx, clFuncArgs) {
cl_int clStat;
size_t globalOffset[] = {0};
size_t globalSize[] = {binN*binN};
size_t localSize[] = {1};
// -- set argument to kernel
clStat = clSetKernelArg(clKrnAdd[devIdx], 0, sizeof(cl_mem), &(L->clV));
CheckFailAndExit(clStat);
clStat = clSetKernelArg(clKrnAdd[devIdx], 1, sizeof(cl_mem), &(R->clV));
CheckFailAndExit(clStat);
clStat = clSetKernelArg(clKrnAdd[devIdx], 2, sizeof(cl_mem), &(U->clV));
CheckFailAndExit(clStat);
// -- find wait events
int waitN = 0, waitCnt = 0;
if (L->event) waitCnt++;
if (R->event) waitCnt++;
cl_event *events = (cl_event*) malloc(sizeof(cl_event) * waitCnt);
if (L->event) events[waitN++] = L->event;
if (R->event) events[waitN++] = R->event;
U->waitEvents = events, U->waitEventsN = waitCnt;
// -- execute
clStat = clEnqueueNDRangeKernel(clQue[devIdx], clKrnAdd[devIdx], 1, globalOffset,
globalSize, localSize, U->waitEventsN, U->waitEvents, &(U->event) );
CheckFailAndExit(clStat);
}
int executeGPU(Node *workQue[][128], int workQueSz[], uint32_t resultBuff[], clFuncArgs) {
cl_int clStat;
Node* nodes[2][128];
int offset[2] = {};
#pragma omp parallel for
for (int p = 0; p < clNeedDevCnt; p++) {
for (int q = 0; q < workQueSz[p]; q++) {
// -- flatten binary tree
offset[p] = 0;
nodes[p][offset[p]++] = workQue[p][q];
for (int i = 0; i < offset[p]; i++) {
Node *u = nodes[p][i];
if (u->l != NULL)
nodes[p][offset[p]++] = u->l;
if (u->r != NULL)
nodes[p][offset[p]++] = u->r;
}
// -- execute in order
int reuseId = 0;
for (int i = offset[p]-1; i >= 0; i--) {
Node *u = nodes[p][i];
if (u->l == NULL) // is leaf
continue;
u->clV = clMemMid[p][reuseId++];
if (u->opcode == '*')
GPUmultiply(N, u, u->l, u->r, p, clCallFunc);
else
GPUadd(N, u, u->l, u->r, p, clCallFunc);
}
clFlush(clQue[p]);
clFinish(clQue[p]);
nodes[p][0]->hostV = (uint32_t *) malloc(sizeof(uint32_t)*binN*binN);
int waitN = nodes[p][0]->event != NULL;
clStat = clEnqueueReadBuffer(clQue[p], nodes[p][0]->clV, CL_TRUE, 0,
sizeof(uint32_t)*binN*binN, nodes[p][0]->hostV, waitN,
waitN ? &(nodes[p][0]->event): NULL, NULL);
uint32_t ret = writeMatrixOut(N, nodes[p][0]->hostV);
resultBuff[nodes[p][0]->pid] = ret;
// -- free inner node buffer
for (int i = 0; i < offset[p]; i++) {
Node *u = nodes[p][i];
if (u->l != NULL && u->hostV)
free(u->hostV);
if (u->l != NULL && u->event)
clReleaseEvent(u->event);
if (u->l != NULL && u->waitEvents)
free(u->waitEvents);
free(u);
}
}
}
return 1;
}
void CPUmultiply(int N, uint32_t *A, uint32_t *B, uint32_t *C) {
#pragma omp parallel for
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
uint32_t sum = 0;
for (int k = 0; k < N; k++)
sum += A[i*binN+k] * B[k*binN+j];
C[i*binN+j] = sum;
}
}
}
void CPUadd(int N, uint32_t *A, uint32_t *B, uint32_t *C) {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
C[i*binN+j] = A[i*binN+j] + B[i*binN+j];
}
}
}
int executeCPU(Node *root) {
// -- flatten binary tree
Node* nodes[128];
int offset = 0;
nodes[offset++] = root;
for (int i = 0; i < offset; i++) {
Node *u = nodes[i];
if (u->l != NULL)
nodes[offset++] = u->l;
if (u->r != NULL)
nodes[offset++] = u->r;
}
for (int i = offset-1; i >= 0; i--) {
Node *u = nodes[i];
if (u->l == NULL) // is leaf
continue;
u->hostV = (uint32_t *) calloc(1, sizeof(uint32_t)*binN*binN);
if (u->opcode == '*')
CPUmultiply(N, u->l->hostV, u->r->hostV, u->hostV);
else
CPUadd(N, u->l->hostV, u->r->hostV, u->hostV);
// -- free inner node buffer
if (u->l->l != NULL)
free(u->l->hostV), u->l->hostV = NULL;
if (u->r->l != NULL)
free(u->r->hostV), u->r->hostV = NULL;
}
/*
for (int k = 0; k < M; k++) {
printf("=== Matrix %c ===\n", k + 'A');
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++)
printf("%u ", hostMtx[k][i*N+j]);
puts("");
}
}
*/
/* puts("=== final");
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++)
printf("%u ", nodes[0]->hostV[i*binN+j]);
puts("");
}
*/
uint32_t ret = writeMatrixOut(N, nodes[0]->hostV);
printf("%u\n", ret);
for (int i = 0; i < offset; i++) {
Node *u = nodes[i];
if (u->l != NULL && u->hostV)
free(u->hostV);
free(u);
}
}
int readIn() {
if (scanf("%s", expr) != 1)
return 0;
return 1;
}
int balance_cmp(const void *a, const void *b) {
Node *x = *(Node **) a;
Node *y = *(Node **) b;
if (x->h == y->h) return 0;
if (x->h < y->h) return 1;
return -1;
}
void onStart(clFuncArgs) {
int S[64];
M = 6;
assert(scanf("%d", &N) == 1);
binN = N;
while (binN % GPULOCAL)
binN++;
for (int i = 0; i < M; i++)
assert(scanf("%d", &S[i]) == 1);
#pragma omp parallel for
for (int p = 0; p < M; p++) {
uint32_t x = 2, n = N*N;
memset(hostMtx[p], 0, sizeof(uint32_t)*binN*binN);
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
x = (x * x + S[p] + i + j)%n;
hostMtx[p][i*binN+j] = x;
}
}
}
initAllGPU("matrix-lib.cl", clCallFunc);
Node *procBuff[128];
Q = 2;
for (int i = 0; i < Q; i++) {
if (i == 0) strcpy(expr, "AB+CD");
else strcpy(expr, "ABE+CDF");
int expr_len = strlen(expr);
procBuff[i] = parseExpr(0, expr_len-1, expr, i, clCallFunc);
}
/*
for (int i = 0; i < Q; i++)
executeCPU(procBuff[i]);
return ;
*/
qsort(procBuff, Q, sizeof(Node*), balance_cmp);
long long workload[16] = {};
int workQueSz[2] = {};
uint32_t resultBuff[128];
Node *workQue[2][128];
for (int i = 0; i < Q; i++) {
int mn = 0;
for (int j = 0; j < clNeedDevCnt; j++) {
if (workload[j] < workload[mn])
mn = j;
}
assignGPU(procBuff[i], mn);
workload[mn] += procBuff[i]->h;
workQue[mn][workQueSz[mn]++] = procBuff[i];
}
executeGPU(workQue, workQueSz, resultBuff, clCallFunc);
for (int i = 0; i < Q; i++)
printf("%u\n", resultBuff[i]);
destroyGPU(clCallFunc);
}
void sigHandler(int signo) {
printf("God Bless Me\n");
destroyGPU(clCallFuncOuter);
exit(0);
}
int main(int argc, char *argv[]) {
const char sigErr[] = "I can't catch signal.\n";
if (signal(SIGTRAP, sigHandler) == SIG_ERR)
fprintf(stderr, sigErr);
if (signal(SIGSEGV, sigHandler) == SIG_ERR)
fprintf(stderr, sigErr);
if (signal(SIGILL, sigHandler) == SIG_ERR)
fprintf(stderr, sigErr);
if (signal(SIGFPE, sigHandler) == SIG_ERR)
fprintf(stderr, sigErr);
if (signal(SIGKILL, sigHandler) == SIG_ERR)
fprintf(stderr, sigErr);
if (signal(SIGINT, sigHandler) == SIG_ERR)
fprintf(stderr, sigErr);
onStart(clCallFuncOuter);
return 0;
}

matrix-lib.cl

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
#define N %d
#define CTYPE unsigned int
#define UNLOOP 8
__kernel void matrixAdd(__global CTYPE *in1,
__global CTYPE *in2,
__global CTYPE *out) {
int x = get_global_id(0);
out[x] = in1[x] + in2[x];
}
__kernel void matrixMul(__global CTYPE *in1,
__global CTYPE *in2,
__global CTYPE *out) {
CTYPE rbuf[N];
int r = get_global_id(0);
int localID = get_local_id(0);
int localSz = get_local_size(0);
__local CTYPE cbuf[N];
for (int i = 0; i < N; i++)
rbuf[i] = in1[r * N + i];
for (int c = 0; c < N; c++) {
for (int cr = localID; cr < N; cr += localSz)
cbuf[cr] = in2[cr * N + c];
barrier(CLK_LOCAL_MEM_FENCE);
CTYPE sum = 0;
for (int k = 0; k+UNLOOP-1 < N; k += UNLOOP) {
sum += rbuf[k+0] * cbuf[k+0];
sum += rbuf[k+1] * cbuf[k+1];
sum += rbuf[k+2] * cbuf[k+2];
sum += rbuf[k+3] * cbuf[k+3];
sum += rbuf[k+4] * cbuf[k+4];
sum += rbuf[k+5] * cbuf[k+5];
sum += rbuf[k+6] * cbuf[k+6];
sum += rbuf[k+7] * cbuf[k+7];
}
out[r * N + c] = sum;
}
}

作弊版本

單一個 device 完成,因為 create context 的 overhead 過大,倒不如直接用一個最好的 device 完成所有計算。

main.c

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
#include <stdio.h>
#include <assert.h>
#include <inttypes.h>
#include <string.h>
#include <signal.h>
#include <unistd.h>
#include <CL/cl.h>
#include <omp.h>
#define MAXGPU 1
#define MAXN 1024
#define MAXM 6
#define GPULOCAL 32
#define MAXMID 8
uint32_t hostMtx[MAXM][MAXN*MAXN];
uint32_t hostX[MAXN*MAXN], hostY[MAXN*MAXN];
int N, M, Q;
char clSrcFormat[32767] = "";
char clSrc[32767] = "";
// -- start working with OpenCL
const int clNeedDevCnt = 1;
cl_context clCtx[2];
cl_program clPrg[2];
cl_kernel clKrnAdd[2], clKrnMul[2];
cl_command_queue clQue[2];
cl_mem clMemIn[2][MAXM], clMemMid[2][MAXMID];
#define CheckFailAndExit(status) \
if (status != CL_SUCCESS) { \
fprintf(stderr, "Error %d: Line %u in file %s\n\n", status, __LINE__, __FILE__), \
destroyGPU(clCtx, clPrg, clKrnAdd, clKrnMul, clQue, clMemIn); \
}
#define clFuncArgs cl_context clCtx[], cl_program clPrg[], cl_kernel clKrnAdd[], \
cl_kernel clKrnMul[], cl_command_queue clQue[], cl_mem clMemIn[][MAXM]
#define clCallFunc clCtx, clPrg, clKrnAdd, clKrnMul, clQue, clMemIn
#define clCallFuncOuter clCtx, clPrg, clKrnAdd, clKrnMul, clQue, clMemIn
uint32_t writeMatrixOut(int N, uint32_t *A) {
uint32_t h = 0;
uint32_t *Aend = A + N*N;
for (; A != Aend; A++)
h = (h + *A) * 2654435761LU;
return h;
}
void destroyGPU(clFuncArgs) {
fprintf(stderr, "Starting Cleanup ...\n\n");
for (int i = 0; i < clNeedDevCnt; i++) {
for (int j = 0; j < M; j++) {
if (clMemIn[i][j])
clReleaseMemObject(clMemIn[i][j]);
}
}
for (int i = 0; i < clNeedDevCnt; i++) {
for (int j = 0; j < MAXMID; j++) {
if (clMemMid[i][j])
clReleaseMemObject(clMemMid[i][j]);
}
}
for (int i = 0; i < clNeedDevCnt; i++) {
if (clKrnAdd[i]) clReleaseKernel(clKrnAdd[i]);
if (clKrnMul[i]) clReleaseKernel(clKrnMul[i]);
if (clPrg[i]) clReleaseProgram(clPrg[i]);
}
for (int i = 0; i < clNeedDevCnt; i++) {
if (clQue[i])
clReleaseCommandQueue(clQue[i]);
}
for (int i = 0; i < clNeedDevCnt; i++) {
if (clCtx[i]) clReleaseContext(clCtx[i]);
}
exit(0);
}
int initAllGPU(char fileName[], clFuncArgs) {
// -- generate kernel code
FILE *codefin = fopen(fileName, "r");
assert(codefin != NULL);
assert(fread(clSrcFormat, 1, 32767, codefin) < 32767);
sprintf(clSrc, clSrcFormat, N);
size_t clSrcLen = strlen(clSrc);
fclose(codefin);
cl_int clStat;
cl_uint clPlatN, clGPUN, clDevN;
cl_platform_id clPlatID;
cl_device_id clGPUID[MAXGPU];
const char *clSrcPtr = clSrc;
// -- basic OpenCL setup
clGetPlatformIDs(1, &clPlatID, &clPlatN);
clGetDeviceIDs(clPlatID, CL_DEVICE_TYPE_GPU, MAXGPU, clGPUID, &clDevN);
assert(clDevN >= clNeedDevCnt);
clCtx[0] = clCreateContext(NULL, 1, clGPUID, NULL, NULL, &clStat);
CheckFailAndExit(clStat);
for (int i = 0; i < clNeedDevCnt; i++) {
clQue[i] = clCreateCommandQueue(clCtx[0], clGPUID[i],
/*CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE*/ 0, &clStat);
CheckFailAndExit(clStat);
}
clPrg[0] = clCreateProgramWithSource(clCtx[0], 1, &clSrcPtr, &clSrcLen, &clStat);
CheckFailAndExit(clStat);
clStat = clBuildProgram(clPrg[0], 1, clGPUID, NULL, NULL, NULL);
if (clStat != CL_SUCCESS) {
fprintf(stderr, "Error: Line %u in file %s\n\n", __LINE__, __FILE__);
size_t log_size;
clGetProgramBuildInfo(*clPrg, clGPUID[0],
CL_PROGRAM_BUILD_LOG, 0, NULL, &log_size);
char *program_log = (char *) calloc(log_size+1, sizeof(char));
clGetProgramBuildInfo(*clPrg, clGPUID[0],
CL_PROGRAM_BUILD_LOG, log_size+1, program_log, NULL);
printf("%s", program_log);
free(program_log);
CheckFailAndExit(CL_BUILD_PROGRAM_FAILURE);
}
clKrnAdd[0] = clCreateKernel(clPrg[0], "matrixAdd", &clStat);
CheckFailAndExit(clStat);
clKrnMul[0] = clCreateKernel(clPrg[0], "matrixMul", &clStat);
CheckFailAndExit(clStat);
// -- create all buffers
cl_mem_flags clInBuffFlag = CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR;
for (int j = 0; j < clNeedDevCnt; j++) {
for (int i = 0; i < M; i++) {
clMemIn[j][i] = clCreateBuffer(clCtx[0], clInBuffFlag, sizeof(uint32_t)*N*N,
hostMtx[i], &clStat);
CheckFailAndExit(clStat);
}
}
for (int j = 0; j < clNeedDevCnt; j++) {
for (int i = 0; i < MAXMID; i++) {
clMemMid[j][i] = clCreateBuffer(clCtx[0], CL_MEM_READ_WRITE,
sizeof(uint32_t)*N*N, NULL, &clStat);
CheckFailAndExit(clStat);
}
}
return 1;
}
void GPUmultiply(int N, int waitN, cl_event events[], cl_event *ret_event,
int devIdx, cl_mem *LIN, cl_mem *RIN, cl_mem *OUT, clFuncArgs) {
cl_int clStat;
size_t globalOffset[] = {0};
size_t globalSize[] = {N*N};
size_t localSize[] = {GPULOCAL};
// -- set argument to kernel
clStat = clSetKernelArg(clKrnMul[0], 0, sizeof(cl_mem), LIN);
CheckFailAndExit(clStat);
clStat = clSetKernelArg(clKrnMul[0], 1, sizeof(cl_mem), RIN);
CheckFailAndExit(clStat);
clStat = clSetKernelArg(clKrnMul[0], 2, sizeof(cl_mem), OUT);
CheckFailAndExit(clStat);
// -- execute
clStat = clEnqueueNDRangeKernel(clQue[devIdx], clKrnMul[0], 1, globalOffset,
globalSize, NULL, waitN, events, ret_event);
CheckFailAndExit(clStat);
}
void GPUadd(int N, int waitN, cl_event events[], cl_event *ret_event,
int devIdx, cl_mem *LIN, cl_mem *RIN, cl_mem *OUT, clFuncArgs) {
cl_int clStat;
size_t globalOffset[] = {0};
size_t globalSize[] = {N*N};
// -- set argument to kernel
clStat = clSetKernelArg(clKrnAdd[0], 0, sizeof(cl_mem), LIN);
CheckFailAndExit(clStat);
clStat = clSetKernelArg(clKrnAdd[0], 1, sizeof(cl_mem), RIN);
CheckFailAndExit(clStat);
clStat = clSetKernelArg(clKrnAdd[0], 2, sizeof(cl_mem), OUT);
CheckFailAndExit(clStat);
// -- execute
clStat = clEnqueueNDRangeKernel(clQue[devIdx], clKrnAdd[0], 1, globalOffset,
globalSize, NULL, waitN, events, ret_event);
CheckFailAndExit(clStat);
}
int executeGPU(clFuncArgs) {
cl_int clStat;
cl_event events[4];
// AB
GPUmultiply(N, 0, NULL, &events[0], 0, &clMemIn[0]['A'-'A'], &clMemIn[0]['B'-'A'],
&clMemMid[0][0], clCallFunc);
fprintf(stderr, "AB\n");
// CD
GPUmultiply(N, 0, NULL, &events[1], 0, &clMemIn[0]['C'-'A'], &clMemIn[0]['D'-'A'],
&clMemMid[0][1], clCallFunc);
fprintf(stderr, "CD\n");
// ABE
GPUmultiply(N, 1, &events[0], &events[2], 0, &clMemMid[0][0], &clMemIn[0]['E'-'A'],
&clMemMid[0][2], clCallFunc);
fprintf(stderr, "ABE\n");
// CDF
GPUmultiply(N, 1, &events[1], &events[3], 0, &clMemMid[0][1], &clMemIn[0]['F'-'A'],
&clMemMid[0][3], clCallFunc);
fprintf(stderr, "CDF\n");
// AB+CD
GPUadd(N, 2, &events[0], NULL, 0, &clMemMid[0][0], &clMemMid[0][1], &clMemMid[0][4],
clCallFunc);
fprintf(stderr, "AB+CD\n");
// ABE+CDF
GPUadd(N, 2, &events[2], NULL, 0, &clMemMid[0][2], &clMemMid[0][3], &clMemMid[0][5],
clCallFunc);
fprintf(stderr, "ABE+CDF\n");
clFinish(clQue[0]);
clStat = clEnqueueReadBuffer(clQue[0], clMemMid[0][4], CL_TRUE, 0,
sizeof(uint32_t)*N*N, hostX, 0, NULL, NULL);
CheckFailAndExit(clStat);
clStat = clEnqueueReadBuffer(clQue[0], clMemMid[0][5], CL_TRUE, 0,
sizeof(uint32_t)*N*N, hostY, 0, NULL, NULL);
CheckFailAndExit(clStat);
printf("%u\n", writeMatrixOut(N, hostX));
printf("%u\n", writeMatrixOut(N, hostY));
return 1;
}
void onStart(clFuncArgs) {
int S[64];
assert(scanf("%d", &N) == 1);
M = 6;
for (int i = 0; i < M; i++)
assert(scanf("%d", &S[i]) == 1);
#pragma omp parallel for
for (int p = 0; p < M; p++) {
uint32_t x = 2, n = N*N;
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
x = (x * x + S[p] + i + j)%n;
hostMtx[p][i*N+j] = x;
}
}
}
initAllGPU("matrix-lib.cl", clCallFunc);
executeGPU(clCallFunc);
destroyGPU(clCallFunc);
}
void sigHandler(int signo) {
printf("God Bless Me\n");
destroyGPU(clCallFuncOuter);
exit(0);
}
int main(int argc, char *argv[]) {
const char sigErr[] = "I can't catch signal.\n";
if (signal(SIGTRAP, sigHandler) == SIG_ERR)
fprintf(stderr, sigErr);
if (signal(SIGSEGV, sigHandler) == SIG_ERR)
fprintf(stderr, sigErr);
if (signal(SIGILL, sigHandler) == SIG_ERR)
fprintf(stderr, sigErr);
if (signal(SIGFPE, sigHandler) == SIG_ERR)
fprintf(stderr, sigErr);
if (signal(SIGINT, sigHandler) == SIG_ERR)
fprintf(stderr, sigErr);
onStart(clCallFuncOuter);
return 0;
}

matrix-lib.cl

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#define N %d
#define CTYPE unsigned int
__kernel void matrixAdd(__global CTYPE *in1,
__global CTYPE *in2,
__global CTYPE *out) {
int x = get_global_id(0);
out[x] = in1[x] + in2[x];
}
__kernel void matrixMul(__global CTYPE *in1,
__global CTYPE *in2,
__global CTYPE *out) {
int id = get_global_id(0);
int x = id / N, y = id % N;
CTYPE sum = 0;
for (int i = 0; i < N; i++)
sum += in1[x*N + i] * in2[i*N + y];
out[x * N + y] = sum;
}