kernel-tuner 0.1.4__tar.gz → 0.1.6__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. kernel_tuner-0.1.6/LICENSE +202 -0
  2. {kernel_tuner-0.1.4 → kernel_tuner-0.1.6}/PKG-INFO +11 -4
  3. {kernel_tuner-0.1.4 → kernel_tuner-0.1.6}/README.rst +10 -3
  4. {kernel_tuner-0.1.4 → kernel_tuner-0.1.6}/kernel_tuner/c.py +5 -8
  5. kernel_tuner-0.1.6/kernel_tuner/core.py +278 -0
  6. {kernel_tuner-0.1.4 → kernel_tuner-0.1.6}/kernel_tuner/cuda.py +12 -10
  7. kernel_tuner-0.1.6/kernel_tuner/interface.py +462 -0
  8. {kernel_tuner-0.1.4 → kernel_tuner-0.1.6}/kernel_tuner/opencl.py +4 -12
  9. kernel_tuner-0.1.6/kernel_tuner/runners/noodles.py +121 -0
  10. kernel_tuner-0.1.6/kernel_tuner/runners/sequential.py +80 -0
  11. kernel_tuner-0.1.6/kernel_tuner/strategies/__init__.py +0 -0
  12. kernel_tuner-0.1.6/kernel_tuner/strategies/basinhopping.py +58 -0
  13. kernel_tuner-0.1.6/kernel_tuner/strategies/brute_force.py +45 -0
  14. kernel_tuner-0.1.6/kernel_tuner/strategies/diff_evo.py +71 -0
  15. kernel_tuner-0.1.6/kernel_tuner/strategies/minimize.py +206 -0
  16. kernel_tuner-0.1.6/kernel_tuner/strategies/random_sample.py +51 -0
  17. {kernel_tuner-0.1.4 → kernel_tuner-0.1.6}/kernel_tuner/util.py +123 -113
  18. {kernel_tuner-0.1.4 → kernel_tuner-0.1.6}/kernel_tuner.egg-info/PKG-INFO +11 -4
  19. {kernel_tuner-0.1.4 → kernel_tuner-0.1.6}/kernel_tuner.egg-info/SOURCES.txt +12 -4
  20. kernel_tuner-0.1.6/kernel_tuner.egg-info/requires.txt +2 -0
  21. kernel_tuner-0.1.6/requirements.txt +2 -0
  22. {kernel_tuner-0.1.4 → kernel_tuner-0.1.6}/setup.cfg +0 -1
  23. {kernel_tuner-0.1.4 → kernel_tuner-0.1.6}/setup.py +2 -2
  24. {kernel_tuner-0.1.4 → kernel_tuner-0.1.6}/test/test_c_functions.py +1 -1
  25. {kernel_tuner-0.1.4 → kernel_tuner-0.1.6}/test/test_cuda_functions.py +0 -3
  26. {kernel_tuner-0.1.4 → kernel_tuner-0.1.6}/test/test_cuda_mocked.py +1 -1
  27. kernel_tuner-0.1.6/test/test_device_interface.py +50 -0
  28. {kernel_tuner-0.1.4 → kernel_tuner-0.1.6}/test/test_interface.py +33 -46
  29. kernel_tuner-0.1.6/test/test_minimize.py +92 -0
  30. {kernel_tuner-0.1.4 → kernel_tuner-0.1.6}/test/test_opencl_functions.py +2 -2
  31. kernel_tuner-0.1.6/test/test_runners.py +125 -0
  32. kernel_tuner-0.1.4/test/test_kernel_tuner.py → kernel_tuner-0.1.6/test/test_util_functions.py +26 -7
  33. kernel_tuner-0.1.4/LICENSE +0 -14
  34. kernel_tuner-0.1.4/kernel_tuner/core.py +0 -198
  35. kernel_tuner-0.1.4/kernel_tuner/interface.py +0 -355
  36. kernel_tuner-0.1.4/kernel_tuner/runners/random_sample.py +0 -101
  37. kernel_tuner-0.1.4/kernel_tuner/runners/sequential_brute_force.py +0 -97
  38. kernel_tuner-0.1.4/kernel_tuner.egg-info/requires.txt +0 -1
  39. kernel_tuner-0.1.4/requirements.txt +0 -1
  40. kernel_tuner-0.1.4/test/test_runners.py +0 -24
  41. {kernel_tuner-0.1.4 → kernel_tuner-0.1.6}/MANIFEST.in +0 -0
  42. {kernel_tuner-0.1.4 → kernel_tuner-0.1.6}/kernel_tuner/__init__.py +0 -0
  43. {kernel_tuner-0.1.4 → kernel_tuner-0.1.6}/kernel_tuner/runners/__init__.py +0 -0
  44. {kernel_tuner-0.1.4 → kernel_tuner-0.1.6}/kernel_tuner.egg-info/dependency_links.txt +0 -0
  45. {kernel_tuner-0.1.4 → kernel_tuner-0.1.6}/kernel_tuner.egg-info/top_level.txt +0 -0
@@ -0,0 +1,202 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "{}"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright {yyyy} {name of copyright owner}
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
202
+
@@ -1,12 +1,12 @@
1
1
  Metadata-Version: 1.1
2
2
  Name: kernel_tuner
3
- Version: 0.1.4
3
+ Version: 0.1.6
4
4
  Summary: A simple CUDA/OpenCL kernel tuner in Python
5
5
  Home-page: http://benvanwerkhoven.github.io/kernel_tuner/
6
6
  Author: Ben van Werkhoven
7
7
  Author-email: b.vanwerkhoven@esciencecenter.nl
8
8
  License: Apache 2.0
9
- Description: Kernel Tuner: A simple CUDA/OpenCL kernel tuner in Python
9
+ Description: Kernel Tuner: A simple CUDA/OpenCL Auto-Tuner in Python
10
10
  =========================================================
11
11
 
12
12
  |Build Status| |Codacy Badge| |Codacy Badge2|
@@ -139,6 +139,13 @@ Description: Kernel Tuner: A simple CUDA/OpenCL kernel tuner in Python
139
139
  `documentation <http://benvanwerkhoven.github.io/kernel_tuner/hostcode.html>`__
140
140
  for a detailed explanation of the kernel tuner Python script.
141
141
 
142
+ Search strategies for tuning
143
+ ----------------------------
144
+
145
+ Kernel Tuner supports several strategies: brute_force (default), random_sample, minimize, basinhopping, and diff_evo (differential
146
+ evolution). Using different strategies is easy, you only need to specify to ``tune_kernel`` which strategy you would like to use, for example: ``strategy="basinhopping", method="TNC"``. For a full overview of the supported search strategies and methods please see the
147
+ `user api <http://benvanwerkhoven.github.io/kernel_tuner/user-api.html>`__.
148
+
142
149
  Correctness verification
143
150
  ------------------------
144
151
 
@@ -165,8 +172,8 @@ Description: Kernel Tuner: A simple CUDA/OpenCL kernel tuner in Python
165
172
 
166
173
  @misc{
167
174
  author = {Ben van Werkhoven},
168
- title = {Kernel Tuner: A simple CUDA/OpenCL Kernel Tuner in Python},
169
- year = {2017}
175
+ title = {Kernel Tuner: A simple CUDA/OpenCL Auto-Tuner in Python},
176
+ year = {2018}
170
177
  }
171
178
 
172
179
  Related work
@@ -1,4 +1,4 @@
1
- Kernel Tuner: A simple CUDA/OpenCL kernel tuner in Python
1
+ Kernel Tuner: A simple CUDA/OpenCL Auto-Tuner in Python
2
2
  =========================================================
3
3
 
4
4
  |Build Status| |Codacy Badge| |Codacy Badge2|
@@ -131,6 +131,13 @@ and the
131
131
  `documentation <http://benvanwerkhoven.github.io/kernel_tuner/hostcode.html>`__
132
132
  for a detailed explanation of the kernel tuner Python script.
133
133
 
134
+ Search strategies for tuning
135
+ ----------------------------
136
+
137
+ Kernel Tuner supports several strategies: brute_force (default), random_sample, minimize, basinhopping, and diff_evo (differential
138
+ evolution). Using different strategies is easy, you only need to specify to ``tune_kernel`` which strategy you would like to use, for example: ``strategy="basinhopping", method="TNC"``. For a full overview of the supported search strategies and methods please see the
139
+ `user api <http://benvanwerkhoven.github.io/kernel_tuner/user-api.html>`__.
140
+
134
141
  Correctness verification
135
142
  ------------------------
136
143
 
@@ -157,8 +164,8 @@ A scientific paper about the Kernel Tuner is in preparation, in the meantime ple
157
164
 
158
165
  @misc{
159
166
  author = {Ben van Werkhoven},
160
- title = {Kernel Tuner: A simple CUDA/OpenCL Kernel Tuner in Python},
161
- year = {2017}
167
+ title = {Kernel Tuner: A simple CUDA/OpenCL Auto-Tuner in Python},
168
+ year = {2018}
162
169
  }
163
170
 
164
171
  Related work
@@ -57,11 +57,6 @@ class CFunctions(object):
57
57
  self.env = env
58
58
  self.name = platform.processor()
59
59
 
60
- def get_environment(self):
61
- """Return dictionary with information about the environment"""
62
- return self.env
63
-
64
-
65
60
  def ready_argument_list(self, arguments):
66
61
  """ready argument list to be passed to the C function
67
62
 
@@ -119,8 +114,7 @@ class CFunctions(object):
119
114
  if self.lib != None:
120
115
  self.cleanup_lib()
121
116
 
122
- filename = get_temp_filename()
123
- source_file = filename+".cc"
117
+ suffix = ".cc"
124
118
 
125
119
  if not "extern \"C\"" in kernel_string:
126
120
  kernel_string = "extern \"C\" {\n" + kernel_string + "\n}"
@@ -136,7 +130,7 @@ class CFunctions(object):
136
130
  self.compiler = "nvcc"
137
131
 
138
132
  if self.compiler == "nvcc":
139
- source_file = source_file[:-1] + "u"
133
+ suffix = suffix[:-1] + "u"
140
134
  compiler_options = ["-Xcompiler=" + c for c in compiler_options]
141
135
 
142
136
  if self.compiler_options:
@@ -150,6 +144,9 @@ class CFunctions(object):
150
144
  logging.debug('compiler_options ' + " ".join(compiler_options))
151
145
  logging.debug('lib_args ' + " ".join(lib_args))
152
146
 
147
+ source_file = get_temp_filename(suffix=suffix)
148
+ filename = ".".join(source_file.split(".")[:-1])
149
+
153
150
  try:
154
151
  write_file(source_file, kernel_string)
155
152
 
@@ -0,0 +1,278 @@
1
+ """ Module for grouping the core functionality needed by most runners """
2
+ from __future__ import print_function
3
+
4
+ from collections import namedtuple
5
+ import resource
6
+ import logging
7
+ import numpy
8
+
9
+ from kernel_tuner.cuda import CudaFunctions
10
+ from kernel_tuner.opencl import OpenCLFunctions
11
+ from kernel_tuner.c import CFunctions
12
+ import kernel_tuner.util as util
13
+
14
+ KernelInstance = namedtuple("KernelInstance", ["name", "kernel_string", "temp_files", "threads", "grid", "params", "arguments"])
15
+
16
+ class DeviceInterface(object):
17
+ """Class that offers a High-Level Device Interface to the rest of the Kernel Tuner"""
18
+
19
+ def __init__(self, original_kernel, device=0, platform=0, lang=None, quiet=False, compiler_options=None, iterations=7):
20
+ """ Instantiate the DeviceInterface, based on language in kernel source
21
+
22
+ :param original_kernel: The source of the kernel as passed to tune_kernel
23
+ :type original_kernel: kernel source as a string or a list of strings denoting filenames
24
+
25
+ :param device: CUDA/OpenCL device to use, in case you have multiple
26
+ CUDA-capable GPUs or OpenCL devices you may use this to select one,
27
+ 0 by default. Ignored if you are tuning host code by passing lang="C".
28
+ :type device: int
29
+
30
+ :param platform: OpenCL platform to use, in case you have multiple
31
+ OpenCL platforms you may use this to select one,
32
+ 0 by default. Ignored if not using OpenCL.
33
+ :type device: int
34
+
35
+ :param lang: Specifies the language used for GPU kernels. The kernel_tuner
36
+ automatically detects the language, but if it fails, you may specify
37
+ the language using this argument, currently supported: "CUDA", "OpenCL", or "C"
38
+ :type lang: string
39
+
40
+ :param compiler_options: The compiler options to use when compiling kernels for this device.
41
+ :type compiler_options: list of strings
42
+
43
+ :param iterations: Number of iterations to be used when benchmarking using this device.
44
+ :type iterations: int
45
+
46
+ """
47
+ logging.debug('DeviceInterface instantiated, lang=%s', lang)
48
+
49
+ lang = util.detect_language(lang, original_kernel)
50
+ if lang == "CUDA":
51
+ dev = CudaFunctions(device, compiler_options=compiler_options, iterations=iterations)
52
+ elif lang == "OpenCL":
53
+ dev = OpenCLFunctions(device, platform, compiler_options=compiler_options, iterations=iterations)
54
+ elif lang == "C":
55
+ dev = CFunctions(compiler_options=compiler_options, iterations=iterations)
56
+ else:
57
+ raise Exception("Sorry, support for languages other than CUDA, OpenCL, or C is not implemented yet")
58
+ self.lang = lang
59
+ self.dev = dev
60
+ self.name = dev.name
61
+ if not quiet:
62
+ print("Using: " + self.dev.name)
63
+
64
+ def benchmark(self, func, gpu_args, instance, verbose):
65
+ """benchmark the kernel instance"""
66
+ logging.debug('benchmark ' + instance.name)
67
+ logging.debug('thread block dimensions x,y,z=%d,%d,%d', *instance.threads)
68
+ logging.debug('grid dimensions x,y,z=%d,%d,%d', *instance.grid)
69
+
70
+ time = None
71
+ try:
72
+ time = self.dev.benchmark(func, gpu_args, instance.threads, instance.grid)
73
+ except Exception as e:
74
+ #some launches may fail because too many registers are required
75
+ #to run the kernel given the current thread block size
76
+ #the desired behavior is to simply skip over this configuration
77
+ #and proceed to try the next one
78
+ if "too many resources requested for launch" in str(e) or "OUT_OF_RESOURCES" in str(e):
79
+ logging.debug('benchmark fails due to runtime failure too many resources required')
80
+ if verbose:
81
+ print("skipping config", instance.name, "reason: too many resources requested for launch")
82
+ else:
83
+ logging.debug('benchmark encountered runtime failure: ' + str(e))
84
+ print("Error while benchmarking:", instance.name)
85
+ raise e
86
+ return time
87
+
88
+ def check_kernel_correctness(self, func, gpu_args, instance, answer, atol, verify, verbose):
89
+ """runs the kernel once and checks the result against answer"""
90
+ logging.debug('check_kernel_correctness')
91
+ params = instance.params
92
+
93
+ #zero GPU memory for output arguments
94
+ for i, arg in enumerate(instance.arguments):
95
+ if answer[i] is not None:
96
+ self.dev.memset(gpu_args[i], 0, arg.nbytes)
97
+
98
+ #run the kernel
99
+ if not self.run_kernel(func, gpu_args, instance):
100
+ return True #runtime failure occured that should be ignored, skip correctness check
101
+
102
+ def _ravel(a):
103
+ if hasattr(a, 'ravel') and len(a.shape) > 1:
104
+ return a.ravel()
105
+ return a
106
+
107
+ def _flatten(a):
108
+ if hasattr(a, 'flatten'):
109
+ return a.flatten()
110
+ return a
111
+
112
+ #check correctness of each output argument
113
+ correct = True
114
+ for i, arg in enumerate(instance.arguments):
115
+ expected = answer[i]
116
+ if expected is not None:
117
+ result_host = numpy.zeros_like(arg)
118
+ self.dev.memcpy_dtoh(result_host, gpu_args[i])
119
+
120
+ result_host = _ravel(result_host)
121
+ expected = _flatten(expected)
122
+ if verify is None:
123
+ output_test = numpy.allclose(expected, result_host, atol=atol)
124
+ else:
125
+ try:
126
+ output_test = verify(expected, result_host, atol=atol)
127
+ except TypeError:
128
+ output_test = verify(expected, result_host)
129
+
130
+ if not output_test and verbose:
131
+ print("Error: " + util.get_config_string(params) + " detected during correctness check")
132
+ print("Printing kernel output and expected result, set verbose=False to suppress this debug print")
133
+ numpy.set_printoptions(edgeitems=50)
134
+ print("Kernel output:")
135
+ print(result_host)
136
+ print("Expected:")
137
+ print(expected)
138
+ correct = correct and output_test
139
+ del result_host
140
+ if not correct:
141
+ logging.debug('correctness check has found a correctness issue')
142
+ raise Exception("Error: " + util.get_config_string(params) + " failed correctness check")
143
+ return correct
144
+
145
+ def compile_and_benchmark(self, gpu_args, params, kernel_options, tuning_options):
146
+ """ Compile and benchmark a kernel instance based on kernel strings and parameters """
147
+
148
+ instance_string = util.get_instance_string(params)
149
+
150
+ logging.debug('compile_and_benchmark ' + instance_string)
151
+ mem_usage = round(resource.getrusage(resource.RUSAGE_SELF).ru_maxrss/1024.0, 1)
152
+ logging.debug('Memory usage : %2.2f MB', mem_usage)
153
+
154
+ verbose = tuning_options.verbose
155
+
156
+ instance = self.create_kernel_instance(kernel_options, params, verbose)
157
+ if instance is None:
158
+ return None
159
+
160
+ try:
161
+ #compile the kernel
162
+ func = self.compile_kernel(instance, verbose)
163
+ if func is None:
164
+ return None
165
+
166
+ #add constant memory arguments to compiled module
167
+ if kernel_options.cmem_args is not None:
168
+ self.dev.copy_constant_memory_args(kernel_options.cmem_args)
169
+
170
+ #test kernel for correctness and benchmark
171
+ if tuning_options.answer is not None:
172
+ self.check_kernel_correctness(func, gpu_args, instance, tuning_options.answer, tuning_options.atol, tuning_options.verify, verbose)
173
+
174
+ #benchmark
175
+ time = self.benchmark(func, gpu_args, instance, verbose)
176
+
177
+ except Exception as e:
178
+ #dump kernel_string to temp file
179
+ temp_filename = util.get_temp_filename(suffix=".c")
180
+ util.write_file(temp_filename, instance.kernel_string)
181
+ print("Error while compiling or benchmarking, see source files: " + temp_filename + " ".join(instance.temp_files.values()))
182
+ raise e
183
+
184
+ #clean up any temporary files, if no error occured
185
+ for v in instance.temp_files.values():
186
+ util.delete_temp_file(v)
187
+
188
+ return time
189
+
190
+ def compile_kernel(self, instance, verbose):
191
+ """compile the kernel for this specific instance"""
192
+ logging.debug('compile_kernel ' + instance.name)
193
+
194
+ #compile kernel_string into device func
195
+ func = None
196
+ try:
197
+ func = self.dev.compile(instance.name, instance.kernel_string)
198
+ except Exception as e:
199
+ #compiles may fail because certain kernel configurations use too
200
+ #much shared memory for example, the desired behavior is to simply
201
+ #skip over this configuration and try the next one
202
+ if "uses too much shared data" in str(e):
203
+ logging.debug('compile_kernel failed due to kernel using too much shared memory')
204
+ if verbose:
205
+ print("skipping config", instance.name, "reason: too much shared memory used")
206
+ else:
207
+ logging.debug('compile_kernel failed due to error: ' + str(e))
208
+ print("Error while compiling:", instance.name)
209
+ raise e
210
+ return func
211
+
212
+ def copy_constant_memory_args(self, cmem_args):
213
+ """adds constant memory arguments to the most recently compiled module, if using CUDA"""
214
+ if self.lang == "CUDA":
215
+ self.dev.copy_constant_memory_args(cmem_args)
216
+ else:
217
+ raise Exception("Error cannot copy constant memory arguments when language is not CUDA")
218
+
219
+ def create_kernel_instance(self, kernel_options, params, verbose):
220
+ """create kernel instance from kernel source, parameters, problem size, grid divisors, and so on"""
221
+ instance_string = util.get_instance_string(params)
222
+ grid_div = (kernel_options.grid_div_x, kernel_options.grid_div_y, kernel_options.grid_div_z)
223
+
224
+ #setup thread block and grid dimensions
225
+ threads, grid = util.setup_block_and_grid(kernel_options.problem_size, grid_div, params, kernel_options.block_size_names)
226
+ if numpy.prod(threads) > self.dev.max_threads:
227
+ if verbose:
228
+ print("skipping config", instance_string, "reason: too many threads per block")
229
+ return None
230
+
231
+ #obtain the kernel_string and prepare additional files, if any
232
+ temp_files = dict()
233
+ original_kernel = kernel_options.kernel_string
234
+ if isinstance(original_kernel, list):
235
+ kernel_string, temp_files = util.prepare_list_of_files(original_kernel, params, grid)
236
+ else:
237
+ kernel_string = util.get_kernel_string(original_kernel, params)
238
+
239
+ #prepare kernel_string for compilation
240
+ name, kernel_string = util.setup_kernel_strings(kernel_options.kernel_name, kernel_string, params, grid)
241
+
242
+ #collect everything we know about this instance and return it
243
+ return KernelInstance(name, kernel_string, temp_files, threads, grid, params, kernel_options.arguments)
244
+
245
+ def get_environment(self):
246
+ """Return dictionary with information about the environment"""
247
+ return self.dev.env
248
+
249
+ def memcpy_dtoh(self, dest, src):
250
+ """perform a device to host memory copy"""
251
+ self.dev.memcpy_dtoh(dest, src)
252
+
253
+ def ready_argument_list(self, arguments):
254
+ """ready argument list to be passed to the kernel, allocates gpu mem if necessary"""
255
+ return self.dev.ready_argument_list(arguments)
256
+
257
+ def run_kernel(self, func, gpu_args, instance):
258
+ """ Run a compiled kernel instance on a device """
259
+ logging.debug('run_kernel %s', instance.name)
260
+ logging.debug('thread block dims (%d, %d, %d)', *instance.threads)
261
+ logging.debug('grid dims (%d, %d, %d)', *instance.grid)
262
+
263
+ try:
264
+ self.dev.run_kernel(func, gpu_args, instance.threads, instance.grid)
265
+ except Exception as e:
266
+ if "too many resources requested for launch" in str(e) or "OUT_OF_RESOURCES" in str(e):
267
+ logging.debug('ignoring runtime failure due to too many resources required')
268
+ return False
269
+ else:
270
+ logging.debug('encountered unexpected runtime failure: ' + str(e))
271
+ raise e
272
+ return True
273
+
274
+
275
+ def __del__(self):
276
+ if hasattr(self, 'dev'):
277
+ del self.dev
278
+
@@ -8,10 +8,10 @@ import numpy
8
8
  #and run tests without pycuda installed
9
9
  try:
10
10
  import pycuda.driver as drv
11
- from pycuda.compiler import SourceModule
11
+ from pycuda.compiler import DynamicSourceModule
12
12
  except ImportError:
13
13
  drv = None
14
- SourceModule = None
14
+ DynamicSourceModule = None
15
15
 
16
16
 
17
17
  class CudaFunctions(object):
@@ -55,15 +55,15 @@ class CudaFunctions(object):
55
55
  env["device_properties"] = devprops
56
56
  self.env = env
57
57
  self.name = env["device_name"]
58
+ self.allocations = []
58
59
 
59
60
  def __del__(self):
61
+ for gpu_mem in self.allocations:
62
+ if hasattr(gpu_mem, 'free'): #if needed for when using mocks during testing
63
+ gpu_mem.free()
60
64
  if hasattr(self, 'context'):
61
65
  self.context.pop()
62
66
 
63
- def get_environment(self):
64
- """Return dictionary with information about the environment"""
65
- return self.env
66
-
67
67
  def ready_argument_list(self, arguments):
68
68
  """ready argument list to be passed to the kernel, allocates gpu mem
69
69
 
@@ -79,7 +79,9 @@ class CudaFunctions(object):
79
79
  for arg in arguments:
80
80
  # if arg i is a numpy array copy to device
81
81
  if isinstance(arg, numpy.ndarray):
82
- gpu_args.append(drv.mem_alloc(arg.nbytes))
82
+ alloc = drv.mem_alloc(arg.nbytes)
83
+ self.allocations.append(alloc)
84
+ gpu_args.append(alloc)
83
85
  drv.memcpy_htod(gpu_args[-1], arg)
84
86
  else: # if not an array, just pass argument along
85
87
  gpu_args.append(arg)
@@ -106,7 +108,7 @@ class CudaFunctions(object):
106
108
  if self.compiler_options:
107
109
  compiler_options += self.compiler_options
108
110
 
109
- self.current_module = SourceModule(kernel_string, options=self.compiler_options + ["-e", kernel_name],
111
+ self.current_module = DynamicSourceModule(kernel_string, options=self.compiler_options + ["-e", kernel_name],
110
112
  arch='compute_' + self.cc, code='sm_' + self.cc,
111
113
  cache_dir=False, no_extern_c=no_extern_c)
112
114
  func = self.current_module.get_function(kernel_name)
@@ -209,13 +211,13 @@ class CudaFunctions(object):
209
211
  :type allocation: pycuda.driver.DeviceAllocation
210
212
 
211
213
  :param value: The value to set the memory to
212
- :type value: a single 32-bit float or int
214
+ :type value: a single 8-bit unsigned int
213
215
 
214
216
  :param size: The size of to the allocation unit in bytes
215
217
  :type size: int
216
218
 
217
219
  """
218
- drv.memset_d8(allocation, value, size)
220
+ drv.memset_d8(allocation, int(value), int(size))
219
221
 
220
222
  def memcpy_dtoh(self, dest, src):
221
223
  """perform a device to host memory copy