-
Notifications
You must be signed in to change notification settings - Fork 14
/
clra_nonlinearities.py
2405 lines (2104 loc) · 72.7 KB
/
clra_nonlinearities.py
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
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
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
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
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
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
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
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
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
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
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""OpenCL kernels for everything other than GEMV."""
# pylint: disable=missing-class-docstring,missing-function-docstring
import nengo.dists as nengod
import numpy as np
import pyopencl as cl
from mako.template import Template
from nengo.utils.numpy import is_number
from nengo_ocl import ast_conversion
from nengo_ocl.clraggedarray import CLRaggedArray, to_device
from nengo_ocl.plan import Plan
from nengo_ocl.raggedarray import RaggedArray
from nengo_ocl.utils import as_ascii, indent, nonelist, round_up
def get_mwgs(queue, cap=256):
return min(queue.device.max_work_group_size, cap)
def blockify_ij(max_size, ra):
"""Blockify a single matrix or vector using the offset method"""
sizes = []
inds = []
offsets = []
for k in range(len(ra)):
size = ra.sizes[k]
for offset in range(0, size, max_size):
inds.append(k)
sizes.append(min(size - offset, max_size))
offsets.append(offset)
return (
np.array(sizes, dtype=np.int32),
np.array(inds, dtype=np.int32),
np.array(offsets, dtype=np.int32),
)
def blockify_matrices(max_size, ras):
# NOTE: must be contiguous
ras = list(ras)
ra0 = ras[0]
N = len(ra0)
for ra in ras:
assert len(ra) == N
assert (ra.shape1s == ra0.shape1s).all()
assert (ra.shape0s == ra0.shape0s).all()
assert (ra.shape1s == ra.stride0s).all(), "not contiguous"
sizes = []
inds = []
starts = [[] for _ in ras]
for i in range(N):
size = ra0.sizes[i]
startsi = [ra.starts[i] for ra in ras]
while size > 0:
sizes.append(min(size, max_size))
size -= max_size
inds.append(i)
for k, ra in enumerate(ras):
starts[k].append(startsi[k])
startsi[k] += max_size
return (
np.array(sizes, dtype=np.int32),
np.array(inds, dtype=np.int32),
np.array(starts, dtype=np.int32),
)
def blockify_matrix(max_size, ra):
sizes, inds, starts = blockify_matrices(max_size, [ra])
return sizes, inds, starts[0]
def blockify_vectors(max_size, ras):
ras = list(ras)
ra0 = ras[0] if len(ras) > 0 else None
N = len(ra0) if ra0 is not None else 0
for ra in ras:
assert len(ra) == N
assert (ra.shape1s == 1).all()
assert (ra.shape0s == ra0.shape0s).all()
sizes = []
inds = []
starts = [[] for _ in ras]
for i in range(N):
size = ra0.shape0s[i]
startsi = [ra.starts[i] for ra in ras]
while size > 0:
sizes.append(min(size, max_size))
size -= max_size
inds.append(i)
for k, ra in enumerate(ras):
starts[k].append(startsi[k])
startsi[k] += max_size * ra.stride0s[i]
return (
np.array(sizes, dtype=np.int32),
np.array(inds, dtype=np.int32),
np.array(starts, dtype=np.int32),
)
def blockify_vector(max_size, ra):
sizes, inds, starts = blockify_vectors(max_size, [ra])
return sizes, inds, starts[0]
def plan_timeupdate(queue, step, time, dt):
assert len(step) == len(time) == 1
assert step.ctype == time.ctype == "float"
assert step.shape0s[0] == step.shape1s[0] == 1
assert time.shape0s[0] == time.shape1s[0] == 1
text = """
////////// MAIN FUNCTION //////////
__kernel void timeupdate(
__global const int *step_starts,
__global float *step_data,
__global const int *time_starts,
__global float *time_data
)
{
__global float *step = step_data + step_starts[0];
__global float *time = time_data + time_starts[0];
step[0] += 1;
time[0] = ${dt} * step[0];
}
"""
text = as_ascii(Template(text, output_encoding="ascii").render(dt=dt))
full_args = (step.cl_starts, step.cl_buf, time.cl_starts, time.cl_buf)
_fn = cl.Program(queue.context, text).build().timeupdate
_fn.set_args(*[arr.data for arr in full_args])
gsize = (1,)
lsize = None
plan = Plan(queue, _fn, gsize, lsize=lsize, name="cl_timeupdate")
plan.full_args = full_args # prevent garbage-collection
return plan
def plan_reset(queue, Y, values, tag=None):
assert len(Y) == len(values)
assert (Y.stride0s == Y.shape1s).all()
assert (Y.stride1s == 1).all()
assert Y.ctype == values.ctype
text = """
////////// MAIN FUNCTION //////////
__kernel void reset(
__global const ${Ytype} *values,
__global const int *Ysizes,
__global const int *Ystarts,
__global ${Ytype} *Ydata
)
{
const int i = get_global_id(0);
int n = get_global_id(1);
% for k in range(n_per_item):
if (n < ${N} && i < Ysizes[n])
(Ydata + Ystarts[n])[i] = values[n];
n += get_global_size(1);
% endfor
}
"""
n_per_item = 1
lsize0 = 16
lsize1 = get_mwgs(queue, cap=256) // lsize0
# lsize0 = min(256, Y.sizes.max())
Ysizes, Yinds, Ystarts = blockify_matrix(lsize0, Y)
clYsizes = to_device(queue, Ysizes)
clYstarts = to_device(queue, Ystarts)
values = values.get()
clvalues = to_device(queue, values[Yinds])
N = len(Ysizes)
NN = -(-N // n_per_item) # ceiling division
lsize = (lsize0, lsize1)
gsize = (lsize0, round_up(NN, lsize1))
# lsize = None
# gsize = (lsize0, NN)
textconf = dict(Ytype=Y.ctype, N=N, n_per_item=n_per_item)
text = as_ascii(Template(text, output_encoding="ascii").render(**textconf))
full_args = (
clvalues,
clYsizes,
clYstarts,
Y.cl_buf,
)
_fn = cl.Program(queue.context, text).build().reset
_fn.set_args(*[arr.data for arr in full_args])
plan = Plan(queue, _fn, gsize, lsize=lsize, name="cl_reset", tag=tag)
plan.full_args = full_args # prevent garbage-collection
plan.bw_per_call = Y.nbytes + values.nbytes + clYsizes.nbytes + clYstarts.nbytes
plan.description = "groups: %d; items: %d; items/group: %0.1f [%d, %d]" % (
len(Y),
Y.sizes.sum(),
Y.sizes.mean(),
Y.sizes.min(),
Y.sizes.max(),
)
return plan
def plan_copy(queue, X, Y, incs, tag=None):
assert len(X) == len(Y)
assert (X.shape0s == Y.shape0s).all()
assert (X.shape1s == Y.shape1s).all()
assert (X.stride1s == 1).all()
assert (Y.stride1s == 1).all()
assert X.ctype == Y.ctype
text = """
////////// MAIN FUNCTION //////////
__kernel void copy(
% if inc is None:
__global const int *incdata,
% endif
__global const int *offsets,
__global const int *shape0s,
__global const int *shape1s,
__global const int *Xstride0s,
__global const int *Xstarts,
__global const ${Xtype} *Xdata,
__global const int *Ystride0s,
__global const int *Ystarts,
__global ${Ytype} *Ydata
)
{
const int n = get_global_id(1);
const int ij = get_global_id(0) + offsets[n];
const int shape1 = shape1s[n];
const int i = ij / shape1;
const int j = ij % shape1;
const int xo = Xstarts[n] + i*Xstride0s[n] + j;
const int yo = Ystarts[n] + i*Ystride0s[n] + j;
if (i < shape0s[n]) {
% if inc is True:
Ydata[yo] += Xdata[xo];
% elif inc is False:
Ydata[yo] = Xdata[xo];
% else:
if (incdata[n]) Ydata[yo] += Xdata[xo];
else Ydata[yo] = Xdata[xo];
% endif
}
}
"""
lsize0 = get_mwgs(queue, cap=256)
sizes, inds, offsets = blockify_ij(lsize0, Y)
lsize = None
gsize = (lsize0, len(sizes))
textconf = dict(Xtype=X.ctype, Ytype=Y.ctype, inc=None)
full_args = [
to_device(queue, offsets),
to_device(queue, X.shape0s[inds]),
to_device(queue, X.shape1s[inds]),
to_device(queue, X.stride0s[inds]),
to_device(queue, X.starts[inds]),
X.cl_buf,
to_device(queue, Y.stride0s[inds]),
to_device(queue, Y.starts[inds]),
Y.cl_buf,
]
if (incs == 0).all():
textconf["inc"] = False
elif (incs == 1).all():
textconf["inc"] = True
else:
full_args.insert(0, to_device(queue, incs[inds].astype(np.int32)))
text = as_ascii(Template(text, output_encoding="ascii").render(**textconf))
_fn = cl.Program(queue.context, text).build().copy
_fn.set_args(*[arr.data for arr in full_args])
plan = Plan(queue, _fn, gsize, lsize=lsize, name="cl_copy", tag=tag)
plan.full_args = tuple(full_args) # prevent garbage-collection
plan.bw_per_call = X.nbytes + Y.nbytes
plan.description = "groups: %d; items: %d; items/group: %0.1f [%d, %d]" % (
len(X),
X.sizes.sum(),
X.sizes.mean(),
X.sizes.min(),
X.sizes.max(),
)
return plan
def plan_slicedcopy(queue, X, Y, Xinds, Yinds, incs, tag=None):
N = len(X)
assert len(X) == len(Y) == len(Xinds) == len(Yinds)
for arr in [X, Y, Xinds, Yinds]:
assert (arr.shape1s == 1).all()
assert (arr.stride1s == 1).all()
for arr in [Xinds, Yinds]:
assert (arr.stride0s == 1).all()
assert (Xinds.shape0s == Yinds.shape0s).all()
assert X.ctype == Y.ctype
assert Xinds.ctype == Yinds.ctype == "int"
text = """
////////// MAIN FUNCTION //////////
__kernel void slicedcopy(
% if inc is None:
__global const int *incdata,
% endif
__global const int *Xstride0s,
__global const int *Xstarts,
__global const ${Xtype} *Xdata,
__global const int *Ystride0s,
__global const int *Ystarts,
__global ${Ytype} *Ydata,
__global const int *Isizes,
__global const int *XIstarts,
__global const int *XIdata,
__global const int *YIstarts,
__global const int *YIdata
)
{
const int i = get_global_id(0);
const int n = get_global_id(1);
if (n >= ${N})
return;
__global const ${Xtype} *a = Xdata + Xstarts[n];
__global ${Ytype} *b = Ydata + Ystarts[n];
__global const int *aind = XIdata + XIstarts[n];
__global const int *bind = YIdata + YIstarts[n];
const int Xstride0 = Xstride0s[n], Ystride0 = Ystride0s[n];
if (i < Isizes[n]) {
% if inc is True:
b[bind[i]*Ystride0] += a[aind[i]*Xstride0];
% elif inc is False:
b[bind[i]*Ystride0] = a[aind[i]*Xstride0];
% else:
if (incdata[n])
b[bind[i]*Ystride0] += a[aind[i]*Xstride0];
else
b[bind[i]*Ystride0] = a[aind[i]*Xstride0];
% endif
}
}
"""
lsize0 = 16
lsize1 = get_mwgs(queue) // lsize0
sizes, inds, [XIstarts, YIstarts] = blockify_vectors(lsize0, [Xinds, Yinds])
N = len(sizes)
lsize = (lsize0, lsize1)
gsize = (lsize0, round_up(N, lsize1))
textconf = dict(Xtype=X.ctype, Ytype=Y.ctype, N=N, inc=None)
full_args = [
to_device(queue, X.stride0s[inds]),
to_device(queue, X.starts[inds]),
X.cl_buf,
to_device(queue, Y.stride0s[inds]),
to_device(queue, Y.starts[inds]),
Y.cl_buf,
to_device(queue, sizes),
to_device(queue, XIstarts),
Xinds.cl_buf,
to_device(queue, YIstarts),
Yinds.cl_buf,
]
if (incs == 0).all():
textconf["inc"] = False
elif (incs == 1).all():
textconf["inc"] = True
else:
full_args.insert(0, to_device(queue, incs[inds].astype(np.int32)))
text = as_ascii(Template(text, output_encoding="ascii").render(**textconf))
_fn = cl.Program(queue.context, text).build().slicedcopy
_fn.set_args(*[arr.data for arr in full_args])
plan = Plan(queue, _fn, gsize, lsize=lsize, name="cl_slicedcopy", tag=tag)
plan.full_args = tuple(full_args) # prevent garbage-collection
plan.bw_per_call = 2 * (Xinds.nbytes + Xinds.sizes.sum() * X.dtype.itemsize)
plan.description = "groups: %d; items: %d; items/group: %0.1f [%d, %d]" % (
len(Xinds),
Xinds.sizes.sum(),
Xinds.sizes.mean(),
Xinds.sizes.min(),
Xinds.sizes.max(),
)
return plan
def plan_elementwise_inc(queue, A, X, Y, alpha=None, outer=False, inc=True, tag=None):
"""Implements an element-wise increment Y += alpha * A * X
Parameters
----------
alpha : np.ndarray or None
Scalars to apply to each operation.
outer : bool
Perform an outer product. ``A`` and ``X`` must be vectors.
inc : bool
Whether to increment ``Y`` (True), or set it (False).
"""
assert len(Y) == len(X) == len(A)
for arr in [A, X, Y]:
assert (arr.stride1s == 1).all()
if outer:
assert (A.shape1s == 1).all()
assert (X.shape1s == 1).all()
assert ((A.shape0s == 1) | (A.shape0s == Y.shape0s)).all()
assert ((X.shape0s == 1) | (X.shape0s == Y.shape1s)).all()
else:
assert ((X.shape0s == 1) | (X.shape0s == Y.shape0s)).all()
assert ((X.shape1s == 1) | (X.shape1s == Y.shape1s)).all()
assert ((A.shape0s == 1) | (A.shape0s == Y.shape0s)).all()
assert ((A.shape1s == 1) | (A.shape1s == Y.shape1s)).all()
assert X.ctype == Y.ctype
assert A.ctype == Y.ctype
if alpha is not None:
assert isinstance(alpha, np.ndarray)
assert alpha.shape == (len(Y),)
text = """
inline ${Ytype} get_element(
__global const ${Ytype} *data,
const int shape0, const int shape1, const int stride0,
const int i, const int j
)
{
if (shape0 == 1 && shape1 == 1)
return data[0];
else if (shape0 == 1)
return data[j];
else if (shape1 == 1)
return data[i * stride0];
else
return data[i * stride0 + j];
}
////////// MAIN FUNCTION //////////
__kernel void elementwise_inc(
% if alpha is not None:
__global const ${Ytype} *alphas,
% endif
__global const int *offsets,
__global const int *Ashape0s,
__global const int *Ashape1s,
__global const int *Astride0s,
__global const int *Astarts,
__global const ${Atype} *Adata,
__global const int *Xshape0s,
__global const int *Xshape1s,
__global const int *Xstride0s,
__global const int *Xstarts,
__global const ${Xtype} *Xdata,
__global const int *Yshape0s,
__global const int *Yshape1s,
__global const int *Ystride0s,
__global const int *Ystarts,
__global ${Ytype} *Ydata
)
{
const int n = get_global_id(1);
const int ij = get_global_id(0) + offsets[n];
__global const ${Atype} *a = Adata + Astarts[n];
__global const ${Xtype} *x = Xdata + Xstarts[n];
__global ${Ytype} *y = Ydata + Ystarts[n];
const int Ystride0 = Ystride0s[n];
const int Yshape0 = Yshape0s[n];
const int Yshape1 = Yshape1s[n];
const int i = ij / Yshape1;
const int j = ij % Yshape1;
% if outer:
const ${Atype} aa = get_element(a, Ashape0s[n], 1, Astride0s[n], i, 0);
const ${Xtype} xx = get_element(x, Xshape0s[n], 1, Xstride0s[n], j, 0);
% else:
const ${Atype} aa = get_element(
a, Ashape0s[n], Ashape1s[n], Astride0s[n], i, j);
const ${Xtype} xx = get_element(
x, Xshape0s[n], Xshape1s[n], Xstride0s[n], i, j);
% endif
% if alpha is not None:
const ${Ytype} alpha = alphas[n];
% else:
const ${Ytype} alpha = 1;
% endif
if (i < Yshape0)
% if inc:
y[i*Ystride0 + j] += alpha * aa * xx;
% else:
y[i*Ystride0 + j] = alpha * aa * xx;
% endif
}
"""
# --- blockify
lsize0 = get_mwgs(queue, cap=256)
sizes, inds, offsets = blockify_ij(lsize0, Y)
textconf = dict(
Atype=A.ctype, Xtype=X.ctype, Ytype=Y.ctype, alpha=alpha, outer=outer, inc=inc
)
text = as_ascii(Template(text, output_encoding="ascii").render(**textconf))
if alpha is not None:
alpha = to_device(queue, alpha[inds].astype(Y.dtype))
full_args = nonelist(alpha) + [
to_device(queue, offsets),
to_device(queue, A.shape0s[inds]),
to_device(queue, A.shape1s[inds]),
to_device(queue, A.stride0s[inds]),
to_device(queue, A.starts[inds]),
A.cl_buf,
to_device(queue, X.shape0s[inds]),
to_device(queue, X.shape1s[inds]),
to_device(queue, X.stride0s[inds]),
to_device(queue, X.starts[inds]),
X.cl_buf,
to_device(queue, Y.shape0s[inds]),
to_device(queue, Y.shape1s[inds]),
to_device(queue, Y.stride0s[inds]),
to_device(queue, Y.starts[inds]),
Y.cl_buf,
]
_fn = cl.Program(queue.context, text).build().elementwise_inc
_fn.set_args(*[arr.data for arr in full_args])
gsize = (lsize0, len(sizes))
plan = Plan(queue, _fn, gsize, lsize=None, name="cl_elementwise_inc", tag=tag)
plan.full_args = full_args # prevent garbage-collection
plan.flops_per_call = 2 * Y.sizes.sum()
plan.bw_per_call = (
A.nbytes + X.nbytes + Y.nbytes + (0 if alpha is None else alpha.nbytes)
)
plan.description = "groups: %d; items: %d; items/group: %0.1f [%d, %d]" % (
len(Y),
Y.sizes.sum(),
Y.sizes.mean(),
Y.sizes.min(),
Y.sizes.max(),
)
return plan
def plan_linearfilter(queue, X, Y, A, B, Xbuf, Ybuf, tag=None):
"""
Implements a filter of the form
y[n+1] + a[0] y[n] + ... + a[i] y[n-i] = b[0] x[n] + ... + b[j] x[n-j]
"""
assert len(X) == len(Y) == len(A) == len(B) == len(Xbuf) == len(Ybuf)
# X, Y
assert (X.shape0s == Y.shape0s).all()
assert (X.shape1s == Y.shape1s).all()
# A, B, Xbuf, Ybuf
for arr in [A, B, Xbuf, Ybuf]: # contiguous
assert (arr.shape1s == arr.stride0s).all()
assert (arr.stride1s == 1).all()
for arr in [A, B]: # vectors
assert (arr.shape1s == 1).all()
assert (B.shape0s >= 1).all()
assert ((B.shape0s == 1) | (Xbuf.shape0s == B.shape0s)).all()
assert ((A.shape0s == 1) | (Ybuf.shape0s == A.shape0s)).all()
assert (Xbuf.shape1s == X.sizes).all()
assert (Ybuf.shape1s == Y.sizes).all()
assert X.ctype == Xbuf.ctype
assert Y.ctype == Ybuf.ctype
text = """
////////// MAIN FUNCTION //////////
__kernel void linearfilter(
__global const int *offsets,
__global const int *shape0s,
__global const int *shape1s,
__global const int *Xstride0s,
__global const int *Xstride1s,
__global const int *Xstarts,
__global const ${Xtype} *x,
__global const int *Ystride0s,
__global const int *Ystride1s,
__global const int *Ystarts,
__global ${Ytype} *y,
__global const int *Ashape0s,
__global const int *Astarts,
__global const ${Atype} *Adata,
__global const int *Bshape0s,
__global const int *Bstarts,
__global const ${Btype} *Bdata,
__global const int *Xbufstarts,
__global ${Xtype} *Xbufdata,
__global const int *Ybufstarts,
__global ${Ytype} *Ybufdata,
__global const int *Xbufpos,
__global const int *Ybufpos
)
{
const int k = get_global_id(1);
const int ij = get_global_id(0) + offsets[k];
const int shape0 = shape0s[k];
const int shape1 = shape1s[k];
const int i = ij / shape1;
const int j = ij % shape1;
const int xij = Xstarts[k] + i*Xstride0s[k] + j*Xstride1s[k];
const int yij = Ystarts[k] + i*Ystride0s[k] + j*Ystride1s[k];
const int na = Ashape0s[k];
const int nb = Bshape0s[k];
__local ${Atype} a[${na_max}];
__local ${Btype} b[${nb_max}];
const int ti = get_local_id(0);
if (ti < na)
a[ti] = (Adata + Astarts[k])[ti];
if (ti < nb)
b[ti] = (Bdata + Bstarts[k])[ti];
barrier(CLK_LOCAL_MEM_FENCE);
if (i >= shape0)
return;
if (na == 0 && nb == 1) {
y[yij] = b[0] * x[xij];
} else if (na == 1 && nb == 1) {
y[yij] = b[0] * x[xij] - a[0] * y[yij];
% if uses_buf: # save registers: only compile if needed
} else { // general filtering
__global ${Xtype} *xbuf = Xbufdata + Xbufstarts[k];
__global ${Ytype} *ybuf = Ybufdata + Ybufstarts[k];
const int ix = Xbufpos[k];
const int iy = Ybufpos[k];
const int ix1 = (ix > 0) ? ix - 1 : nb - 1;
const int iy1 = (iy > 0) ? iy - 1 : na - 1;
const int size = shape0 * shape1;
${Ytype} yi = b[0] * x[xij];
if (nb > 1) {
xbuf[ix*size + ij] = x[xij]; // copy input to buffer
for (int p = 1; p < nb; p++)
yi += b[p] * xbuf[((ix + p) % nb)*size + ij];
}
if (na > 0) {
yi -= a[0] * y[yij];
if (na > 1) {
for (int p = 1; p < na; p++)
yi -= a[p] * ybuf[((iy + p) % na)*size + ij];
ybuf[iy1*size + ij] = yi; // copy output to buffer
}
}
y[yij] = yi;
% endif
}
}
% if uses_buf: # only compile if needed
__kernel void linearfilter_inc(
__global const int *Ashape0s,
__global const int *Bshape0s,
__global int *Xbufpos,
__global int *Ybufpos
)
{
const int k = get_global_id(0);
const int na = Ashape0s[k];
const int nb = Bshape0s[k];
const int ix = Xbufpos[k];
const int iy = Ybufpos[k];
Xbufpos[k] = (ix > 0) ? ix - 1 : nb - 1;
Ybufpos[k] = (iy > 0) ? iy - 1 : na - 1;
}
% endif
"""
na_max = A.sizes.max()
nb_max = B.sizes.max()
assert nb_max >= 1
uses_buf = na_max > 1 or nb_max > 1
textconf = dict(
Xtype=X.ctype,
Ytype=Y.ctype,
Atype=A.ctype,
Btype=B.ctype,
na_max=na_max,
nb_max=nb_max,
uses_buf=uses_buf,
)
text = as_ascii(Template(text, output_encoding="ascii").render(**textconf))
max_len = X.sizes.max()
lsize0 = min(max(max_len, na_max, nb_max), get_mwgs(queue))
assert na_max <= lsize0 and nb_max <= lsize0
sizes, inds, offsets = blockify_ij(lsize0, X)
n = len(sizes)
Xbufpos = to_device(queue, np.zeros(n if uses_buf else 0, dtype="int32"))
Ybufpos = to_device(queue, np.zeros(n if uses_buf else 0, dtype="int32"))
full_args = (
to_device(queue, offsets),
to_device(queue, X.shape0s[inds]),
to_device(queue, X.shape1s[inds]),
to_device(queue, X.stride0s[inds]),
to_device(queue, X.stride1s[inds]),
to_device(queue, X.starts[inds]),
X.cl_buf,
to_device(queue, Y.stride0s[inds]),
to_device(queue, Y.stride1s[inds]),
to_device(queue, Y.starts[inds]),
Y.cl_buf,
to_device(queue, A.shape0s[inds]),
to_device(queue, A.starts[inds]),
A.cl_buf,
to_device(queue, B.shape0s[inds]),
to_device(queue, B.starts[inds]),
B.cl_buf,
to_device(queue, Xbuf.starts[inds]),
Xbuf.cl_buf,
to_device(queue, Ybuf.starts[inds]),
Ybuf.cl_buf,
Xbufpos,
Ybufpos,
)
# --- build and print info (change maxregcount to avoid cache, force build)
# program = cl.Program(queue.context, text).build(
# options=['-cl-nv-maxrregcount=55', '-cl-nv-verbose'])
# print(program.get_build_info(queue.device, cl.program_build_info.LOG))
program = cl.Program(queue.context, text).build()
_fn = program.linearfilter
_fn.set_args(*[arr.data for arr in full_args])
lsize = (lsize0, 1)
gsize = (lsize0, n)
plan = Plan(queue, _fn, gsize, lsize=lsize, name="cl_linearfilter", tag=tag)
plan.full_args = full_args # prevent garbage-collection
plan.bw_per_call = (
X.nbytes + Y.nbytes + A.nbytes + B.nbytes + Xbuf.nbytes + Ybuf.nbytes
)
plan.description = "groups: %d; items: %d; items/group: %0.1f [%d, %d]" % (
len(Y),
Y.sizes.sum(),
Y.sizes.mean(),
Y.sizes.min(),
Y.sizes.max(),
)
if not uses_buf:
return [plan]
else:
inc = program.linearfilter_inc
inc_args = (
to_device(queue, A.shape0s[inds]),
to_device(queue, B.shape0s[inds]),
Xbufpos,
Ybufpos,
)
inc.set_args(*[arr.data for arr in inc_args])
inc_plan = Plan(queue, inc, gsize=(n,), name="cl_linearfilter_inc")
inc_plan.full_args = inc_args # prevent garbage-collection
return [plan, inc_plan]
def plan_probes(queue, periods, X, Y, tag=None):
"""
Parameters
----------
P : raggedarray of ints
The period (in time-steps) of each probe
"""
assert len(X) == len(Y)
assert len(X) == len(periods)
assert X.ctype == Y.ctype
N = len(X)
# N.B. X[i].shape = (M, N)
# Y[i].shape = (buf_len, M * N)
assert (X.shape0s * X.shape1s == Y.shape1s).all()
# Y must be contiguous
assert (Y.stride0s == Y.shape1s).all()
assert (Y.stride1s == 1).all()
periods = np.asarray(periods, dtype="float32")
cl_periods = to_device(queue, periods)
cl_countdowns = to_device(queue, periods - 1)
cl_bufpositions = to_device(queue, np.zeros(N, dtype="int32"))
text = """
////////// MAIN FUNCTION //////////
__kernel void probes(
__global ${Ctype} *countdowns,
__global int *bufpositions,
__global const ${Ptype} *periods,
__global const int *Xstarts,
__global const int *Xshape0s,
__global const int *Xshape1s,
__global const int *Xstride0s,
__global const int *Xstride1s,
__global const ${Xtype} *Xdata,
__global const int *Ystarts,
__global ${Ytype} *Ydata
)
{
const int n = get_global_id(1);
const ${Ctype} countdown = countdowns[n];
if (countdown <= 0) {
const int ni = Xshape0s[n];
const int nj = Xshape1s[n];
const int n_dims = ni * nj;
% if has_stride_i:
const int sti = Xstride0s[n];
% else:
const int sti = 1;
% endif
% if has_stride_j:
const int stj = Xstride1s[n];
% else:
const int stj = 1;
% endif
__global const ${Xtype} *x = Xdata + Xstarts[n];
const int bufpos = bufpositions[n];
__global ${Ytype} *y = Ydata + Ystarts[n] + bufpos * n_dims;
const int gsize0 = get_global_size(0);
if (ni == 1) {
for (int j = get_global_id(0); j < n_dims; j += gsize0)
y[j] = x[j * stj];
} else if (nj == 1) {
for (int i = get_global_id(0); i < n_dims; i += gsize0)
y[i] = x[i * sti];
} else {
for (int ij = get_global_id(0); ij < n_dims; ij += gsize0) {
const int i = ij / nj;
const int j = ij % nj;
y[ij] = x[i*sti + j*stj];
}
}
// This should *not* cause deadlock because
// all local threads guaranteed to be
// in this branch together.
barrier(CLK_LOCAL_MEM_FENCE);
if (get_global_id(0) == 0)
{
countdowns[n] = countdown + periods[n] - 1;
bufpositions[n] = bufpos + 1;
}
}
else
{
barrier(CLK_LOCAL_MEM_FENCE);
if (get_global_id(0) == 0)
{
countdowns[n] = countdown - 1;
}
}
}
"""
textconf = dict(
N=N,
Xtype=X.ctype,
Ytype=Y.ctype,
Ctype=cl_countdowns.ctype,
Ptype=cl_periods.ctype,
has_stride_i=(X.stride0s != 1).any(),
has_stride_j=(X.stride1s != 1).any(),
)
text = as_ascii(Template(text, output_encoding="ascii").render(**textconf))
full_args = (
cl_countdowns,
cl_bufpositions,
cl_periods,
X.cl_starts,
X.cl_shape0s,
X.cl_shape1s,
X.cl_stride0s,
X.cl_stride1s,
X.cl_buf,
Y.cl_starts,
Y.cl_buf,
)
_fn = cl.Program(queue.context, text).build().probes
_fn.set_args(*[arr.data for arr in full_args])
max_len = min(max(X.shape0s), get_mwgs(queue))
gsize = (
max_len,
N,
)
lsize = (max_len, 1)
plan = Plan(queue, _fn, gsize, lsize=lsize, name="cl_probes", tag=tag)
plan.full_args = full_args # prevent garbage-collection
plan.cl_bufpositions = cl_bufpositions
plan.Y = Y
plan.bw_per_call = (
2 * X.nbytes + cl_periods.nbytes + cl_countdowns.nbytes + cl_bufpositions.nbytes
)
plan.description = "groups: %d; items: %d; items/group: %0.1f [%d, %d]" % (
len(X),
X.sizes.sum(),
X.sizes.mean(),
X.sizes.min(),
X.sizes.max(),
)
return plan
def plan_direct(queue, code, init, input_names, inputs, output, tag=None):
assert len(input_names) == len(inputs)
N = len(inputs[0])
for x in inputs:
assert len(x) == len(output)
for x in inputs + [output]:
assert (x.shape1s == 1).all() and (x.stride1s == 1).all()
assert (x.stride0s == 1).all()
input_types = [x.ctype for x in inputs]
output_type = output.ctype
text = """
////////// MAIN FUNCTION //////////
__kernel void direct(
% for iname, itype in zip(input_names, input_types):
__global const int *${iname}_starts__,
__global const ${itype} *${iname}_data__,
% endfor
__global const int *${oname}_starts__,
__global ${otype} *${oname}_data__
)
{
const int n = get_global_id(0);
if (n >= ${N}) return;
% for iname, itype in zip(input_names, input_types):
__global const ${itype} *${iname} =
${iname}_data__ + ${iname}_starts__[n];
% endfor
__global ${otype} *${oname} =
${oname}_data__ + ${oname}_starts__[n];
/////vvvvv USER DECLARATIONS BELOW vvvvv
${init}
/////vvvvv USER COMPUTATIONS BELOW vvvvv
${code}
// END OF FUNC: put nothing after user code, since it can return
}
"""
textconf = dict(
init=indent(init, 12),
code=indent(code, 12),
N=N,