提交 23460ad2 authored 作者: Brandon T. Willard's avatar Brandon T. Willard

Convert remaining exception tests to pytest format

上级 6e8c2b92
...@@ -8,7 +8,6 @@ from six import reraise ...@@ -8,7 +8,6 @@ from six import reraise
from theano import config from theano import config
from theano import gof from theano import gof
import theano import theano
from theano.compat import exc_message
from theano.compile import debugmode from theano.compile import debugmode
import theano.tensor import theano.tensor
from theano.tests import unittest_tools as utt from theano.tests import unittest_tools as utt
...@@ -214,14 +213,10 @@ def test_badthunkoutput(): ...@@ -214,14 +213,10 @@ def test_badthunkoutput():
if not theano.config.cxx: if not theano.config.cxx:
pytest.skip("G++ not available, so we need to skip this test.") pytest.skip("G++ not available, so we need to skip this test.")
try: with pytest.raises(debugmode.BadThunkOutput) as einfo:
f_inconsistent([1.0, 2.0, 3.0], [2, 3, 4]) f_inconsistent([1.0, 2.0, 3.0], [2, 3, 4])
except debugmode.BadThunkOutput as e:
# print repr(e)
assert e.r.owner.op is inconsistent
return # TEST PASS
assert False # an error should have been detected assert einfo.value.r.owner.op is inconsistent
def test_badoptimization(): def test_badoptimization():
...@@ -240,15 +235,11 @@ def test_badoptimization(): ...@@ -240,15 +235,11 @@ def test_badoptimization():
f = theano.function([a, b], a + b, mode=debugmode.DebugMode(optimizer=opt)) f = theano.function([a, b], a + b, mode=debugmode.DebugMode(optimizer=opt))
try: with pytest.raises(debugmode.BadOptimization) as einfo:
f( f(
[1.0, 2.0, 3.0], [2, 3, 4], [1.0, 2.0, 3.0], [2, 3, 4],
) )
except debugmode.BadOptimization as e: assert str(einfo.value.reason) == "insert_broken_add"
assert str(e.reason) == "insert_broken_add"
return # TEST PASS
assert False
def test_badoptimization_opt_err(): def test_badoptimization_opt_err():
...@@ -283,17 +274,15 @@ def test_badoptimization_opt_err(): ...@@ -283,17 +274,15 @@ def test_badoptimization_opt_err():
b = theano.tensor.dvector() b = theano.tensor.dvector()
f = theano.function([a, b], a + b, mode=debugmode.DebugMode(optimizer=opt)) f = theano.function([a, b], a + b, mode=debugmode.DebugMode(optimizer=opt))
try: with pytest.raises(ValueError, match=r"insert_bigger_b_add"):
f( f(
[1.0, 2.0, 3.0], [2, 3, 4], [1.0, 2.0, 3.0], [2, 3, 4],
) )
except ValueError as e:
assert "insert_bigger_b_add" in exc_message(e)
else:
assert False
# Test that opt that do an illegal change still get the error from gof. # Test that opt that do an illegal change still get the error from gof.
try: with pytest.raises(
theano.gof.toolbox.BadOptimization, match=r"insert_bad_dtype"
) as einfo:
with theano.change_flags(on_opt_error="raise"): with theano.change_flags(on_opt_error="raise"):
f2 = theano.function( f2 = theano.function(
[a, b], [a, b],
...@@ -303,20 +292,14 @@ def test_badoptimization_opt_err(): ...@@ -303,20 +292,14 @@ def test_badoptimization_opt_err():
f2( f2(
[1.0, 2.0, 3.0], [2, 3, 4], [1.0, 2.0, 3.0], [2, 3, 4],
) )
except theano.gof.toolbox.BadOptimization as e:
assert "insert_bad_dtype" in str(e) # Test that we can reraise the error with an extended message
# Test that we can reraise the error with an extended message with pytest.raises(theano.gof.toolbox.BadOptimization):
try: e = einfo.value
new_e = e.__class__("TTT" + str(e)) new_e = e.__class__("TTT" + str(e))
exc_type, exc_value, exc_trace = sys.exc_info() exc_type, exc_value, exc_trace = sys.exc_info()
exc_value = new_e exc_value = new_e
reraise(e.__class__, exc_value, exc_trace) reraise(e.__class__, exc_value, exc_trace)
except theano.gof.toolbox.BadOptimization:
pass
else:
assert False
else:
assert False
def test_stochasticoptimization(): def test_stochasticoptimization():
...@@ -340,7 +323,7 @@ def test_stochasticoptimization(): ...@@ -340,7 +323,7 @@ def test_stochasticoptimization():
a = theano.tensor.dvector() a = theano.tensor.dvector()
b = theano.tensor.dvector() b = theano.tensor.dvector()
try: with pytest.raises(debugmode.StochasticOrder):
theano.function( theano.function(
[a, b], [a, b],
theano.tensor.add(a, b), theano.tensor.add(a, b),
...@@ -350,9 +333,6 @@ def test_stochasticoptimization(): ...@@ -350,9 +333,6 @@ def test_stochasticoptimization():
stability_patience=max(2, config.DebugMode.patience), stability_patience=max(2, config.DebugMode.patience),
), ),
) )
except debugmode.StochasticOrder:
return # TEST PASS
assert False
def test_just_c_code(): def test_just_c_code():
...@@ -379,11 +359,8 @@ def test_baddestroymap(): ...@@ -379,11 +359,8 @@ def test_baddestroymap():
y = theano.tensor.dvector() y = theano.tensor.dvector()
f = theano.function([x, y], BadAdd()(x, y), mode="DEBUG_MODE") f = theano.function([x, y], BadAdd()(x, y), mode="DEBUG_MODE")
try: with pytest.raises(debugmode.BadDestroyMap):
f([1, 2], [3, 4]) f([1, 2], [3, 4])
assert False # failed to raise error
except debugmode.BadDestroyMap:
pass
def test_baddestroymap_c(): def test_baddestroymap_c():
...@@ -391,11 +368,8 @@ def test_baddestroymap_c(): ...@@ -391,11 +368,8 @@ def test_baddestroymap_c():
pytest.skip("G++ not available, so we need to skip this test.") pytest.skip("G++ not available, so we need to skip this test.")
x = theano.tensor.dvector() x = theano.tensor.dvector()
f = theano.function([x], wb2i(x), mode=debugmode.DebugMode(check_py_code=False)) f = theano.function([x], wb2i(x), mode=debugmode.DebugMode(check_py_code=False))
try: with pytest.raises(debugmode.BadDestroyMap):
assert np.all(f([1, 2]) == [2, 4]) assert np.all(f([1, 2]) == [2, 4])
assert False # failed to raise error
except debugmode.BadDestroyMap:
pass
class TestViewMap: class TestViewMap:
...@@ -423,21 +397,15 @@ class TestViewMap: ...@@ -423,21 +397,15 @@ class TestViewMap:
x = theano.tensor.dvector() x = theano.tensor.dvector()
y = theano.tensor.dvector() y = theano.tensor.dvector()
f = theano.function([x, y], self.BadAddRef()(x, y), mode="DEBUG_MODE") f = theano.function([x, y], self.BadAddRef()(x, y), mode="DEBUG_MODE")
try: with pytest.raises(debugmode.BadViewMap):
f([1, 2], [3, 4]) f([1, 2], [3, 4])
assert False # failed to raise error
except debugmode.BadViewMap:
return
def test_badviewmap_slice(self): def test_badviewmap_slice(self):
x = theano.tensor.dvector() x = theano.tensor.dvector()
y = theano.tensor.dvector() y = theano.tensor.dvector()
f = theano.function([x, y], self.BadAddSlice()(x, y), mode="DEBUG_MODE") f = theano.function([x, y], self.BadAddSlice()(x, y), mode="DEBUG_MODE")
try: with pytest.raises(debugmode.BadViewMap):
f([1, 2], [3, 4]) f([1, 2], [3, 4])
assert False # failed to raise error
except debugmode.BadViewMap:
return
def test_goodviewmap(self): def test_goodviewmap(self):
goodop = self.BadAddRef() goodop = self.BadAddRef()
...@@ -445,22 +413,16 @@ class TestViewMap: ...@@ -445,22 +413,16 @@ class TestViewMap:
x = theano.tensor.dvector() x = theano.tensor.dvector()
y = theano.tensor.dvector() y = theano.tensor.dvector()
f = theano.function([x, y], goodop(x, y), mode="DEBUG_MODE") f = theano.function([x, y], goodop(x, y), mode="DEBUG_MODE")
try: # Shouldn't raise an error
f([1, 5, 1], [3, 4, 2, 1, 4]) f([1, 5, 1], [3, 4, 2, 1, 4])
return
except debugmode.BadViewMap:
assert False # failed to raise error
def test_badviewmap_c(self): def test_badviewmap_c(self):
if not theano.config.cxx: if not theano.config.cxx:
pytest.skip("G++ not available, so we need to skip this test.") pytest.skip("C++ not available, so we need to skip this test.")
x = theano.tensor.dvector() x = theano.tensor.dvector()
f = theano.function([x], wb1i(x), mode=debugmode.DebugMode(check_py_code=False)) f = theano.function([x], wb1i(x), mode=debugmode.DebugMode(check_py_code=False))
try: with pytest.raises(debugmode.BadViewMap):
f([1, 2]) f([1, 2])
assert False # failed to raise error
except debugmode.BadViewMap:
pass
def test_aliased_outputs_ok(self): def test_aliased_outputs_ok(self):
# here aliased outputs is ok because they are both aliased to an input # here aliased outputs is ok because they are both aliased to an input
...@@ -563,12 +525,8 @@ class TestViewMap: ...@@ -563,12 +525,8 @@ class TestViewMap:
out = bad_xy0 * 2 + bad_xy1 * 2 out = bad_xy0 * 2 + bad_xy1 * 2
f = theano.function([x, y], out, mode="DEBUG_MODE") f = theano.function([x, y], out, mode="DEBUG_MODE")
try: with pytest.raises(debugmode.BadViewMap):
f([1, 2, 3, 4], [5, 6, 7, 8]) f([1, 2, 3, 4], [5, 6, 7, 8])
assert False # DebugMode should have caught the error
except debugmode.BadViewMap:
# print e
pass
# the situation can be rescued by picking one of the inputs and # the situation can be rescued by picking one of the inputs and
# pretending that it is aliased to both the outputs. # pretending that it is aliased to both the outputs.
......
...@@ -365,14 +365,11 @@ def test_duallinker_mismatch(): ...@@ -365,14 +365,11 @@ def test_duallinker_mismatch():
# (purposely) wrong # (purposely) wrong
assert PerformLinker().accept(g).make_function()(1.0, 2.0, 3.0) == -10.0 assert PerformLinker().accept(g).make_function()(1.0, 2.0, 3.0) == -10.0
try: with pytest.raises(MyExc):
# this runs OpWiseCLinker and PerformLinker in parallel and feeds # this runs OpWiseCLinker and PerformLinker in parallel and feeds
# variables of matching operations to _my_checker to verify that they # variables of matching operations to _my_checker to verify that they
# are the same. # are the same.
fn(1.0, 2.0, 3.0) fn(1.0, 2.0, 3.0)
raise Exception("An exception should have been raised here!")
except MyExc:
pass
################################ ################################
...@@ -407,12 +404,8 @@ def test_c_fail_error(): ...@@ -407,12 +404,8 @@ def test_c_fail_error():
e = add_fail(mul(x, y), mul(y, z)) e = add_fail(mul(x, y), mul(y, z))
lnk = OpWiseCLinker().accept(Env([y, z], [e])) lnk = OpWiseCLinker().accept(Env([y, z], [e]))
fn = lnk.make_function() fn = lnk.make_function()
try: with pytest.raises(RuntimeError):
fn(1.5, 3.0) fn(1.5, 3.0)
except RuntimeError:
print("Yay, TEST PASSED")
return # test passed
assert 0 # test failed
def test_shared_input_output(): def test_shared_input_output():
......
from __future__ import absolute_import, print_function, division from __future__ import absolute_import, print_function, division
import pytest
from six.moves import xrange from six.moves import xrange
from theano.gof.type import Type from theano.gof.type import Type
...@@ -137,26 +138,6 @@ class FailureWatch: ...@@ -137,26 +138,6 @@ class FailureWatch:
self.failures += 1 self.failures += 1
def consistent(g):
# print "Testing consistent:", g
try:
assert g.consistent()
except AssertionError:
print("Test failed! The graph was marked as NOT consistent.")
raise
# print "Test OK"
def inconsistent(g):
# print "Testing NOT consistent:", g
try:
assert not g.consistent()
except AssertionError:
print("Test failed! The graph was marked as consistent.")
raise
# print "Test OK"
################# #################
# Test protocol # # Test protocol #
################# #################
...@@ -166,7 +147,7 @@ def test_misc(): ...@@ -166,7 +147,7 @@ def test_misc():
x, y, z = inputs() x, y, z = inputs()
e = transpose_view(transpose_view(transpose_view(transpose_view(x)))) e = transpose_view(transpose_view(transpose_view(transpose_view(x))))
g = Env([x, y, z], [e]) g = Env([x, y, z], [e])
consistent(g) assert g.consistent()
PatternOptimizer((transpose_view, (transpose_view, "x")), "x").optimize(g) PatternOptimizer((transpose_view, (transpose_view, "x")), "x").optimize(g)
assert str(g) == "[x]" assert str(g) == "[x]"
new_e = add(x, y) new_e = add(x, y)
...@@ -174,7 +155,7 @@ def test_misc(): ...@@ -174,7 +155,7 @@ def test_misc():
assert str(g) == "[Add(x, y)]" assert str(g) == "[Add(x, y)]"
g.replace(new_e, dot(add_in_place(x, y), transpose_view(x))) g.replace(new_e, dot(add_in_place(x, y), transpose_view(x)))
assert str(g) == "[Dot(AddInPlace(x, y), TransposeView(x))]" assert str(g) == "[Dot(AddInPlace(x, y), TransposeView(x))]"
inconsistent(g) assert not g.consistent()
###################### ######################
...@@ -190,15 +171,15 @@ def test_aliased_inputs_replacement(): ...@@ -190,15 +171,15 @@ def test_aliased_inputs_replacement():
sx = sigmoid(x) sx = sigmoid(x)
e = add_in_place(x, tv) e = add_in_place(x, tv)
g = Env([x, y], [e], False) g = Env([x, y], [e], False)
inconsistent(g) assert not g.consistent()
g.replace(tv, sx) g.replace(tv, sx)
consistent(g) assert g.consistent()
g.replace(sx, tv) g.replace(sx, tv)
inconsistent(g) assert not g.consistent()
g.replace(tv, tvv) g.replace(tv, tvv)
inconsistent(g) assert not g.consistent()
g.replace(tv, sx) g.replace(tv, sx)
consistent(g) assert g.consistent()
def test_indestructible(): def test_indestructible():
...@@ -209,9 +190,9 @@ def test_indestructible(): ...@@ -209,9 +190,9 @@ def test_indestructible():
assert x.tag.indestructible assert x.tag.indestructible
e = add_in_place(x, y) e = add_in_place(x, y)
g = Env([x, y, z], [e], False) g = Env([x, y, z], [e], False)
inconsistent(g) assert not g.consistent()
g.replace_validate(e, add(x, y)) g.replace_validate(e, add(x, y))
consistent(g) assert g.consistent()
@assertFailure_fast @assertFailure_fast
...@@ -220,9 +201,9 @@ def test_usage_loop_through_views_2(): ...@@ -220,9 +201,9 @@ def test_usage_loop_through_views_2():
e0 = transpose_view(transpose_view(sigmoid(x))) e0 = transpose_view(transpose_view(sigmoid(x)))
e = dot(add_in_place(x, y), transpose_view(e0)) e = dot(add_in_place(x, y), transpose_view(e0))
g = Env([x, y, z], [e]) g = Env([x, y, z], [e])
consistent(g) # because sigmoid can do the copy assert g.consistent() # because sigmoid can do the copy
g.replace(e0, x) g.replace(e0, x)
inconsistent(g) # we cut off the path to the sigmoid assert not g.consistent() # we cut off the path to the sigmoid
@assertFailure_fast @assertFailure_fast
...@@ -232,29 +213,23 @@ def test_destroyers_loop(): ...@@ -232,29 +213,23 @@ def test_destroyers_loop():
e1 = add(x, y) e1 = add(x, y)
e2 = add(y, x) e2 = add(y, x)
g = Env([x, y, z], [e1, e2]) g = Env([x, y, z], [e1, e2])
consistent(g) assert g.consistent()
g.replace_validate(e1, add_in_place(x, y)) g.replace_validate(e1, add_in_place(x, y))
consistent(g) assert g.consistent()
try: with pytest.raises(InconsistencyError):
g.replace_validate(e2, add_in_place(y, x)) g.replace_validate(e2, add_in_place(y, x))
raise Exception("Shouldn't have reached this point.") assert g.consistent()
except InconsistencyError:
pass
consistent(g)
x, y, z = inputs() x, y, z = inputs()
e1 = add(x, y) e1 = add(x, y)
e2 = add(y, x) e2 = add(y, x)
g = Env([x, y, z], [e1, e2]) g = Env([x, y, z], [e1, e2])
consistent(g) assert g.consistent()
g.replace_validate(e2, add_in_place(y, x)) g.replace_validate(e2, add_in_place(y, x))
consistent(g) assert g.consistent()
try: with pytest.raises(InconsistencyError):
g.replace_validate(e1, add_in_place(x, y)) g.replace_validate(e1, add_in_place(x, y))
raise Exception("Shouldn't have reached this point.") assert g.consistent()
except InconsistencyError:
pass
consistent(g)
######## ########
...@@ -266,14 +241,14 @@ def test_aliased_inputs(): ...@@ -266,14 +241,14 @@ def test_aliased_inputs():
x, y, z = inputs() x, y, z = inputs()
e = add_in_place(x, x) e = add_in_place(x, x)
g = Env([x], [e], False) g = Env([x], [e], False)
inconsistent(g) assert not g.consistent()
def test_aliased_inputs2(): def test_aliased_inputs2():
x, y, z = inputs() x, y, z = inputs()
e = add_in_place(x, transpose_view(x)) e = add_in_place(x, transpose_view(x))
g = Env([x], [e], False) g = Env([x], [e], False)
inconsistent(g) assert not g.consistent()
@assertFailure_fast @assertFailure_fast
...@@ -281,14 +256,14 @@ def test_aliased_inputs_tolerate(): ...@@ -281,14 +256,14 @@ def test_aliased_inputs_tolerate():
x, y, z = inputs() x, y, z = inputs()
e = add_in_place_2(x, x) e = add_in_place_2(x, x)
g = Env([x], [e], False) g = Env([x], [e], False)
consistent(g) assert g.consistent()
def test_aliased_inputs_tolerate2(): def test_aliased_inputs_tolerate2():
x, y, z = inputs() x, y, z = inputs()
e = add_in_place_2(x, transpose_view(x)) e = add_in_place_2(x, transpose_view(x))
g = Env([x], [e], False) g = Env([x], [e], False)
inconsistent(g) assert not g.consistent()
@assertFailure_fast @assertFailure_fast
...@@ -296,7 +271,7 @@ def test_same_aliased_inputs_ignored(): ...@@ -296,7 +271,7 @@ def test_same_aliased_inputs_ignored():
x, y, z = inputs() x, y, z = inputs()
e = add_in_place_3(x, x) e = add_in_place_3(x, x)
g = Env([x], [e], False) g = Env([x], [e], False)
consistent(g) assert g.consistent()
@assertFailure_fast @assertFailure_fast
...@@ -304,7 +279,7 @@ def test_different_aliased_inputs_ignored(): ...@@ -304,7 +279,7 @@ def test_different_aliased_inputs_ignored():
x, y, z = inputs() x, y, z = inputs()
e = add_in_place_3(x, transpose_view(x)) e = add_in_place_3(x, transpose_view(x))
g = Env([x], [e], False) g = Env([x], [e], False)
consistent(g) assert g.consistent()
# warning - don't run this because it would produce the wrong answer # warning - don't run this because it would produce the wrong answer
# add_in_place_3 is actually not correct when aliasing of inputs # add_in_place_3 is actually not correct when aliasing of inputs
# is ignored. # is ignored.
...@@ -316,9 +291,9 @@ def test_indestructible_through_views(): ...@@ -316,9 +291,9 @@ def test_indestructible_through_views():
tv = transpose_view(x) tv = transpose_view(x)
e = add_in_place(tv, y) e = add_in_place(tv, y)
g = Env([x, y, z], [e], False) g = Env([x, y, z], [e], False)
inconsistent(g) assert not g.consistent()
g.replace_validate(tv, sigmoid(x)) g.replace_validate(tv, sigmoid(x))
consistent(g) assert g.consistent()
def test_indirect(): def test_indirect():
...@@ -326,12 +301,12 @@ def test_indirect(): ...@@ -326,12 +301,12 @@ def test_indirect():
e0 = add_in_place(x, y) e0 = add_in_place(x, y)
e = dot(sigmoid(e0), transpose_view(x)) e = dot(sigmoid(e0), transpose_view(x))
g = Env([x, y, z], [e], False) g = Env([x, y, z], [e], False)
inconsistent(g) assert not g.consistent()
new_e0 = add(x, y) new_e0 = add(x, y)
g.replace(e0, new_e0) g.replace(e0, new_e0)
consistent(g) assert g.consistent()
g.replace(new_e0, add_in_place(x, y)) g.replace(new_e0, add_in_place(x, y))
inconsistent(g) assert not g.consistent()
@assertFailure_fast @assertFailure_fast
...@@ -340,10 +315,10 @@ def test_indirect_2(): ...@@ -340,10 +315,10 @@ def test_indirect_2():
e0 = transpose_view(x) e0 = transpose_view(x)
e = dot(sigmoid(add_in_place(x, y)), e0) e = dot(sigmoid(add_in_place(x, y)), e0)
g = Env([x, y, z], [e], False) g = Env([x, y, z], [e], False)
inconsistent(g) assert not g.consistent()
new_e0 = add(e0, y) new_e0 = add(e0, y)
g.replace(e0, new_e0) g.replace(e0, new_e0)
consistent(g) assert g.consistent()
@assertFailure_fast @assertFailure_fast
...@@ -351,17 +326,14 @@ def test_long_destroyers_loop(): ...@@ -351,17 +326,14 @@ def test_long_destroyers_loop():
x, y, z = inputs() x, y, z = inputs()
e = dot(dot(add_in_place(x, y), add_in_place(y, z)), add(z, x)) e = dot(dot(add_in_place(x, y), add_in_place(y, z)), add(z, x))
g = Env([x, y, z], [e]) g = Env([x, y, z], [e])
consistent(g) assert g.consistent()
OpSubOptimizer(add, add_in_place).optimize(g) OpSubOptimizer(add, add_in_place).optimize(g)
consistent(g) assert g.consistent()
# we don't want to see that! # we don't want to see that!
assert str(g) != "[Dot(Dot(AddInPlace(x, y), AddInPlace(y, z)), AddInPlace(z, x))]" assert str(g) != "[Dot(Dot(AddInPlace(x, y), AddInPlace(y, z)), AddInPlace(z, x))]"
e2 = dot(dot(add_in_place(x, y), add_in_place(y, z)), add_in_place(z, x)) e2 = dot(dot(add_in_place(x, y), add_in_place(y, z)), add_in_place(z, x))
try: with pytest.raises(InconsistencyError):
Env(*graph.clone([x, y, z], [e2])) Env(*graph.clone([x, y, z], [e2]))
raise Exception("Shouldn't have reached this point.")
except InconsistencyError:
pass
def test_misc_2(): def test_misc_2():
...@@ -369,19 +341,16 @@ def test_misc_2(): ...@@ -369,19 +341,16 @@ def test_misc_2():
tv = transpose_view(x) tv = transpose_view(x)
e = add_in_place(x, tv) e = add_in_place(x, tv)
g = Env([x, y], [e], False) g = Env([x, y], [e], False)
inconsistent(g) assert not g.consistent()
g.replace(tv, x) g.replace(tv, x)
inconsistent(g) assert not g.consistent()
def test_multi_destroyers(): def test_multi_destroyers():
x, y, z = inputs() x, y, z = inputs()
e = add(add_in_place(x, y), add_in_place(x, y)) e = add(add_in_place(x, y), add_in_place(x, y))
try: with pytest.raises(InconsistencyError):
Env([x, y, z], [e]) Env([x, y, z], [e])
raise Exception("Shouldn't have reached this point.")
except InconsistencyError:
pass
@assertFailure_fast @assertFailure_fast
...@@ -389,10 +358,10 @@ def test_multi_destroyers_through_views(): ...@@ -389,10 +358,10 @@ def test_multi_destroyers_through_views():
x, y, z = inputs() x, y, z = inputs()
e = dot(add(transpose_view(z), y), add(z, x)) e = dot(add(transpose_view(z), y), add(z, x))
g = Env([x, y, z], [e]) g = Env([x, y, z], [e])
consistent(g) assert g.consistent()
fail = FailureWatch() fail = FailureWatch()
OpSubOptimizer(add, add_in_place, fail).optimize(g) OpSubOptimizer(add, add_in_place, fail).optimize(g)
consistent(g) assert g.consistent()
assert fail.failures == 1 # should have succeeded once and failed once assert fail.failures == 1 # should have succeeded once and failed once
...@@ -403,18 +372,18 @@ def test_repair_destroy_path(): ...@@ -403,18 +372,18 @@ def test_repair_destroy_path():
e3 = add_in_place(e2, y) e3 = add_in_place(e2, y)
e4 = add_in_place(e1, z) e4 = add_in_place(e1, z)
g = Env([x, y, z], [e3, e4], False) g = Env([x, y, z], [e3, e4], False)
inconsistent(g) assert not g.consistent()
g.replace(e2, transpose_view(x)) g.replace(e2, transpose_view(x))
inconsistent(g) assert not g.consistent()
def test_usage_loop(): def test_usage_loop():
x, y, z = inputs() x, y, z = inputs()
g = Env([x, y, z], [dot(add_in_place(x, z), x)], False) g = Env([x, y, z], [dot(add_in_place(x, z), x)], False)
inconsistent(g) assert not g.consistent()
# replace add_in_place with add # replace add_in_place with add
OpSubOptimizer(add_in_place, add).optimize(g) OpSubOptimizer(add_in_place, add).optimize(g)
consistent(g) assert g.consistent()
def test_usage_loop_through_views(): def test_usage_loop_through_views():
...@@ -422,9 +391,9 @@ def test_usage_loop_through_views(): ...@@ -422,9 +391,9 @@ def test_usage_loop_through_views():
aip = add_in_place(x, y) aip = add_in_place(x, y)
e = dot(aip, transpose_view(x)) e = dot(aip, transpose_view(x))
g = Env([x, y, z], [e], False) g = Env([x, y, z], [e], False)
inconsistent(g) assert not g.consistent()
g.replace_validate(aip, add(x, z)) g.replace_validate(aip, add(x, z))
consistent(g) assert g.consistent()
@assertFailure_fast @assertFailure_fast
...@@ -432,10 +401,10 @@ def test_usage_loop_insert_views(): ...@@ -432,10 +401,10 @@ def test_usage_loop_insert_views():
x, y, z = inputs() x, y, z = inputs()
e = dot(add_in_place(x, add(y, z)), sigmoid(sigmoid(sigmoid(sigmoid(sigmoid(x)))))) e = dot(add_in_place(x, add(y, z)), sigmoid(sigmoid(sigmoid(sigmoid(sigmoid(x))))))
g = Env([x, y, z], [e]) g = Env([x, y, z], [e])
consistent(g) assert g.consistent()
fail = FailureWatch() fail = FailureWatch()
OpSubOptimizer(sigmoid, transpose_view, fail).optimize(g) OpSubOptimizer(sigmoid, transpose_view, fail).optimize(g)
consistent(g) assert g.consistent()
# it must keep one sigmoid in the long sigmoid chain # it must keep one sigmoid in the long sigmoid chain
assert fail.failures == 1 assert fail.failures == 1
...@@ -445,9 +414,9 @@ def test_value_repl(): ...@@ -445,9 +414,9 @@ def test_value_repl():
sy = sigmoid(y) sy = sigmoid(y)
e = add_in_place(x, sy) e = add_in_place(x, sy)
g = Env([x, y], [e], False) g = Env([x, y], [e], False)
consistent(g) assert g.consistent()
g.replace(sy, MyConstant("abc")) g.replace(sy, MyConstant("abc"))
consistent(g) assert g.consistent()
@change_flags(compute_test_value="off") @change_flags(compute_test_value="off")
...@@ -456,9 +425,9 @@ def test_value_repl_2(): ...@@ -456,9 +425,9 @@ def test_value_repl_2():
sy = sigmoid(y) sy = sigmoid(y)
e = add_in_place(x, sy) e = add_in_place(x, sy)
g = Env([x, y], [e], False) g = Env([x, y], [e], False)
consistent(g) assert g.consistent()
g.replace(sy, transpose_view(MyConstant("abc"))) g.replace(sy, transpose_view(MyConstant("abc")))
consistent(g) assert g.consistent()
@assertFailure_fast @assertFailure_fast
...@@ -475,28 +444,28 @@ def test_multiple_inplace(): ...@@ -475,28 +444,28 @@ def test_multiple_inplace():
# before multiple and then multiple can still run in-place on y # before multiple and then multiple can still run in-place on y
e_2 = dot(y, y) e_2 = dot(y, y)
g = Env([x, y], [e_1, e_2], False) g = Env([x, y], [e_1, e_2], False)
consistent(g) assert g.consistent()
# try to work in-place on x/0 and y/1 (this should fail) # try to work in-place on x/0 and y/1 (this should fail)
fail = FailureWatch() fail = FailureWatch()
OpSubOptimizer(multiple, multiple_in_place_0_1, fail).optimize(g) OpSubOptimizer(multiple, multiple_in_place_0_1, fail).optimize(g)
consistent(g) assert g.consistent()
assert fail.failures == 1 assert fail.failures == 1
# try to work in-place on x/0 (this should fail) # try to work in-place on x/0 (this should fail)
fail = FailureWatch() fail = FailureWatch()
OpSubOptimizer(multiple, multiple_in_place_0, fail).optimize(g) OpSubOptimizer(multiple, multiple_in_place_0, fail).optimize(g)
consistent(g) assert g.consistent()
assert fail.failures == 1 assert fail.failures == 1
# try to work in-place on y/1 (this should succeed) # try to work in-place on y/1 (this should succeed)
fail = FailureWatch() fail = FailureWatch()
OpSubOptimizer(multiple, multiple_in_place_1, fail).optimize(g) OpSubOptimizer(multiple, multiple_in_place_1, fail).optimize(g)
consistent(g) assert g.consistent()
assert fail.failures == 0 assert fail.failures == 0
# try to work in-place on x/0 and y/1 (this should still fail) # try to work in-place on x/0 and y/1 (this should still fail)
fail = FailureWatch() fail = FailureWatch()
OpSubOptimizer(multiple_in_place_1, multiple_in_place_0_1, fail).optimize(g) OpSubOptimizer(multiple_in_place_1, multiple_in_place_0_1, fail).optimize(g)
consistent(g) assert g.consistent()
assert fail.failures == 1 assert fail.failures == 1
from __future__ import absolute_import, print_function, division from __future__ import absolute_import, print_function, division
import pytest
from theano.compat import exc_message
from theano.gof.optdb import opt, DB from theano.gof.optdb import opt, DB
class TestDB: class TestDB:
def test_0(self): def test_name_clashes(self):
class Opt(opt.Optimizer): # inheritance buys __hash__ class Opt(opt.Optimizer): # inheritance buys __hash__
name = "blah" name = "blah"
...@@ -20,35 +20,11 @@ class TestDB: ...@@ -20,35 +20,11 @@ class TestDB:
assert "b" in db assert "b" in db
assert "c" in db assert "c" in db
try: with pytest.raises(ValueError, match=r"The name.*"):
db.register("c", Opt()) # name taken db.register("c", Opt()) # name taken
self.fail()
except ValueError as e: with pytest.raises(ValueError, match=r"The name.*"):
if exc_message(e).startswith("The name"):
pass
else:
raise
except Exception:
self.fail()
try:
db.register("z", Opt()) # name collides with tag db.register("z", Opt()) # name collides with tag
self.fail()
except ValueError as e: with pytest.raises(ValueError, match=r"The tag.*"):
if exc_message(e).startswith("The name"):
pass
else:
raise
except Exception:
self.fail()
try:
db.register("u", Opt(), "b") # name new but tag collides with name db.register("u", Opt(), "b") # name new but tag collides with name
self.fail()
except ValueError as e:
if exc_message(e).startswith("The tag"):
pass
else:
raise
except Exception:
self.fail()
...@@ -187,38 +187,31 @@ def makeTester( ...@@ -187,38 +187,31 @@ def makeTester(
raise raise
for i, (variable, expected) in enumerate(izip(variables, expecteds)): for i, (variable, expected) in enumerate(izip(variables, expecteds)):
if ( condition = (
variable.dtype != expected.dtype variable.dtype != expected.dtype
or variable.shape != expected.shape or variable.shape != expected.shape
or not TensorType.values_eq_approx(variable, expected) or not TensorType.values_eq_approx(variable, expected)
): )
self.fail( assert not condition, (
( "Test %s::%s: Output %s gave the wrong "
"Test %s::%s: Output %s gave the wrong " "value. With inputs %s, expected %s "
"value. With inputs %s, expected %s " "(dtype %s), got %s (dtype %s)."
"(dtype %s), got %s (dtype %s)." % (
% ( self.op,
self.op, testname,
testname, i,
i, inputs,
inputs, expected,
expected, expected.dtype,
expected.dtype, variable,
variable, variable.dtype,
variable.dtype,
)
)
) )
)
for description, check in iteritems(self.checks): for description, check in iteritems(self.checks):
if not check(inputs, variables): assert check(inputs, variables), (
self.fail( "Test %s::%s: Failed check: %s " "(inputs were %s, ouputs were %s)"
( ) % (self.op, testname, description, inputs, variables)
"Test %s::%s: Failed check: %s "
"(inputs were %s, ouputs were %s)"
)
% (self.op, testname, description, inputs, variables)
)
Checker.__name__ = name Checker.__name__ = name
if hasattr(Checker, "__qualname__"): if hasattr(Checker, "__qualname__"):
......
...@@ -529,42 +529,35 @@ def makeTester( ...@@ -529,42 +529,35 @@ def makeTester(
expecteds = (expecteds,) expecteds = (expecteds,)
for i, (variable, expected) in enumerate(izip(variables, expecteds)): for i, (variable, expected) in enumerate(izip(variables, expecteds)):
if ( condition = (
variable.dtype != expected.dtype variable.dtype != expected.dtype
or variable.shape != expected.shape or variable.shape != expected.shape
or not np.allclose(variable, expected, atol=eps, rtol=eps) or not np.allclose(variable, expected, atol=eps, rtol=eps)
): )
self.fail( assert not condition, (
( "Test %s::%s: Output %s gave the wrong"
"Test %s::%s: Output %s gave the wrong" " value. With inputs %s, expected %s (dtype %s),"
" value. With inputs %s, expected %s (dtype %s)," " got %s (dtype %s). eps=%f"
" got %s (dtype %s). eps=%f" " np.allclose returns %s %s"
" np.allclose returns %s %s" ) % (
) self.op,
% ( testname,
self.op, i,
testname, inputs,
i, expected,
inputs, expected.dtype,
expected, variable,
expected.dtype, variable.dtype,
variable, eps,
variable.dtype, np.allclose(variable, expected, atol=eps, rtol=eps),
eps, np.allclose(variable, expected),
np.allclose(variable, expected, atol=eps, rtol=eps), )
np.allclose(variable, expected),
)
)
for description, check in iteritems(self.checks): for description, check in iteritems(self.checks):
if not check(inputs, variables): assert check(inputs, variables), (
self.fail( "Test %s::%s: Failed check: %s (inputs"
( " were %s, outputs were %s)"
"Test %s::%s: Failed check: %s (inputs" ) % (self.op, testname, description, inputs, variables)
" were %s, outputs were %s)"
)
% (self.op, testname, description, inputs, variables)
)
def test_bad_build(self): def test_bad_build(self):
if skip: if skip:
...@@ -4080,10 +4073,12 @@ class TestMinMax: ...@@ -4080,10 +4073,12 @@ class TestMinMax:
n = as_tensor_variable(data) n = as_tensor_variable(data)
assert min(n).dtype == "bool" assert min(n).dtype == "bool"
i = eval_outputs(min(n)) i = eval_outputs(min(n))
assert i is False assert i.ndim == 0
assert not np.any(i)
assert max(n).dtype == "bool" assert max(n).dtype == "bool"
i = eval_outputs(max(n)) i = eval_outputs(max(n))
assert i is True assert i.ndim == 0
assert np.all(i)
def test_basic_allclose(): def test_basic_allclose():
...@@ -5353,10 +5348,8 @@ class TestDivimpl: ...@@ -5353,10 +5348,8 @@ class TestDivimpl:
class TestMean: class TestMean:
def test_regression_mean_of_ndarray_failure(self): def test_regression_mean_of_ndarray_failure(self):
try: # This shouldn't throw an `AttributeError` (or any other, for that matter)
tensor.mean(np.zeros(1)) tensor.mean(np.zeros(1))
except AttributeError:
self.fail()
def test_mean_f16(self): def test_mean_f16(self):
x = tensor.vector(dtype="float16") x = tensor.vector(dtype="float16")
......
...@@ -24,8 +24,6 @@ from six.moves import xrange ...@@ -24,8 +24,6 @@ from six.moves import xrange
import theano import theano
import theano.tensor as T import theano.tensor as T
from theano import tensor, In, shared, config from theano import tensor, In, shared, config
from theano.compat import exc_message # noqa: E401
from theano.printing import pp
from theano.tensor.blas import ( from theano.tensor.blas import (
_dot22, _dot22,
_dot22scalar, _dot22scalar,
...@@ -128,28 +126,16 @@ class TestGemm: ...@@ -128,28 +126,16 @@ class TestGemm:
def test_basic(self): def test_basic(self):
Gemm.debug = True Gemm.debug = True
try: with pytest.raises(TypeError, match=Gemm.E_rank):
gemm_no_inplace([1.0], 1.0, [1.0], [1.0], 1.0) gemm_no_inplace([1.0], 1.0, [1.0], [1.0], 1.0)
except TypeError as e:
if exc_message(e) is Gemm.E_rank:
return
self.fail()
def test_basic_1(self): def test_basic_1(self):
try: with pytest.raises(TypeError, match=Gemm.E_rank):
self.cmp(1.0, 0.0, 1.0, 1.0, 1.0) self.cmp(1.0, 0.0, 1.0, 1.0, 1.0)
except TypeError as e:
if exc_message(e) is Gemm.E_rank:
return
self.fail()
def test_basic_2(self): def test_basic_2(self):
try: with pytest.raises(TypeError, match=Gemm.E_rank):
self.cmp(2.0, 1.0, [3, 2, 1.0], [[1], [2], [3.0]], 1.0) self.cmp(2.0, 1.0, [3, 2, 1.0], [[1], [2], [3.0]], 1.0)
except TypeError as e:
assert exc_message(e) == Gemm.E_rank
return
self.fail()
def test_basic_4(self): def test_basic_4(self):
self.cmp(self.rand(3, 4), 1.0, self.rand(3, 5), self.rand(5, 4), 0.0) self.cmp(self.rand(3, 4), 1.0, self.rand(3, 5), self.rand(5, 4), 0.0)
...@@ -233,45 +219,29 @@ class TestGemm: ...@@ -233,45 +219,29 @@ class TestGemm:
def test_destroy_map0(self): def test_destroy_map0(self):
# test that only first input can be overwritten. # test that only first input can be overwritten.
Z = as_tensor_variable(self.rand(2, 2)) Z = as_tensor_variable(self.rand(2, 2))
try: with pytest.raises(InconsistencyError, match=Gemm.E_z_uniq):
gemm_inplace(Z, 1.0, Z, Z, 1.0) gemm_inplace(Z, 1.0, Z, Z, 1.0)
except InconsistencyError as e:
if exc_message(e) == Gemm.E_z_uniq:
return
self.fail()
def test_destroy_map1(self): def test_destroy_map1(self):
# test that only first input can be overwritten. # test that only first input can be overwritten.
Z = as_tensor_variable(self.rand(2, 2)) Z = as_tensor_variable(self.rand(2, 2))
A = as_tensor_variable(self.rand(2, 2)) A = as_tensor_variable(self.rand(2, 2))
try: with pytest.raises(InconsistencyError, match=Gemm.E_z_uniq):
gemm_inplace(Z, 1.0, A, inplace.transpose_inplace(Z), 1.0) gemm_inplace(Z, 1.0, A, inplace.transpose_inplace(Z), 1.0)
except InconsistencyError as e:
if exc_message(e) == Gemm.E_z_uniq:
return
self.fail()
def test_destroy_map2(self): def test_destroy_map2(self):
# test that only first input can be overwritten. # test that only first input can be overwritten.
Z = as_tensor_variable(self.rand(2, 2)) Z = as_tensor_variable(self.rand(2, 2))
A = as_tensor_variable(self.rand(2, 2)) A = as_tensor_variable(self.rand(2, 2))
try: with pytest.raises(InconsistencyError, match=Gemm.E_z_uniq):
gemm_inplace(Z, 1.0, inplace.transpose_inplace(Z), A, 1.0) gemm_inplace(Z, 1.0, inplace.transpose_inplace(Z), A, 1.0)
except InconsistencyError as e:
if exc_message(e) == Gemm.E_z_uniq:
return
self.fail()
def test_destroy_map3(self): def test_destroy_map3(self):
# test that only first input can be overwritten # test that only first input can be overwritten
Z = as_tensor_variable(self.rand(2, 2)) Z = as_tensor_variable(self.rand(2, 2))
A = as_tensor_variable(self.rand(2, 2)) A = as_tensor_variable(self.rand(2, 2))
try: with pytest.raises(InconsistencyError, match=Gemm.E_z_uniq):
gemm_inplace(Z, 1.0, Z, A, 1.0) gemm_inplace(Z, 1.0, Z, A, 1.0)
except InconsistencyError as e:
if exc_message(e) == Gemm.E_z_uniq:
return
self.fail()
def test_destroy_map4(self): def test_destroy_map4(self):
# test that dot args can be aliased # test that dot args can be aliased
...@@ -337,12 +307,8 @@ class TestGemm: ...@@ -337,12 +307,8 @@ class TestGemm:
t(C, A[:2, :].T, B[:, :2].T) t(C, A[:2, :].T, B[:, :2].T)
t(C.T, A[:2, :].T, B[:, :2].T) t(C.T, A[:2, :].T, B[:, :2].T)
try: with pytest.raises(ValueError, match=r".*aligned.*"):
t(C.T, A[:2, :], B[:, :2].T) t(C.T, A[:2, :], B[:, :2].T)
except ValueError as e:
if exc_message(e).find("aligned") >= 0:
return
self.fail()
def test_non_contiguous(self): def test_non_contiguous(self):
# Like test_transposes but with matrices without any # Like test_transposes but with matrices without any
...@@ -598,7 +564,7 @@ class TestAsScalar: ...@@ -598,7 +564,7 @@ class TestAsScalar:
# Test that it fails on nonscalar variables # Test that it fails on nonscalar variables
a = T.matrix() a = T.matrix()
assert _as_scalar(a) is None assert _as_scalar(a) is None
assert _as_scalar(T.DimShuffle([False, False], [0, "x", 1])(1)) is None assert _as_scalar(T.DimShuffle([False, False], [0, "x", 1])(a)) is None
class TestRealMatrix: class TestRealMatrix:
...@@ -622,61 +588,49 @@ def XYZab(): ...@@ -622,61 +588,49 @@ def XYZab():
return T.matrix(), T.matrix(), T.matrix(), T.scalar(), T.scalar() return T.matrix(), T.matrix(), T.matrix(), T.scalar(), T.scalar()
class Failure(Exception):
pass
def just_gemm( def just_gemm(
i, o, ishapes=[(4, 3), (3, 5), (4, 5), (), ()], max_graphlen=0, expected_nb_gemm=1 i, o, ishapes=[(4, 3), (3, 5), (4, 5), (), ()], max_graphlen=0, expected_nb_gemm=1
): ):
try: f = inplace_func(
f = inplace_func( [In(ii, mutable=True, allow_downcast=True) for ii in i],
[In(ii, mutable=True, allow_downcast=True) for ii in i], o,
o, mode="FAST_RUN",
mode="FAST_RUN", on_unused_input="ignore",
on_unused_input="ignore", )
) nb_gemm = 0
nb_gemm = 0 for node in f.maker.fgraph.apply_nodes:
for node in f.maker.fgraph.apply_nodes: assert not isinstance(
if isinstance(node.op, T.Dot): node.op, T.Dot
raise Failure("dot not changed to gemm_inplace in graph") ), "_dot22 not changed to gemm_inplace in graph"
if node.op == _dot22: assert node.op != _dot22
raise Failure("_dot22 not changed to gemm_inplace in graph") if node.op == gemm_inplace:
if node.op == gemm_inplace: nb_gemm += 1
nb_gemm += 1 assert nb_gemm == expected_nb_gemm, (nb_gemm, expected_nb_gemm)
assert nb_gemm == expected_nb_gemm, (nb_gemm, expected_nb_gemm) g = inplace_func(
g = inplace_func( i,
i, o,
o, mode=compile.Mode(linker="py", optimizer=None),
mode=compile.Mode(linker="py", optimizer=None), allow_input_downcast=True,
allow_input_downcast=True, on_unused_input="ignore",
on_unused_input="ignore", )
) for node in g.maker.fgraph.apply_nodes:
for node in g.maker.fgraph.apply_nodes: assert node.op != gemm_inplace, "gemm_inplace in original graph"
if node.op == gemm_inplace:
raise Exception("gemm_inplace in original graph") graphlen = len(f.maker.fgraph.toposort())
assert not (max_graphlen and (graphlen <= max_graphlen)), "graphlen=%i>%i" % (
graphlen = len(f.maker.fgraph.toposort()) graphlen,
if max_graphlen and (graphlen <= max_graphlen): max_graphlen,
# theano.printing.debugprint(f) )
assert False, "graphlen=%i>%i" % (graphlen, max_graphlen)
rng = np.random.RandomState(unittest_tools.fetch_seed(234))
rng = np.random.RandomState(unittest_tools.fetch_seed(234)) r0 = f(*[np.asarray(rng.randn(*sh), config.floatX) for sh in ishapes])
r0 = f(*[np.asarray(rng.randn(*sh), config.floatX) for sh in ishapes]) rng = np.random.RandomState(unittest_tools.fetch_seed(234))
rng = np.random.RandomState(unittest_tools.fetch_seed(234)) r1 = g(*[np.asarray(rng.randn(*sh), config.floatX) for sh in ishapes])
r1 = g(*[np.asarray(rng.randn(*sh), config.floatX) for sh in ishapes]) max_abs_err = np.max(np.abs(r0[0] - r1[0]))
max_abs_err = np.max(np.abs(r0[0] - r1[0])) eps = 1.0e-8
eps = 1.0e-8 if config.floatX == "float32":
if config.floatX == "float32": eps = 1.0e-6
eps = 1.0e-6 assert max_abs_err <= eps, "GEMM is computing the wrong output. max_rel_err ="
if max_abs_err > eps:
raise Failure(
"GEMM is computing the wrong output. max_rel_err =", max_abs_err
)
except Failure:
for node in f.maker.fgraph.toposort():
print("GRAPH", node)
raise
@unittest_tools.assertFailure_fast @unittest_tools.assertFailure_fast
...@@ -732,43 +686,28 @@ def test_gemm_opt_double_gemm(): ...@@ -732,43 +686,28 @@ def test_gemm_opt_double_gemm():
+ gemm_inplace(Z, b, S.T, R.T, T.constant(1.0).astype(config.floatX)) + gemm_inplace(Z, b, S.T, R.T, T.constant(1.0).astype(config.floatX))
) )
] ]
try: f = inplace_func(
f = inplace_func( [In(ii, mutable=True) for ii in i],
[In(ii, mutable=True) for ii in i], o,
o, mode="FAST_RUN",
mode="FAST_RUN", on_unused_input="ignore",
on_unused_input="ignore", )
) for node in f.maker.fgraph.apply_nodes:
for node in f.maker.fgraph.apply_nodes: assert not isinstance(node.op, T.Dot)
if isinstance(node.op, T.Dot): assert node.op != _dot22
raise Failure("dot in graph") g = inplace_func(
if node.op == _dot22: i, o, mode=compile.Mode(linker="py", optimizer=None), on_unused_input="ignore",
raise Failure("_dot22 in graph") )
g = inplace_func(
i, rng = np.random.RandomState(unittest_tools.fetch_seed(234))
o, r0 = f(*[np.asarray(rng.randn(*sh), config.floatX) for sh in ishapes])
mode=compile.Mode(linker="py", optimizer=None), rng = np.random.RandomState(unittest_tools.fetch_seed(234))
on_unused_input="ignore", r1 = g(*[np.asarray(rng.randn(*sh), config.floatX) for sh in ishapes])
) max_abs_err = np.max(np.abs(r0[0] - r1[0]))
# for node in g.maker.fgraph.apply_nodes: eps = 1.0e-8
# if node.op == gemm_inplace: raise Failure('gemm_inplace in graph') if config.floatX == "float32":
eps = 1.0e-6
rng = np.random.RandomState(unittest_tools.fetch_seed(234)) assert max_abs_err <= eps, "GEMM is computing the wrong output. max_rel_err ="
r0 = f(*[np.asarray(rng.randn(*sh), config.floatX) for sh in ishapes])
rng = np.random.RandomState(unittest_tools.fetch_seed(234))
r1 = g(*[np.asarray(rng.randn(*sh), config.floatX) for sh in ishapes])
max_abs_err = np.max(np.abs(r0[0] - r1[0]))
eps = 1.0e-8
if config.floatX == "float32":
eps = 1.0e-6
if max_abs_err > eps:
raise Failure(
"GEMM is computing the wrong output. max_rel_err =", max_abs_err
)
except Failure:
for node in f.maker.fgraph.toposort():
print("GRAPH", node)
raise
def test_gemm_canonicalize(): def test_gemm_canonicalize():
...@@ -954,12 +893,10 @@ def test_gemm_opt_vector_stuff(): ...@@ -954,12 +893,10 @@ def test_gemm_opt_vector_stuff():
u, v = T.vector(), T.vector() u, v = T.vector(), T.vector()
f = inplace_func([a, u, v], a + T.dot(u, v), mode="FAST_RUN") f = inplace_func([a, u, v], a + T.dot(u, v), mode="FAST_RUN")
if gemm_inplace in [n.op for n in f.maker.fgraph.apply_nodes]: assert gemm_inplace not in [n.op for n in f.maker.fgraph.apply_nodes]
raise Failure("gemm_inplace in graph")
f = inplace_func([a, u, X, Y], a * u + T.dot(X, Y), mode="FAST_RUN") f = inplace_func([a, u, X, Y], a * u + T.dot(X, Y), mode="FAST_RUN")
if gemm_inplace in [n.op for n in f.maker.fgraph.apply_nodes]: assert gemm_inplace not in [n.op for n in f.maker.fgraph.apply_nodes]
raise Failure("gemm_inplace in graph")
def test_gemm_unrolled(): def test_gemm_unrolled():
...@@ -1029,9 +966,7 @@ def test_inplace0(): ...@@ -1029,9 +966,7 @@ def test_inplace0():
R, S, c = T.matrix("R"), T.matrix("S"), T.scalar("c") R, S, c = T.matrix("R"), T.matrix("S"), T.scalar("c")
f = inplace_func([Z, b, R, S], [Z * (Z + b * T.dot(R, S).T)], mode="FAST_RUN") f = inplace_func([Z, b, R, S], [Z * (Z + b * T.dot(R, S).T)], mode="FAST_RUN")
if gemm_inplace in [n.op for n in f.maker.fgraph.apply_nodes]: assert gemm_inplace not in [n.op for n in f.maker.fgraph.apply_nodes]
print(pp(f.maker.fgraph.outputs[0]))
raise Failure("gemm_inplace in graph")
assert gemm_no_inplace in [n.op for n in f.maker.fgraph.apply_nodes] assert gemm_no_inplace in [n.op for n in f.maker.fgraph.apply_nodes]
# gemm_inplace should be inserted here, to work in-place on Z*c # gemm_inplace should be inserted here, to work in-place on Z*c
...@@ -1040,9 +975,7 @@ def test_inplace0(): ...@@ -1040,9 +975,7 @@ def test_inplace0():
[Z * (c * Z + a * T.dot(X, Y) + b * T.dot(R, S).T)], [Z * (c * Z + a * T.dot(X, Y) + b * T.dot(R, S).T)],
mode="FAST_RUN", mode="FAST_RUN",
) )
if gemm_inplace not in [n.op for n in f.maker.fgraph.apply_nodes]: assert gemm_inplace in [n.op for n in f.maker.fgraph.apply_nodes]
theano.printing.debugprint(f)
raise Failure("no gemm_inplace in graph")
def test_inplace1(): def test_inplace1():
......
...@@ -482,13 +482,8 @@ class TestCAReduce(unittest_tools.InferShapeTester): ...@@ -482,13 +482,8 @@ class TestCAReduce(unittest_tools.InferShapeTester):
% str(scalar_op) % str(scalar_op)
) )
if scalar_op in [scalar.maximum, scalar.minimum] and numpy_raised: if scalar_op in [scalar.maximum, scalar.minimum] and numpy_raised:
try: with pytest.raises(ValueError):
out = f(xv) f(xv)
assert out.dtype == dtype
except ValueError:
pass
else:
self.fail()
else: else:
if test_nan: if test_nan:
try: try:
......
...@@ -142,25 +142,15 @@ class TestSubtensor(utt.OptimizationTestMixin): ...@@ -142,25 +142,15 @@ class TestSubtensor(utt.OptimizationTestMixin):
oldlevel = _logger.level oldlevel = _logger.level
_logger.setLevel(logging.CRITICAL) _logger.setLevel(logging.CRITICAL)
try: try:
try: with pytest.raises(IndexError):
self.eval_output_and_check(t) self.eval_output_and_check(t)
except IndexError:
return
self.fail()
finally: finally:
_logger.setLevel(oldlevel) _logger.setLevel(oldlevel)
def test_err_subslice(self): def test_err_subslice(self):
n = self.shared(np.ones(3, dtype=self.dtype)) n = self.shared(np.ones(3, dtype=self.dtype))
try: with pytest.raises(Exception):
n[slice(0, slice(1, 2, None), None)] n[slice(0, slice(1, 2, None), None)]
except Exception:
# Relax constraint on the type of Exception,
# since this might be handled by AvancedSubtensor
# if e[0] != Subtensor.e_indextype:
# raise
return
self.fail()
def test_ok_range_finite(self): def test_ok_range_finite(self):
n = self.shared(np.arange(3, dtype=self.dtype)) n = self.shared(np.arange(3, dtype=self.dtype))
...@@ -1095,24 +1085,12 @@ class TestSubtensor(utt.OptimizationTestMixin): ...@@ -1095,24 +1085,12 @@ class TestSubtensor(utt.OptimizationTestMixin):
a = fscalar() a = fscalar()
b = fscalar() b = fscalar()
c = vector() c = vector()
try: with pytest.raises(TypeError):
c[a:b] c[a:b]
except NotImplementedError: with pytest.raises(TypeError):
self.fail()
except TypeError:
pass
try:
c[a:] c[a:]
except NotImplementedError: with pytest.raises(TypeError):
self.fail()
except TypeError:
pass
try:
c[:b] c[:b]
except NotImplementedError:
self.fail()
except TypeError:
pass
@pytest.mark.slow @pytest.mark.slow
def test_grad_list(self): def test_grad_list(self):
......
...@@ -77,18 +77,8 @@ class RopLopChecker: ...@@ -77,18 +77,8 @@ class RopLopChecker:
If your op is not differentiable(so you can't define Rop) If your op is not differentiable(so you can't define Rop)
test that an error is raised. test that an error is raised.
""" """
raised = False with pytest.raises(ValueError):
try:
tensor.Rop(y, self.x, self.v) tensor.Rop(y, self.x, self.v)
except ValueError:
raised = True
if not raised:
self.fail(
(
"Op did not raise an error even though the function"
" is not differentiable"
)
)
def check_mat_rop_lop(self, y, out_shape): def check_mat_rop_lop(self, y, out_shape):
""" """
...@@ -162,10 +152,13 @@ class RopLopChecker: ...@@ -162,10 +152,13 @@ class RopLopChecker:
v1 = rop_f(vx, vv) v1 = rop_f(vx, vv)
v2 = scan_f(vx, vv) v2 = scan_f(vx, vv)
assert np.allclose(v1, v2), "ROP mismatch: %s %s" % (v1, v2) assert np.allclose(v1, v2), "ROP mismatch: %s %s" % (v1, v2)
known_fail = False known_fail = False
try: try:
self.check_nondiff_rop(theano.clone(y, replace={self.x: break_op(self.x)})) tensor.Rop(
except AssertionError: theano.clone(y, replace={self.x: break_op(self.x)}), self.x, self.v
)
except ValueError:
known_fail = True known_fail = True
# TEST LOP # TEST LOP
......
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论