Newer
Older
from __future__ import division, absolute_import, print_function
__copyright__ = "Copyright (C) 2012 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 six
from six.moves import range
import numpy as np
import loopy as lp
import pyopencl as cl
Andreas Klöckner
committed
import pyopencl.clmath # noqa
logger = logging.getLogger(__name__)
try:
import faulthandler
except ImportError:
pass
else:
faulthandler.enable()
from pyopencl.tools import pytest_generate_tests_for_pyopencl \
as pytest_generate_tests
__all__ = [
"pytest_generate_tests",
"cl" # 'cl.create_some_context'
from loopy.version import LOOPY_USE_LANGUAGE_VERSION_2018_1 # noqa
Andreas Klöckner
committed
def test_globals_decl_once_with_multi_subprogram(ctx_factory):
ctx = ctx_factory()
queue = cl.CommandQueue(ctx)
a = np.random.randn(16)
cnst = np.random.randn(16)
knl = lp.make_kernel(
"{[i, ii]: 0<=i, ii<n}",
"""
out[i] = a[i]+cnst[i]{id=first}
out[ii] = 2*out[ii]+cnst[ii]{id=second}
""",
[lp.TemporaryVariable(
'cnst', shape=('n'), initializer=cnst,
scope=lp.temp_var_scope.GLOBAL,
read_only=True), '...'])
knl = lp.fix_parameters(knl, n=16)
knl = lp.add_barrier(knl, "id:first", "id:second")
knl = lp.split_iname(knl, "i", 2, outer_tag="g.0", inner_tag="l.0")
knl = lp.split_iname(knl, "ii", 2, outer_tag="g.0", inner_tag="l.0")
evt, (out,) = knl(queue, a=a)
assert np.linalg.norm(out-((2*(a+cnst)+cnst))) <= 1e-15
Andreas Klöckner
committed
def test_complicated_subst(ctx_factory):
Andreas Klöckner
committed
knl = lp.make_kernel(
Andreas Klöckner
committed
"{[i]: 0<=i<n}",
"""
f(x) := x*a[x]
g(x) := 12 + f(x)
h(x) := 1 + g(x) + 20*g$two(x)
a[i] = h$one(i) * h$two(i)
Andreas Klöckner
committed
knl = lp.expand_subst(knl, "... > id:h and tag:two > id:g and tag:two")
Andreas Klöckner
committed
Andreas Klöckner
committed
Andreas Klöckner
committed
for letter, how_many in [
("f", 1),
("g", 1),
("h", 2)
]:
substs_with_letter = sum(1 for k in sr_keys if k.startswith(letter))
assert substs_with_letter == how_many
def test_type_inference_no_artificial_doubles(ctx_factory):
ctx = ctx_factory()
knl = lp.make_kernel(
"{[i]: 0<=i<n}",
"""
<> bb = a[i] - b[i]
c[i] = bb
""",
[
lp.GlobalArg("a", np.float32, shape=("n",)),
lp.GlobalArg("b", np.float32, shape=("n",)),
lp.GlobalArg("c", np.float32, shape=("n",)),
lp.ValueArg("n", np.int32),
],
assumptions="n>=1")
knl = lp.preprocess_kernel(knl, ctx.devices[0])
for k in lp.generate_loop_schedules(knl):
code = lp.generate_code(k)
assert "double" not in code
def test_type_inference_with_type_dependencies():
knl = lp.make_kernel(
"{[i]: i=0}",
"""
<>a = 99
a = a + 1
<>b = 0
<>c = 1
b = b + c + 1.0
c = b + c
<>d = b + 2 + 1j
""",
"...")
knl = lp.infer_unknown_types(knl)
from loopy.types import to_loopy_type
assert knl.temporary_variables["a"].dtype == to_loopy_type(np.int32)
assert knl.temporary_variables["b"].dtype == to_loopy_type(np.float32)
assert knl.temporary_variables["c"].dtype == to_loopy_type(np.float32)
assert knl.temporary_variables["d"].dtype == to_loopy_type(np.complex128)
def test_sized_and_complex_literals(ctx_factory):
ctx = ctx_factory()
knl = lp.make_kernel(
"{[i]: 0<=i<n}",
"""
<> aa = 5jf
<> bb = 5j
a[i] = imag(aa)
b[i] = imag(bb)
c[i] = 5f
""",
[
lp.GlobalArg("a", np.float32, shape=("n",)),
lp.GlobalArg("b", np.float32, shape=("n",)),
lp.GlobalArg("c", np.float32, shape=("n",)),
lp.ValueArg("n", np.int32),
],
assumptions="n>=1")
lp.auto_test_vs_ref(knl, ctx, knl, parameters=dict(n=5))
def test_simple_side_effect(ctx_factory):
ctx = ctx_factory()
knl = lp.make_kernel(
"{[i,j]: 0<=i,j<100}",
"""
a[i] = a[i] + 1
""",
[lp.GlobalArg("a", np.float32, shape=(100,))]
)
knl = lp.preprocess_kernel(knl, ctx.devices[0])
kernel_gen = lp.generate_loop_schedules(knl)
for gen_knl in kernel_gen:
compiled = lp.CompiledKernel(ctx, gen_knl)
def test_owed_barriers(ctx_factory):
ctx = ctx_factory()
knl = lp.make_kernel(
"{[i]: 0<=i<100}",
[
Andreas Klöckner
committed
"<float32> z[i] = a[i]"
],
[lp.GlobalArg("a", np.float32, shape=(100,))]
Andreas Klöckner
committed
knl = lp.tag_inames(knl, dict(i="l.0"))
knl = lp.preprocess_kernel(knl, ctx.devices[0])
kernel_gen = lp.generate_loop_schedules(knl)
for gen_knl in kernel_gen:
compiled = lp.CompiledKernel(ctx, gen_knl)
Andreas Klöckner
committed
def test_wg_too_small(ctx_factory):
ctx = ctx_factory()
knl = lp.make_kernel(
Andreas Klöckner
committed
"{[i]: 0<=i<100}",
[
Andreas Klöckner
committed
"<float32> z[i] = a[i] {id=copy}"
Andreas Klöckner
committed
],
[lp.GlobalArg("a", np.float32, shape=(100,))],
Andreas Klöckner
committed
local_sizes={0: 16})
Andreas Klöckner
committed
knl = lp.tag_inames(knl, dict(i="l.0"))
knl = lp.preprocess_kernel(knl, ctx.devices[0])
Andreas Klöckner
committed
kernel_gen = lp.generate_loop_schedules(knl)
Andreas Klöckner
committed
import pytest
Andreas Klöckner
committed
for gen_knl in kernel_gen:
Andreas Klöckner
committed
with pytest.raises(RuntimeError):
lp.CompiledKernel(ctx, gen_knl).get_code()
Andreas Klöckner
committed
def test_multi_cse(ctx_factory):
ctx = ctx_factory()
knl = lp.make_kernel(
"{[i]: 0<=i<100}",
[
Andreas Klöckner
committed
"<float32> z[i] = a[i] + a[i]**2"
],
[lp.GlobalArg("a", np.float32, shape=(100,))],
local_sizes={0: 16})
knl = lp.split_iname(knl, "i", 16, inner_tag="l.0")
knl = lp.add_prefetch(knl, "a", [])
knl = lp.preprocess_kernel(knl, ctx.devices[0])
kernel_gen = lp.generate_loop_schedules(knl)
for gen_knl in kernel_gen:
compiled = lp.CompiledKernel(ctx, gen_knl)
def make_random_value():
from random import randrange, uniform
v = randrange(3)
if v == 0:
while True:
z = randrange(-1000, 1000)
if z:
return z
elif v == 1:
return uniform(-10, 10)
else:
cval = uniform(-10, 10) + 1j*uniform(-10, 10)
if randrange(0, 2) == 0:
return np.complex128(cval)
else:
return np.complex128(cval)
def make_random_expression(var_values, size):
from random import randrange
import pymbolic.primitives as p
v = randrange(1500)
size[0] += 1
if v < 500 and size[0] < 40:
term_count = randrange(2, 5)
if randrange(2) < 1:
cls = p.Sum
else:
cls = p.Product
return cls(tuple(
make_random_expression(var_values, size)
for i in range(term_count)))
elif v < 750:
return make_random_value()
elif v < 1000:
var_name = "var_%d" % len(var_values)
assert var_name not in var_values
var_values[var_name] = make_random_value()
return p.Variable(var_name)
elif v < 1250:
# Cannot use '-' because that destroys numpy constants.
return p.Sum((
make_random_expression(var_values, size),
- make_random_expression(var_values, size)))
elif v < 1500:
# Cannot use '/' because that destroys numpy constants.
return p.Quotient(
make_random_expression(var_values, size),
make_random_expression(var_values, size))
def generate_random_fuzz_examples(count):
size = [0]
var_values = {}
expr = make_random_expression(var_values, size)
yield expr, var_values
def test_fuzz_code_generator(ctx_factory):
ctx = ctx_factory()
queue = cl.CommandQueue(ctx)
if ctx.devices[0].platform.vendor.startswith("Advanced Micro"):
pytest.skip("crashes on AMD 15.12")
#from expr_fuzz import get_fuzz_examples
#for expr, var_values in get_fuzz_examples():
for expr, var_values in generate_random_fuzz_examples(50):
from pymbolic import evaluate
try:
true_value = evaluate(expr, var_values)
except ZeroDivisionError:
continue
def get_dtype(x):
if isinstance(x, (complex, np.complexfloating)):
return np.complex128
else:
return np.float64
knl = lp.make_kernel("{ : }",
[lp.GlobalArg("value", np.complex128, shape=())]
+ [
])
ck = lp.CompiledKernel(ctx, knl)
evt, (lp_value,) = ck(queue, out_host=True, **var_values)
err = abs(true_value-lp_value)/abs(true_value)
if abs(err) > 1e-10:
print(80*"-")
print("WRONG: rel error=%g" % err)
print("true=%r" % true_value)
print("loopy=%r" % lp_value)
print(80*"-")
print(80*"-")
print(var_values)
print(80*"-")
print(repr(expr))
print(80*"-")
print(expr)
print(80*"-")
def test_bare_data_dependency(ctx_factory):
Andreas Klöckner
committed
dtype = np.dtype(np.float32)
ctx = ctx_factory()
queue = cl.CommandQueue(ctx)
knl = lp.make_kernel(
Andreas Klöckner
committed
[
Andreas Klöckner
committed
],
[
Andreas Klöckner
committed
],
[
lp.GlobalArg("a", dtype, shape=("n"), order="C"),
Andreas Klöckner
committed
])
cknl = lp.CompiledKernel(ctx, knl)
n = 20000
evt, (a,) = cknl(queue, n=n, out_host=True)
Andreas Klöckner
committed
assert a.shape == (n,)
assert (a == 1).all()
Andreas Klöckner
committed
Andreas Klöckner
committed
@pytest.mark.skipif("sys.version_info < (2,6)")
def test_ilp_write_race_detection_global(ctx_factory):
Andreas Klöckner
committed
ctx = ctx_factory()
knl = lp.make_kernel(
Andreas Klöckner
committed
[
Andreas Klöckner
committed
],
[
lp.GlobalArg("a", np.float32),
lp.ValueArg("n", np.int32, approximately=1000),
Andreas Klöckner
committed
],
Andreas Klöckner
committed
knl = lp.tag_inames(knl, dict(j="ilp"))
Andreas Klöckner
committed
knl = lp.preprocess_kernel(knl, ctx.devices[0])
with lp.CacheMode(False):
from loopy.diagnostic import WriteRaceConditionWarning
from warnings import catch_warnings
with catch_warnings(record=True) as warn_list:
list(lp.generate_loop_schedules(knl))
assert any(isinstance(w.message, WriteRaceConditionWarning)
for w in warn_list)
def test_ilp_write_race_avoidance_local(ctx_factory):
knl = lp.make_kernel(
knl = lp.tag_inames(knl, dict(i="l.0", j="ilp"))
knl = lp.preprocess_kernel(knl, ctx.devices[0])
for k in lp.generate_loop_schedules(knl):
assert k.temporary_variables["a"].shape == (16, 17)
def test_ilp_write_race_avoidance_private(ctx_factory):
knl = lp.make_kernel(
knl = lp.tag_inames(knl, dict(j="ilp"))
Andreas Klöckner
committed
knl = lp.preprocess_kernel(knl, ctx.devices[0])
for k in lp.generate_loop_schedules(knl):
assert k.temporary_variables["a"].shape == (16,)
Andreas Klöckner
committed
Andreas Klöckner
committed
def test_write_parameter(ctx_factory):
dtype = np.float32
Andreas Klöckner
committed
ctx = ctx_factory()
knl = lp.make_kernel(
a = sum((i,j), i*j)
b = sum(i, sum(j, i*j))
n = 15
""",
lp.GlobalArg("a", dtype, shape=()),
lp.GlobalArg("b", dtype, shape=()),
lp.ValueArg("n", np.int32, approximately=1000),
Andreas Klöckner
committed
],
Andreas Klöckner
committed
import pytest
with pytest.raises(RuntimeError):
lp.CompiledKernel(ctx, knl).get_code()
Andreas Klöckner
committed
def test_arg_shape_guessing(ctx_factory):
Andreas Klöckner
committed
ctx = ctx_factory()
knl = lp.make_kernel(
a = 1.5 + sum((i,j), i*j)
b[i, j] = i*j
c[i+j, j] = b[j,i]
""",
lp.GlobalArg("a", shape=lp.auto),
lp.GlobalArg("b", shape=lp.auto),
lp.GlobalArg("c", shape=lp.auto),
lp.ValueArg("n"),
Andreas Klöckner
committed
],
print(knl)
print(lp.CompiledKernel(ctx, knl).get_highlighted_code())
Andreas Klöckner
committed
def test_arg_guessing(ctx_factory):
ctx = ctx_factory()
knl = lp.make_kernel(
"{[i,j]: 0<=i,j<n }",
"""
a = 1.5 + sum((i,j), i*j)
b[i, j] = i*j
c[i+j, j] = b[j,i]
""",
assumptions="n>=1")
print(knl)
print(lp.CompiledKernel(ctx, knl).get_highlighted_code())
def test_arg_guessing_with_reduction(ctx_factory):
#logging.basicConfig(level=logging.DEBUG)
ctx = ctx_factory()
knl = lp.make_kernel(
a = 1.5 + simul_reduce(sum, (i,j), i*j)
d = 1.5 + simul_reduce(sum, (i,j), b[i,j])
b[i, j] = i*j
c[i+j, j] = b[j,i]
""",
assumptions="n>=1")
print(knl)
print(lp.CompiledKernel(ctx, knl).get_highlighted_code())
def test_unknown_arg_shape(ctx_factory):
ctx = ctx_factory()
from loopy.target.pyopencl import PyOpenCLTarget
from loopy.compiled import CompiledKernel
bsize = [256, 0]
knl = lp.make_kernel(
"{[i,j]: 0<=i<n and 0<=j<m}",
"""
for i
<int32> gid = i/256
<int32> start = gid*256
for j
a[start + j] = a[start + j] + j
end
end
""",
seq_dependencies=True,
name="uniform_l",
target=PyOpenCLTarget(),
assumptions="m<=%d and m>=1 and n mod %d = 0" % (bsize[0], bsize[0]))
knl = lp.add_and_infer_dtypes(knl, dict(a=np.float32))
kernel_info = CompiledKernel(ctx, knl).kernel_info(frozenset()) # noqa
def test_nonlinear_index(ctx_factory):
ctx = ctx_factory()
knl = lp.make_kernel(
"{[i,j]: 0<=i,j<n }",
"""
a[i*i] = 17
""",
[
lp.GlobalArg("a", shape="n"),
lp.ValueArg("n"),
],
assumptions="n>=1")
print(knl)
print(lp.CompiledKernel(ctx, knl).get_highlighted_code())
def test_offsets_and_slicing(ctx_factory):
ctx = ctx_factory()
queue = cl.CommandQueue(ctx)
knl = lp.make_kernel(
"{[i,j]: 0<=i<n and 0<=j<m }",
"""
b[i,j] = 2*a[i,j]
""",
assumptions="n>=1 and m>=1",
default_offset=lp.auto)
knl = lp.tag_data_axes(knl, "a,b", "stride:auto,stride:1")
cknl = lp.CompiledKernel(ctx, knl)
a_full = cl.clrandom.rand(queue, (n, n), np.float64)
a_full_h = a_full.get()
b_full = cl.clrandom.rand(queue, (n, n), np.float64)
b_full_h = b_full.get()
a_sub = (slice(3, 10), slice(5, 10))
a = a_full[a_sub]
b_sub = (slice(3+3, 10+3), slice(5+4, 10+4))
b = b_full[b_sub]
b_full_h[b_sub] = 2*a_full_h[a_sub]
print(cknl.get_highlighted_code({"a": a.dtype}))
import numpy.linalg as la
assert la.norm(b_full.get() - b_full_h) < 1e-13
Andreas Klöckner
committed
def test_vector_ilp_with_prefetch(ctx_factory):
ctx = ctx_factory()
knl = lp.make_kernel(
Andreas Klöckner
committed
"{ [i]: 0<=i<n }",
"out[i] = 2*a[i]",
[
# Tests that comma'd arguments interoperate with
Andreas Klöckner
committed
# argument guessing.
lp.GlobalArg("out,a", np.float32, shape=lp.auto),
"..."
])
Andreas Klöckner
committed
knl = lp.split_iname(knl, "i", 128, inner_tag="l.0")
knl = lp.split_iname(knl, "i_outer", 4, outer_tag="g.0", inner_tag="ilp")
knl = lp.add_prefetch(knl, "a", ["i_inner", "i_outer_inner"])
Andreas Klöckner
committed
import re
Andreas Klöckner
committed
assert len(list(re.finditer("barrier", code))) == 1
def test_c_instruction(ctx_factory):
ctx = ctx_factory()
knl = lp.make_kernel(
"{[i,j]: 0<=i,j<n }",
[
lp.CInstruction("i,j", """
x = sin((float) i*j);
""", assignees="x"),
],
[
lp.GlobalArg("a", shape=lp.auto, dtype=np.float32),
lp.TemporaryVariable("x", np.float32),
],
assumptions="n>=1")
knl = lp.split_iname(knl, "i", 128, outer_tag="g.0", inner_tag="l.0")
print(knl)
print(lp.CompiledKernel(ctx, knl).get_highlighted_code())
def test_dependent_domain_insn_iname_finding(ctx_factory):
ctx = ctx_factory()
knl = lp.make_kernel([
"{[isrc_box]: 0<=isrc_box<nsrc_boxes}",
"{[isrc,idim]: isrc_start<=isrc<isrc_end and 0<=idim<dim}",
],
"""
<> src_ibox = source_boxes[isrc_box]
<> isrc_start = box_source_starts[src_ibox]
<> isrc_end = isrc_start+box_source_counts_nonchild[src_ibox]
<> strength = strengths[isrc] {id=set_strength}
""",
[
lp.GlobalArg("box_source_starts,box_source_counts_nonchild",
None, shape=None),
lp.GlobalArg("strengths",
None, shape="nsources"),
assert "isrc_box" in knl.insn_inames("set_strength")
print(lp.CompiledKernel(ctx, knl).get_highlighted_code(
dict(
source_boxes=np.int32,
box_source_starts=np.int32,
box_source_counts_nonchild=np.int32,
strengths=np.float64,
def test_inames_deps_from_write_subscript(ctx_factory):
knl = lp.make_kernel(
"{[i,j]: 0<=i,j<n}",
"""
<> src_ibox = source_boxes[i]
<int32> something = 5
a[src_ibox] = sum(j, something) {id=myred}
""",
[
lp.GlobalArg("box_source_starts,box_source_counts_nonchild,a",
None, shape=None),
"..."])
assert "i" in knl.insn_inames("myred")
def test_modulo_indexing(ctx_factory):
ctx = ctx_factory()
knl = lp.make_kernel(
"{[i,j]: 0<=i<n and 0<=j<5}",
"""
b[i] = sum(j, a[(i+j)%n])
""",
[
lp.GlobalArg("a", None, shape="n"),
"..."
]
)
print(knl)
print(lp.CompiledKernel(ctx, knl).get_highlighted_code(
@pytest.mark.parametrize("vec_len", [2, 3, 4, 8, 16])
def test_vector_types(ctx_factory, vec_len):
knl = lp.make_kernel(
"{ [i,j]: 0<=i<n and 0<=j<vec_len }",
"out[i,j] = 2*a[i,j]",
[
lp.GlobalArg("a", np.float32, shape=lp.auto),
lp.GlobalArg("out", np.float32, shape=lp.auto),
"..."
knl = lp.fix_parameters(knl, vec_len=vec_len)
ref_knl = knl
knl = lp.tag_data_axes(knl, "out", "c,vec")
knl = lp.tag_inames(knl, dict(j="unr"))
knl = lp.split_iname(knl, "i", 128, outer_tag="g.0", inner_tag="l.0")
lp.auto_test_vs_ref(ref_knl, ctx, knl,
parameters=dict(
n=20000
def test_conditional(ctx_factory):
#logging.basicConfig(level=logging.DEBUG)
knl = lp.make_kernel(
"{ [i,j]: 0<=i,j<n }",
"""
<> my_a = a[i,j] {id=read_a}
<> a_less_than_zero = my_a < 0 {dep=read_a,inames=i:j}
my_a = 2*my_a {id=twice_a,dep=read_a,if=a_less_than_zero}
my_a = my_a+1 {id=aplus,dep=twice_a,if=a_less_than_zero}
out[i,j] = 2*my_a {dep=aplus}
""",
[
lp.GlobalArg("a", np.float32, shape=lp.auto),
lp.GlobalArg("out", np.float32, shape=lp.auto),
"..."
])
ref_knl = knl
lp.auto_test_vs_ref(ref_knl, ctx, knl,
parameters=dict(
n=200
))
Andreas Klöckner
committed
def test_ilp_loop_bound(ctx_factory):
# The salient bit of this test is that a joint bound on (outer, inner)
# from a split occurs in a setting where the inner loop has been ilp'ed.
# In 'normal' parallel loops, the inner index is available for conditionals
# throughout. In ILP'd loops, not so much.
ctx = ctx_factory()
knl = lp.make_kernel(
Andreas Klöckner
committed
"{ [i,j,k]: 0<=i,j,k<n }",
"""
out[i,k] = sum(j, a[i,j]*b[j,k])
""",
[
lp.GlobalArg("a,b", np.float32, shape=lp.auto),
"...",
],
assumptions="n>=1")
ref_knl = knl
knl = lp.prioritize_loops(knl, "j,i,k")
Andreas Klöckner
committed
knl = lp.split_iname(knl, "k", 4, inner_tag="ilp")
lp.auto_test_vs_ref(ref_knl, ctx, knl,
parameters=dict(
n=200
))
def test_arg_shape_uses_assumptions(ctx_factory):
# If arg shape determination does not use assumptions, then it won't find a
# static shape for out, which is at least 1 x 1 in size, but otherwise of
# size n x n.
lp.make_kernel(
"{ [i,j]: 0<=i,j<n }",
"""
out[i,j] = 2*a[i,j]
out[0,0] = 13.0
""", assumptions="n>=1")
def test_slab_decomposition_does_not_double_execute(ctx_factory):
ctx = ctx_factory()
queue = cl.CommandQueue(ctx)
knl = lp.make_kernel(
"{ [i]: 0<=i<n }",
ref_knl = knl
for outer_tag in ["for", "g.0"]:
knl = ref_knl
knl = lp.split_iname(knl, "i", 4, slabs=(0, 1), inner_tag="unr",
outer_tag=outer_tag)
knl = lp.prioritize_loops(knl, "i_outer")
a = cl.array.empty(queue, 20, np.float32)
a.fill(17)
a_ref = a.copy()
a_knl = a.copy()
knl = lp.set_options(knl, write_cl=True)
print("TEST-----------------------------------------")
print("REF-----------------------------------------")
print("DONE-----------------------------------------")
print("REF", a_ref)
print("KNL", a_knl)
assert (a_ref == a_knl).get().all()
print("_________________________________")
# Loopy would previously only handle barrier insertion correctly if exactly
# one instruction wrote to each local temporary. This tests that multiple
# writes are OK.
knl = lp.make_kernel(
"{[i,e]: 0<=i<5 and 0<=e<nelements}",
"""
<> temp[i, 0] = 17
""")
knl = lp.tag_inames(knl, dict(i="l.0"))
knl = lp.preprocess_kernel(knl)
for k in lp.generate_loop_schedules(knl):
code, _ = lp.generate_code(k)
print(code)
def test_make_copy_kernel(ctx_factory):
ctx = ctx_factory()
cknl1 = lp.make_copy_kernel(intermediate_format)
cknl1 = lp.set_options(cknl1, write_cl=True)
evt, a2 = cknl1(queue, input=a1)
cknl2 = lp.make_copy_kernel("c,c,c", intermediate_format)
cknl2 = lp.fix_parameters(cknl2, n2=3)
def test_auto_test_can_detect_problems(ctx_factory):
ctx = ctx_factory()
"""
""")
knl = lp.make_kernel(
"{[i]: 0<=i<n}",
"""
a[i,i] = 25
""")
ref_knl = lp.add_and_infer_dtypes(ref_knl, dict(a=np.float32))
knl = lp.add_and_infer_dtypes(knl, dict(a=np.float32))
from loopy.diagnostic import AutomaticTestFailure
with pytest.raises(AutomaticTestFailure):
lp.auto_test_vs_ref(
ref_knl, ctx, knl,
parameters=dict(n=123))
def test_sci_notation_literal(ctx_factory):
ctx = ctx_factory()
queue = cl.CommandQueue(ctx)
set_kernel = lp.make_kernel(
''' { [i]: 0<=i<12 } ''',
''' out[i] = 1e-12''')
set_kernel = lp.set_options(set_kernel, write_cl=True)
evt, (out,) = set_kernel(queue)
assert (np.abs(out.get() - 1e-12) < 1e-20).all()
def test_variable_size_temporary():
knl = lp.make_kernel(
''' { [i,j]: 0<=i,j<n } ''',
''' out[i] = sum(j, a[i,j])''')
knl = lp.add_and_infer_dtypes(knl, {"a": np.float32})
knl = lp.add_prefetch(
knl, "a[:,:]", default_tag=None)
# Make sure that code generation succeeds even if
# there are variable-length arrays.
knl = lp.preprocess_kernel(knl)
for k in lp.generate_loop_schedules(knl):
lp.generate_code(k)
def test_indexof(ctx_factory):
ctx = ctx_factory()
queue = cl.CommandQueue(ctx)
knl = lp.make_kernel(
''' { [i,j]: 0<=i,j<5 } ''',
''' out[i,j] = indexof(out[i,j])''')
knl = lp.set_options(knl, write_cl=True)
(evt, (out,)) = knl(queue)
out = out.get()
assert np.array_equal(out.ravel(order="C"), np.arange(25))