/usr/lib/python2.7/dist-packages/pyopencl/capture_call.py is in python-pyopencl 2017.2.2-1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
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 | from __future__ import with_statement, division
from __future__ import absolute_import
from six.moves import zip
__copyright__ = "Copyright (C) 2013 Andreas Kloeckner"
__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.
"""
import pyopencl as cl
import numpy as np
from pytools.py_codegen import PythonCodeGenerator, Indentation
def capture_kernel_call(kernel, filename, queue, g_size, l_size, *args, **kwargs):
try:
source = kernel._source
except AttributeError:
raise RuntimeError("cannot capture call, kernel source not available")
if source is None:
raise RuntimeError("cannot capture call, kernel source not available")
cg = PythonCodeGenerator()
cg("# generated by pyopencl.capture_call")
cg("")
cg("import numpy as np")
cg("import pyopencl as cl")
cg("from base64 import b64decode")
cg("from zlib import decompress")
cg("mf = cl.mem_flags")
cg("")
cg('CODE = r"""//CL//')
for l in source.split("\n"):
cg(l)
cg('"""')
# {{{ invocation
arg_data = []
cg("")
cg("")
cg("def main():")
with Indentation(cg):
cg("ctx = cl.create_some_context()")
cg("queue = cl.CommandQueue(ctx)")
cg("")
kernel_args = []
for i, arg in enumerate(args):
if isinstance(arg, cl.Buffer):
buf = bytearray(arg.size)
cl.enqueue_copy(queue, buf, arg)
arg_data.append(("arg%d_data" % i, buf))
cg("arg%d = cl.Buffer(ctx, "
"mf.READ_WRITE | cl.mem_flags.COPY_HOST_PTR,"
% i)
cg(" hostbuf=decompress(b64decode(arg%d_data)))"
% i)
kernel_args.append("arg%d" % i)
elif isinstance(arg, (int, float)):
kernel_args.append(repr(arg))
elif isinstance(arg, np.integer):
kernel_args.append("np.%s(%s)" % (
arg.dtype.type.__name__, repr(int(arg))))
elif isinstance(arg, np.floating):
kernel_args.append("np.%s(%s)" % (
arg.dtype.type.__name__, repr(float(arg))))
elif isinstance(arg, np.complexfloating):
kernel_args.append("np.%s(%s)" % (
arg.dtype.type.__name__, repr(complex(arg))))
else:
try:
arg_buf = memoryview(arg)
except Exception:
raise RuntimeError("cannot capture: "
"unsupported arg nr %d (0-based)" % i)
arg_data.append(("arg%d_data" % i, arg_buf))
kernel_args.append("decompress(b64decode(arg%d_data))" % i)
cg("")
g_times_l = kwargs.get("g_times_l", False)
if g_times_l:
dim = max(len(g_size), len(l_size))
l_size = l_size + (1,) * (dim-len(l_size))
g_size = g_size + (1,) * (dim-len(g_size))
g_size = tuple(
gs*ls for gs, ls in zip(g_size, l_size))
global_offset = kwargs.get("global_offset", None)
if global_offset is not None:
kernel_args.append("global_offset=%s" % repr(global_offset))
cg("prg = cl.Program(ctx, CODE).build()")
cg("knl = prg.%s" % kernel.function_name)
if hasattr(kernel, "_scalar_arg_dtypes"):
def strify_dtype(d):
if d is None:
return "None"
d = np.dtype(d)
s = repr(d)
if s.startswith("dtype"):
s = "np."+s
return s
cg("knl.set_scalar_arg_dtypes((%s,))"
% ", ".join(
strify_dtype(dt) for dt in kernel._scalar_arg_dtypes))
cg("knl(queue, %s, %s," % (repr(g_size), repr(l_size)))
cg(" %s)" % ", ".join(kernel_args))
cg("")
cg("queue.finish()")
# }}}
# {{{ data
from zlib import compress
from base64 import b64encode
cg("")
line_len = 70
for name, val in arg_data:
cg("%s = (" % name)
with Indentation(cg):
val = str(b64encode(compress(memoryview(val))))
i = 0
while i < len(val):
cg(repr(val[i:i+line_len]))
i += line_len
cg(")")
# }}}
# {{{ file trailer
cg("")
cg("if __name__ == \"__main__\":")
with Indentation(cg):
cg("main()")
cg("")
cg("# vim: filetype=pyopencl")
# }}}
with open(filename, "w") as outf:
outf.write(cg.get())
|