提交 7e6a3dc5 authored 作者: Frédéric Bastien's avatar Frédéric Bastien

Merge pull request #4126 from olimastro/master

flake8 compile/tests/*.py
...@@ -4,7 +4,6 @@ from theano import config, shared ...@@ -4,7 +4,6 @@ from theano import config, shared
from theano.compile import function from theano.compile import function
from theano import tensor
from theano import tensor as T from theano import tensor as T
from theano.tensor.shared_randomstreams import RandomStreams from theano.tensor.shared_randomstreams import RandomStreams
...@@ -24,8 +23,8 @@ class T_OpFromGraph(unittest_tools.InferShapeTester): ...@@ -24,8 +23,8 @@ class T_OpFromGraph(unittest_tools.InferShapeTester):
fn = function([x, y, z], f) fn = function([x, y, z], f)
xv = numpy.ones((2, 2), dtype=config.floatX) xv = numpy.ones((2, 2), dtype=config.floatX)
yv = numpy.ones((2, 2), dtype=config.floatX)*3 yv = numpy.ones((2, 2), dtype=config.floatX) * 3
zv = numpy.ones((2, 2), dtype=config.floatX)*5 zv = numpy.ones((2, 2), dtype=config.floatX) * 5
# print function, function.__module__ # print function, function.__module__
# print fn.maker.fgraph.toposort() # print fn.maker.fgraph.toposort()
fn(xv, yv, zv) fn(xv, yv, zv)
...@@ -39,8 +38,8 @@ class T_OpFromGraph(unittest_tools.InferShapeTester): ...@@ -39,8 +38,8 @@ class T_OpFromGraph(unittest_tools.InferShapeTester):
f = op(x, op(y, z)) f = op(x, op(y, z))
fn = function([x, y, z], f) fn = function([x, y, z], f)
xv = numpy.ones((2, 3), dtype=config.floatX) xv = numpy.ones((2, 3), dtype=config.floatX)
yv = numpy.ones((3, 4), dtype=config.floatX)*3 yv = numpy.ones((3, 4), dtype=config.floatX) * 3
zv = numpy.ones((4, 5), dtype=config.floatX)*5 zv = numpy.ones((4, 5), dtype=config.floatX) * 5
res = fn(xv, yv, zv) res = fn(xv, yv, zv)
assert res.shape == (2, 5) assert res.shape == (2, 5)
assert numpy.all(180.0 == res) assert numpy.all(180.0 == res)
...@@ -56,8 +55,8 @@ class T_OpFromGraph(unittest_tools.InferShapeTester): ...@@ -56,8 +55,8 @@ class T_OpFromGraph(unittest_tools.InferShapeTester):
f = f - T.grad(T.sum(f), y) f = f - T.grad(T.sum(f), y)
fn = function([x, y, z], f) fn = function([x, y, z], f)
xv = numpy.ones((2, 2), dtype=config.floatX) xv = numpy.ones((2, 2), dtype=config.floatX)
yv = numpy.ones((2, 2), dtype=config.floatX)*3 yv = numpy.ones((2, 2), dtype=config.floatX) * 3
zv = numpy.ones((2, 2), dtype=config.floatX)*5 zv = numpy.ones((2, 2), dtype=config.floatX) * 5
assert numpy.all(11.0 == fn(xv, yv, zv)) assert numpy.all(11.0 == fn(xv, yv, zv))
def test_grad_grad(self): def test_grad_grad(self):
...@@ -69,8 +68,8 @@ class T_OpFromGraph(unittest_tools.InferShapeTester): ...@@ -69,8 +68,8 @@ class T_OpFromGraph(unittest_tools.InferShapeTester):
f = f - T.grad(T.sum(f), y) f = f - T.grad(T.sum(f), y)
fn = function([x, y, z], f) fn = function([x, y, z], f)
xv = numpy.ones((2, 2), dtype=config.floatX) xv = numpy.ones((2, 2), dtype=config.floatX)
yv = numpy.ones((2, 2), dtype=config.floatX)*3 yv = numpy.ones((2, 2), dtype=config.floatX) * 3
zv = numpy.ones((2, 2), dtype=config.floatX)*5 zv = numpy.ones((2, 2), dtype=config.floatX) * 5
assert numpy.allclose(6.0, fn(xv, yv, zv)) assert numpy.allclose(6.0, fn(xv, yv, zv))
def test_shared(self): def test_shared(self):
...@@ -83,8 +82,8 @@ class T_OpFromGraph(unittest_tools.InferShapeTester): ...@@ -83,8 +82,8 @@ class T_OpFromGraph(unittest_tools.InferShapeTester):
fn = function([x, y, z], f) fn = function([x, y, z], f)
xv = numpy.ones((2, 2), dtype=config.floatX) xv = numpy.ones((2, 2), dtype=config.floatX)
yv = numpy.ones((2, 2), dtype=config.floatX)*3 yv = numpy.ones((2, 2), dtype=config.floatX) * 3
zv = numpy.ones((2, 2), dtype=config.floatX)*5 zv = numpy.ones((2, 2), dtype=config.floatX) * 5
# print function, function.__module__ # print function, function.__module__
# print fn.maker.fgraph.toposort() # print fn.maker.fgraph.toposort()
assert numpy.allclose(8.0, fn(xv, yv, zv)) assert numpy.allclose(8.0, fn(xv, yv, zv))
...@@ -109,14 +108,14 @@ class T_OpFromGraph(unittest_tools.InferShapeTester): ...@@ -109,14 +108,14 @@ class T_OpFromGraph(unittest_tools.InferShapeTester):
fn = function([x, y, z], f) fn = function([x, y, z], f)
assert numpy.allclose(15.0 + s.get_value(), assert numpy.allclose(15.0 + s.get_value(),
fn(xv, yv, zv)) fn(xv, yv, zv))
def test_connection_pattern(self): def test_connection_pattern(self):
# Basic case # Basic case
x, y, z = T.matrices('xyz') x, y, z = T.matrices('xyz')
out1 = x * y out1 = x * y
out2 = y * z out2 = y * z
op1 = OpFromGraph([x ,y, z], [out1, out2]) op1 = OpFromGraph([x, y, z], [out1, out2])
results = op1.connection_pattern(None) results = op1.connection_pattern(None)
expect_result = [[True, False], expect_result = [[True, False],
[True, True], [True, True],
...@@ -124,7 +123,7 @@ class T_OpFromGraph(unittest_tools.InferShapeTester): ...@@ -124,7 +123,7 @@ class T_OpFromGraph(unittest_tools.InferShapeTester):
assert results == expect_result assert results == expect_result
# Graph with ops that don't have a 'full' connection pattern # Graph with ops that don't have a 'full' connection pattern
# and with ops that have multiple outputs # and with ops that have multiple outputs
m, n, p, q = T.matrices('mnpq') m, n, p, q = T.matrices('mnpq')
o1, o2 = op1(m, n, p) o1, o2 = op1(m, n, p)
out1, out2 = op1(o1, q, o2) out1, out2 = op1(o1, q, o2)
...@@ -139,7 +138,7 @@ class T_OpFromGraph(unittest_tools.InferShapeTester): ...@@ -139,7 +138,7 @@ class T_OpFromGraph(unittest_tools.InferShapeTester):
# Inner graph where some computation doesn't rely on explicit inputs # Inner graph where some computation doesn't rely on explicit inputs
srng = RandomStreams(seed=234) srng = RandomStreams(seed=234)
rv_u = srng.uniform((2,2)) rv_u = srng.uniform((2, 2))
x, y = T.matrices('xy') x, y = T.matrices('xy')
out1 = x + rv_u out1 = x + rv_u
out2 = y + 3 out2 = y + 3
...@@ -155,14 +154,14 @@ class T_OpFromGraph(unittest_tools.InferShapeTester): ...@@ -155,14 +154,14 @@ class T_OpFromGraph(unittest_tools.InferShapeTester):
def test_infer_shape(self): def test_infer_shape(self):
x = T.matrix('x') x = T.matrix('x')
y = T.matrix('y') y = T.matrix('y')
o1 = x+y o1 = x + y
o2 = x*y o2 = x * y
op_graph = OpFromGraph([x,y], [o1,o2]) op_graph = OpFromGraph([x, y], [o1, o2])
q = T.matrix('q') q = T.matrix('q')
p = T.matrix('p') p = T.matrix('p')
self._compile_and_check([q,p], self._compile_and_check([q, p],
op_graph(q,p), op_graph(q, p),
[numpy.ones([3,4], dtype=config.floatX), [numpy.ones([3, 4], dtype=config.floatX),
numpy.ones([3,4], dtype=config.floatX)], numpy.ones([3, 4], dtype=config.floatX)],
OpFromGraph) OpFromGraph)
...@@ -22,7 +22,7 @@ def test0(): ...@@ -22,7 +22,7 @@ def test0():
class BROKEN_ON_PURPOSE_Add(gof.Op): class BROKEN_ON_PURPOSE_Add(gof.Op):
__props__ = ("py_offset",) __props__ = ("py_offset",)
def __init__(self, py_offset): def __init__(self, py_offset):
gof.Op.__init__(self) gof.Op.__init__(self)
self.py_offset = py_offset self.py_offset = py_offset
...@@ -102,7 +102,7 @@ class WeirdBrokenOp(gof.Op): ...@@ -102,7 +102,7 @@ class WeirdBrokenOp(gof.Op):
it should raise an error in DebugMode. it should raise an error in DebugMode.
""" """
__props__ = ("behaviour", ) __props__ = ("behaviour", )
def __init__(self, behaviour): def __init__(self, behaviour):
gof.Op.__init__(self) gof.Op.__init__(self)
self.behaviour = behaviour self.behaviour = behaviour
...@@ -160,16 +160,16 @@ class WeirdBrokenOp(gof.Op): ...@@ -160,16 +160,16 @@ class WeirdBrokenOp(gof.Op):
if self.behaviour == 'times2': if self.behaviour == 'times2':
behaviour = " Dz[m * Sz] = 2 * Da[m * Sa]; " behaviour = " Dz[m * Sz] = 2 * Da[m * Sa]; "
#out[0] = a * 2 # out[0] = a * 2
elif self.behaviour == 'times2_inplace': elif self.behaviour == 'times2_inplace':
#out[0] = a # out[0] = a
#out[0] *= 2 # out[0] *= 2
behaviour = " Dz[m * Sz] = 2 * Da[m * Sa]; " behaviour = " Dz[m * Sz] = 2 * Da[m * Sa]; "
elif self.behaviour == 'times1': elif self.behaviour == 'times1':
#out[0] = a * 1 # out[0] = a * 1
behaviour = " Dz[m * Sz] = Da[m * Sa]; " behaviour = " Dz[m * Sz] = Da[m * Sa]; "
elif self.behaviour == 'times1_inplace': elif self.behaviour == 'times1_inplace':
#out[0] = a # out[0] = a
behaviour = "" behaviour = ""
else: else:
raise ValueError(self.behaviour) raise ValueError(self.behaviour)
...@@ -179,7 +179,7 @@ class WeirdBrokenOp(gof.Op): ...@@ -179,7 +179,7 @@ class WeirdBrokenOp(gof.Op):
""" """
total = ((z_code + prep_vars + behaviour + prep_vars2) total = ((z_code + prep_vars + behaviour + prep_vars2)
% dict(locals(), **sub)) % dict(locals(), **sub))
return total return total
wb2i = WeirdBrokenOp('times2_inplace') wb2i = WeirdBrokenOp('times2_inplace')
...@@ -189,16 +189,16 @@ wb1 = WeirdBrokenOp('times1') ...@@ -189,16 +189,16 @@ wb1 = WeirdBrokenOp('times1')
def test_badthunkoutput(): def test_badthunkoutput():
# Check if the c and python code is consistent. # Check if the c and python code is consistent.
a = theano.tensor.dvector() a = theano.tensor.dvector()
b = theano.tensor.dvector() b = theano.tensor.dvector()
f_good = theano.function([a, b], f_good = theano.function([a, b],
off_by_half(a, b), off_by_half(a, b),
mode=debugmode.DebugMode(check_c_code=theano.config.cxx)) mode=debugmode.DebugMode(check_c_code=theano.config.cxx))
f_inconsistent = theano.function([a, b], f_inconsistent = theano.function([a, b],
inconsistent(a, b), inconsistent(a, b),
mode=debugmode.DebugMode(check_c_code=theano.config.cxx)) mode=debugmode.DebugMode(check_c_code=theano.config.cxx))
# this should evaluate with no error # this should evaluate with no error
f_good([1.0, 2.0, 3.0], [2, 3, 4]) f_good([1.0, 2.0, 3.0], [2, 3, 4])
...@@ -229,7 +229,7 @@ def test_badoptimization(): ...@@ -229,7 +229,7 @@ def test_badoptimization():
b = theano.tensor.dvector() b = theano.tensor.dvector()
f = theano.function([a, b], a + b, f = theano.function([a, b], a + b,
mode=debugmode.DebugMode(optimizer=opt)) mode=debugmode.DebugMode(optimizer=opt))
try: try:
f([1.0, 2.0, 3.0], [2, 3, 4],) f([1.0, 2.0, 3.0], [2, 3, 4],)
...@@ -289,9 +289,9 @@ def test_stochasticoptimization(): ...@@ -289,9 +289,9 @@ def test_stochasticoptimization():
edb = gof.EquilibriumDB() edb = gof.EquilibriumDB()
edb.register( edb.register(
'insert_broken_add_sometimes', 'insert_broken_add_sometimes',
insert_broken_add_sometimes, insert_broken_add_sometimes,
'all') 'all')
opt = edb.query('+all') opt = edb.query('+all')
a = theano.tensor.dvector() a = theano.tensor.dvector()
...@@ -299,11 +299,11 @@ def test_stochasticoptimization(): ...@@ -299,11 +299,11 @@ def test_stochasticoptimization():
try: try:
theano.function([a, b], theano.function([a, b],
theano.tensor.add(a, b), theano.tensor.add(a, b),
mode=debugmode.DebugMode( mode=debugmode.DebugMode(
optimizer=opt, optimizer=opt,
check_c_code=True, check_c_code=True,
stability_patience=max(2, config.DebugMode.patience))) stability_patience=max(2, config.DebugMode.patience)))
except debugmode.StochasticOrder: except debugmode.StochasticOrder:
return # TEST PASS return # TEST PASS
assert False assert False
...@@ -314,7 +314,7 @@ def test_just_c_code(): ...@@ -314,7 +314,7 @@ def test_just_c_code():
raise SkipTest("G++ not available, so we need to skip this test.") raise SkipTest("G++ not available, so we need to skip this test.")
x = theano.tensor.dvector() x = theano.tensor.dvector()
f = theano.function([x], wb2(x), f = theano.function([x], wb2(x),
mode=debugmode.DebugMode(check_py_code=False)) mode=debugmode.DebugMode(check_py_code=False))
assert numpy.all(f([1, 2]) == [2, 4]) assert numpy.all(f([1, 2]) == [2, 4])
...@@ -346,7 +346,7 @@ def test_baddestroymap_c(): ...@@ -346,7 +346,7 @@ def test_baddestroymap_c():
raise SkipTest("G++ not available, so we need to skip this test.") raise SkipTest("G++ not available, so we need to skip this test.")
x = theano.tensor.dvector() x = theano.tensor.dvector()
f = theano.function([x], wb2i(x), f = theano.function([x], wb2i(x),
mode=debugmode.DebugMode(check_py_code=False)) mode=debugmode.DebugMode(check_py_code=False))
try: try:
assert numpy.all(f([1, 2]) == [2, 4]) assert numpy.all(f([1, 2]) == [2, 4])
assert False # failed to raise error assert False # failed to raise error
...@@ -390,7 +390,7 @@ class Test_ViewMap(unittest.TestCase): ...@@ -390,7 +390,7 @@ class Test_ViewMap(unittest.TestCase):
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), f = theano.function([x, y], self.BadAddSlice()(x, y),
mode='DEBUG_MODE') mode='DEBUG_MODE')
try: try:
f([1, 2], [3, 4]) f([1, 2], [3, 4])
assert False # failed to raise error assert False # failed to raise error
...@@ -414,7 +414,7 @@ class Test_ViewMap(unittest.TestCase): ...@@ -414,7 +414,7 @@ class Test_ViewMap(unittest.TestCase):
raise SkipTest("G++ not available, so we need to skip this test.") raise SkipTest("G++ not available, so we need to skip this test.")
x = theano.tensor.dvector() x = theano.tensor.dvector()
f = theano.function([x], wb1i(x), f = theano.function([x], wb1i(x),
mode=debugmode.DebugMode(check_py_code=False)) mode=debugmode.DebugMode(check_py_code=False))
try: try:
f([1, 2]) f([1, 2])
assert False # failed to raise error assert False # failed to raise error
...@@ -525,7 +525,7 @@ class Test_ViewMap(unittest.TestCase): ...@@ -525,7 +525,7 @@ class Test_ViewMap(unittest.TestCase):
try: try:
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 assert False # DebugMode should have caught the error
except debugmode.BadViewMap as e: except debugmode.BadViewMap:
# print e # print e
pass pass
...@@ -533,7 +533,7 @@ class Test_ViewMap(unittest.TestCase): ...@@ -533,7 +533,7 @@ class Test_ViewMap(unittest.TestCase):
# pretending that it is aliased to both the outputs. # pretending that it is aliased to both the outputs.
# This unfairly disables any destructive operations on the # This unfairly disables any destructive operations on the
# input, but guarantees correctness. # input, but guarantees correctness.
#custom_op.view_map = {0:[0], 1:[1]} # custom_op.view_map = {0:[0], 1:[1]}
# f([1,2,3,4],[5,6,7,8]) # f([1,2,3,4],[5,6,7,8])
...@@ -541,12 +541,12 @@ class Test_check_isfinite(unittest.TestCase): ...@@ -541,12 +541,12 @@ class Test_check_isfinite(unittest.TestCase):
def setUp(self): def setUp(self):
self.old_ts = theano.tensor.TensorType.filter_checks_isfinite self.old_ts = theano.tensor.TensorType.filter_checks_isfinite
self.old_dm = theano.compile.mode.predefined_modes[ self.old_dm = theano.compile.mode.predefined_modes[
'DEBUG_MODE'].check_isfinite 'DEBUG_MODE'].check_isfinite
def tearDown(self): def tearDown(self):
theano.tensor.TensorType.filter_checks_isfinite = self.old_ts theano.tensor.TensorType.filter_checks_isfinite = self.old_ts
theano.compile.mode.predefined_modes[ theano.compile.mode.predefined_modes[
'DEBUG_MODE'].check_isfinite = self.old_dm 'DEBUG_MODE'].check_isfinite = self.old_dm
def test_check_isfinite(self): def test_check_isfinite(self):
x = theano.tensor.vector() x = theano.tensor.vector()
...@@ -561,29 +561,29 @@ class Test_check_isfinite(unittest.TestCase): ...@@ -561,29 +561,29 @@ class Test_check_isfinite(unittest.TestCase):
# if not, DebugMode will check internally, and raise InvalidValueError # if not, DebugMode will check internally, and raise InvalidValueError
# passing an invalid value as an input should trigger ValueError # passing an invalid value as an input should trigger ValueError
self.assertRaises(debugmode.InvalidValueError, f, self.assertRaises(debugmode.InvalidValueError, f,
numpy.log([3, -4, 5]).astype(config.floatX)) numpy.log([3, -4, 5]).astype(config.floatX))
self.assertRaises(debugmode.InvalidValueError, f, self.assertRaises(debugmode.InvalidValueError, f,
(numpy.asarray([0, 1.0, 0]) / 0).astype(config.floatX)) (numpy.asarray([0, 1.0, 0]) / 0).astype(config.floatX))
self.assertRaises(debugmode.InvalidValueError, f, self.assertRaises(debugmode.InvalidValueError, f,
(numpy.asarray([1.0, 1.0, 1.0]) / 0).astype(config.floatX)) (numpy.asarray([1.0, 1.0, 1.0]) / 0).astype(config.floatX))
# generating an invalid value internally should trigger # generating an invalid value internally should trigger
# InvalidValueError # InvalidValueError
self.assertRaises(debugmode.InvalidValueError, g, self.assertRaises(debugmode.InvalidValueError, g,
numpy.asarray([3, -4, 5], dtype=config.floatX)) numpy.asarray([3, -4, 5], dtype=config.floatX))
# this should disable the exception # this should disable the exception
theano.tensor.TensorType.filter_checks_isfinite = False theano.tensor.TensorType.filter_checks_isfinite = False
theano.compile.mode.predefined_modes[ theano.compile.mode.predefined_modes[
'DEBUG_MODE'].check_isfinite = False 'DEBUG_MODE'].check_isfinite = False
# insert several Inf # insert several Inf
f(numpy.asarray(numpy.asarray([1.0, 1.0, 1.0]) / 0, f(numpy.asarray(numpy.asarray([1.0, 1.0, 1.0]) / 0,
dtype=config.floatX)) dtype=config.floatX))
def test_check_isfinite_disabled(self): def test_check_isfinite_disabled(self):
x = theano.tensor.dvector() x = theano.tensor.dvector()
f = theano.function([x], (x + 2) * 5, f = theano.function([x], (x + 2) * 5,
mode=debugmode.DebugMode(check_isfinite=False)) mode=debugmode.DebugMode(check_isfinite=False))
# nan should go through # nan should go through
f(numpy.log([3, -4, 5])) f(numpy.log([3, -4, 5]))
...@@ -734,17 +734,17 @@ class Test_preallocated_output(unittest.TestCase): ...@@ -734,17 +734,17 @@ class Test_preallocated_output(unittest.TestCase):
# Should work # Should work
mode = debugmode.DebugMode( mode = debugmode.DebugMode(
check_preallocated_output=['c_contiguous']) check_preallocated_output=['c_contiguous'])
f = theano.function([a, b], out, mode=mode) f = theano.function([a, b], out, mode=mode)
out_val = f(a_val, b_val) f(a_val, b_val)
# print 'out_val =', out_val # print 'out_val =', out_val
# print out_val.strides # print out_val.strides
# Should raise an Exception, since the output buffer is # Should raise an Exception, since the output buffer is
# used incorrectly. # used incorrectly.
mode = debugmode.DebugMode( mode = debugmode.DebugMode(
check_preallocated_output=['f_contiguous']) check_preallocated_output=['f_contiguous'])
f = theano.function([a, b], out, mode=mode) f = theano.function([a, b], out, mode=mode)
...@@ -766,17 +766,17 @@ class Test_preallocated_output(unittest.TestCase): ...@@ -766,17 +766,17 @@ class Test_preallocated_output(unittest.TestCase):
# Should work # Should work
mode = debugmode.DebugMode( mode = debugmode.DebugMode(
check_preallocated_output=['c_contiguous']) check_preallocated_output=['c_contiguous'])
f = theano.function([a, b], out, mode=mode) f = theano.function([a, b], out, mode=mode)
out_val = f(a_val, b_val) f(a_val, b_val)
# print 'out_val =', out_val # print 'out_val =', out_val
# print out_val.strides # print out_val.strides
# Should raise an Exception, since the output buffer is # Should raise an Exception, since the output buffer is
# used incorrectly. # used incorrectly.
mode = debugmode.DebugMode( mode = debugmode.DebugMode(
check_preallocated_output=['f_contiguous']) check_preallocated_output=['f_contiguous'])
f = theano.function([a, b], out, mode=mode) f = theano.function([a, b], out, mode=mode)
......
...@@ -19,7 +19,9 @@ import theano ...@@ -19,7 +19,9 @@ import theano
import numpy as N import numpy as N
PatternOptimizer = lambda p1, p2, ign=True: gof.OpKeyOptimizer(gof.PatternSub(p1, p2), ignore_newtrees=ign)
def PatternOptimizer(p1, p2, ign=True):
return gof.OpKeyOptimizer(gof.PatternSub(p1, p2), ignore_newtrees=ign)
def checkfor(testcase, fn, E): def checkfor(testcase, fn, E):
...@@ -59,80 +61,80 @@ class T_function(unittest.TestCase): ...@@ -59,80 +61,80 @@ class T_function(unittest.TestCase):
def fn(): def fn():
x, s = T.scalars('xs') x, s = T.scalars('xs')
fn = function([], [x]) function([], [x])
checkfor(self, fn, MissingInputError) checkfor(self, fn, MissingInputError)
def fn(): def fn():
x, s = T.scalars('xs') x, s = T.scalars('xs')
# Ignore unused input s, as it hides the other error # Ignore unused input s, as it hides the other error
fn = function([s], [x], on_unused_input='ignore') function([s], [x], on_unused_input='ignore')
checkfor(self, fn, MissingInputError) checkfor(self, fn, MissingInputError)
def fn(): def fn():
x, s = T.scalars('xs') x, s = T.scalars('xs')
fn = function([s], [x]) function([s], [x])
checkfor(self, fn, UnusedInputError) checkfor(self, fn, UnusedInputError)
def fn(): def fn():
x, s = T.scalars('xs') x, s = T.scalars('xs')
# Ignore unused input s, as it hides the other error # Ignore unused input s, as it hides the other error
fn = function([s], x, on_unused_input='ignore') function([s], x, on_unused_input='ignore')
checkfor(self, fn, MissingInputError) checkfor(self, fn, MissingInputError)
def fn(): def fn():
x, s = T.scalars('xs') x, s = T.scalars('xs')
fn = function([s], x) function([s], x)
checkfor(self, fn, UnusedInputError) checkfor(self, fn, UnusedInputError)
def fn(): def fn():
x, s = T.scalars('xs') x, s = T.scalars('xs')
# Ignore unused input s, as it hides the other error # Ignore unused input s, as it hides the other error
fn = function([s], Out(x), on_unused_input='ignore') function([s], Out(x), on_unused_input='ignore')
checkfor(self, fn, MissingInputError) checkfor(self, fn, MissingInputError)
def fn(): def fn():
x, s = T.scalars('xs') x, s = T.scalars('xs')
fn = function([s], Out(x)) function([s], Out(x))
checkfor(self, fn, UnusedInputError) checkfor(self, fn, UnusedInputError)
def fn(): def fn():
x, s = T.scalars('xs') x, s = T.scalars('xs')
fn = function([In(x, update=s+x)], x) function([In(x, update=s + x)], x)
checkfor(self, fn, MissingInputError) checkfor(self, fn, MissingInputError)
def fn(): def fn():
x, s = T.scalars('xs') x, s = T.scalars('xs')
fn = function([In(x, update=((s * s) + x))], x) function([In(x, update=((s * s) + x))], x)
checkfor(self, fn, MissingInputError) checkfor(self, fn, MissingInputError)
def test_input_anon_singleton(self): def test_input_anon_singleton(self):
x, s = T.scalars('xs') x, s = T.scalars('xs')
fn = function([s, x], [x+s]) fn = function([s, x], [x + s])
self.assertTrue(fn(2, 3) == [5]) self.assertTrue(fn(2, 3) == [5])
# no state # no state
self.assertTrue(fn(2, 3) == [5]) self.assertTrue(fn(2, 3) == [5])
def test_input_anon_unpack(self): def test_input_anon_unpack(self):
x, s = T.scalars('xs') x, s = T.scalars('xs')
fn = function([s, x], x+s) fn = function([s, x], x + s)
self.assertTrue(fn(2, 3) == 5) self.assertTrue(fn(2, 3) == 5)
def test_naming_rule0(self): def test_naming_rule0(self):
x, s = T.scalars('xs') x, s = T.scalars('xs')
f = function([x, s], x/s) f = function([x, s], x / s)
self.assertTrue(f(1, 2) == 0.5) self.assertTrue(f(1, 2) == 0.5)
self.assertTrue(f(2, 1) == 2.0) self.assertTrue(f(2, 1) == 2.0)
self.assertTrue(f(s=2, x=1) == 0.5) self.assertTrue(f(s=2, x=1) == 0.5)
self.assertTrue(f(x=2, s=1) == 2.0) self.assertTrue(f(x=2, s=1) == 2.0)
self.assertTrue(f(2, s=1) == 2.0) self.assertTrue(f(2, s=1) == 2.0)
checkfor(self, lambda : f(2, x=2.0), TypeError) # got multiple values for keyword argument 'x' checkfor(self, lambda: f(2, x=2.0), TypeError) # got multiple values for keyword argument 'x'
checkfor(self, lambda : f(x=1), TypeError) # takes exactly 2 non-keyword arguments (1 given) checkfor(self, lambda: f(x=1), TypeError) # takes exactly 2 non-keyword arguments (1 given)
checkfor(self, lambda : f(s=1), TypeError) # takes exactly 2 non-keyword arguments (0 given) checkfor(self, lambda: f(s=1), TypeError) # takes exactly 2 non-keyword arguments (0 given)
def test_naming_rule1(self): def test_naming_rule1(self):
a = T.scalar() # the a is for 'anonymous' (un-named). a = T.scalar() # the a is for 'anonymous' (un-named).
x, s = T.scalars('xs') x, s = T.scalars('xs')
f = function([a, s], a/s) f = function([a, s], a / s)
self.assertTrue(f(1, 2) == 0.5) self.assertTrue(f(1, 2) == 0.5)
self.assertTrue(f(2, 1) == 2.0) self.assertTrue(f(2, 1) == 2.0)
self.assertTrue(f(2, s=1) == 2.0) self.assertTrue(f(2, s=1) == 2.0)
...@@ -145,7 +147,7 @@ class T_function(unittest.TestCase): ...@@ -145,7 +147,7 @@ class T_function(unittest.TestCase):
# x's name is ignored because it is followed by anonymous parameter a. # x's name is ignored because it is followed by anonymous parameter a.
# Ignore unused input x, as it hides the other error # Ignore unused input x, as it hides the other error
f = function([x, a, s], a/s, on_unused_input='ignore') f = function([x, a, s], a / s, on_unused_input='ignore')
self.assertTrue(f(9, 1, 2) == 0.5) self.assertTrue(f(9, 1, 2) == 0.5)
self.assertTrue(f(9, 2, 1) == 2.0) self.assertTrue(f(9, 2, 1) == 2.0)
self.assertTrue(f(9, 2, s=1) == 2.0) self.assertTrue(f(9, 2, s=1) == 2.0)
...@@ -157,7 +159,7 @@ class T_function(unittest.TestCase): ...@@ -157,7 +159,7 @@ class T_function(unittest.TestCase):
x, s = T.scalars('xs') x, s = T.scalars('xs')
# x's name is not ignored (as in test_naming_rule2) because a has a default value. # x's name is not ignored (as in test_naming_rule2) because a has a default value.
f = function([x, In(a, value=1.0), s], a/s+x) f = function([x, In(a, value=1.0), s], a / s + x)
self.assertTrue(f(9, 2, 4) == 9.5) # can specify all args in order self.assertTrue(f(9, 2, 4) == 9.5) # can specify all args in order
self.assertTrue(f(9, 2, s=4) == 9.5) # can give s as kwarg self.assertTrue(f(9, 2, s=4) == 9.5) # can give s as kwarg
self.assertTrue(f(9, s=4) == 9.25) # can give s as kwarg, get default a self.assertTrue(f(9, s=4) == 9.25) # can give s as kwarg, get default a
...@@ -170,7 +172,7 @@ class T_function(unittest.TestCase): ...@@ -170,7 +172,7 @@ class T_function(unittest.TestCase):
a = T.scalar() # the a is for 'anonymous' (un-named). a = T.scalar() # the a is for 'anonymous' (un-named).
x, s = T.scalars('xs') x, s = T.scalars('xs')
f = function([x, In(a, value=1.0, name='a'), s], a/s+x) f = function([x, In(a, value=1.0, name='a'), s], a / s + x)
self.assertTrue(f(9, 2, 4) == 9.5) # can specify all args in order self.assertTrue(f(9, 2, 4) == 9.5) # can specify all args in order
self.assertTrue(f(9, 2, s=4) == 9.5) # can give s as kwarg self.assertTrue(f(9, 2, s=4) == 9.5) # can give s as kwarg
...@@ -185,7 +187,7 @@ class T_function(unittest.TestCase): ...@@ -185,7 +187,7 @@ class T_function(unittest.TestCase):
a = T.scalar() # the a is for 'anonymous' (un-named). a = T.scalar() # the a is for 'anonymous' (un-named).
x, s = T.scalars('xs') x, s = T.scalars('xs')
f = function([x, In(a, value=1.0, name='a'), In(s, value=0.0, update=s+a*x)], s+a*x) f = function([x, In(a, value=1.0, name='a'), In(s, value=0.0, update=s + a * x)], s + a * x)
self.assertTrue(f[a] == 1.0) self.assertTrue(f[a] == 1.0)
self.assertTrue(f[s] == 0.0) self.assertTrue(f[s] == 0.0)
...@@ -204,7 +206,7 @@ class T_function(unittest.TestCase): ...@@ -204,7 +206,7 @@ class T_function(unittest.TestCase):
def test_same_names(self): def test_same_names(self):
a, x, s = T.scalars('xxx') a, x, s = T.scalars('xxx')
# implicit names would cause error. What do we do? # implicit names would cause error. What do we do?
f = function([a, x, s], a+x+s) f = function([a, x, s], a + x + s)
self.assertTrue(f(1, 2, 3) == 6) self.assertTrue(f(1, 2, 3) == 6)
checkfor(self, lambda: f(1, 2, x=3), TypeError) checkfor(self, lambda: f(1, 2, x=3), TypeError)
...@@ -216,14 +218,17 @@ class T_function(unittest.TestCase): ...@@ -216,14 +218,17 @@ class T_function(unittest.TestCase):
def t(): def t():
f = function([In(a, name=set(['adsf', ()]), value=1.0), f = function([In(a, name=set(['adsf', ()]), value=1.0),
In(x, name=(), value=2.0), In(x, name=(), value=2.0),
In(s, name=T.scalar(), value=3.0)], a+x+s) In(s, name=T.scalar(), value=3.0)], a + x + s)
return f
checkfor(self, t, TypeError) checkfor(self, t, TypeError)
def test_copy(self): def test_copy(self):
a = T.scalar() # the a is for 'anonymous' (un-named). a = T.scalar() # the a is for 'anonymous' (un-named).
x, s = T.scalars('xs') x, s = T.scalars('xs')
f = function([x, In(a, value=1.0, name='a'), In(s, value=0.0, update=s+a*x, mutable=True)], s+a*x) f = function([x, In(a, value=1.0, name='a'),
In(s, value=0.0, update=s + a * x, mutable=True)],
s + a * x)
g = copy.copy(f) g = copy.copy(f)
# if they both return, assume that they return equivalent things. # if they both return, assume that they return equivalent things.
...@@ -246,27 +251,26 @@ class T_function(unittest.TestCase): ...@@ -246,27 +251,26 @@ class T_function(unittest.TestCase):
# SharedVariable for tests, one of them has update # SharedVariable for tests, one of them has update
y = theano.shared(value=1) y = theano.shared(value=1)
z = theano.shared(value=2) z = theano.shared(value=2)
out = T.tanh((x+y+2)/(x+z-0.2)**2) out = T.tanh((x + y + 2) / (x + z - 0.2)**2)
# Test for different linkers # Test for different linkers
for mode in ["FAST_RUN","FAST_COMPILE"]: for mode in ["FAST_RUN", "FAST_COMPILE"]:
ori = theano.function([x], [out], mode=mode,updates={z:z+1}) ori = theano.function([x], [out], mode=mode, updates={z: z + 1})
cpy = ori.copy(share_memory=True) cpy = ori.copy(share_memory=True)
# Test if memories shared # Test if memories shared
storage_map_ori = ori.fn.storage_map storage_map_ori = ori.fn.storage_map
storage_map_cpy = cpy.fn.storage_map storage_map_cpy = cpy.fn.storage_map
fgraph_ori = ori.maker.fgraph
fgraph_cpy = cpy.maker.fgraph fgraph_cpy = cpy.maker.fgraph
# Assert intermediate and Constants storages are shared. # Assert intermediate and Constants storages are shared.
# and output stoarges are not shared # and output stoarges are not shared
i_o_variables = fgraph_cpy.inputs + fgraph_cpy.outputs i_o_variables = fgraph_cpy.inputs + fgraph_cpy.outputs
ori_storages = storage_map_ori.values() ori_storages = storage_map_ori.values()
for key in storage_map_cpy.keys(): l = [val for key, val in storage_map_cpy.items()
storage = storage_map_cpy[key] if key not in i_o_variables or isinstance(key, theano.tensor.Constant)]
if key not in i_o_variables or isinstance(key, theano.tensor.Constant): for storage in l:
self.assertTrue(any([ storage is s for s in ori_storages])) self.assertTrue(any([storage is s for s in ori_storages]))
# Assert storages of SharedVariable without updates are shared # Assert storages of SharedVariable without updates are shared
for (input, _1, _2), here, there in zip(ori.indices, for (input, _1, _2), here, there in zip(ori.indices,
...@@ -285,24 +289,24 @@ class T_function(unittest.TestCase): ...@@ -285,24 +289,24 @@ class T_function(unittest.TestCase):
m = theano.shared(value=0, name='m') m = theano.shared(value=0, name='m')
# SharedVariable to replace # SharedVariable to replace
y_rpl = theano.shared(value=3,name ='y_rpl') y_rpl = theano.shared(value=3, name='y_rpl')
z_rpl = theano.shared(value=4, name='z_rpl') z_rpl = theano.shared(value=4, name='z_rpl')
swap = {y:y_rpl, z:z_rpl} swap = {y: y_rpl, z: z_rpl}
map_SV = {'y_rpl':y_rpl, 'z_rpl':z_rpl} map_SV = {'y_rpl': y_rpl, 'z_rpl': z_rpl}
out = x+y+z+m out = x + y + z + m
# Test for different linkers # Test for different linkers
# for mode in ["FAST_RUN","FAST_COMPILE"]: # for mode in ["FAST_RUN","FAST_COMPILE"]:
second_time = False second_time = False
for mode in ["FAST_RUN","FAST_COMPILE"]: for mode in ["FAST_RUN", "FAST_COMPILE"]:
ori = theano.function([i], [out], mode=mode, ori = theano.function([i], [out], mode=mode,
updates=[(z,z+1),(m,m+2)], updates=[(z, z + 1), (m, m + 2)],
givens={x:x_list[i]}) givens={x: x_list[i]})
cpy = ori.copy(swap=swap) cpy = ori.copy(swap=swap)
# run fuction several time # run fuction several time
ori(1), cpy(1),cpy(2) ori(1), cpy(1), cpy(2)
# assert same SharedVariable are update in different function # assert same SharedVariable are update in different function
if not second_time: if not second_time:
...@@ -311,7 +315,7 @@ class T_function(unittest.TestCase): ...@@ -311,7 +315,7 @@ class T_function(unittest.TestCase):
# z should be updated once # z should be updated once
assert z.get_value() == 3 assert z.get_value() == 3
# z_rpl should be updated twice # z_rpl should be updated twice
assert z_rpl.get_value() == 6 assert z_rpl.get_value() == 6
# y and y_rpl should not be updated # y and y_rpl should not be updated
assert y_rpl.get_value() == 3 assert y_rpl.get_value() == 3
assert y.get_value() == 1 assert y.get_value() == 1
...@@ -329,20 +333,20 @@ class T_function(unittest.TestCase): ...@@ -329,20 +333,20 @@ class T_function(unittest.TestCase):
for key in cpy.fn.storage_map: for key in cpy.fn.storage_map:
if key.name in names: if key.name in names:
assert map_SV[key.name].container.storage[0] ==\ assert map_SV[key.name].container.storage[0] ==\
cpy.fn.storage_map[key][0] cpy.fn.storage_map[key][0]
second_time = True second_time = True
def test_swap_SharedVaraile_with_given(self): def test_swap_SharedVariable_with_given(self):
""" """
A special testcase for logistic_sgd.py in Deep Learning Tutorial A special testcase for logistic_sgd.py in Deep Learning Tutorial
This test assert that SharedVariable in different function have same storage This test assert that SharedVariable in different function have same storage
""" """
train_x = theano.shared(value=numpy.random.rand(10,10).astype(config.floatX)) train_x = theano.shared(value=numpy.random.rand(10, 10).astype(config.floatX))
test_x = theano.shared(value=numpy.random.rand(10,10).astype(config.floatX)) test_x = theano.shared(value=numpy.random.rand(10, 10).astype(config.floatX))
train_y = theano.shared(value=numpy.random.rand(10,1).astype(config.floatX)) train_y = theano.shared(value=numpy.random.rand(10, 1).astype(config.floatX))
test_y = theano.shared(value=numpy.random.rand(10,1).astype(config.floatX)) test_y = theano.shared(value=numpy.random.rand(10, 1).astype(config.floatX))
i = T.iscalar('index') i = T.iscalar('index')
x = T.vector('x') x = T.vector('x')
...@@ -350,14 +354,14 @@ class T_function(unittest.TestCase): ...@@ -350,14 +354,14 @@ class T_function(unittest.TestCase):
# this formular has no sense but for a test # this formular has no sense but for a test
out = (T.sum(x) - y) ** 2 out = (T.sum(x) - y) ** 2
train = theano.function([i], out, train = theano.function([i], out,
givens={x:train_x[i], y:train_y[i]}, givens={x: train_x[i], y: train_y[i]},
updates={train_x:train_x+0.1}) updates={train_x: train_x + 0.1})
test_def = theano.function([i], out, givens={x:test_x[i], y:test_y[i]}) test_def = theano.function([i], out, givens={x: test_x[i], y: test_y[i]})
test_cpy = train.copy(swap={train_x:test_x, train_y:test_y}, test_cpy = train.copy(swap={train_x: test_x, train_y: test_y},
delete_updates=True) delete_updates=True)
for in1, in2 in zip( test_def.maker.inputs, test_def.maker.inputs): for in1, in2 in zip(test_def.maker.inputs, test_cpy.maker.inputs):
assert in1.value is in2.value assert in1.value is in2.value
def test_copy_delete_updates(self): def test_copy_delete_updates(self):
...@@ -365,13 +369,13 @@ class T_function(unittest.TestCase): ...@@ -365,13 +369,13 @@ class T_function(unittest.TestCase):
# SharedVariable for tests, one of them has update # SharedVariable for tests, one of them has update
y = theano.shared(value=1, name='y') y = theano.shared(value=1, name='y')
z = theano.shared(value=2, name='z') z = theano.shared(value=2, name='z')
out = x+y+z out = x + y + z
# Test for different linkers # Test for different linkers
# for mode in ["FAST_RUN","FAST_COMPILE"]: # for mode in ["FAST_RUN","FAST_COMPILE"]:
second_time = False # second_time = False
for mode in ["FAST_RUN","FAST_COMPILE"]: for mode in ["FAST_RUN", "FAST_COMPILE"]:
ori = theano.function([x], out, mode=mode,updates={z:z*2}) ori = theano.function([x], out, mode=mode, updates={z: z * 2})
cpy = ori.copy(delete_updates=True) cpy = ori.copy(delete_updates=True)
assert cpy(1)[0] == 4 assert cpy(1)[0] == 4
...@@ -382,8 +386,12 @@ class T_function(unittest.TestCase): ...@@ -382,8 +386,12 @@ class T_function(unittest.TestCase):
a = T.scalar() # the a is for 'anonymous' (un-named). a = T.scalar() # the a is for 'anonymous' (un-named).
x, s = T.scalars('xs') x, s = T.scalars('xs')
f = function([x, In(a, value=1.0, name='a'), In(s, value=0.0, update=s+a*x, mutable=True)], s+a*x) f = function([x, In(a, value=1.0, name='a'),
g = function([x, In(a, value=1.0, name='a'), In(s, value=f.container[s], update=s-a*x, mutable=True)], s+a*x) In(s, value=0.0, update=s + a * x, mutable=True)],
s + a * x)
g = function([x, In(a, value=1.0, name='a'),
In(s, value=f.container[s], update=s - a * x, mutable=True)],
s + a * x)
f(1, 2) f(1, 2)
self.assertTrue(f[s] == 2) self.assertTrue(f[s] == 2)
...@@ -396,8 +404,10 @@ class T_function(unittest.TestCase): ...@@ -396,8 +404,10 @@ class T_function(unittest.TestCase):
a = T.scalar() # the a is for 'anonymous' (un-named). a = T.scalar() # the a is for 'anonymous' (un-named).
x, s = T.scalars('xs') x, s = T.scalars('xs')
f = function([x, In(a, value=1.0, name='a'), In(s, value=0.0, update=s+a*x, mutable=True)], s+a*x) f = function([x, In(a, value=1.0, name='a'),
g = function([x, In(a, value=1.0, name='a'), In(s, value=f.container[s])], s+a*x) In(s, value=0.0, update=s + a * x, mutable=True)], s + a * x)
g = function([x, In(a, value=1.0, name='a'),
In(s, value=f.container[s])], s + a * x)
f(1, 2) f(1, 2)
self.assertTrue(f[s] == 2) self.assertTrue(f[s] == 2)
...@@ -411,9 +421,9 @@ class T_function(unittest.TestCase): ...@@ -411,9 +421,9 @@ class T_function(unittest.TestCase):
a = T.scalar() # the a is for 'anonymous' (un-named). a = T.scalar() # the a is for 'anonymous' (un-named).
x, s = T.scalars('xs') x, s = T.scalars('xs')
f = function([x, In(a, value=1.0, name='a'), In(s, value=0.0, update=s+a*x, f = function([x, In(a, value=1.0, name='a'), In(s, value=0.0, update=s + a * x,
mutable=False)], s+a*x) mutable=False)], s + a * x)
g = function([x, In(a, value=1.0, name='a'), In(s, value=f.container[s])], s+a*x) g = function([x, In(a, value=1.0, name='a'), In(s, value=f.container[s])], s + a * x)
f(1, 2) f(1, 2)
self.assertTrue(f[s] == 2) self.assertTrue(f[s] == 2)
...@@ -431,9 +441,9 @@ class T_function(unittest.TestCase): ...@@ -431,9 +441,9 @@ class T_function(unittest.TestCase):
# behavior is still intended the doc and the test should both be # behavior is still intended the doc and the test should both be
# updated accordingly. # updated accordingly.
x, s = T.scalars('xs') x, s = T.scalars('xs')
inc = function([x, In(s, update=(s+x), value=10.0)], []) inc = function([x, In(s, update=(s + x), value=10.0)], [])
dec = function([x, In(s, update=(s-x), value=inc.container[s], dec = function([x, In(s, update=(s - x), value=inc.container[s],
implicit=False)], []) implicit=False)], [])
self.assertTrue(dec[s] is inc[s]) self.assertTrue(dec[s] is inc[s])
inc[s] = 2 inc[s] = 2
self.assertTrue(dec[s] == 2) self.assertTrue(dec[s] == 2)
...@@ -482,8 +492,8 @@ class T_function(unittest.TestCase): ...@@ -482,8 +492,8 @@ class T_function(unittest.TestCase):
aval = numpy.random.rand(3, 3) aval = numpy.random.rand(3, 3)
# when borrow=False, test that a destroy map cannot alias output to input # when borrow=False, test that a destroy map cannot alias output to input
f = theano.function([In(a, borrow=False)], Out(a+1, borrow=True)) f = theano.function([In(a, borrow=False)], Out(a + 1, borrow=True))
assert numpy.all(f(aval) == aval+1) assert numpy.all(f(aval) == aval + 1)
assert not numpy.may_share_memory(aval, f(aval)) assert not numpy.may_share_memory(aval, f(aval))
# when borrow=False, test that a viewmap cannot alias output to input # when borrow=False, test that a viewmap cannot alias output to input
...@@ -497,18 +507,18 @@ class T_function(unittest.TestCase): ...@@ -497,18 +507,18 @@ class T_function(unittest.TestCase):
o = N.ones((3, 3)) o = N.ones((3, 3))
assert o is not f(o) # function no longer permits aliasing outputs to inputs assert o is not f(o) # function no longer permits aliasing outputs to inputs
f = function([a], Out(a*4, borrow=False)) f = function([a], Out(a * 4, borrow=False))
o = N.ones((3, 3)) o = N.ones((3, 3))
four = f(o) four = f(o)
assert numpy.all(four == 4) assert numpy.all(four == 4)
f(o+.1) # should not clobber the memory used to store four f(o + .1) # should not clobber the memory used to store four
assert numpy.all(four == 4) assert numpy.all(four == 4)
f = function([a], Out(a*4, borrow=True), mode=theano.Mode('c|py_nogc', 'fast_run')) f = function([a], Out(a * 4, borrow=True), mode=theano.Mode('c|py_nogc', 'fast_run'))
o = N.ones((3, 3)) o = N.ones((3, 3))
four = f(o) four = f(o)
assert numpy.all(four == 4) assert numpy.all(four == 4)
f(o+.1) # should clobber the memory used to store four f(o + .1) # should clobber the memory used to store four
if theano.config.cxx: if theano.config.cxx:
assert not numpy.all(four == 4) assert not numpy.all(four == 4)
else: else:
...@@ -519,15 +529,15 @@ class T_function(unittest.TestCase): ...@@ -519,15 +529,15 @@ class T_function(unittest.TestCase):
def test_disconnected_input(self): def test_disconnected_input(self):
a = T.scalar('a') a = T.scalar('a')
v = T.vector('v') v = T.vector('v')
self.assertRaises(UnusedInputError, function, [a, v], v*2) self.assertRaises(UnusedInputError, function, [a, v], v * 2)
f = function([a, v], v*2, on_unused_input='ignore') function([a, v], v * 2, on_unused_input='ignore')
def test_masked_input(self): def test_masked_input(self):
m = T.matrix('m') m = T.matrix('m')
mt = m.T mt = m.T
mt.name = 'm.T' mt.name = 'm.T'
self.assertRaises(UnusedInputError, function, [m, mt], mt*2) self.assertRaises(UnusedInputError, function, [m, mt], mt * 2)
f = function([m, mt], mt*2, on_unused_input='ignore') function([m, mt], mt * 2, on_unused_input='ignore')
def test_givens_input_var(self): def test_givens_input_var(self):
""" """
...@@ -542,7 +552,7 @@ class T_function(unittest.TestCase): ...@@ -542,7 +552,7 @@ class T_function(unittest.TestCase):
Make test on free() function Make test on free() function
""" """
x = T.vector('x') x = T.vector('x')
func = function([x], x+1) func = function([x], x + 1)
func.fn.allow_gc = False func.fn.allow_gc = False
func([1]) func([1])
...@@ -565,7 +575,8 @@ class T_picklefunction(unittest.TestCase): ...@@ -565,7 +575,8 @@ class T_picklefunction(unittest.TestCase):
a = T.scalar() # the a is for 'anonymous' (un-named). a = T.scalar() # the a is for 'anonymous' (un-named).
x, s = T.scalars('xs') x, s = T.scalars('xs')
f = function([x, In(a, value=1.0, name='a'), In(s, value=0.0, update=s+a*x, mutable=True)], s+a*x) f = function([x, In(a, value=1.0, name='a'),
In(s, value=0.0, update=s + a * x, mutable=True)], s + a * x)
try: try:
g = copy.deepcopy(f) g = copy.deepcopy(f)
...@@ -587,9 +598,9 @@ class T_picklefunction(unittest.TestCase): ...@@ -587,9 +598,9 @@ class T_picklefunction(unittest.TestCase):
# print 'f.defaults = %s' % (f.defaults, ) # print 'f.defaults = %s' % (f.defaults, )
# print 'g.defaults = %s' % (g.defaults, ) # print 'g.defaults = %s' % (g.defaults, )
self.assertTrue(all([f_req == g_req and f_feed == g_feed and self.assertTrue(all([f_req == g_req and f_feed == g_feed and
f_val == g_val f_val == g_val
for ((f_req, f_feed, f_val), (g_req, g_feed, g_val)) in zip( for ((f_req, f_feed, f_val), (g_req, g_feed, g_val)) in zip(
f.defaults, g.defaults)])) f.defaults, g.defaults)]))
self.assertFalse(g.value[1] is f.value[1]) # should not have been copied self.assertFalse(g.value[1] is f.value[1]) # should not have been copied
self.assertFalse(g.value[2] is f.value[2]) # should have been copied because it is mutable. self.assertFalse(g.value[2] is f.value[2]) # should have been copied because it is mutable.
...@@ -630,7 +641,8 @@ class T_picklefunction(unittest.TestCase): ...@@ -630,7 +641,8 @@ class T_picklefunction(unittest.TestCase):
a = T.scalar() # the a is for 'anonymous' (un-named). a = T.scalar() # the a is for 'anonymous' (un-named).
x, s = T.scalars('xs') x, s = T.scalars('xs')
f = function([x, In(a, value=1.0, name='a'), In(s, value=0.0, update=s+a*x, mutable=True)], s+a*x) f = function([x, In(a, value=1.0, name='a'),
In(s, value=0.0, update=s + a * x, mutable=True)], s + a * x)
try: try:
# Note that here we also test protocol 0 on purpose, since it # Note that here we also test protocol 0 on purpose, since it
...@@ -668,9 +680,9 @@ class T_picklefunction(unittest.TestCase): ...@@ -668,9 +680,9 @@ class T_picklefunction(unittest.TestCase):
xm = T.dmatrix('x') xm = T.dmatrix('x')
sm = T.dmatrix('s') sm = T.dmatrix('s')
f = function([a, x, s, xm, sm], ((a.T.T)*(tensor.dot(xm, (sm.T.T.T)) + x).T * (x/x) + s)) f = function([a, x, s, xm, sm], ((a.T.T) * (tensor.dot(xm, (sm.T.T.T)) + x).T * (x / x) + s))
old_default_mode = config.mode old_default_mode = config.mode
old_default_opt = config.optimizer old_default_opt = config.optimizer
old_default_link = config.linker old_default_link = config.linker
try: try:
try: try:
...@@ -713,13 +725,17 @@ class T_picklefunction(unittest.TestCase): ...@@ -713,13 +725,17 @@ class T_picklefunction(unittest.TestCase):
list_of_things = [s, x, v] list_of_things = [s, x, v]
# some derived thing, whose inputs aren't all in the list # some derived thing, whose inputs aren't all in the list
list_of_things.append(a * x + s ) list_of_things.append(a * x + s)
f1 = function([x, In(a, value=1.0, name='a'), In(s, value=0.0, update=s+a*x, mutable=True)], s+a*x) f1 = function([x, In(a, value=1.0, name='a'),
In(s, value=0.0, update=s + a * x, mutable=True)],
s + a * x)
list_of_things.append(f1) list_of_things.append(f1)
# now put in a function sharing container with the previous one # now put in a function sharing container with the previous one
f2 = function([x, In(a, value=1.0, name='a'), In(s, value=f1.container[s], update=s+a*x, mutable=True)], s+a*x) f2 = function([x, In(a, value=1.0, name='a'),
In(s, value=f1.container[s], update=s + a * x, mutable=True)],
s + a * x)
list_of_things.append(f2) list_of_things.append(f2)
assert isinstance(f2.container[s].storage, list) assert isinstance(f2.container[s].storage, list)
...@@ -727,7 +743,7 @@ class T_picklefunction(unittest.TestCase): ...@@ -727,7 +743,7 @@ class T_picklefunction(unittest.TestCase):
# now put in a function with non-scalar # now put in a function with non-scalar
v_value = numpy.asarray([2, 3, 4.], dtype=config.floatX) v_value = numpy.asarray([2, 3, 4.], dtype=config.floatX)
f3 = function([x, In(v, value=v_value)], x+v) f3 = function([x, In(v, value=v_value)], x + v)
list_of_things.append(f3) list_of_things.append(f3)
# try to pickle the entire things # try to pickle the entire things
...@@ -777,16 +793,17 @@ class T_picklefunction(unittest.TestCase): ...@@ -777,16 +793,17 @@ class T_picklefunction(unittest.TestCase):
def test_broken_pickle_with_shared(self): def test_broken_pickle_with_shared(self):
saves = [] saves = []
def pers_save(obj): def pers_save(obj):
if isinstance(obj, numpy.ndarray): if isinstance(obj, numpy.ndarray):
saves.append(obj) saves.append(obj)
return len(saves)-1 return len(saves) - 1
else: else:
return None return None
def pers_load(id): def pers_load(id):
return saves[id] return saves[id]
a = numpy.random.rand(4, 5)
b = numpy.random.rand(5, 4) b = numpy.random.rand(5, 4)
x = theano.tensor.matrix() x = theano.tensor.matrix()
...@@ -809,7 +826,7 @@ class T_picklefunction(unittest.TestCase): ...@@ -809,7 +826,7 @@ class T_picklefunction(unittest.TestCase):
fp.close() fp.close()
p = pickle.Unpickler(fp2) p = pickle.Unpickler(fp2)
p.persistent_load = pers_load p.persistent_load = pers_load
f2 = p.load() p.load()
fp2.close() fp2.close()
def test_pickle_class_with_functions(self): def test_pickle_class_with_functions(self):
...@@ -845,9 +862,14 @@ class SomethingToPickle(object): ...@@ -845,9 +862,14 @@ class SomethingToPickle(object):
self.e = a * x + s self.e = a * x + s
self.f1 = function([x, In(a, value=1.0, name='a'), In(s, value=0.0, update=s+a*x, mutable=True)], s+a*x) self.f1 = function([x, In(a, value=1.0, name='a'),
In(s, value=0.0, update=s + a * x, mutable=True)],
s + a * x)
self.f2 = function([x, In(a, value=1.0, name='a'), In(s, value=self.f1.container[s], update=s+a*x, mutable=True)], s+a*x) self.f2 = function([x, In(a, value=1.0, name='a'),
In(s, value=self.f1.container[s], update=s + a * x,
mutable=True)],
s + a * x)
def test_empty_givens_updates(): def test_empty_givens_updates():
...@@ -870,16 +892,17 @@ if __name__ == '__main__': ...@@ -870,16 +892,17 @@ if __name__ == '__main__':
testcases = [] testcases = []
testcases.append(T_function) testcases.append(T_function)
#<testsuite boilerplate> # <testsuite boilerplate>
testloader = unittest.TestLoader() testloader = unittest.TestLoader()
suite = unittest.TestSuite() suite = unittest.TestSuite()
for testcase in testcases: for testcase in testcases:
suite.addTest(testloader.loadTestsFromTestCase(testcase)) suite.addTest(testloader.loadTestsFromTestCase(testcase))
unittest.TextTestRunner(verbosity=2).run(suite) unittest.TextTestRunner(verbosity=2).run(suite)
#</boilerplate> # </boilerplate>
elif 0: elif 0:
theano.config.mode = 'FAST_COMPILE' theano.config.mode = 'FAST_COMPILE'
t = T_picklefunction() t = T_picklefunction()
def fu(b): def fu(b):
assert b assert b
t.assertTrue = fu t.assertTrue = fu
......
import numpy, theano, unittest import numpy
import unittest
from theano.compile.pfunc import pfunc from theano.compile.pfunc import pfunc
from theano.compile.sharedvalue import shared from theano.compile.sharedvalue import shared
...@@ -9,9 +10,9 @@ from theano.tensor.nnet import sigmoid ...@@ -9,9 +10,9 @@ from theano.tensor.nnet import sigmoid
class NNet(object): class NNet(object):
def __init__(self, def __init__(self,
input=tensor.dvector('input'), input=tensor.dvector('input'),
target=tensor.dvector('target'), target=tensor.dvector('target'),
n_input=1, n_hidden=1, n_output=1, lr=1e-3, **kw): n_input=1, n_hidden=1, n_output=1, lr=1e-3, **kw):
super(NNet, self).__init__(**kw) super(NNet, self).__init__(**kw)
self.input = input self.input = input
...@@ -26,15 +27,15 @@ class NNet(object): ...@@ -26,15 +27,15 @@ class NNet(object):
self.cost = tensor.sum((self.output - self.target)**2) self.cost = tensor.sum((self.output - self.target)**2)
self.sgd_updates = { self.sgd_updates = {
self.w1: self.w1 - self.lr * tensor.grad(self.cost, self.w1), self.w1: self.w1 - self.lr * tensor.grad(self.cost, self.w1),
self.w2: self.w2 - self.lr * tensor.grad(self.cost, self.w2)} self.w2: self.w2 - self.lr * tensor.grad(self.cost, self.w2)}
self.sgd_step = pfunc( self.sgd_step = pfunc(
params=[self.input, self.target], params=[self.input, self.target],
outputs=[self.output, self.cost], outputs=[self.output, self.cost],
updates=self.sgd_updates) updates=self.sgd_updates)
self.compute_output = pfunc([self.input], self.output) self.compute_output = pfunc([self.input], self.output)
self.output_from_hidden = pfunc([self.hidden], self.output) self.output_from_hidden = pfunc([self.hidden], self.output)
...@@ -56,5 +57,5 @@ class TestNnet(unittest.TestCase): ...@@ -56,5 +57,5 @@ class TestNnet(unittest.TestCase):
# print 'Mean cost at epoch %s: %s' % (epoch, mean_cost) # print 'Mean cost at epoch %s: %s' % (epoch, mean_cost)
self.assertTrue(abs(mean_cost - 0.20588975452) < 1e-6) self.assertTrue(abs(mean_cost - 0.20588975452) < 1e-6)
# Just call functions to make sure they do not crash. # Just call functions to make sure they do not crash.
out = nnet.compute_output(input) nnet.compute_output(input)
out = nnet.output_from_hidden(numpy.ones(10)) nnet.output_from_hidden(numpy.ones(10))
...@@ -75,7 +75,7 @@ def test_not_inplace(): ...@@ -75,7 +75,7 @@ def test_not_inplace():
x = theano.tensor.vector('x') x = theano.tensor.vector('x')
mode = theano.compile.MonitorMode(post_func=detect_nan) mode = theano.compile.MonitorMode(post_func=detect_nan)
#mode = mode.excluding('fusion', 'inplace') # mode = mode.excluding('fusion', 'inplace')
mode = mode.excluding('local_elemwise_fusion', mode = mode.excluding('local_elemwise_fusion',
'inplace_elemwise_optimizer') 'inplace_elemwise_optimizer')
o = theano.tensor.outer(x, x) o = theano.tensor.outer(x, x)
......
...@@ -8,8 +8,9 @@ from theano.tensor import dmatrix, iscalar, lscalar, dmatrices ...@@ -8,8 +8,9 @@ from theano.tensor import dmatrix, iscalar, lscalar, dmatrices
from theano import tensor from theano import tensor
from theano.compile import In from theano.compile import In
from theano.compile.sharedvalue import * from theano.compile import pfunc
from theano.compile.pfunc import * from theano.compile import shared
from theano.compile import config
def data_of(s): def data_of(s):
...@@ -196,7 +197,7 @@ class Test_pfunc(unittest.TestCase): ...@@ -196,7 +197,7 @@ class Test_pfunc(unittest.TestCase):
# For performance reasons, no check of the data is explicitly performed # For performance reasons, no check of the data is explicitly performed
# (It might be OK to change this in the future.) # (It might be OK to change this in the future.)
self.assertRaises(TypeError, f, self.assertRaises(TypeError, f,
[3], numpy.array([6], dtype='int16'), 1) [3], numpy.array([6], dtype='int16'), 1)
# Value too big for a, silently ignored # Value too big for a, silently ignored
assert numpy.all(f([2 ** 20], numpy.ones(1, dtype='int8'), 1) == 2) assert numpy.all(f([2 ** 20], numpy.ones(1, dtype='int8'), 1) == 2)
...@@ -275,7 +276,7 @@ class Test_pfunc(unittest.TestCase): ...@@ -275,7 +276,7 @@ class Test_pfunc(unittest.TestCase):
# For performance reasons, no check of the data is explicitly performed # For performance reasons, no check of the data is explicitly performed
# (It might be OK to change this in the future.) # (It might be OK to change this in the future.)
self.assertRaises(TypeError, g, self.assertRaises(TypeError, g,
[3], numpy.array([6], dtype='int16'), 0) [3], numpy.array([6], dtype='int16'), 0)
# Value too big for b, raises TypeError # Value too big for b, raises TypeError
self.assertRaises(TypeError, g, [3], [312], 0) self.assertRaises(TypeError, g, [3], [312], 0)
...@@ -284,7 +285,7 @@ class Test_pfunc(unittest.TestCase): ...@@ -284,7 +285,7 @@ class Test_pfunc(unittest.TestCase):
# Everything here should behave like with False # Everything here should behave like with False
assert numpy.all(h([3], [6], 0) == 9) assert numpy.all(h([3], [6], 0) == 9)
self.assertRaises(TypeError, h, self.assertRaises(TypeError, h,
[3], numpy.array([6], dtype='int16'), 0) [3], numpy.array([6], dtype='int16'), 0)
self.assertRaises(TypeError, h, [3], [312], 0) self.assertRaises(TypeError, h, [3], [312], 0)
def test_allow_downcast_floatX(self): def test_allow_downcast_floatX(self):
...@@ -344,13 +345,13 @@ class Test_pfunc(unittest.TestCase): ...@@ -344,13 +345,13 @@ class Test_pfunc(unittest.TestCase):
# the update_var has type matrix, and the update expression # the update_var has type matrix, and the update expression
# is a broadcasted scalar, and that should be allowed. # is a broadcasted scalar, and that should be allowed.
self.assertRaises(TypeError, theano.function, inputs=[], outputs=[], self.assertRaises(TypeError, theano.function, inputs=[], outputs=[],
updates={output_var: output_var.sum().dimshuffle('x', 'x')}) updates={output_var: output_var.sum().dimshuffle('x', 'x')})
def test_duplicate_updates(self): def test_duplicate_updates(self):
x, y = dmatrices('x', 'y') x, y = dmatrices('x', 'y')
z = shared(numpy.ones((2, 3))) z = shared(numpy.ones((2, 3)))
self.assertRaises(ValueError, theano.function, [x, y], [z], self.assertRaises(ValueError, theano.function, [x, y], [z],
updates=[(z, (z + x + y)), (z, (z - x))]) updates=[(z, (z + x + y)), (z, (z - x))])
def test_givens(self): def test_givens(self):
x = shared(0) x = shared(0)
...@@ -366,7 +367,7 @@ class Test_pfunc(unittest.TestCase): ...@@ -366,7 +367,7 @@ class Test_pfunc(unittest.TestCase):
z = tensor.ivector() z = tensor.ivector()
c = z * y c = z * y
f = pfunc([y], (c + 7), f = pfunc([y], (c + 7),
givens={z: theano._asarray([4, 4, 4], dtype='int32')}) givens={z: theano._asarray([4, 4, 4], dtype='int32')})
assert numpy.all(f([1, 1, 1]) == [11, 11, 11]) assert numpy.all(f([1, 1, 1]) == [11, 11, 11])
assert x.get_value() == 0 assert x.get_value() == 0
...@@ -433,7 +434,7 @@ class Test_pfunc(unittest.TestCase): ...@@ -433,7 +434,7 @@ class Test_pfunc(unittest.TestCase):
self.assertRaises(TypeError, pfunc, [], [x], no_default_updates=(x)) self.assertRaises(TypeError, pfunc, [], [x], no_default_updates=(x))
self.assertRaises(TypeError, pfunc, [], [x], no_default_updates=x) self.assertRaises(TypeError, pfunc, [], [x], no_default_updates=x)
self.assertRaises(TypeError, pfunc, [], [x], self.assertRaises(TypeError, pfunc, [], [x],
no_default_updates='canard') no_default_updates='canard')
# Mix explicit updates and no_default_updates # Mix explicit updates and no_default_updates
g1 = pfunc([], [x], updates=[(x, (x - 1))], no_default_updates=True) g1 = pfunc([], [x], updates=[(x, (x - 1))], no_default_updates=True)
...@@ -617,7 +618,7 @@ class Test_pfunc(unittest.TestCase): ...@@ -617,7 +618,7 @@ class Test_pfunc(unittest.TestCase):
def test_duplicate_inputs(self): def test_duplicate_inputs(self):
x = theano.tensor.lscalar('x') x = theano.tensor.lscalar('x')
self.assertRaises(theano.compile.UnusedInputError, self.assertRaises(theano.compile.UnusedInputError,
theano.function, [x, x, x], x) theano.function, [x, x, x], x)
def test_update_same(self): def test_update_same(self):
# There was a bug in CVM, triggered when a shared variable # There was a bug in CVM, triggered when a shared variable
...@@ -699,7 +700,7 @@ class Test_aliasing_rules(unittest.TestCase): ...@@ -699,7 +700,7 @@ class Test_aliasing_rules(unittest.TestCase):
# rule #2 reading back from theano-managed memory # rule #2 reading back from theano-managed memory
assert not numpy.may_share_memory(A.get_value(borrow=False), assert not numpy.may_share_memory(A.get_value(borrow=False),
data_of(A)) data_of(A))
def test_sparse_input_aliasing_affecting_inplace_operations(self): def test_sparse_input_aliasing_affecting_inplace_operations(self):
## ##
...@@ -712,7 +713,7 @@ class Test_aliasing_rules(unittest.TestCase): ...@@ -712,7 +713,7 @@ class Test_aliasing_rules(unittest.TestCase):
pass pass
from theano.sparse import enable_sparse from theano.sparse import enable_sparse
if enable_sparse == False: if not enable_sparse:
raise SkipTest('Optional package sparse disabled') raise SkipTest('Optional package sparse disabled')
from theano import sparse from theano import sparse
...@@ -761,8 +762,8 @@ class Test_aliasing_rules(unittest.TestCase): ...@@ -761,8 +762,8 @@ class Test_aliasing_rules(unittest.TestCase):
y = theano.tensor.dvector() y = theano.tensor.dvector()
m1 = theano.tensor.dmatrix() m1 = theano.tensor.dmatrix()
m2 = theano.tensor.dmatrix() m2 = theano.tensor.dmatrix()
f = theano.function([theano.In(x, mutable=True), f = theano.function([theano.In(x, mutable=True),
theano.In(y, mutable=True), theano.In(y, mutable=True),
theano.In(m1, mutable=True), theano.In(m1, mutable=True),
theano.In(m2, mutable=True)], theano.In(m2, mutable=True)],
theano.dot((x * 2), m1) + theano.dot((y * 3), m2)) theano.dot((x * 2), m1) + theano.dot((y * 3), m2))
...@@ -810,15 +811,14 @@ class Test_aliasing_rules(unittest.TestCase): ...@@ -810,15 +811,14 @@ class Test_aliasing_rules(unittest.TestCase):
# c does not share memory with a # c does not share memory with a
f = theano.function( f = theano.function(
[theano.In(x, mutable=True), [theano.In(x, mutable=True),
theano.In(y, mutable=True), theano.In(y, mutable=True),
theano.In(z, mutable=True), theano.In(z, mutable=True),
theano.In(m1, mutable=True), theano.In(m1, mutable=True),
theano.In(m2, mutable=True), theano.In(m2, mutable=True),
theano.In(m3, mutable=True)], theano.In(m3, mutable=True)],
(theano.dot((x * 2), m1) (theano.dot((x * 2), m1) + theano.dot((y * 3), m2) +
+ theano.dot((y * 3), m2) theano.dot((z * 4), m3)))
+ theano.dot((z * 4), m3)))
# Compute bogus values # Compute bogus values
v = numpy.asarray([1, 2, 3, 4, 5], dtype='float64') v = numpy.asarray([1, 2, 3, 4, 5], dtype='float64')
...@@ -875,14 +875,14 @@ class Test_aliasing_rules(unittest.TestCase): ...@@ -875,14 +875,14 @@ class Test_aliasing_rules(unittest.TestCase):
assert not numpy.may_share_memory(R, data_of(A)) assert not numpy.may_share_memory(R, data_of(A))
f = pfunc([D], (DD * 4), f = pfunc([D], (DD * 4),
updates=[(A, (DD[:1] * 3)), (B, (DD[:1] * 2))]) updates=[(A, (DD[:1] * 3)), (B, (DD[:1] * 2))])
R = f(C) R = f(C)
assert not numpy.may_share_memory(data_of(A), data_of(B)) assert not numpy.may_share_memory(data_of(A), data_of(B))
assert not numpy.may_share_memory(R, data_of(B)) assert not numpy.may_share_memory(R, data_of(B))
assert not numpy.may_share_memory(R, data_of(A)) assert not numpy.may_share_memory(R, data_of(A))
f = pfunc([D], (DD * 4), f = pfunc([D], (DD * 4),
updates=[(A, (DD[:1] * 3)), (B, (DD[:1] * 3))]) updates=[(A, (DD[:1] * 3)), (B, (DD[:1] * 3))])
R = f(C) R = f(C)
assert not numpy.may_share_memory(data_of(A), data_of(B)) assert not numpy.may_share_memory(data_of(A), data_of(B))
assert not numpy.may_share_memory(R, data_of(B)) assert not numpy.may_share_memory(R, data_of(B))
......
...@@ -44,7 +44,7 @@ class Test_profiling(unittest.TestCase): ...@@ -44,7 +44,7 @@ class Test_profiling(unittest.TestCase):
mode=m) mode=m)
inp = [numpy.arange(1024, dtype='float32') + 1 for i in range(len(x))] inp = [numpy.arange(1024, dtype='float32') + 1 for i in range(len(x))]
output = f(*inp) f(*inp)
buf = StringIO() buf = StringIO()
f.profile.summary(buf) f.profile.summary(buf)
...@@ -72,7 +72,6 @@ class Test_profiling(unittest.TestCase): ...@@ -72,7 +72,6 @@ class Test_profiling(unittest.TestCase):
theano.config.profile_memory = config2 theano.config.profile_memory = config2
theano.config.profiling.min_peak_memory = config3 theano.config.profiling.min_peak_memory = config3
def test_ifelse(self): def test_ifelse(self):
config1 = theano.config.profile config1 = theano.config.profile
config2 = theano.config.profile_memory config2 = theano.config.profile_memory
...@@ -101,7 +100,7 @@ class Test_profiling(unittest.TestCase): ...@@ -101,7 +100,7 @@ class Test_profiling(unittest.TestCase):
big_mat1 = 10 big_mat1 = 10
big_mat2 = 11 big_mat2 = 11
out = f_ifelse(val1, val2, big_mat1, big_mat2) f_ifelse(val1, val2, big_mat1, big_mat2)
finally: finally:
theano.config.profile = config1 theano.config.profile = config1
......
...@@ -3,27 +3,21 @@ import unittest ...@@ -3,27 +3,21 @@ import unittest
import theano import theano
from theano.tensor import Tensor, TensorType from theano.tensor import Tensor, TensorType
from theano.compile.sharedvalue import * from theano.compile.sharedvalue import shared
from theano.compile.sharedvalue import SharedVariable
from theano.compile.sharedvalue import generic
class Test_SharedVariable(unittest.TestCase): class Test_SharedVariable(unittest.TestCase):
def test_ctors(self): def test_ctors(self):
if 0: if theano.configdefaults.python_int_bitwidth() == 32:
# when using an implementation that handles scalars with assert shared(7).type == theano.tensor.iscalar, shared(7).type
# Scalar type
assert shared(7).type == Scalar('int64')
assert shared(7.0).type == Scalar('float64')
assert shared(7, dtype='float64').type == Scalar('float64')
else: else:
if theano.configdefaults.python_int_bitwidth() == 32: assert shared(7).type == theano.tensor.lscalar, shared(7).type
assert shared(7).type == theano.tensor.iscalar, shared(7).type assert shared(7.0).type == theano.tensor.dscalar
else: assert shared(numpy.float32(7)).type == theano.tensor.fscalar
assert shared(7).type == theano.tensor.lscalar, shared(7).type
assert shared(7.0).type == theano.tensor.dscalar
assert shared(numpy.float32(7)).type == theano.tensor.fscalar
# test tensor constructor # test tensor constructor
b = shared(numpy.zeros((5, 5), dtype='int32')) b = shared(numpy.zeros((5, 5), dtype='int32'))
...@@ -31,8 +25,7 @@ class Test_SharedVariable(unittest.TestCase): ...@@ -31,8 +25,7 @@ class Test_SharedVariable(unittest.TestCase):
b = shared(numpy.random.rand(4, 5)) b = shared(numpy.random.rand(4, 5))
assert b.type == TensorType('float64', broadcastable=[False, False]) assert b.type == TensorType('float64', broadcastable=[False, False])
b = shared(numpy.random.rand(5, 1, 2)) b = shared(numpy.random.rand(5, 1, 2))
assert b.type == TensorType('float64', assert b.type == TensorType('float64', broadcastable=[False, False, False])
broadcastable=[False, False, False])
assert shared([]).type == generic assert shared([]).type == generic
...@@ -56,35 +49,35 @@ class Test_SharedVariable(unittest.TestCase): ...@@ -56,35 +49,35 @@ class Test_SharedVariable(unittest.TestCase):
# here the value is perfect, and we're not strict about it, # here the value is perfect, and we're not strict about it,
# so creation should work # so creation should work
SharedVariable( SharedVariable(
name='u', name='u',
type=Tensor(broadcastable=[False], dtype='float64'), type=Tensor(broadcastable=[False], dtype='float64'),
value=numpy.asarray([1., 2.]), value=numpy.asarray([1., 2.]),
strict=False) strict=False)
# here the value is castable, and we're not strict about it, # here the value is castable, and we're not strict about it,
# so creation should work # so creation should work
SharedVariable( SharedVariable(
name='u', name='u',
type=Tensor(broadcastable=[False], dtype='float64'), type=Tensor(broadcastable=[False], dtype='float64'),
value=[1., 2.], value=[1., 2.],
strict=False) strict=False)
# here the value is castable, and we're not strict about it, # here the value is castable, and we're not strict about it,
# so creation should work # so creation should work
SharedVariable( SharedVariable(
name='u', name='u',
type=Tensor(broadcastable=[False], dtype='float64'), type=Tensor(broadcastable=[False], dtype='float64'),
value=[1, 2], # different dtype and not a numpy array value=[1, 2], # different dtype and not a numpy array
strict=False) strict=False)
# here the value is not castable, and we're not strict about it, # here the value is not castable, and we're not strict about it,
# this is beyond strictness, it must fail # this is beyond strictness, it must fail
try: try:
SharedVariable( SharedVariable(
name='u', name='u',
type=Tensor(broadcastable=[False], dtype='float64'), type=Tensor(broadcastable=[False], dtype='float64'),
value=dict(), # not an array by any stretch value=dict(), # not an array by any stretch
strict=False) strict=False)
assert 0 assert 0
except TypeError: except TypeError:
pass pass
...@@ -94,10 +87,10 @@ class Test_SharedVariable(unittest.TestCase): ...@@ -94,10 +87,10 @@ class Test_SharedVariable(unittest.TestCase):
# here the value is perfect, and we're not strict about it, # here the value is perfect, and we're not strict about it,
# so creation should work # so creation should work
u = SharedVariable( u = SharedVariable(
name='u', name='u',
type=Tensor(broadcastable=[False], dtype='float64'), type=Tensor(broadcastable=[False], dtype='float64'),
value=numpy.asarray([1., 2.]), value=numpy.asarray([1., 2.]),
strict=False) strict=False)
# check that assignments to value are cast properly # check that assignments to value are cast properly
u.set_value([3, 4]) u.set_value([3, 4])
...@@ -298,7 +291,7 @@ class Test_SharedVariable(unittest.TestCase): ...@@ -298,7 +291,7 @@ class Test_SharedVariable(unittest.TestCase):
# f(b,[8]) # f(b,[8])
b = shared(numpy.asarray([7.234], dtype=theano.config.floatX), b = shared(numpy.asarray([7.234], dtype=theano.config.floatX),
allow_downcast=True) allow_downcast=True)
assert b.dtype == theano.config.floatX assert b.dtype == theano.config.floatX
f(b, [8]) f(b, [8])
assert b.get_value() == 8 assert b.get_value() == 8
......
...@@ -30,15 +30,6 @@ whitelist_flake8 = [ ...@@ -30,15 +30,6 @@ whitelist_flake8 = [
"tests/__init__.py", "tests/__init__.py",
"compile/__init__.py", "compile/__init__.py",
"compile/profiling.py", "compile/profiling.py",
"compile/tests/test_builders.py",
"compile/tests/test_misc.py",
"compile/tests/test_monitormode.py",
"compile/tests/test_function_module.py",
"compile/tests/test_shared.py",
"compile/tests/test_ops.py",
"compile/tests/test_pfunc.py",
"compile/tests/test_debugmode.py",
"compile/tests/test_profiling.py",
"typed_list/__init__.py", "typed_list/__init__.py",
"tensor/__init__.py", "tensor/__init__.py",
"tensor/tests/test_subtensor.py", "tensor/tests/test_subtensor.py",
......
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论