批改娘 10097. Advanced Matrix Calculator (OpenCL)

contents

  1. 1. 題目描述
    1. 1.1. sequence.c
  2. 2. 輸入格式
  3. 3. 輸出格式
  4. 4. 範例輸入 1
  5. 5. 範例輸出 1
  6. 6. 編譯參數
  7. 7. Solution
    1. 7.1. main.c
    2. 7.2. matrix-lib.cl

題目描述

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

題目給定數個 $N \times N$ 的矩陣和 $Q$ 小題,每一小題只由加法和乘法構成。

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;
}

輸入格式

測資只有一組,第一行會有兩個整數 $M,N$,表示題目給定 $M$ 個 $N \times N$ 矩陣,第二行上會有 $N$ 個整數 $S_i$ 個第 $i$ 個矩陣生成種子。最後會有一行一個整數 $Q$,表示接下來有 $Q$ 行詢問,每一行上會有一個字串 $E$ 表示接下來要處理的矩陣表達式,$E$ 只包含 A-Z 以及 +

  • $1 \le M \le 26$
  • $1 \le N \le 1024$
  • $0 \le S_i \le 2^{31}$
  • $1 \le Q \le 100$
  • $|E| \le 26$

輸出格式

對於每一組測資輸出一行。

範例輸入 1

1
2
3
4
5
6 2
0 1 2 3 4 5
2
AB+CD
ABE+CDF

範例輸出 1

1
2
2385860290
1374821695

編譯參數

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

Solution

這一題是 10095. Matrix Calculator (OpenCL) 的強化版,針對計算量在多個 GPU 裝置上分配工作。由於每一個表達式的計算量多寡不定,為了批次解決一坨工作,讓三個 GPU 的執行時間最大值最小化,貪心分配表達式,將計算量由大排到小後,依序取出,挑選目前 workload 最小的 GPU 分配到這之上,但 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
#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 3
#define MAXN 1024
#define MAXM 26
#define MAXMID 32
uint32_t hostMtx[MAXM][MAXN*MAXN];
int N, M, Q;
char expr[1024];
char clSrcFormat[32767] = "";
char clSrc[32767] = "";
// -- start working with OpenCL
const int clNeedDevCnt = 3;
cl_context clCtx[MAXGPU];
cl_program clPrg[MAXGPU];
cl_kernel clKrnAdd[MAXGPU], clKrnMul[MAXGPU];
cl_command_queue clQue[MAXGPU];
cl_mem clMemIn[MAXGPU][MAXM], clMemMid[MAXGPU][MAXMID];
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*N + 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, 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);
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*/ 0, &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)*N*N,
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)*N*N, 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[] = {N*N};
size_t localSize[] = {0};
for (int i = 1; i <= 1024; i++) {
if (N*N%i == 0)
localSize[0] = i;
}
// -- 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[] = {N*N};
size_t localSize[] = {0};
for (int i = 1; i <= 1024; i++) {
if (N*N%i == 0)
localSize[0] = i;
}
// -- 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[MAXGPU][128];
int offset[MAXGPU] = {};
#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)*N*N);
int waitN = nodes[p][0]->event != NULL;
clStat = clEnqueueReadBuffer(clQue[p], nodes[p][0]->clV, CL_TRUE, 0,
sizeof(uint32_t)*N*N, 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;
}
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];
assert(scanf("%d %d", &M, &N) == 2);
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;
uint32_t c = S[p];
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
x = (x * x + c + i + j)%n;
hostMtx[p][i*N+j] = x;
}
}
}
initAllGPU("matrix-lib.cl", clCallFunc);
Node *procBuff[128];
if (scanf("%d", &Q) != 1)
return ;
for (int i = 0; i < Q; i++) {
readIn();
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);
float gpuSpeed[16] = {1.f, 1.8f, 3.2f};
long long workload[16] = {};
int workQueSz[MAXGPU] = {};
uint32_t resultBuff[128] = {};
Node *workQue[MAXGPU][128];
for (int i = 0; i < Q; i++) {
int mn = 0;
for (int j = 0; j < clNeedDevCnt; j++) {
if (workload[j]*gpuSpeed[j] < workload[mn]*gpuSpeed[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
#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) {
int r = get_global_id(0);
int x = r / N, y = r % N;
unsigned int sum = 0;
for (int i = 0; i < N; i++)
sum += in1[x*N+i] * in2[i*N+y];
out[x*N+y] = sum;
}