rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
rng_seed = numpy.random.RandomState(234).randint(2**30)
rng_seed = numpy.random.RandomState(utt.fetch_seed()).randint(2**30)
def test_multinomial(self): """Test that RandomStreams.multinomial generates the same results as numpy""" # Check over two calls to see if the random state is correctly updated. random = RandomStreams(234) fn = function([], random.multinomial((4,4), 1, [0.1]*10), updates=random.updates())
random = RandomStreams(234)
random = RandomStreams(utt.fetch_seed())
def test_shuffle_row_elements(self): """Test that RandomStreams.shuffle_row_elements generates the right results""" # Check over two calls to see if the random state is correctly updated.
val_rng = numpy.random.RandomState(unittest_tools.fetch_seed())
val_rng = numpy.random.RandomState(utt.fetch_seed()+42)
def test_shuffle_row_elements(self): """Test that RandomStreams.shuffle_row_elements generates the right results""" # Check over two calls to see if the random state is correctly updated.
rng_seed = numpy.random.RandomState(234).randint(2**30)
rng_seed = numpy.random.RandomState(utt.fetch_seed()).randint(2**30)
def test_shuffle_row_elements(self): """Test that RandomStreams.shuffle_row_elements generates the right results""" # Check over two calls to see if the random state is correctly updated.
random1 = RandomStreams(234)
random1 = RandomStreams(utt.fetch_seed())
def test_shuffle_row_elements(self): """Test that RandomStreams.shuffle_row_elements generates the right results""" # Check over two calls to see if the random state is correctly updated.
random_a = RandomStreams(234)
random_a = RandomStreams(utt.fetch_seed())
def test_default_updates(self): # Basic case: default_updates random_a = RandomStreams(234) out_a = random_a.uniform((2,2)) fn_a = function([], out_a) fn_a_val0 = fn_a() fn_a_val1 = fn_a() assert not numpy.all(fn_a_val0 == fn_a_val1)
random_b = RandomStreams(234)
random_b = RandomStreams(utt.fetch_seed())
def test_default_updates(self): # Basic case: default_updates random_a = RandomStreams(234) out_a = random_a.uniform((2,2)) fn_a = function([], out_a) fn_a_val0 = fn_a() fn_a_val1 = fn_a() assert not numpy.all(fn_a_val0 == fn_a_val1)
random_c = RandomStreams(234)
random_c = RandomStreams(utt.fetch_seed())
def test_default_updates(self): # Basic case: default_updates random_a = RandomStreams(234) out_a = random_a.uniform((2,2)) fn_a = function([], out_a) fn_a_val0 = fn_a() fn_a_val1 = fn_a() assert not numpy.all(fn_a_val0 == fn_a_val1)
random_d = RandomStreams(234)
random_d = RandomStreams(utt.fetch_seed())
def test_default_updates(self): # Basic case: default_updates random_a = RandomStreams(234) out_a = random_a.uniform((2,2)) fn_a = function([], out_a) fn_a_val0 = fn_a() fn_a_val1 = fn_a() assert not numpy.all(fn_a_val0 == fn_a_val1)
random_e = RandomStreams(234)
random_e = RandomStreams(utt.fetch_seed())
def test_default_updates(self): # Basic case: default_updates random_a = RandomStreams(234) out_a = random_a.uniform((2,2)) fn_a = function([], out_a) fn_a_val0 = fn_a() fn_a_val1 = fn_a() assert not numpy.all(fn_a_val0 == fn_a_val1)
elif config.warn.ignore_bug_before == '0.3':
elif config.warn.ignore_bug_before >= '0.3':
def warning(*msg): _logger.warning('WARNING theano.configdefaults: '+' '.join(msg))
return gof.Apply(self, [x, shp], [tensor(x.type.dtype, [False]*self.ndim)])
bcasts = [False] * self.ndim for index in xrange(self.ndim): y = shp_orig[index] try: bcasts[index] = (hasattr(y, 'get_constant_value') and y.get_constant_value() == 1) except TypeError: pass return gof.Apply(self, [x, shp], [tensor(x.type.dtype, bcasts)])
def make_node(self, x, shp): x = as_tensor_variable(x) shp = as_tensor_variable(shp, ndim=1) if not shp.dtype.startswith('int'): raise TypeError("Shape must be integers") assert shp.ndim == 1 if isinstance(shp, TensorConstant): bcast = [s==1 for s in shp.data] return gof.Apply(self, [x, shp], [tensor(x.type.dtype, bcas...
def hash_list(list):
def hash_listsDictsTuples(x):
def info(*msg): _logger.info('INFO theano.scan: '+' '.join(msg))
for v in list: hash_value ^= hash(v)
if type(x) == dict : for k,v in x.iteritems(): hash_value ^= hash_listsDictsTuples(k) hash_value ^= hash_listsDictsTuples(v) elif type(x) in (list,tuple): for v in x: hash_value ^= hash_listsDictsTuples(v) else: try: hash_value ^= hash(x) except: pass
def hash_list(list): hash_value = 0 for v in list: hash_value ^= hash(v) return hash_value
def hash_dict(dictionary): hash_value = 0 for k,v in dictionary.iteritems(): hash_value ^= hash(k) if type(v) in (list,tuple): hash_value ^= hash_list(v) else: hash_value ^= hash(v) return hash_value
def hash_list(list): hash_value = 0 for v in list: hash_value ^= hash(v) return hash_value
hash_list(self.outputs) ^ \ hash_list(self.inputs) ^ \ hash_list(self.g_ins) ^ \ hash_list(self.g_outs) ^ \ hash_dict(self.seqs_taps) ^\ hash_dict(self.outs_taps) ^\ hash_dict(self.updates)
hash_listsDictsTuples(self.outputs) ^ \ hash_listsDictsTuples(self.inputs) ^ \ hash_listsDictsTuples(self.g_ins) ^ \ hash_listsDictsTuples(self.g_outs) ^ \ hash_listsDictsTuples(self.seqs_taps) ^\ hash_listsDictsTuples(self.outs_taps) ^\ hash_listsDictsTuples(self.updates)
def __hash__(self): return hash(type(self)) ^ \ hash(self.n_seqs) ^ \ hash(self.n_outs) ^ \ hash(self.force_gradient) ^\ hash(self.inplace) ^\ hash(self.go_backwards) ^\ hash(self.truncate_gradient) ^\ hash(self.n_args) ^ \ hash_list(self.outputs) ^ \ hash_list(self.inputs) ^ \ hash_list(self.g_ins) ^ \ hash_list(self....
skip_identities_fn = None, name = None):
skip_identities_fn = None, name = None, pdb = False):
def __init__(self, in_pattern, out_pattern, allow_multiple_clients = False, skip_identities_fn = None, name = None): """ Creates a PatternSub that replaces occurrences of in_pattern by occurrences of out_pattern.
If allow_multiple_clients is False, the pattern matching will fail if one of the subpatterns has more than one client.
:param in_pattern: the input pattern that we want to replace :param out_pattern: the replacement pattern :param allow_multiple_clients: if False, the pattern matching will fail if one of the subpatterns has more than one client. :param pdb: if True, we invoke pdb when the first node in the pattern match.
def __init__(self, in_pattern, out_pattern, allow_multiple_clients = False, skip_identities_fn = None, name = None): """ Creates a PatternSub that replaces occurrences of in_pattern by occurrences of out_pattern.
def match(pattern, expr, u, allow_multiple_clients = False):
def match(pattern, expr, u, allow_multiple_clients = False, pdb = False):
def match(pattern, expr, u, allow_multiple_clients = False): def retry_with_equiv(): expr_equiv = self.skip_identities(expr) if expr_equiv is None: return False #TODO: Not sure how to handle multiple_clients flag ###print 'retrying match', pattern, expr_equiv return match(pattern, expr_equiv, u, allow_multiple_clients=...
u = match(self.in_pattern, node.out, unify.Unification(), True)
u = match(self.in_pattern, node.out, unify.Unification(), True, self.pdb)
def build(pattern, u): if isinstance(pattern, (list, tuple)): args = [build(p, u) for p in pattern[1:]] return pattern[0](*args) elif isinstance(pattern, str): return u[unify.Var(pattern)] elif isinstance(pattern, (int,float)): return pattern else: return pattern.clone()
A convolution op that should mimic scipy.signal.convolve2d, but faster! In development.
A convolution op that should extend scipy.signal.convolve2d, but much faster!
def getFilterOutShp(inshp, kshp, (dx,dy)=(1,1), mode='valid'): """Returns numpy ndarray of len 2 """ if mode=='valid': s = -1 else: s = 1 inshp, kshp = N.array(inshp), N.array(kshp) return N.int64(N.ceil((inshp[1:] + s*kshp - s*1)/\ N.array([dx,dy], dtype='float')))
[tensor.tensor(dtype_out, (False, False))])
[tensor.tensor(dtype_out, (False, b.type.broadcastable[1]))])
def make_node(self, a_val, a_ind, a_ptr, a_nrows, b): dtype_out = scalar.upcast(a_val.type.dtype, b.type.dtype) r = gof.Apply(self, [a_val, a_ind, a_ptr, a_nrows, b], [tensor.tensor(dtype_out, (False, False))]) return r
[tensor.tensor(self.dtype_out, (False, False))])
[tensor.tensor(self.dtype_out, (False, b.type.broadcastable[1]))])
def make_node(self, a_val, a_ind, a_ptr, b): self.dtype_out = scalar.upcast(a_val.type.dtype, b.type.dtype) r = gof.Apply(self, [a_val, a_ind, a_ptr, b], [tensor.tensor(self.dtype_out, (False, False))]) return r
unittest_tools.verify_grad(fn, [images_val])
unittest_tools.verify_grad(fn, [images_val], mode=mode_without_gpu) if cuda.cuda_available: unittest_tools.verify_grad(fn, [images_val], mode=mode_with_gpu)
def fn(images): return T.sum(T.sqr(images2neibs(images, (2,2))), axis=[0,1])
mode = theano.compile.get_default_mode().including('local_useless_eq')
mode = theano.compile.get_default_mode().including('canonicalize')
def test_local_useless_eq(): mode = theano.compile.get_default_mode().including('local_useless_eq') x=T.dmatrix() y=T.dmatrix() f=theano.function([x,y],T.eq(x,y), mode=mode) vx=numpy.random.rand(5,4) vy=numpy.random.rand(5,4) f(vx,vy) topo = f.maker.env.toposort() assert len(topo)==1 assert isinstance(topo[0].op,T.Elem...
mode = theano.compile.get_default_mode().including('local_useless_neq')
mode = theano.compile.get_default_mode().including('canonicalize')
def test_local_useless_neq(): mode = theano.compile.get_default_mode().including('local_useless_neq') x=T.dmatrix() y=T.dmatrix() f=theano.function([x,y],T.neq(x,y), mode=mode) vx=numpy.random.rand(5,4) vy=numpy.random.rand(5,4) f(vx,vy) topo = f.maker.env.toposort() assert len(topo)==1 assert isinstance(topo[0].op,T.E...
implicit=None):
implicit=None, borrow=False):
def __init__(self, variable, name=None, value=None, update=None, mutable=None, strict=False, allow_downcast=False, autoname=True, implicit=None): if implicit is None: implicit = (isinstance(value, gof.Container) or isinstance(value, SharedVariable)) super(In, self).__init__( variable=variable, name=name, update=update,...
m = compile.mode.get_mode(m) m = m.excluding('fusion')
def test_log1p(): m = theano.config.mode if m == 'FAST_COMPILE': m = 'FAST_RUN' # check some basic cases x = dvector() f = function([x], T.log(1+(x)), mode=m) assert [node.op for node in f.maker.env.toposort()] == [T.log1p] f = function([x], T.log(1+(-x)), mode=m) assert [node.op for node in f.maker.env.toposort()] ==...
return (2,)
return (3,)
def c_code_cache_version(self): #return () return (2,)
if (x_col >= ds1 * D3)
if (%(ignore_border)s && x_col >= ds1 * D3)
def c_support_code_apply(self, node, nodename): # This code considers every position in the output z, andthen computes the gradient for the # input pixels that were downsampled to that z-position. It does so by running along every # z row (sometimes plus one, to make sure every gx row gets totally filled), and by # run...
// = (my_z ==
// = (my_z == x[image_row][image_col][x_row][x_col]) ? my_gz : 0.0f;
def c_support_code_apply(self, node, nodename): # This code considers every position in the output z, andthen computes the gradient for the # input pixels that were downsampled to that z-position. It does so by running along every # z row (sometimes plus one, to make sure every gx row gets totally filled), and by # run...
assert b.value is bval
def test_shared_mutable(self): bval = numpy.arange(5) b = shared(bval) assert b.value is bval b_out = b * 2
def data_of(s): """Return the raw value of a shared variable""" return s.container.storage[0]
def data_of(s): """Return the raw value of a shared variable""" return s.container.storage[0]
code we recommand though to provide them to scan.
code we recommend though to provide them to scan.
def scan( fn , sequences = None , outputs_info = None , non_sequences = None , n_steps = None , truncate_gradient = -1 , go_backwards = False , mode = None , name = None ): """ This function constructs and applies a Scan op to the provided arguments. :param fn:...
They are provided as a list of integers, where a value ``k`` impiles
They are provided as a list of integers, where a value ``k`` implies
def scan( fn , sequences = None , outputs_info = None , non_sequences = None , n_steps = None , truncate_gradient = -1 , go_backwards = False , mode = None , name = None ): """ This function constructs and applies a Scan op to the provided arguments. :param fn:...
wrapped into a dictionary where ``taps`` is set to ``[0]``
wrapped into a dictionary where ``taps`` is set to ``[0]``.
def scan( fn , sequences = None , outputs_info = None , non_sequences = None , n_steps = None , truncate_gradient = -1 , go_backwards = False , mode = None , name = None ): """ This function constructs and applies a Scan op to the provided arguments. :param fn:...
recursively (think of a map) and does not require a initial state this field can be skiped. Given that only the previous
recursively (think of a map) and does not require an initial state this field can be skipped. Given that only the previous
def scan( fn , sequences = None , outputs_info = None , non_sequences = None , n_steps = None , truncate_gradient = -1 , go_backwards = False , mode = None , name = None ): """ This function constructs and applies a Scan op to the provided arguments. :param fn:...
``output[-5]``. ``init_y[1]`` *correponds to* ``output[-4]``, ``init_y[2]`` corresponds to ``output[-3]``, ``init_y[3]`` coresponds to ``output[-2]``, ``init_y[4]`` corresponds to
``output[-5]``; ``init_y[1]`` *correponds to* ``output[-4]``; ``init_y[2]`` corresponds to ``output[-3]``; ``init_y[3]`` coresponds to ``output[-2]``; ``init_y[4]`` corresponds to
def scan( fn , sequences = None , outputs_info = None , non_sequences = None , n_steps = None , truncate_gradient = -1 , go_backwards = False , mode = None , name = None ): """ This function constructs and applies a Scan op to the provided arguments. :param fn:...
* ``taps`` -- Temporal taps of the output that will be pass to
* ``taps`` -- Temporal taps of the output that will be passed to
def scan( fn , sequences = None , outputs_info = None , non_sequences = None , n_steps = None , truncate_gradient = -1 , go_backwards = False , mode = None , name = None ): """ This function constructs and applies a Scan op to the provided arguments. :param fn:...
intermidiate results. If not given, or ``0``, ``scan`` will return
intermediate results. If not given, or ``0``, ``scan`` will return
def scan( fn , sequences = None , outputs_info = None , non_sequences = None , n_steps = None , truncate_gradient = -1 , go_backwards = False , mode = None , name = None ): """ This function constructs and applies a Scan op to the provided arguments. :param fn:...
intermidiate steps ``scan`` should use for a given output. Use
intermediate steps ``scan`` should use for a given output. Use
def scan( fn , sequences = None , outputs_info = None , non_sequences = None , n_steps = None , truncate_gradient = -1 , go_backwards = False , mode = None , name = None ): """ This function constructs and applies a Scan op to the provided arguments. :param fn:...
is recommendat to let scan decide for you the ammount of memory
it is recommended to let scan decide for you the ammount of memory
def scan( fn , sequences = None , outputs_info = None , non_sequences = None , n_steps = None , truncate_gradient = -1 , go_backwards = False , mode = None , name = None ): """ This function constructs and applies a Scan op to the provided arguments. :param fn:...
``fn`` at each steps. Once can opt to exclude shared variables
``fn`` at each steps. One can opt to exclude shared variables
def scan( fn , sequences = None , outputs_info = None , non_sequences = None , n_steps = None , truncate_gradient = -1 , go_backwards = False , mode = None , name = None ): """ This function constructs and applies a Scan op to the provided arguments. :param fn:...
in time. If n stpes is not provided, or evaluates to ``None``, ``inf`` or ``NaN``, ``scan`` will figure out the amount of
in time. If ``n_steps`` is not provided, or evaluates to ``None``, ``inf`` or ``NaN``, then ``scan`` will figure out the amount of
def scan( fn , sequences = None , outputs_info = None , non_sequences = None , n_steps = None , truncate_gradient = -1 , go_backwards = False , mode = None , name = None ): """ This function constructs and applies a Scan op to the provided arguments. :param fn:...
be accurate). If you prefer the computations of one step os ``scan`` to be done differently then the entire function set
be accurate). If you prefer the computations of one step of ``scan`` to be done differently compared to the entire function, set
def scan( fn , sequences = None , outputs_info = None , non_sequences = None , n_steps = None , truncate_gradient = -1 , go_backwards = False , mode = None , name = None ): """ This function constructs and applies a Scan op to the provided arguments. :param fn:...
'provide a initial state for it', outs_info[i])
'provide an initial state for it', outs_info[i])
def scan( fn , sequences = None , outputs_info = None , non_sequences = None , n_steps = None , truncate_gradient = -1 , go_backwards = False , mode = None , name = None ): """ This function constructs and applies a Scan op to the provided arguments. :param fn:...
warning('You are providing a initial state for an output and then '
warning('You are providing an initial state for an output and then '
def scan( fn , sequences = None , outputs_info = None , non_sequences = None , n_steps = None , truncate_gradient = -1 , go_backwards = False , mode = None , name = None ): """ This function constructs and applies a Scan op to the provided arguments. :param fn:...
'store all intermidiate results (remove store_steps'
'store all intermediate results (remove store_steps'
def zero(p): try: use_dtype = p.type.dtype except: use_dtype = theano.config.floatX return tensor.TensorConstant(tensor.TensorType(\ dtype=use_dtype, broadcastable=[]), safe_asarray._asarray(0,dtype = use_dtype))
dummy_f = function(filter(lambda x: isinstance(x, gof.Variable) and \
if n_fixed_steps in [-1,1]: ''' We do have a special case here, namely is so might happen that whatever we have in dummy_args is not sufficient to compile the function( i.e. missing inputs). Furthermore we might not even need to compile the function here for this special case. But due to the way I wrote the code is eas...
def scan(fn, sequences=[], outputs_info=[], non_sequences=[], n_steps = None, truncate_gradient = -1, go_backwards = False, mode = None, name = None): """Function that constructs and applies a Scan op :param fn: Function that describes the operations involved in one step of scan Given variables representing all the sl...
args += non_seqs
for non_seq in non_seqs : if not isinstance(non_seq, theano.compile.sharedvalue.SharedVariable): args += [non_seq] else: tmp_var = theano.tensor.Tensor(dtype = non_seq.dtype, broadcastable = non_seq.broadcastable)() args += [ tmp_var ]
def scan(fn, sequences, initial_states, non_sequences, inplace_map={}, \ sequences_taps={}, outputs_taps = {}, n_steps = 0, \ truncate_gradient = -1, go_backwards = False, mode = 'FAST_RUN'): '''Function that constructs and applies a Scan op :param fn: Function that describes the operations involved in one step of sca...
else: out_types += [inputs[i].type()]
else: if self.stored_steps_output[i-1-self.n_seqs] != 1 : out_types += [ theano.tensor.Tensor(dtype = inputs[i].dtype, broadcastable = (False,)+inputs[i].broadcastable)()] else: out_types += [ theano.tensor.Tensor(dtype = inputs[i].dtype, broadcastable = inputs[i].broadcastable)()]
def make_node(self,*inputs): n_args = len(inputs) if n_args < self.n_args : err = 'There should be at least '+str(self.n_args)+ 'arguments' raise ValueError(err)
print 'YAY!'
def local_advanced_indexing_crossentropy_onehot_grad(node): if not (node.op == softmax_grad): return sm = None try: out_grad, sm = node.inputs except: return if sm is not None and sm.owner and sm.owner.op == softmax: x_var = sm.owner.inputs[0] else: return # Two cases are supported: # 1. AdvancedIncSubtensor( # ...
logging.getLogger('theano.tensor.nnet.nnet').warn("WARNING: their was a bug in Theano fixed the 27 may 2010 in this case. I.E. when we take the max of a softplus, softmax, exp, log, tanh, sigmoid, softmax_with_bias op, we where doing the max of the parent of the input. To remove this warning set the Theano flags 'warn....
logging.getLogger('theano.tensor.nnet.nnet').warn("WARNING: there " "was a bug in Theano fixed on May 27th, 2010 in this case." " I.E. when we take the max of a softplus, softmax, exp, " "log, tanh, sigmoid, softmax_with_bias op, we were doing " "the max of the parent of the input. To remove this " "warning set the The...
def local_argmax_pushdown(node): if node.op == tensor._max_and_argmax and node.inputs[0].owner and \ len(node.outputs[0].clients)>0 and node.inputs[0].owner.op in \ (softmax, softplus, tensor.exp, tensor.log, tensor.tanh, sigmoid, softmax_with_bias): if theano.config.warn.argmax_pushdown_bug: logging.getLogger('theano....
assert numpy.allclose(function([i, ii, d, f, c], i/d)(5, 3, 7.0, 11.0, complex(5,3)),
assert numpy.allclose(function([i, ii, d, f, c], i/d)(5, 3, 7.0, 11.0, numpy.complex(5,3)),
def test_impls(self): i = iscalar() ii = lscalar() d = dscalar() f = fscalar() c = cscalar()
assert numpy.allclose(function([i, ii, d, f, c], d/i)(5, 3, 7.0, 11.0, complex(5,3)),
assert numpy.allclose(function([i, ii, d, f, c], d/i)(5, 3, 7.0, 11.0, numpy.complex(5,3)),
def test_impls(self): i = iscalar() ii = lscalar() d = dscalar() f = fscalar() c = cscalar()
assert numpy.allclose(function([i, ii, d, f, c], i/f)(5, 3, 7.0, 11.0, complex(5,3)),
assert numpy.allclose(function([i, ii, d, f, c], i/f)(5, 3, 7.0, 11.0, numpy.complex(5,3)),
def test_impls(self): i = iscalar() ii = lscalar() d = dscalar() f = fscalar() c = cscalar()
assert numpy.allclose(function([i, ii, d, f, c], f/i)(5, 3, 7.0, 11.0, complex(5,3)),
assert numpy.allclose(function([i, ii, d, f, c], f/i)(5, 3, 7.0, 11.0, numpy.complex(5,3)),
def test_impls(self): i = iscalar() ii = lscalar() d = dscalar() f = fscalar() c = cscalar()
assert numpy.allclose(function([i, ii, d, f, c], i/ii)(5, 3, 7.0, 11.0, complex(5,3)),
assert numpy.allclose(function([i, ii, d, f, c], i/ii)(5, 3, 7.0, 11.0, numpy.complex(5,3)),
def test_impls(self): i = iscalar() ii = lscalar() d = dscalar() f = fscalar() c = cscalar()
assert numpy.allclose(function([i, ii, d, f, c], ii/i)(5, 3, 7.0, 11.0, complex(5,3)),
assert numpy.allclose(function([i, ii, d, f, c], ii/i)(5, 3, 7.0, 11.0, numpy.complex(5,3)),
def test_impls(self): i = iscalar() ii = lscalar() d = dscalar() f = fscalar() c = cscalar()
assert numpy.allclose(function([i, ii, d, f, c], true_div(i,ii))(5, 3, 7.0, 11.0, complex(5,3)),
assert numpy.allclose(function([i, ii, d, f, c], true_div(i,ii))(5, 3, 7.0, 11.0, numpy.complex(5,3)),
def test_impls(self): i = iscalar() ii = lscalar() d = dscalar() f = fscalar() c = cscalar()
assert numpy.allclose(function([i, ii, d, f, c], true_div(ii,i))(5, 3, 7.0, 11.0, complex(5,3)),
assert numpy.allclose(function([i, ii, d, f, c], true_div(ii,i))(5, 3, 7.0, 11.0, numpy.complex(5,3)),
def test_impls(self): i = iscalar() ii = lscalar() d = dscalar() f = fscalar() c = cscalar()
def exec_multilayer_conv_nnet(conv_mode, ss, bsize, imshp, kshps, nkerns, unroll_batch=0, unroll_kern=0, img=T.dmatrix(), validate=True, conv_op_py=False, do_convolve2=False, do_print=True, repeat=1, unroll_patch=0):
def exec_multilayer_conv_nnet(conv_mode, ss, bsize, imshp, kshps, nkerns, unroll_batch=0, unroll_kern=0, img=T.dmatrix(), validate=True, conv_op_py=False, do_convolve2=False, do_print=True, repeat=1, unroll_patch=False, unroll_patch_size=False, verbose=0):
def exec_multilayer_conv_nnet(conv_mode, ss, bsize, imshp, kshps, nkerns, unroll_batch=0, unroll_kern=0, img=T.dmatrix(), validate=True, conv_op_py=False, do_convolve2=False, do_print=True, repeat=1, unroll_patch=0): # build actual input images imgval = global_rng.rand(bsize, imshp[0], imshp[1], imshp[2]) a=T.dmatrix...
if unroll_patch:
if unroll_patch and not unroll_patch_size:
def exec_multilayer_conv_nnet(conv_mode, ss, bsize, imshp, kshps, nkerns, unroll_batch=0, unroll_kern=0, img=T.dmatrix(), validate=True, conv_op_py=False, do_convolve2=False, do_print=True, repeat=1, unroll_patch=0): # build actual input images imgval = global_rng.rand(bsize, imshp[0], imshp[1], imshp[2]) a=T.dmatrix...
unroll_patch=unroll_patch)(inputs4, kerns4)
unroll_patch=unroll_patch, verbose=verbose)(inputs4, kerns4)
def exec_multilayer_conv_nnet(conv_mode, ss, bsize, imshp, kshps, nkerns, unroll_batch=0, unroll_kern=0, img=T.dmatrix(), validate=True, conv_op_py=False, do_convolve2=False, do_print=True, repeat=1, unroll_patch=0): # build actual input images imgval = global_rng.rand(bsize, imshp[0], imshp[1], imshp[2]) a=T.dmatrix...
unroll_batch=unroll_batch, unroll_kern=unroll_kern, unroll_patch=unroll_patch)(inputs4, kerns4)
unroll_batch=unroll_batch, unroll_kern=unroll_kern, unroll_patch=unroll_patch, verbose=verbose)(inputs4, kerns4)
def exec_multilayer_conv_nnet(conv_mode, ss, bsize, imshp, kshps, nkerns, unroll_batch=0, unroll_kern=0, img=T.dmatrix(), validate=True, conv_op_py=False, do_convolve2=False, do_print=True, repeat=1, unroll_patch=0): # build actual input images imgval = global_rng.rand(bsize, imshp[0], imshp[1], imshp[2]) a=T.dmatrix...
do_speed_test = False
def test_multilayer_conv(self): print '\n\n*************************************************' print ' TEST MULTILAYER CONVOLUTION' print '*************************************************'
if do_speed_test: validate=False unroll_batch = [1,2,4,5,10,20] unroll_kern = [1,2,4,5,10,20] unroll_batch = [1,4,5] unroll_kern = [1,4,5] bsize = 20 imshp_start = (1,48,48) kshps = ([11,12],[12,11]) nkerns = [20,20] ssizes = [(1,1),] convmodes = ['valid','full'] do_convolve2=False a=T.dmatrix() kerns = [a for i i...
def test_multilayer_conv(self): print '\n\n*************************************************' print ' TEST MULTILAYER CONVOLUTION' print '*************************************************'
raise Exception("Expected an error from Theano!")
if should_raise: raise Exception("Expected an error from Theano!")
def test_unalign(): a = numpy.empty(1e6, dtype="b1,f8")['f1'] b = numpy.empty(1e6, dtype="b1,f8")['f1'] assert not a.flags.aligned assert not b.flags.aligned a[:] = numpy.random.rand(len(a)) b[:] = numpy.random.rand(len(b)) out_numpy = 2*a + 3*b av,bv = tensor.vectors('ab') f = theano.function([av,bv],2*av+3*bv) f.mak...
pass
if not should_raise: raise Exception("Theano raised an exception when none was expected")
def test_unalign(): a = numpy.empty(1e6, dtype="b1,f8")['f1'] b = numpy.empty(1e6, dtype="b1,f8")['f1'] assert not a.flags.aligned assert not b.flags.aligned a[:] = numpy.random.rand(len(a)) b[:] = numpy.random.rand(len(b)) out_numpy = 2*a + 3*b av,bv = tensor.vectors('ab') f = theano.function([av,bv],2*av+3*bv) f.mak...
if hasattr(node.outputs[0].type,"may_share_memory"): if not node.outputs[0].type.may_share_memory(storage_map[node.outputs[oo]][0],storage_map[node.inputs[ii[0]]][0]): if storage_map[node.outputs[oo]][0].ndim>0 and storage_map[node.outputs[oo]][0].size>0: warning("input idx %d marked as viewed but new memory allocate...
if not _may_share_memory(storage_map[node.outputs[oo]][0],storage_map[node.inputs[ii[0]]][0]): if storage_map[node.outputs[oo]][0].ndim>0 and storage_map[node.outputs[oo]][0].size>0: import pdb;pdb.set_trace() _may_share_memory(storage_map[node.outputs[oo]][0],storage_map[node.inputs[ii[0]]][0]) warning("input idx %d...
def _check_inputs(node, storage_map, r_vals, dr_vals, active_nodes, clobber_dr_vals=True, perform=None, warn_input_not_reused=True): """Raise BadDestroyMap if necessary, update dr_vals""" destroyed_idx_list = [] destroy_map = getattr(node.op, 'destroy_map', {}) for o_pos, i_pos_list in destroy_map.iteritems(): destroye...
try: return numpy.may_share_memory(a, b) except: return False
from theano.misc.may_share_memory import may_share_memory return may_share_memory(a,b,False)
def _may_share_memory(a, b): try: return numpy.may_share_memory(a, b) except: return False #return (hasattr(a,'__array_interface__') and #hasattr(b,'__array_interface__') and #numpy.may_share_memory(a,b))
n_samples = self.n_streams(size)
n_samples = numpy.prod(size)
def normal(self, size=None, avg=0.0, std=1.0, ndim=None, dtype=config.floatX): # We need an even number of ]0,1[ samples. Then we split them # in two halves. First half becomes our U1's for Box-Muller, # second half our U2's. See Wikipedia page: # http://en.wikipedia.org/wiki/Box%E2%80%93Muller_transform
''' dummy_f = function(filter(lambda x: isinstance(x, gof.Variable) and \ not isinstance(x,SharedVariable) and not isinstance(x,gof.Constant), \ dummy_args), outputs, updates = updates, mode = compile.mode.Mode(linker='py',optimizer=None))
def scan(fn, sequences=[], outputs_info=[], non_sequences=[], n_steps = None, truncate_gradient = -1, go_backwards = False, mode = None, name = None): """Function that constructs and applies a Scan op :param fn: Function that describes the operations involved in one step of scan Given variables representing all the sl...
return Apply(self, [ten4, neib_shape], [CudaNdarrayType(broadcastable=(False,)*2)()])
return Apply(self, [ten4, neib_shape], [ten4.type()])
def make_node(self, ten4, neib_shape): assert ten4.dtype == 'float32' #assert neib_shape.dtype == 'float32' if not isinstance(ten4.type, CudaNdarrayType): raise TypeError('pvals must be cudandarray', ten4) #if not isinstance(neib_shape.type, CudaNdarrayType): # raise TypeError('unis must be cudandarray', neib_shape)...
if theano.config.device.startswith('gpu'): register_specialize(use_gpu_images2neibs)
if cuda_available: register_gpu_opt()(use_gpu_images2neibs)
def use_gpu_images2neibs(node): if node.op == images2neibs: return [host_from_gpu(gpu_images2neibs(*[gpu_from_host(node.inputs[0]),node.inputs[1]]))]
if topo:
if topo and not(len(topo)==1 and topo[0].op==theano.compile.function_module.deep_copy_op):
def test_multiple_case(self): """ test those case take from the comment in Canonizer x / x -> 1 (x * y) / x -> y x / y / x -> 1 / y x / y / z -> x / (y * z) x / (y / z) -> (x * z) / y (a / b) * (b / c) * (c / d) -> a / d (2.0 * x) / (4.0 * y) -> (0.5 * x) / y 2 * x / 2 -> x with and without DimShuffle TODO: with DimShu...
assert len(topo)==0
assert len(topo)==1 topo[0].op==theano.compile.function_module.deep_copy_op
def test_multiple_case(self): """ test those case take from the comment in Canonizer x / x -> 1 (x * y) / x -> y x / y / x -> 1 / y x / y / z -> x / (y * z) x / (y / z) -> (x * z) / y (a / b) * (b / c) * (c / d) -> a / d (2.0 * x) / (4.0 * y) -> (0.5 * x) / y 2 * x / 2 -> x with and without DimShuffle TODO: with DimShu...
optdb.register('scanOp_remove_from_graph', ScanRemoveFromGraph() , 30, 'fast_run')
def my_replace( node, replace_pairs): # Turns out that using env replace (while safe) is # a real pain because of many condition that have to # be met which I can not met while doing the # replacement, so I did my little hack that does # something like a replacement # ASSUMPTIONS: # we do not do anything crazy like r...
import pdb;pdb.set_trace()
def test_reshape(): a = tcn.CudaNdarrayType((False,))() b = tcn.CudaNdarrayType((False,False))() c = T.reshape(a, [2,3]) #basic f = theano.function([a], c) fv = f(cuda_ndarray.CudaNdarray(numpy.asarray([0,1,2,3,4,5],dtype='float32'))) import pdb;pdb.set_trace() assert numpy.all(fv == numpy.asarray([[0,1,2], [3,4,5]])...
assert (fvector()+ 1.1).dtype == 'float64'
assert (fvector()+ 1.1).dtype == theano.config.floatX
def test_autocast(): orig_autocast = autocast_float.dtypes # test that autocast_float_as sets the autocast dtype correctly try: #ghetto 2.4 version of with ac = autocast_float_as('float32') ac.__enter__() assert autocast_float.dtypes == ('float32',) finally: ac.__exit__() assert autocast_float.dtypes == orig_autocast ...
' match', tensors)
' have the same broadcast behavior', tensors)
def _make_node_internal(self, axis, tensors, as_tensor_variable_args, output_maker): if not all(targs.type.ndim for targs in as_tensor_variable_args): raise TypeError('Join cannot handle arguments of dimension 0. For joining scalar values, see @stack');
storage_map[r][0] = _lessbroken_deepcopy(r_vals[r])
if env.destroyers(r): storage_map[r][0] = _lessbroken_deepcopy(r_vals[r])
def f(): debug("starting a DebugMode call") for x in no_recycling: x[0] = None
env.replace_all_validate([(nll, new_nll),(sm, new_sm)], reason="Merge")
env.replace_all_validate([(nll, new_nll),(sm, new_sm)], reason="crossentropy_to_crossentropy_with_softmax")
def search_make_one_sub(): for node in env.toposort(): if node.op == crossentropy_categorical_1hot: nll, = node.outputs sm, one_of_n = node.inputs if sm.owner and sm.owner.op == softmax: x, = sm.owner.inputs new_nll, new_sm, new_am = crossentropy_softmax_argmax_1hot_with_bias(x, tensor.zeros_like(x[0]), one_of_n) env.r...
AddConfigVar('warn.old_bug_default', "If False, will disable by default the warning about old Theano bug. If you never used Theano, you set it to False.", BoolParam(True)) default_warn = config.warn.old_bug_default
AddConfigVar('warn.ignore_bug_before', "If None, we warn about all Theano bug found by default. If all we don't warn about Theano bug found by default. If a version, we print warning only for Theano bug found after that version.", EnumStr('None', 'all', '0.3', allow_override=False)) default_0_3 = True if config.warn.i...
def warning(*msg): _logger.warning('WARNING theano.configdefaults: '+' '.join(msg))
BoolParam(default_warn))
BoolParam(default_0_3))
def warning(*msg): _logger.warning('WARNING theano.configdefaults: '+' '.join(msg))
def makeTester(name, op, expected, checks = {}, good = {}, bad_build = {}, bad_runtime = {}, grad = {}):
def makeTester(name, op, expected, checks = {}, good = {}, bad_build = {}, bad_runtime = {}, grad = {}, mode = None):
def makeTester(name, op, expected, checks = {}, good = {}, bad_build = {}, bad_runtime = {}, grad = {}): if grad is True: grad = good _op, _expected, _checks, _good, _bad_build, _bad_runtime, _grad = op, expected, checks, good, bad_build, bad_runtime, grad class Checker(unittest.TestCase): op = _op expected = static...
_op, _expected, _checks, _good, _bad_build, _bad_runtime, _grad = op, expected, checks, good, bad_build, bad_runtime, grad
_op, _expected, _checks, _good, _bad_build, _bad_runtime, _grad, _mode = op, expected, checks, good, bad_build, bad_runtime, grad, mode
def makeTester(name, op, expected, checks = {}, good = {}, bad_build = {}, bad_runtime = {}, grad = {}): if grad is True: grad = good _op, _expected, _checks, _good, _bad_build, _bad_runtime, _grad = op, expected, checks, good, bad_build, bad_runtime, grad class Checker(unittest.TestCase): op = _op expected = static...
f = inplace_func(inputrs, node.outputs)
f = inplace_func(inputrs, node.outputs, mode = mode)
def test_good(self): for testname, inputs in self.good.items(): inputs = [copy(input) for input in inputs] inputrs = [value(input) for input in inputs] try: #node = self.op.make_node(*inputrs) node = safe_make_node(self.op, *inputrs) except: type, exc_value, traceback = sys.exc_info() err_msg = "Test %s::%s: Error occu...
utt.verify_grad(self.op, inputs)
utt.verify_grad(self.op, inputs, mode=self.mode)
def test_grad(self): for testname, inputs in self.grad.items(): inputs = [copy(input) for input in inputs] inputrs = [value(input) for input in inputs] try: utt.verify_grad(self.op, inputs) except: type, exc_value, traceback = sys.exc_info() err_msg = "Test %s::%s: Error occurred while computing the gradient on the fol...
grad = _grad_broadcast_unary_normal)
grad = _grad_broadcast_unary_normal, mode = mode_no_scipy)
def inplace_check(inputs, outputs): # this used to be inputs[0] is output[0] # I changed it so that it was easier to satisfy by the DebugMode return numpy.all(inputs[0] == outputs[0])
return scipy.special.erf(x)
return scipy.special.erfc(x)
def impl(self, x): if imported_scipy_special: return scipy.special.erf(x) else: super(Erfc,self).impl(x)
time = mode.apply_time.get((topo.index(node),node.op),0)
time = mode.apply_time.get((topo.index(node),node),0)
def apply_name(node): prof_str='' if mode: time = mode.apply_time.get((topo.index(node),node.op),0) #second, % total time in profiler, %fct time in profiler if mode.local_time[0]==0: pt=0 else: pt=time*100/mode.local_time[0] if mode.fct_call[fct]==0: pf=0 else: pf = time*100/mode.fct_call_time[fct] prof_str=' (%.3fs,...
f = theano.function([a,b],updates={s:lr1*T.dot(a,b)+l2_reg*lr2*s}).maker.env.toposort()
f = theano.function([a,b],updates={s:lr1*T.dot(a,b)+l2_reg*lr2*s},mode=mode_not_fast_compile).maker.env.toposort()
def test_factorised_scalar(self): a=T.matrix() b=T.matrix() c=T.matrix() s=theano.shared(numpy.zeros((5,5)))
f = theano.function([a,b],updates={s:lr1*(T.dot(a,b)-l2_reg*s)}).maker.env.toposort()
f = theano.function([a,b],updates={s:lr1*(T.dot(a,b)-l2_reg*s)},mode=mode_not_fast_compile).maker.env.toposort()
def test_factorised_scalar(self): a=T.matrix() b=T.matrix() c=T.matrix() s=theano.shared(numpy.zeros((5,5)))
f = theano.function([a,b],updates={s:s-lr1*(s*.0002+T.dot(a,b))}).maker.env.toposort()
f = theano.function([a,b],updates={s:s-lr1*(s*.0002+T.dot(a,b))},mode=mode_not_fast_compile).maker.env.toposort()
def test_factorised_scalar(self): a=T.matrix() b=T.matrix() c=T.matrix() s=theano.shared(numpy.zeros((5,5)))
if config.mode == 'FAST_COMPILE': m = 'FAST_RUN' else: m = config.mode
def test_dot22(): if config.mode == 'FAST_COMPILE': m = 'FAST_RUN' else: m = config.mode a=T.matrix() b=T.matrix() f = theano.function([a,b],T.dot(a,b),mode=m) topo = f.maker.env.toposort() assert _dot22 in [x.op for x in topo] av=numpy.random.rand(5,5) bv=numpy.random.rand(5,5) f(av,bv)
f = theano.function([a,b],T.dot(a,b),mode=m)
f = theano.function([a,b],T.dot(a,b),mode=mode_blas_opt)
def test_dot22(): if config.mode == 'FAST_COMPILE': m = 'FAST_RUN' else: m = config.mode a=T.matrix() b=T.matrix() f = theano.function([a,b],T.dot(a,b),mode=m) topo = f.maker.env.toposort() assert _dot22 in [x.op for x in topo] av=numpy.random.rand(5,5) bv=numpy.random.rand(5,5) f(av,bv)
m = theano.compile.get_default_mode().including('BlasOpt', 'specialize')
def test_dot22scalar(): ## including does not seem to work for 'local_dot_to_dot22' and ## 'local_dot22_to_dot22scalar' ## TODO: exclude other optimizations in BlasOpt? #m = theano.compile.get_default_mode().including('local_dot_to_dot22','local_dot22_to_dot22scalar','specialize') m = theano.compile.get_default_mode()....
f = theano.function([a,b],0.2*T.dot(a,b),mode=m)
f = theano.function([a,b],0.2*T.dot(a,b),mode=mode_blas_opt)
def test_dot22scalar(): ## including does not seem to work for 'local_dot_to_dot22' and ## 'local_dot22_to_dot22scalar' ## TODO: exclude other optimizations in BlasOpt? #m = theano.compile.get_default_mode().including('local_dot_to_dot22','local_dot22_to_dot22scalar','specialize') m = theano.compile.get_default_mode()....
f = theano.function([a,b,c],0.2*c*T.dot(a,b),mode=m)
f = theano.function([a,b,c],0.2*c*T.dot(a,b),mode=mode_blas_opt)
def test_dot22scalar(): ## including does not seem to work for 'local_dot_to_dot22' and ## 'local_dot22_to_dot22scalar' ## TODO: exclude other optimizations in BlasOpt? #m = theano.compile.get_default_mode().including('local_dot_to_dot22','local_dot22_to_dot22scalar','specialize') m = theano.compile.get_default_mode()....