-
Notifications
You must be signed in to change notification settings - Fork 237
/
algorithm.py
1439 lines (1127 loc) · 49.7 KB
/
algorithm.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
"""Algorithms built on scans."""
from __future__ import division, absolute_import
__copyright__ = """
Copyright 2011-2012 Andreas Kloeckner
Copyright 2017 Hao Gao
"""
__license__ = """
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
"""
from six.moves import range, zip
import numpy as np
import pyopencl as cl
import pyopencl.array # noqa
from pyopencl.scan import ScanTemplate
from pyopencl.tools import dtype_to_ctype, get_arg_offset_adjuster_code
from pytools import memoize, memoize_method, Record
from mako.template import Template
# {{{ "extra args" handling utility
def _extract_extra_args_types_values(extra_args):
from pyopencl.tools import VectorArg, ScalarArg
extra_args_types = []
extra_args_values = []
extra_wait_for = []
for name, val in extra_args:
if isinstance(val, cl.array.Array):
extra_args_types.append(VectorArg(val.dtype, name, with_offset=False))
extra_args_values.append(val)
extra_wait_for.extend(val.events)
elif isinstance(val, np.generic):
extra_args_types.append(ScalarArg(val.dtype, name))
extra_args_values.append(val)
else:
raise RuntimeError("argument '%d' not understood" % name)
return tuple(extra_args_types), extra_args_values, extra_wait_for
# }}}
# {{{ copy_if
_copy_if_template = ScanTemplate(
arguments="item_t *ary, item_t *out, scan_t *count",
input_expr="(%(predicate)s) ? 1 : 0",
scan_expr="a+b", neutral="0",
output_statement="""
if (prev_item != item) out[item-1] = ary[i];
if (i+1 == N) *count = item;
""",
template_processor="printf")
def copy_if(ary, predicate, extra_args=[], preamble="", queue=None, wait_for=None):
"""Copy the elements of *ary* satisfying *predicate* to an output array.
:arg predicate: a C expression evaluating to a `bool`, represented as a string.
The value to test is available as `ary[i]`, and if the expression evaluates
to `true`, then this value ends up in the output.
:arg extra_args: |scan_extra_args|
:arg preamble: |preamble|
:arg wait_for: |explain-waitfor|
:returns: a tuple *(out, count, event)* where *out* is the output array, *count*
is an on-device scalar (fetch to host with `count.get()`) indicating
how many elements satisfied *predicate*, and *event* is a
:class:`pyopencl.Event` for dependency management. *out* is allocated
to the same length as *ary*, but only the first *count* entries carry
meaning.
.. versionadded:: 2013.1
"""
if len(ary) > np.iinfo(np.int32).max:
scan_dtype = np.int64
else:
scan_dtype = np.int32
if wait_for is None:
wait_for = []
extra_args_types, extra_args_values, extra_wait_for = \
_extract_extra_args_types_values(extra_args)
wait_for = wait_for + extra_wait_for
knl = _copy_if_template.build(ary.context,
type_aliases=(("scan_t", scan_dtype), ("item_t", ary.dtype)),
var_values=(("predicate", predicate),),
more_preamble=preamble, more_arguments=extra_args_types)
out = cl.array.empty_like(ary)
count = ary._new_with_changes(data=None, offset=0,
shape=(), strides=(), dtype=scan_dtype)
evt = knl(ary, out, count, *extra_args_values,
queue=queue, wait_for=wait_for)
return out, count, evt
# }}}
# {{{ remove_if
def remove_if(ary, predicate, extra_args=[], preamble="", queue=None, wait_for=None):
"""Copy the elements of *ary* not satisfying *predicate* to an output array.
:arg predicate: a C expression evaluating to a `bool`, represented as a string.
The value to test is available as `ary[i]`, and if the expression evaluates
to `false`, then this value ends up in the output.
:arg extra_args: |scan_extra_args|
:arg preamble: |preamble|
:arg wait_for: |explain-waitfor|
:returns: a tuple *(out, count, event)* where *out* is the output array, *count*
is an on-device scalar (fetch to host with `count.get()`) indicating
how many elements did not satisfy *predicate*, and *event* is a
:class:`pyopencl.Event` for dependency management.
.. versionadded:: 2013.1
"""
return copy_if(ary, "!(%s)" % predicate, extra_args=extra_args,
preamble=preamble, queue=queue, wait_for=wait_for)
# }}}
# {{{ partition
_partition_template = ScanTemplate(
arguments=(
"item_t *ary, item_t *out_true, item_t *out_false, "
"scan_t *count_true"),
input_expr="(%(predicate)s) ? 1 : 0",
scan_expr="a+b", neutral="0",
output_statement="""//CL//
if (prev_item != item)
out_true[item-1] = ary[i];
else
out_false[i-item] = ary[i];
if (i+1 == N) *count_true = item;
""",
template_processor="printf")
def partition(ary, predicate, extra_args=[], preamble="", queue=None, wait_for=None):
"""Copy the elements of *ary* into one of two arrays depending on whether
they satisfy *predicate*.
:arg predicate: a C expression evaluating to a `bool`, represented as a string.
The value to test is available as `ary[i]`.
:arg extra_args: |scan_extra_args|
:arg preamble: |preamble|
:arg wait_for: |explain-waitfor|
:returns: a tuple *(out_true, out_false, count, event)* where *count*
is an on-device scalar (fetch to host with `count.get()`) indicating
how many elements satisfied the predicate, and *event* is a
:class:`pyopencl.Event` for dependency management.
.. versionadded:: 2013.1
"""
if len(ary) > np.iinfo(np.uint32).max:
scan_dtype = np.uint64
else:
scan_dtype = np.uint32
if wait_for is None:
wait_for = []
extra_args_types, extra_args_values, extra_wait_for = \
_extract_extra_args_types_values(extra_args)
wait_for = wait_for + extra_wait_for
knl = _partition_template.build(
ary.context,
type_aliases=(("item_t", ary.dtype), ("scan_t", scan_dtype)),
var_values=(("predicate", predicate),),
more_preamble=preamble, more_arguments=extra_args_types)
out_true = cl.array.empty_like(ary)
out_false = cl.array.empty_like(ary)
count = ary._new_with_changes(data=None, offset=0,
shape=(), strides=(), dtype=scan_dtype)
evt = knl(ary, out_true, out_false, count, *extra_args_values,
queue=queue, wait_for=wait_for)
return out_true, out_false, count, evt
# }}}
# {{{ unique
_unique_template = ScanTemplate(
arguments="item_t *ary, item_t *out, scan_t *count_unique",
input_fetch_exprs=[
("ary_im1", "ary", -1),
("ary_i", "ary", 0),
],
input_expr="(i == 0) || (IS_EQUAL_EXPR(ary_im1, ary_i) ? 0 : 1)",
scan_expr="a+b", neutral="0",
output_statement="""
if (prev_item != item) out[item-1] = ary[i];
if (i+1 == N) *count_unique = item;
""",
preamble="#define IS_EQUAL_EXPR(a, b) %(macro_is_equal_expr)s\n",
template_processor="printf")
def unique(ary, is_equal_expr="a == b", extra_args=[], preamble="",
queue=None, wait_for=None):
"""Copy the elements of *ary* into the output if *is_equal_expr*, applied to the
array element and its predecessor, yields false.
Works like the UNIX command :program:`uniq`, with a potentially custom
comparison. This operation is often used on sorted sequences.
:arg is_equal_expr: a C expression evaluating to a `bool`,
represented as a string. The elements being compared are
available as `a` and `b`. If this expression yields `false`, the
two are considered distinct.
:arg extra_args: |scan_extra_args|
:arg preamble: |preamble|
:arg wait_for: |explain-waitfor|
:returns: a tuple *(out, count, event)* where *out* is the output array, *count*
is an on-device scalar (fetch to host with `count.get()`) indicating
how many elements satisfied the predicate, and *event* is a
:class:`pyopencl.Event` for dependency management.
.. versionadded:: 2013.1
"""
if len(ary) > np.iinfo(np.uint32).max:
scan_dtype = np.uint64
else:
scan_dtype = np.uint32
if wait_for is None:
wait_for = []
extra_args_types, extra_args_values, extra_wait_for = \
_extract_extra_args_types_values(extra_args)
wait_for = wait_for + extra_wait_for
knl = _unique_template.build(
ary.context,
type_aliases=(("item_t", ary.dtype), ("scan_t", scan_dtype)),
var_values=(("macro_is_equal_expr", is_equal_expr),),
more_preamble=preamble, more_arguments=extra_args_types)
out = cl.array.empty_like(ary)
count = ary._new_with_changes(data=None, offset=0,
shape=(), strides=(), dtype=scan_dtype)
evt = knl(ary, out, count, *extra_args_values,
queue=queue, wait_for=wait_for)
return out, count, evt
# }}}
# {{{ radix_sort
def to_bin(n):
# Py 2.5 has no built-in bin()
digs = []
while n:
digs.append(str(n % 2))
n >>= 1
return ''.join(digs[::-1])
def _padded_bin(i, nbits):
s = to_bin(i)
while len(s) < nbits:
s = '0' + s
return s
@memoize
def _make_sort_scan_type(device, bits, index_dtype):
name = "pyopencl_sort_scan_%s_%dbits_t" % (
index_dtype.type.__name__, bits)
fields = []
for mnr in range(2**bits):
fields.append(('c%s' % _padded_bin(mnr, bits), index_dtype))
dtype = np.dtype(fields)
from pyopencl.tools import get_or_register_dtype, match_dtype_to_c_struct
dtype, c_decl = match_dtype_to_c_struct(device, name, dtype)
dtype = get_or_register_dtype(name, dtype)
return name, dtype, c_decl
# {{{ types, helpers preamble
RADIX_SORT_PREAMBLE_TPL = Template(r"""//CL//
typedef ${scan_ctype} scan_t;
typedef ${key_ctype} key_t;
typedef ${index_ctype} index_t;
// #define DEBUG
#ifdef DEBUG
#define dbg_printf(ARGS) printf ARGS
#else
#define dbg_printf(ARGS) /* */
#endif
index_t get_count(scan_t s, int mnr)
{
return ${get_count_branch("")};
}
#define BIN_NR(key_arg) ((key_arg >> base_bit) & ${2**bits - 1})
""", strict_undefined=True)
# }}}
# {{{ scan helpers
RADIX_SORT_SCAN_PREAMBLE_TPL = Template(r"""//CL//
scan_t scan_t_neutral()
{
scan_t result;
%for mnr in range(2**bits):
result.c${padded_bin(mnr, bits)} = 0;
%endfor
return result;
}
// considers bits (base_bit+bits-1, ..., base_bit)
scan_t scan_t_from_value(
key_t key,
int base_bit,
int i
)
{
// extract relevant bit range
key_t bin_nr = BIN_NR(key);
dbg_printf(("i: %d key:%d bin_nr:%d\n", i, key, bin_nr));
scan_t result;
%for mnr in range(2**bits):
result.c${padded_bin(mnr, bits)} = (bin_nr == ${mnr});
%endfor
return result;
}
scan_t scan_t_add(scan_t a, scan_t b, bool across_seg_boundary)
{
%for mnr in range(2**bits):
<% field = "c"+padded_bin(mnr, bits) %>
b.${field} = a.${field} + b.${field};
%endfor
return b;
}
""", strict_undefined=True)
RADIX_SORT_OUTPUT_STMT_TPL = Template(r"""//CL//
{
key_t key = ${key_expr};
key_t my_bin_nr = BIN_NR(key);
index_t previous_bins_size = 0;
%for mnr in range(2**bits):
previous_bins_size +=
(my_bin_nr > ${mnr})
? last_item.c${padded_bin(mnr, bits)}
: 0;
%endfor
index_t tgt_idx =
previous_bins_size
+ get_count(item, my_bin_nr) - 1;
%for arg_name in sort_arg_names:
sorted_${arg_name}[tgt_idx] = ${arg_name}[i];
%endfor
}
""", strict_undefined=True)
# }}}
# {{{ driver
# import hoisted here to be used as a default argument in the constructor
from pyopencl.scan import GenericScanKernel
class RadixSort(object):
"""Provides a general `radix sort <https://en.wikipedia.org/wiki/Radix_sort>`_
on the compute device.
.. seealso:: :class:`pyopencl.algorithm.BitonicSort`
.. versionadded:: 2013.1
"""
def __init__(self, context, arguments, key_expr, sort_arg_names,
bits_at_a_time=2, index_dtype=np.int32, key_dtype=np.uint32,
scan_kernel=GenericScanKernel, options=[]):
"""
:arg arguments: A string of comma-separated C argument declarations.
If *arguments* is specified, then *input_expr* must also be
specified. All types used here must be known to PyOpenCL.
(see :func:`pyopencl.tools.get_or_register_dtype`).
:arg key_expr: An integer-valued C expression returning the
key based on which the sort is performed. The array index
for which the key is to be computed is available as `i`.
The expression may refer to any of the *arguments*.
:arg sort_arg_names: A list of argument names whose corresponding
array arguments will be sorted according to *key_expr*.
"""
# {{{ arg processing
from pyopencl.tools import parse_arg_list
self.arguments = parse_arg_list(arguments)
del arguments
self.sort_arg_names = sort_arg_names
self.bits = int(bits_at_a_time)
self.index_dtype = np.dtype(index_dtype)
self.key_dtype = np.dtype(key_dtype)
self.options = options
# }}}
# {{{ kernel creation
scan_ctype, scan_dtype, scan_t_cdecl = \
_make_sort_scan_type(context.devices[0], self.bits, self.index_dtype)
from pyopencl.tools import VectorArg, ScalarArg
scan_arguments = (
list(self.arguments)
+ [VectorArg(arg.dtype, "sorted_"+arg.name) for arg in self.arguments
if arg.name in sort_arg_names]
+ [ScalarArg(np.int32, "base_bit")])
def get_count_branch(known_bits):
if len(known_bits) == self.bits:
return "s.c%s" % known_bits
boundary_mnr = known_bits + "1" + (self.bits-len(known_bits)-1)*"0"
return ("((mnr < %s) ? %s : %s)" % (
int(boundary_mnr, 2),
get_count_branch(known_bits+"0"),
get_count_branch(known_bits+"1")))
codegen_args = dict(
bits=self.bits,
key_ctype=dtype_to_ctype(self.key_dtype),
key_expr=key_expr,
index_ctype=dtype_to_ctype(self.index_dtype),
index_type_max=np.iinfo(self.index_dtype).max,
padded_bin=_padded_bin,
scan_ctype=scan_ctype,
sort_arg_names=sort_arg_names,
get_count_branch=get_count_branch,
)
preamble = scan_t_cdecl+RADIX_SORT_PREAMBLE_TPL.render(**codegen_args)
scan_preamble = preamble \
+ RADIX_SORT_SCAN_PREAMBLE_TPL.render(**codegen_args)
self.scan_kernel = scan_kernel(
context, scan_dtype,
arguments=scan_arguments,
input_expr="scan_t_from_value(%s, base_bit, i)" % key_expr,
scan_expr="scan_t_add(a, b, across_seg_boundary)",
neutral="scan_t_neutral()",
output_statement=RADIX_SORT_OUTPUT_STMT_TPL.render(**codegen_args),
preamble=scan_preamble, options=self.options)
for i, arg in enumerate(self.arguments):
if isinstance(arg, VectorArg):
self.first_array_arg_idx = i
# }}}
def __call__(self, *args, **kwargs):
"""Run the radix sort. In addition to *args* which must match the
*arguments* specification on the constructor, the following
keyword arguments are supported:
:arg key_bits: specify how many bits (starting from least-significant)
there are in the key.
:arg allocator: See the *allocator* argument of :func:`pyopencl.array.empty`.
:arg queue: A :class:`pyopencl.CommandQueue`, defaulting to the
one from the first argument array.
:arg wait_for: |explain-waitfor|
:returns: A tuple ``(sorted, event)``. *sorted* consists of sorted
copies of the arrays named in *sorted_args*, in the order of that
list. *event* is a :class:`pyopencl.Event` for dependency management.
"""
wait_for = kwargs.pop("wait_for", None)
# {{{ run control
key_bits = kwargs.pop("key_bits", None)
if key_bits is None:
key_bits = int(np.iinfo(self.key_dtype).bits)
n = len(args[self.first_array_arg_idx])
allocator = kwargs.pop("allocator", None)
if allocator is None:
allocator = args[self.first_array_arg_idx].allocator
queue = kwargs.pop("queue", None)
if queue is None:
queue = args[self.first_array_arg_idx].queue
args = list(args)
base_bit = 0
while base_bit < key_bits:
sorted_args = [
cl.array.empty(queue, n, arg_descr.dtype, allocator=allocator)
for arg_descr in self.arguments
if arg_descr.name in self.sort_arg_names]
scan_args = args + sorted_args + [base_bit]
last_evt = self.scan_kernel(*scan_args,
queue=queue, wait_for=wait_for)
wait_for = [last_evt]
# substitute sorted
for i, arg_descr in enumerate(self.arguments):
if arg_descr.name in self.sort_arg_names:
args[i] = sorted_args[self.sort_arg_names.index(arg_descr.name)]
base_bit += self.bits
return [arg_val
for arg_descr, arg_val in zip(self.arguments, args)
if arg_descr.name in self.sort_arg_names], last_evt
# }}}
# }}}
# }}}
# {{{ generic parallel list builder
# {{{ kernel template
_LIST_BUILDER_TEMPLATE = Template("""//CL//
% if double_support:
#if __OPENCL_C_VERSION__ < 120
#pragma OPENCL EXTENSION cl_khr_fp64: enable
#endif
#define PYOPENCL_DEFINE_CDOUBLE
% endif
#include <pyopencl-complex.h>
${preamble}
// {{{ declare helper macros for user interface
typedef ${index_type} index_type;
%if is_count_stage:
#define PLB_COUNT_STAGE
%for name, dtype in list_names_and_dtypes:
%if name in count_sharing:
#define APPEND_${name}(value) { /* nothing */ }
%else:
#define APPEND_${name}(value) { ++(*plb_loc_${name}_count); }
%endif
%endfor
%else:
#define PLB_WRITE_STAGE
%for name, dtype in list_names_and_dtypes:
%if name in count_sharing:
#define APPEND_${name}(value) \
{ plb_${name}_list[(*plb_${count_sharing[name]}_index) - 1] \
= value; }
%else:
#define APPEND_${name}(value) \
{ plb_${name}_list[(*plb_${name}_index)++] = value; }
%endif
%endfor
%endif
#define LIST_ARG_DECL ${user_list_arg_decl}
#define LIST_ARGS ${user_list_args}
#define USER_ARG_DECL ${user_arg_decl_no_offset}
#define USER_ARGS ${user_args_no_offset}
// }}}
${generate_template}
// {{{ kernel entry point
__kernel
%if do_not_vectorize:
__attribute__((reqd_work_group_size(1, 1, 1)))
%endif
void ${kernel_name}(
${kernel_list_arg_decl} ${user_arg_decl_with_offset} index_type n)
{
%if not do_not_vectorize:
int lid = get_local_id(0);
index_type gsize = get_global_size(0);
index_type work_group_start = get_local_size(0)*get_group_id(0);
for (index_type i = work_group_start + lid; i < n; i += gsize)
%else:
const int chunk_size = 128;
index_type chunk_base = get_global_id(0)*chunk_size;
index_type gsize = get_global_size(0);
for (; chunk_base < n; chunk_base += gsize*chunk_size)
for (index_type i = chunk_base; i < min(n, chunk_base+chunk_size); ++i)
%endif
{
%if is_count_stage:
%for name, dtype in list_names_and_dtypes:
%if name not in count_sharing:
index_type plb_loc_${name}_count = 0;
%endif
%endfor
%else:
%for name, dtype in list_names_and_dtypes:
%if name not in count_sharing:
index_type plb_${name}_index;
if (plb_${name}_start_index)
%if name in eliminate_empty_output_lists:
plb_${name}_index =
plb_${name}_start_index[
${name}_compressed_indices[i]
];
%else:
plb_${name}_index = plb_${name}_start_index[i];
%endif
else
plb_${name}_index = 0;
%endif
%endfor
%endif
${arg_offset_adjustment}
generate(${kernel_list_arg_values} USER_ARGS i);
%if is_count_stage:
%for name, dtype in list_names_and_dtypes:
%if name not in count_sharing:
if (plb_${name}_count)
plb_${name}_count[i] = plb_loc_${name}_count;
%endif
%endfor
%endif
}
}
// }}}
""", strict_undefined=True)
# }}}
def _get_arg_decl(arg_list):
result = ""
for arg in arg_list:
result += arg.declarator() + ", "
return result
def _get_arg_list(arg_list, prefix=""):
result = ""
for arg in arg_list:
result += prefix + arg.name + ", "
return result
class BuiltList(Record):
pass
class ListOfListsBuilder:
"""Generates and executes code to produce a large number of variable-size
lists, simply.
.. note:: This functionality is provided as a preview. Its interface
is subject to change until this notice is removed.
.. versionadded:: 2013.1
Here's a usage example::
from pyopencl.algorithm import ListOfListsBuilder
builder = ListOfListsBuilder(context, [("mylist", np.int32)], \"\"\"
void generate(LIST_ARG_DECL USER_ARG_DECL index_type i)
{
int count = i % 4;
for (int j = 0; j < count; ++j)
{
APPEND_mylist(count);
}
}
\"\"\", arg_decls=[])
result, event = builder(queue, 2000)
inf = result["mylist"]
assert inf.count == 3000
assert (inf.list.get()[-6:] == [1, 2, 2, 3, 3, 3]).all()
The function `generate` above is called once for each "input object".
Each input object can then generate zero or more list entries.
The number of these input objects is given to :meth:`__call__` as *n_objects*.
List entries are generated by calls to `APPEND_<list name>(value)`.
Multiple lists may be generated at once.
.. automethod:: __init__
.. automethod:: __call__
"""
def __init__(self, context, list_names_and_dtypes, generate_template,
arg_decls, count_sharing=None, devices=None,
name_prefix="plb_build_list", options=[], preamble="",
debug=False, complex_kernel=False,
eliminate_empty_output_lists=[]):
"""
:arg context: A :class:`pyopencl.Context`.
:arg list_names_and_dtypes: a list of `(name, dtype)` tuples
indicating the lists to be built.
:arg generate_template: a snippet of C as described below
:arg arg_decls: A string of comma-separated C argument declarations.
:arg count_sharing: A mapping consisting of `(child, mother)`
indicating that `mother` and `child` will always have the
same number of indices, and the `APPEND` to `mother`
will always happen *before* the `APPEND` to the child.
:arg name_prefix: the name prefix to use for the compiled kernels
:arg options: OpenCL compilation options for kernels using
*generate_template*.
:arg complex_kernel: If `True`, prevents vectorization on CPUs.
:arg eliminate_empty_output_lists: A Python list of list names
for which the empty output lists are eliminated.
*generate_template* may use the following C macros/identifiers:
* `index_type`: expands to C identifier for the index type used
for the calculation
* `USER_ARG_DECL`: expands to the C declarator for `arg_decls`
* `USER_ARGS`: a list of C argument values corresponding to
`user_arg_decl`
* `LIST_ARG_DECL`: expands to a C argument list representing the
data for the output lists. These are escaped prefixed with
`"plg_"` so as to not interfere with user-provided names.
* `LIST_ARGS`: a list of C argument values corresponding to
`LIST_ARG_DECL`
* `APPEND_name(entry)`: inserts `entry` into the list `name`.
*entry* must be a valid C expression of the correct type.
All argument-list related macros have a trailing comma included
if they are non-empty.
*generate_template* must supply a function:
.. code-block:: c
void generate(USER_ARG_DECL LIST_ARG_DECL index_type i)
{
APPEND_mylist(5);
}
Internally, the `kernel_template` is expanded (at least) twice. Once,
for a 'counting' stage where the size of all the lists is determined,
and a second time, for a 'generation' stage where the lists are
actually filled. A `generate` function that has side effects beyond
calling `append` is therefore ill-formed.
.. versionchanged:: 2018.1
Change *eliminate_empty_output_lists* argument type from `bool` to
`list`.
"""
if devices is None:
devices = context.devices
if count_sharing is None:
count_sharing = {}
self.context = context
self.devices = devices
self.list_names_and_dtypes = list_names_and_dtypes
self.generate_template = generate_template
from pyopencl.tools import parse_arg_list
self.arg_decls = parse_arg_list(arg_decls)
# To match with the signature of the user-supplied generate(), arguments
# can't appear to have offsets.
arg_decls_no_offset = []
from pyopencl.tools import VectorArg
for arg in self.arg_decls:
if isinstance(arg, VectorArg) and arg.with_offset:
arg = VectorArg(arg.dtype, arg.name)
arg_decls_no_offset.append(arg)
self.arg_decls_no_offset = arg_decls_no_offset
self.count_sharing = count_sharing
self.name_prefix = name_prefix
self.preamble = preamble
self.options = options
self.debug = debug
self.complex_kernel = complex_kernel
if eliminate_empty_output_lists is True:
eliminate_empty_output_lists = \
[name for name, _ in self.list_names_and_dtypes]
if eliminate_empty_output_lists is False:
eliminate_empty_output_lists = []
self.eliminate_empty_output_lists = eliminate_empty_output_lists
for list_name in self.eliminate_empty_output_lists:
if not any(list_name == name for name, _ in self.list_names_and_dtypes):
raise ValueError(
"invalid list name '%s' in eliminate_empty_output_lists"
% list_name)
# {{{ kernel generators
@memoize_method
def get_scan_kernel(self, index_dtype):
from pyopencl.scan import GenericScanKernel
return GenericScanKernel(
self.context, index_dtype,
arguments="__global %s *ary" % dtype_to_ctype(index_dtype),
input_expr="ary[i]",
scan_expr="a+b", neutral="0",
output_statement="ary[i+1] = item;",
devices=self.devices)
@memoize_method
def get_compress_kernel(self, index_dtype):
arguments = """
__global ${index_t} *count,
__global ${index_t} *compressed_counts,
__global ${index_t} *nonempty_indices,
__global ${index_t} *compressed_indices,
__global ${index_t} *num_non_empty_list
"""
from sys import version_info
if version_info > (3, 0):
arguments = Template(arguments)
else:
arguments = Template(arguments, disable_unicode=True)
from pyopencl.scan import GenericScanKernel
return GenericScanKernel(
self.context, index_dtype,
arguments=arguments.render(index_t=dtype_to_ctype(index_dtype)),
input_expr="count[i] == 0 ? 0 : 1",
scan_expr="a+b", neutral="0",
output_statement="""
if (i + 1 < N) compressed_indices[i + 1] = item;
if (prev_item != item) {
nonempty_indices[item - 1] = i;
compressed_counts[item - 1] = count[i];
}
if (i + 1 == N) *num_non_empty_list = item;
""",
devices=self.devices)
def do_not_vectorize(self):
from pytools import any
return (self.complex_kernel
and any(dev.type & cl.device_type.CPU
for dev in self.context.devices))
@memoize_method
def get_count_kernel(self, index_dtype):
index_ctype = dtype_to_ctype(index_dtype)
from pyopencl.tools import VectorArg, OtherArg
kernel_list_args = [
VectorArg(index_dtype, "plb_%s_count" % name)
for name, dtype in self.list_names_and_dtypes
if name not in self.count_sharing]
user_list_args = []
for name, dtype in self.list_names_and_dtypes:
if name in self.count_sharing:
continue
name = "plb_loc_%s_count" % name
user_list_args.append(OtherArg("%s *%s" % (
index_ctype, name), name))
kernel_name = self.name_prefix+"_count"
from pyopencl.characterize import has_double_support
src = _LIST_BUILDER_TEMPLATE.render(
is_count_stage=True,
kernel_name=kernel_name,
double_support=all(has_double_support(dev) for dev in
self.context.devices),
debug=self.debug,
do_not_vectorize=self.do_not_vectorize(),
eliminate_empty_output_lists=self.eliminate_empty_output_lists,
kernel_list_arg_decl=_get_arg_decl(kernel_list_args),
kernel_list_arg_values=_get_arg_list(user_list_args, prefix="&"),
user_list_arg_decl=_get_arg_decl(user_list_args),
user_list_args=_get_arg_list(user_list_args),
user_arg_decl_with_offset=_get_arg_decl(self.arg_decls),
user_arg_decl_no_offset=_get_arg_decl(self.arg_decls_no_offset),
user_args_no_offset=_get_arg_list(self.arg_decls_no_offset),
arg_offset_adjustment=get_arg_offset_adjuster_code(self.arg_decls),
list_names_and_dtypes=self.list_names_and_dtypes,
count_sharing=self.count_sharing,
name_prefix=self.name_prefix,
generate_template=self.generate_template,
preamble=self.preamble,
index_type=index_ctype,
)
src = str(src)
prg = cl.Program(self.context, src).build(self.options)
knl = getattr(prg, kernel_name)
from pyopencl.tools import get_arg_list_scalar_arg_dtypes
knl.set_scalar_arg_dtypes(get_arg_list_scalar_arg_dtypes(
kernel_list_args+self.arg_decls) + [index_dtype])
return knl
@memoize_method
def get_write_kernel(self, index_dtype):
index_ctype = dtype_to_ctype(index_dtype)
from pyopencl.tools import VectorArg, OtherArg
kernel_list_args = []
kernel_list_arg_values = ""
user_list_args = []
for name, dtype in self.list_names_and_dtypes:
list_name = "plb_%s_list" % name
list_arg = VectorArg(dtype, list_name)
kernel_list_args.append(list_arg)
user_list_args.append(list_arg)
if name in self.count_sharing:
kernel_list_arg_values += "%s, " % list_name