rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
assert topo[0].op.inplace==True
if config.mode != 'FAST_COMPILE': assert topo[0].op.inplace==True
def test_gemv1(): ''' test vector1+dot(matrix,vector2) ''' v1 = theano.shared( numpy.array(numpy.random.rand(2) , dtype='float32')) v2_orig = numpy.array(numpy.random.rand(2), dtype='float32') v2 = theano.shared( v2_orig ) m = theano.shared( numpy.array(numpy.random.rand(2,2), dtype='float32')) f = theano.function([...
v_u = numpy.array(rng.uniform( size = (300,), low = -.5, high = .5),dtype=theano.config.floatX)
v_u = numpy.array(rng.uniform( size = (10,), low = -.5, high = .5),dtype=theano.config.floatX)
def f_rnn(u_t,x_tm1,W_in, W): return u_t*W_in+x_tm1*W
v_u1 = asarrayX(rng.uniform(size = (13,2), low = -.1, high = .1)) v_u2 = asarrayX(rng.uniform(size = (13,), low = -.1,high = .1))
v_u1 = asarrayX(rng.uniform(size = (7,2), low = -.1, high = .1)) v_u2 = asarrayX(rng.uniform(size = (7,), low = -.1,high = .1))
def test_grad_multiple_outs(self): rng = numpy.random.RandomState(utt.fetch_seed()) vW_in2 = asarrayX(rng.uniform(size = (2,), low = -.1,high = .1)) vW = asarrayX(rng.uniform(size = (2,2), low = -.1,high = .1)) vWout = asarrayX(rng.uniform(size = (2,), low = -.1,high = .1)) vW_in1 = asarrayX(rng.uniform(size = (2,...
l = 60
l = 5
def test_grad_multiple_outs_taps(self): l = 60 rng = numpy.random.RandomState(utt.fetch_seed()) vW_in2 = asarrayX(rng.uniform(size = (2,), low = -.2,high = .2)) vW = asarrayX(rng.uniform(size = (2,2), low = -.2,high = .2)) vWout = asarrayX(rng.uniform(size = (2,), low = -.2,high = .2)) vW_in1 = asarrayX(rng.unifor...
l = 20
l = 5
def test_grad_multiple_outs_taps_backwards(self): l = 20 rng = numpy.random.RandomState(utt.fetch_seed()) vW_in2 = asarrayX(rng.uniform(size = (2,), low = -.2,high = .2)) vW = asarrayX(rng.uniform(size = (2,2), low = -.2,high = .2)) vWout = asarrayX(rng.uniform(size = (2,), low = -.2,high = .2)) vW_in1 = asarrayX(...
v_u = asarrayX(rng.uniform(size = (80,2), low = -.1, high = .1))
v_u = asarrayX(rng.uniform(size = (5,2), low = -.1, high = .1))
def test_grad_multiple_outs_some_uncomputable(self): rng = numpy.random.RandomState(utt.fetch_seed()) vW_in = asarrayX(rng.uniform(size = (2,2), low = -.1,high = .1)) v_u = asarrayX(rng.uniform(size = (80,2), low = -.1, high = .1)) v_x0 = asarrayX(rng.uniform(size = (2,), low = -.1,high = .1))
v_u = asarrayX(rng.uniform(size = (80,2), low = -.1, high = .1))
v_u = asarrayX(rng.uniform(size = (5,2), low = -.1, high = .1))
def test_grad_multiple_outs_some_truncate(self): rng = numpy.random.RandomState(utt.fetch_seed()) vW_in = asarrayX(rng.uniform(size = (2,2), low = -.1,high = .1)) v_u = asarrayX(rng.uniform(size = (80,2), low = -.1, high = .1)) v_x0 = asarrayX(rng.uniform(size = (2,), low = -.1,high = .1))
max_idx[0] = numpy.asarray(numpy.argmax(x, axis), dtype='int32')
max_idx[0] = numpy.asarray(numpy.argmax(x, axis), dtype='int32').view( numpy.int32)
def perform(self, node, (x, axis), (max, max_idx)): max[0] = numpy.asarray(numpy.max(x, axis)) max_idx[0] = numpy.asarray(numpy.argmax(x, axis), dtype='int32')
m.gn = Method([], m.random.normal((2,2))) made = m.make() made.random.initialize() fn_val0 = made.fn() fn_val1 = made.fn() gn_val0 = made.gn() rng_seed = numpy.random.RandomState(234).randint(2**30) rng = numpy.random.RandomState(int(rng_seed))
made = m.make() made.random.initialize(seed=utt.fetch_seed()) fn_val0 = made.fn() fn_val1 = made.fn() rng_seed = numpy.random.RandomState(utt.fetch_seed()).randint(2**30) rng = numpy.random.RandomState(int(rng_seed))
def test_basics(self): m = Module() m.random = RandomStreams(234) m.fn = Method([], m.random.uniform((2,2))) m.gn = Method([], m.random.normal((2,2))) made = m.make() made.random.initialize()
def test_seed_in_initialize(self):
def test_seed_fn(self):
def test_seed_in_initialize(self): m = Module() m.random = RandomStreams(234) m.fn = Method([], m.random.uniform((2,2))) made = m.make() made.random.initialize(seed=888)
made.random.initialize(seed=888) fn_val0 = made.fn() fn_val1 = made.fn() rng_seed = numpy.random.RandomState(888).randint(2**30) rng = numpy.random.RandomState(int(rng_seed)) numpy_val0 = rng.uniform(size=(2,2)) numpy_val1 = rng.uniform(size=(2,2)) assert numpy.all(fn_val0 == numpy_val0) assert numpy.all(fn_val1 ...
def test_seed_in_initialize(self): m = Module() m.random = RandomStreams(234) m.fn = Method([], m.random.uniform((2,2))) made = m.make() made.random.initialize(seed=888)
made.random.seed(888) fn_val0 = made.fn() fn_val1 = made.fn() rng_seed = numpy.random.RandomState(888).randint(2**30)
made.random.seed(utt.fetch_seed()) fn_val0 = made.fn() fn_val1 = made.fn() rng_seed = numpy.random.RandomState(utt.fetch_seed()).randint(2**30)
def test_seed_fn(self): m = Module() m.random = RandomStreams(234) m.fn = Method([], m.random.uniform((2,2))) made = m.make() made.random.initialize(seed=789)
made.random.seed(888)
made.random.seed(utt.fetch_seed())
def test_getitem(self):
realseed = 823874
realseed = utt.fetch_seed()
def test_setitem(self):
M.random = RandomStreams(234)
M.random = RandomStreams(utt.fetch_seed())
def test_multiple(self): M = Module() M.random = RandomStreams(234) out = M.random.uniform((2,2)) M.m2 = Module() M.m2.random = M.random out2 = M.m2.random.uniform((2,2)) M.fn = Method([], out) M.m2.fn2 = Method([], out2) m = M.make() m.random.initialize() m.m2.initialize()
m.random = RandomStreams(234)
m.random = RandomStreams(utt.fetch_seed())
def test_uniform(self): """Test that RandomStreams.uniform generates the same results as numpy""" # Check over two calls to see if the random state is correctly updated. m = Module() m.random = RandomStreams(234) m.fn = Method([], m.random.uniform((2,2), -1, 1))
rng_seed = numpy.random.RandomState(234).randint(2**30)
rng_seed = numpy.random.RandomState(utt.fetch_seed()).randint(2**30)
def test_uniform(self): """Test that RandomStreams.uniform generates the same results as numpy""" # Check over two calls to see if the random state is correctly updated. m = Module() m.random = RandomStreams(234) m.fn = Method([], m.random.uniform((2,2), -1, 1))
m.random = RandomStreams(234)
m.random = RandomStreams(utt.fetch_seed())
def test_normal(self): """Test that RandomStreams.normal generates the same results as numpy""" # Check over two calls to see if the random state is correctly updated. m = Module() m.random = RandomStreams(234) m.fn = Method([], m.random.normal((2,2), -1, 2))
rng_seed = numpy.random.RandomState(234).randint(2**30)
rng_seed = numpy.random.RandomState(utt.fetch_seed()).randint(2**30)
def test_normal(self): """Test that RandomStreams.normal generates the same results as numpy""" # Check over two calls to see if the random state is correctly updated. m = Module() m.random = RandomStreams(234) m.fn = Method([], m.random.normal((2,2), -1, 2))
m.random = RandomStreams(234)
m.random = RandomStreams(utt.fetch_seed())
def test_random_integers(self): """Test that RandomStreams.random_integers generates the same results as numpy""" # Check over two calls to see if the random state is correctly updated. m = Module() m.random = RandomStreams(234) m.fn = Method([], m.random.random_integers((20,20), -5, 5))
rng_seed = numpy.random.RandomState(234).randint(2**30)
rng_seed = numpy.random.RandomState(utt.fetch_seed()).randint(2**30)
def test_random_integers(self): """Test that RandomStreams.random_integers generates the same results as numpy""" # Check over two calls to see if the random state is correctly updated. m = Module() m.random = RandomStreams(234) m.fn = Method([], m.random.random_integers((20,20), -5, 5))
m = Module() m.random = RandomStreams(234)
m = Module() m.random = RandomStreams(utt.fetch_seed())
def test_permutation(self): """Test that RandomStreams.uniform generates the same results as numpy""" # Check over two calls to see if the random state is correctly updated. m = Module() m.random = RandomStreams(234) m.fn = Method([], m.random.permutation((20,), 10))
rng_seed = numpy.random.RandomState(234).randint(2**30)
rng_seed = numpy.random.RandomState(utt.fetch_seed()).randint(2**30)
def test_permutation(self): """Test that RandomStreams.uniform generates the same results as numpy""" # Check over two calls to see if the random state is correctly updated. m = Module() m.random = RandomStreams(234) m.fn = Method([], m.random.permutation((20,), 10))
m.random = RandomStreams(234)
m.random = RandomStreams(utt.fetch_seed())
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. m = Module() m.random = RandomStreams(234) m.fn = Method([], m.random.multinomial((20,20), 1, [0.1]*10))
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. m = Module() m.random = RandomStreams(234) m.fn = Method([], m.random.multinomial((20,20), 1, [0.1]*10))
mm.random = RandomStreams(234)
mm.random = RandomStreams(utt.fetch_seed())
def test_shuffle_row_elements(self): """Ensure RandomStreams.shuffle_row_elements generates right results""" # Check over two calls to see if the random state is correctly updated. # On matrices, for each row, the elements of that row should be # shuffled. # Note that this differs from numpy.random.shuffle, where all t...
val_rng = numpy.random.RandomState(unittest_tools.fetch_seed())
val_rng = numpy.random.RandomState(utt.fetch_seed()+42)
def test_shuffle_row_elements(self): """Ensure RandomStreams.shuffle_row_elements generates right results""" # Check over two calls to see if the random state is correctly updated. # On matrices, for each row, the elements of that row should be # shuffled. # Note that this differs from numpy.random.shuffle, where all t...
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): """Ensure RandomStreams.shuffle_row_elements generates right results""" # Check over two calls to see if the random state is correctly updated. # On matrices, for each row, the elements of that row should be # shuffled. # Note that this differs from numpy.random.shuffle, where all t...
vm.random = RandomStreams(234)
vm.random = RandomStreams(utt.fetch_seed())
def test_shuffle_row_elements(self): """Ensure RandomStreams.shuffle_row_elements generates right results""" # Check over two calls to see if the random state is correctly updated. # On matrices, for each row, the elements of that row should be # shuffled. # Note that this differs from numpy.random.shuffle, where all t...
atexit.register(gc.collect)
def set_cuda_disabled(): """Function used to disable cuda. A warning is displayed, so that the user is aware that cuda-based code is not going to work. Note that there is no point calling this function from outside of `cuda.__init__`, since it has no effect once the module is loaded. """ global cuda_available, cuda_wa...
return len('%x' % sys.maxint) * 4
try: maxint = sys.maxint except AttributeError: maxint = sys.maxsize return len('%x' % maxint) * 4
def local_bitwidth(): """Return 32 for 32bit arch, 64 for 64bit arch""" # Note - it seems from an informal survey of machines at scipy2010 # that platform.architecture is also a reliable way to get the bitwidth return len('%x' % sys.maxint) * 4
if distutils.sysconfig.get_config_var('CFLAGS').rfind('x86_64') < 0: preargs.extend(['-m32'])
n_bits = local_bitwidth() preargs.extend(['-m{0}'.format(n_bits)]) debug("OS X: compiling for {0} bit architecture".format(n_bits))
def gcc_module_compile_str(module_name, src_code, location=None, include_dirs=[], lib_dirs=[], libs=[], preargs=[]): """ :param module_name: string (this has been embedded in the src_code :param src_code: a complete c or c++ source listing for the module :param location: a pre-existing filesystem directory where the cp...
@dec.knownfailureif(True, "This case is not implemented")
def test_basic(self): c = T.matrix() p_y = T.exp(c) / T.exp(c).sum(axis=1).dimshuffle(0,'x')
(fx*fy*fz*fw+fx+fy+fz+fw,(fw,fx,fy,fz),(fwv,fxv,fyv,fzv),1,fxv*fyv*fzv*fwv+fxv+fyv+fzv+fwv,'float32'),
(fx*fy*fz*fw+fx+fy+fz+fw,(fw,fx,fy,fz),(fwv,fxv,fyv,fzv),2,fxv*fyv*fzv*fwv+fxv+fyv+fzv+fwv,'float32'),
def my_init(shp, dtype='float64', num=0): #ret = theano._asarray(numpy.random.rand(*shp),dtype=dtype) ret = numpy.zeros(shp, dtype=dtype)+num return ret
print ' %4.1f%% %5.1f%% %5.3fs %5.3fs %.2es %i %i %s' % (f, ftot, t, tot, t/nb_call,nb_call, a[0], str(a[1]))
if nb_call==0: time_per_call = float('nan') else: time_per_call = t/nb_call print ' %4.1f%% %5.1f%% %5.3fs %5.3fs %.2es %i %i %s' % (f, ftot, t, tot, time_per_call,nb_call, a[0], str(a[1]))
def print_summary_(fct_name, compile_time, fct_call_time, fct_call, apply_time, op_cimpl, n_apply_to_print=15, n_ops_to_print=20, print_apply=True): """ do the actual printing of print_summary and print_diff_summary.
import pdb;pdb.set_trace() vW1 = rng.rand(20,30) vW2 = rng.rand(30,20)
def test_shared_arguments_with_updates(self): rng = numpy.random.RandomState(utt.fetch_seed())
vu2 = rng.rand(3,30) vy0 = rng.rand(3,20) vy1 = rng.rand(20) vy2 = rng.rand(30)
def test_shared_arguments_with_updates(self): rng = numpy.random.RandomState(utt.fetch_seed())
f = theano.function([v1, v2], j)
f = theano.function([v1, v2], j, mode=mode)
def test_local_useless_rebroadcast(self): v1 = T.vector() v2 = T.vector() j = T.join(0, v1, v2) f = theano.function([v1, v2], j) f([1,2], [3,4,5]) e = f.maker.env.toposort() assert len([n for n in e if isinstance(n.op, T.Rebroadcast)]) == 0
f = theano.function([m], v)
f = theano.function([m], v, mode=mode)
def test_rebroadcast_rebroadcast(self): m = T.matrix() s = T.addbroadcast(m, 0, 1) v = T.unbroadcast(s, 1) f = theano.function([m], v) f([[76]]) e = f.maker.env.toposort() assert len([n for n in e if isinstance(n.op, T.Rebroadcast)]) == 1
print "RETURNING GEMV (case 2)"
def _beta_L_plus_alpha_M(beta, L, alpha, M, recurse_flip = True): #print 'BETA L + ALPHA M', beta, L, alpha, M, recurse_flip #EXPRESSION: (beta * L) + (alpha * M) # we've already checked the client counts, now just make the type check. ####if res_is_a(M, _dot22, 1): if M.owner and M.owner.op == _dot22: if M.broadcasta...
print "RETURNING GEMV (case 3)"
def _beta_L_plus_alpha_M(beta, L, alpha, M, recurse_flip = True): #print 'BETA L + ALPHA M', beta, L, alpha, M, recurse_flip #EXPRESSION: (beta * L) + (alpha * M) # we've already checked the client counts, now just make the type check. ####if res_is_a(M, _dot22, 1): if M.owner and M.owner.op == _dot22: if M.broadcasta...
(dx/abs(dx),[dx],[0.0*dxv],'float64'), (fx/abs(fx),[fx],[0.0*fxv],'float32'),
(dx/abs(dx),[dx],[0.1*dxv],'float64'), (fx/abs(fx),[fx],[0.1*fxv],'float32'),
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...
((2*dx)/(3*abs(dx)),[dx],[0.0*dxv],'float64'), ((2*fx)/(3*abs(fx)),[fx],[0.0*fxv],'float32'),
((2*dx)/(3*abs(dx)),[dx],[0.1*dxv],'float64'), ((2*fx)/(3*abs(fx)),[fx],[0.1*fxv],'float32'),
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...
f = theano.function([c],p_y)
f = theano.function([c],p_y, mode=self.mode)
def test_basic(self): c = T.matrix() p_y = T.exp(c) / T.exp(c).sum(axis=1).dimshuffle(0,'x')
mode='FAST_RUN'
#def test_rng_mrg_cpu():
if 0: mean, std, min, max = numpy.mean(l), numpy.std(l), numpy.min(l), numpy.max(l)
print prefix, 'min',min_,'max',max_
def basictest(f, steps, prefix=""): dt = 0.0 for i in xrange(steps): t0 = time.time() ival = f() dt += time.time() - t0 ival = numpy.asarray(ival) if i == 0: mean = numpy.array(ival, copy=True) else: alpha = 1.0 / (1+i) mean = alpha * ival + (1-alpha)*mean assert ival.min()>0 and ival.max()<1
print prefix, 'mean', mean print prefix, 'std', std print prefix, 'min', repr(min) print prefix, 'max', repr(max) assert max < 1.0 assert min >= 0.0 assert abs(mean - 0.5) < .01, 'bad mean?' sample_size = (1000,100)
if mode in ['DEBUG_MODE','FAST_COMPILE']: sample_size = (10,100) steps = int(1e2) else: sample_size = (1000,100) steps = int(1e3)
def basictest(f, steps, prefix=""): dt = 0.0 for i in xrange(steps): t0 = time.time() ival = f() dt += time.time() - t0 ival = numpy.asarray(ival) if i == 0: mean = numpy.array(ival, copy=True) else: alpha = 1.0 / (1+i) mean = alpha * ival + (1-alpha)*mean assert ival.min()>0 and ival.max()<1
print '' print 'ON GPU:' R = MRG_RandomStreams(234, use_cuda=True) u = R.uniform(size=sample_size, dtype='float32') assert u.dtype == 'float32' f = theano.function([], theano.Out( theano.sandbox.cuda.basic_ops.gpu_from_host(u), borrow=True), mode=mode) theano.printing.debugprint(f) print 'random?[:10]\n', numpy.asarray...
if mode!='FAST_COMPILE': print '' print 'ON GPU:' R = MRG_RandomStreams(234, use_cuda=True) u = R.uniform(size=sample_size, dtype='float32') assert u.dtype == 'float32' f = theano.function([], theano.Out( theano.sandbox.cuda.basic_ops.gpu_from_host(u), borrow=True), mode=mode) theano.printing.debugprint(f) print 'rando...
def basictest(f, steps, prefix=""): dt = 0.0 for i in xrange(steps): t0 = time.time() ival = f() dt += time.time() - t0 ival = numpy.asarray(ival) if i == 0: mean = numpy.array(ival, copy=True) else: alpha = 1.0 / (1+i) mean = alpha * ival + (1-alpha)*mean assert ival.min()>0 and ival.max()<1
basictest(ff, 1000, prefix='numpy')
basictest(ff, steps, prefix='numpy')
def basictest(f, steps, prefix=""): dt = 0.0 for i in xrange(steps): t0 = time.time() ival = f() dt += time.time() - t0 ival = numpy.asarray(ival) if i == 0: mean = numpy.array(ival, copy=True) else: alpha = 1.0 / (1+i) mean = alpha * ival + (1-alpha)*mean assert ival.min()>0 and ival.max()<1
assert numpy.all(specify_shape_fct()==x1_2)
assert numpy.all(self.ref_fct(specify_shape_fct()) ==self.ref_fct(x1_2))
def test_specify_shape_partial(self): dtype = self.dtype if dtype is None: dtype = theano.config.floatX
assert len(topo_specify)==6
if theano.config.mode!='FAST_COMPILE': assert len(topo_specify)==6
def test_specify_shape_partial(self): dtype = self.dtype if dtype is None: dtype = theano.config.floatX
assert len(topo_cst)==6
if theano.config.mode!='FAST_COMPILE': assert len(topo_cst)==6
def test_specify_shape_partial(self): dtype = self.dtype if dtype is None: dtype = theano.config.floatX
shape_constant_fct()
if theano.config.mode not in ['FAST_COMPILE','DebugMode','DEBUG_MODE']: shape_constant_fct() else: self.assertRaises(AssertionError, shape_constant_fct)
def test_specify_shape_partial(self): dtype = self.dtype if dtype is None: dtype = theano.config.floatX
import pdb;pdb.set_trace()
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...
out[0] = numpy.eye(n,m,k)
out[0] = numpy.eye(n,m,k,dtype=self.dtype)
def perform(self, node, (n,m,k), (out,)): out[0] = numpy.eye(n,m,k)
if isinstance(inner_out.type, tensor.TensorType):
if isinstance(inner_out.type, tensor.TensorType) and store_steps[pos] != 1:
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...
indices = numpy.asarray(indices).view(numpy.int32)
indices = numpy.asarray(indices, dtype='int32').view(numpy.int32)
def make_node(self, data, indices, indptr, shape): """Build a SparseVariable from the internal parametrization :param data: :param indices: :param indptr: :type data: 1-d tensor :type indices: 1-d tensor of ints :type indptr: 1-d tensor of ints
indptr = numpy.asarray(indptr).view(numpy.int32)
indptr = numpy.asarray(indptr, dtype='int32').view(numpy.int32)
def make_node(self, data, indices, indptr, shape): """Build a SparseVariable from the internal parametrization :param data: :param indices: :param indptr: :type data: 1-d tensor :type indices: 1-d tensor of ints :type indptr: 1-d tensor of ints
shape = numpy.asarray(shape).view(numpy.int32)
shape = numpy.asarray(shape, dtype='int32').view(numpy.int32)
def make_node(self, data, indices, indptr, shape): """Build a SparseVariable from the internal parametrization :param data: :param indices: :param indptr: :type data: 1-d tensor :type indices: 1-d tensor of ints :type indptr: 1-d tensor of ints
return cast(self.uniform(size=size) < p, dtype)
if dtype=='float32' and self.use_cuda: return cast(self.uniform(size=size, dtype=dtype) < p, dtype) else: return cast(self.uniform(size=size) < p, dtype)
def binomial(self, size=None, n=1, p=0.5, ndim=None, dtype='int64'): if n == 1: return cast(self.uniform(size=size) < p, dtype) else: raise NotImplementedError("MRG_RandomStreams.binomial with n > 1")
PyErr_Format(PyExc_ValueError, "number of columns in x (%%zi) does not match length of b (%%zi)",
PyErr_Format(PyExc_ValueError, "number of columns in x (%%ld) does not match length of b (%%ld)",
def c_code_template(): # this implementation was lifted from # /u/bergstrj/cvs/bergstrj/src/feb07/nn.cxx
return (5,)
return (6,)
def c_code_cache_version(): return (5,)
if mode == 'FAST_COMPILE':
if mode == theano.compile.mode.get_mode('FAST_COMPILE'):
def test_get_rid_of_advanced_indexing_version_of_xent(self): verbose = 0 # TODO: add the optimization in FAST_COMPILE? # In the mean time, run it as 'FAST_RUN' instead mode = theano.compile.mode.get_default_mode() if mode == 'FAST_COMPILE': mode = 'FAST_RUN'
if mode == 'FAST_COMPILE':
if mode == theano.compile.mode.get_mode('FAST_COMPILE'):
def test_scale_cost(self): # TODO: add the optimization in FAST_COMPILE? # In the mean time, run it as 'FAST_RUN' instead mode = theano.compile.mode.get_default_mode() if mode == 'FAST_COMPILE': mode = 'FAST_RUN'
info('Waiting for existing lock by %s (I am %s)' % ( read_owner, my_pid)) info("To manually release the lock, delete", lock_file)
info("Waiting for existing lock by process '%s' (I am " "process '%s')" % (read_owner, my_pid)) info("To manually release the lock, delete", tmp_dir)
def lock(tmp_dir, timeout=120, min_wait=5, max_wait=10, verbosity=1): """ Obtain lock access by creating a given temporary directory (whose base will be created if needed, but will not be deleted after the lock is removed). If access is refused by the same lock owner during more than 'timeout' seconds, then the current...
if numpy.any([o.type.dtype == 'float64' for o in node.outputs]): print 'WARNING: THERE ARE STILL float64s in your graph local_gpu_elemwise_0', node else: new_op = GpuElemwise(node.op.scalar_op, node.op.inplace_pattern) return [host_from_gpu(new_op(*(gpu_from_host(i) for i in node.inputs)))] return False
if numpy.all([i.type.dtype == 'float32' for i in node.inputs]): if numpy.all([o.type.dtype == 'float32' for o in node.outputs]): new_op = GpuElemwise(node.op.scalar_op, node.op.inplace_pattern) return [host_from_gpu(new_op(*(gpu_from_host(i) for i in node.inputs)))]
def local_gpu_elemwise_0(node): if isinstance(node.op, tensor.Elemwise): if numpy.any([hasattr(i.owner, 'op') and isinstance(i.owner.op, HostFromGpu) for i in node.inputs]): if numpy.any([o.type.dtype == 'float64' for o in node.outputs]): print 'WARNING: THERE ARE STILL float64s in your graph local_gpu_elemwise_0', nod...
return [libname], []
def std_lib_dirs_and_libs(): python_inc = distutils.sysconfig.get_python_inc() if sys.platform == 'win32': # Typical include directory: C:\Python26\include libname = os.path.basename(os.path.dirname(python_inc)).lower() # Also add directory containing the Python library to the library # directories. python_lib_dir = os...
if 'Python.framework' in sys.prefix:
if python_inc.count('Python.framework')>0 :
def gcc_module_compile_str(module_name, src_code, location=None, include_dirs=[], lib_dirs=[], libs=[], preargs=[]): """ :param module_name: string (this has been embedded in the src_code :param src_code: a complete c or c++ source listing for the module :param location: a pre-existing filesystem directory where the cp...
else : libs = [libname] + libs
def gcc_module_compile_str(module_name, src_code, location=None, include_dirs=[], lib_dirs=[], libs=[], preargs=[]): """ :param module_name: string (this has been embedded in the src_code :param src_code: a complete c or c++ source listing for the module :param location: a pre-existing filesystem directory where the cp...
raise KnownFailureTest("Theano optimize constant before stabilization! This break stabilization optimization is some case!")
def test_constant_get_stabilized(): """ Currently Theano enable the constant_folding optimization before stabilization optimization. This cause some stabilization optimization not being implemented and thus cause inf value to appear when it should not. .. note: we can't simply move the constant_folding optimization to...
and self.verbose == other.verbose
and self.verbose == other.verbose \ and self.kshp == other.kshp
def __eq__(self, other): return type(self) == type(other) \ and self.border_mode == other.border_mode \ and self.subsample == other.subsample \ and self.logical_img_hw == other.logical_img_hw \ and self.logical_kern_hw == other.logical_kern_hw \ and self.logical_kern_align_top == other.logical_kern_align_top \ and self...
^ self.verbose
^ self.verbose \ ^ self.kshp
def __hash__(self): # don't use hash(self.version) as hash(-1)==-2 and hash(-2)==-2 in python! return hash(type(self)) \ ^ hash(self.border_mode) \ ^ hash(self.subsample) \ ^ hash(self.logical_img_hw) \ ^ hash(self.logical_kern_hw) \ ^ hash(self.logical_kern_align_top) \ ^ self.version \ ^ self.verbose
return (0,6)
return (0,7)
def c_code_cache_version(self): return (0,6)
std:stringstream temp;
std::stringstream temp;
def c_code(self, node, name, (img2d, filtersflipped), (z, ), sub): if node.inputs[0].type.dtype != node.inputs[1].type.dtype: raise NotImplementedError() assert node.inputs[0].type.dtype == node.inputs[1].type.dtype d=locals() d.update(sub)
std:stringstream temp;
std::stringstream temp;
def my_dup2(st): s="" iter=0 for i in range(unroll_bsize): d["unroll_biter"]=i for j in range(unroll_ksize): d["unroll_kiter"]=j d["unroll_iter"]=iter iter+=1 s+=st%d return s+"\n"
inputs.extend(i.owner.inputs) s_inputs.extend(s_input)
inputs.extend(tmp_input) s_inputs.extend(tmp_scalar)
def local_fuse(node): """ As part of specialisation, we fuse two consecutive elemwise op of the same shape.
inputs2=[] s_inputs2=[] for i,si in zip(inputs,s_inputs): if i not in inputs2: inputs2.append(i) s_inputs2.append(si) else: assert si in s_inputs2 inputs = inputs2 s_inputs = s_inputs2 del inputs2, s_inputs2
def local_fuse(node): """ As part of specialisation, we fuse two consecutive elemwise op of the same shape.
from theano.version import hg_revision as HG_REVISION
HG_REVISION = "RELEASE"
def write_version_py(filename='theano/version.py'): cnt = """
gpuval = cuda_ndarray.conv(img, kern, mode, subsample=subsample, version=version, verbose=verbose)
i = cuda_tensor4() k = cuda_tensor4() op = theano.sandbox.cuda.blas.GpuConv(border_mode=mode,subsample=subsample, version=version, verbose=verbose)(i,k) f=theano.function([i,k],op) gpuval = f(img,kern)
def _params_allgood(ishape, kshape, mode, subsample=(1,1), img_stride=(1,1), kern_stride=(1,1), version=-1, verbose=0, random=True, print_=None, id=None, rtol=1e-5, atol = 1e-8, nb_iter=0, ones=False): if ones: assert not random npy_img = numpy.asarray(numpy.ones(ishape), dtype='float32') npy_kern = -numpy.asarray(nump...
gpuval2 = cuda_ndarray.conv(img, kern, mode, subsample=subsample, version=version, verbose=0)
gpuval2 = f(img,kern)
def _params_allgood(ishape, kshape, mode, subsample=(1,1), img_stride=(1,1), kern_stride=(1,1), version=-1, verbose=0, random=True, print_=None, id=None, rtol=1e-5, atol = 1e-8, nb_iter=0, ones=False): if ones: assert not random npy_img = numpy.asarray(numpy.ones(ishape), dtype='float32') npy_kern = -numpy.asarray(nump...
print >> sys.stdout, '%15s'% str(ishape), '%15s'% str(kshape), print >> sys.stdout, '%12.5f %7.2f %7.2f %7.1f' % (approx_fp,
if verbose>0: print >> sys.stdout, '%15s'% str(ishape), '%15s'% str(kshape), print >> sys.stdout, '%12.5f %7.2f %7.2f %7.1f' % (approx_fp,
def _params_allgood(ishape, kshape, mode, subsample=(1,1), img_stride=(1,1), kern_stride=(1,1), version=-1, verbose=0, random=True, print_=None, id=None, rtol=1e-5, atol = 1e-8, nb_iter=0, ones=False): if ones: assert not random npy_img = numpy.asarray(numpy.ones(ishape), dtype='float32') npy_kern = -numpy.asarray(nump...
_params_allgood_header()
if verbose>0: _params_allgood_header()
def exec_conv(version, shapes, verbose, random, mode, print_=None, rtol=1e-5, ones=False): _params_allgood_header() nb_failed = 0 nb_tests = 0 failed_version=set() failed_id=[] for ver in version:# I put -1 in case we forget to add version in the test to. for id,(ishape, kshape, subshape, istride, kstride) in enumerat...
class TheanoConfigParser(object): def __str__(self): sio = StringIO.StringIO() _config_print(self.__class__, sio) return sio.getvalue() pass config = TheanoConfigParser()
def fetch_val_for_key(key): """Return the overriding config value for a key. A successful search returs a string value. An unsuccessful search raises a KeyError The (decreasing) priority order is: - THEANO_FLAGS - ~./theanorc """ # first try to find it in the FLAGS rval = None for name_val in THEANO_FLAGS.split(',')...
def AddConfigVar(name, doc, thing, cls=TheanoConfigParser): if cls == TheanoConfigParser: thing.fullname = name if hasattr(TheanoConfigParser, name): raise ValueError('This name is already taken') parts = name.split('.') if len(parts) > 1:
class TheanoConfigParser(object): _i_am_a_config_class = True def __str__(self): sio = StringIO.StringIO() _config_print(self.__class__, sio) return sio.getvalue() config = TheanoConfigParser() def AddConfigVar(name, doc, configparam, root=config): """Add a new variable to theano.config :type name: strin...
def _config_print(thing, buf): for cv in _config_var_list: print >> buf, cv print >> buf, " Doc: ", cv.doc print >> buf, " Value: ", cv.val print >> buf, ""
if not hasattr(cls, parts[0]):
if not hasattr(root, sections[0]):
def AddConfigVar(name, doc, thing, cls=TheanoConfigParser): if cls == TheanoConfigParser: thing.fullname = name if hasattr(TheanoConfigParser, name): raise ValueError('This name is already taken') parts = name.split('.') if len(parts) > 1: # set up a subobject if not hasattr(cls, parts[0]): class SubObj(object): pass s...
pass setattr(cls, parts[0], SubObj) AddConfigVar('.'.join(parts[1:]), doc, thing, cls=getattr(cls, parts[0]))
_i_am_a_config_class = True setattr(root.__class__, sections[0], SubObj()) newroot = getattr(root, sections[0]) if not getattr(newroot, '_i_am_a_config_class', False) or isinstance(newroot, type): raise TypeError('Internal config nodes must be config class instances', newroot) return AddConfigVar('.'.join(sections[1:])...
def AddConfigVar(name, doc, thing, cls=TheanoConfigParser): if cls == TheanoConfigParser: thing.fullname = name if hasattr(TheanoConfigParser, name): raise ValueError('This name is already taken') parts = name.split('.') if len(parts) > 1: # set up a subobject if not hasattr(cls, parts[0]): class SubObj(object): pass s...
thing.doc = doc thing.__get__() setattr(cls, parts[0], thing) _config_var_list.append(thing)
if hasattr(root, name): raise AttributeError('This name is already taken', configparam.fullname) configparam.doc = doc configparam.__get__() setattr(root.__class__, sections[0], configparam) _config_var_list.append(configparam)
def AddConfigVar(name, doc, thing, cls=TheanoConfigParser): if cls == TheanoConfigParser: thing.fullname = name if hasattr(TheanoConfigParser, name): raise ValueError('This name is already taken') parts = name.split('.') if len(parts) > 1: # set up a subobject if not hasattr(cls, parts[0]): class SubObj(object): pass s...
elif self.imshp != self.imshp_logical or self.kshp != self.kshp_logical:
elif all_shape:
def c_code(self, node, name, (img2d, filtersflipped), (z, ), sub): if node.inputs[0].type.dtype != node.inputs[1].type.dtype: raise NotImplementedError() assert node.inputs[0].type.dtype == node.inputs[1].type.dtype d=locals() d.update(sub)
if numpy.ndim==1 or numpy.all(num.broadcastable):
if num.ndim==1 or numpy.all(num.broadcastable):
def local_advanced_indexing_crossentropy_onehot_grad(node): if not (node.op == softmax_grad): return sm = None try: d_sm, sm = node.inputs except: return if (sm is not None) and sm.owner and (sm.owner.op in (softmax, softmax_with_bias)): sm_w_bias = local_softmax_with_bias.transform(sm.owner) if sm_w_bias: assert sm_...
outs[0][0] = copy.deepcopy(args[0])
if hasattr(args[0],'copy'): outs[0][0] = args[0].copy() else: outs[0][0] = copy.deepcopy(args[0])
def perform( self, node, args, outs): outs[0][0] = copy.deepcopy(args[0])
ret = elemwise.CAReduce.perform(self,node,(input,),(output,)) output[0]=numpy.asarray(output[0]/len(input))
output[0]=numpy.mean(input,axis=self.axis)
def perform(self, node, (input, ), (output, )): ret = elemwise.CAReduce.perform(self,node,(input,),(output,)) output[0]=numpy.asarray(output[0]/len(input))
assert numpy.all(data_of(A) < 5) data_of_b += 10 assert numpy.all(data_of(A) > 5) data_of_b -= 10 assert numpy.all(data_of(B) < 5) data_of_a += 10 print data_of(B) assert numpy.all(data_of(B) > 5) data_of_a -= 10 assert numpy.may_share_memory(data_of(A), data_of_b) assert numpy.may_share_memory(data_of(B), data_of_a...
if theano.config.mode not in ['DebugMode', 'DEBUG_MODE']: assert numpy.all(data_of(A) < 5) data_of_b += 10 assert numpy.all(data_of(A) > 5) data_of_b -= 10 assert numpy.all(data_of(B) < 5) data_of_a += 10 print data_of(B) assert numpy.all(data_of(B) > 5) data_of_a -= 10 assert numpy.may_share_memory(data_of(A), dat...
def test_no_aliasing_2b(self): # B and A take one another's values # no copying is necessary since each one is updated. # The twist one `test_no_aliasing_2` is that each shared var is updated with a view of # the other one.
print 'non-equal optimization events', i, ':', j
print >>infolog, 'non-equal optimization events', i, ':', j
def __init__(self, inputs, outputs, optimizer, mode, accept_inplace = False, function_builder = Function): """ :type inputs: a list of SymbolicInput instances
f = theano.function([], u)
f = theano.function([], u, mode=mode)
def basictest(f, steps, prefix=""): dt = 0.0 for i in xrange(steps): t0 = time.time() ival = f() dt += time.time() - t0 ival = numpy.asarray(ival) if i == 0: mean = numpy.array(ival, copy=True) else: alpha = 1.0 / (1+i) mean = alpha * ival + (1-alpha)*mean assert ival.min()>0 and ival.max()<1
basictest(f, 1000, prefix='mrg ')
basictest(f, steps, prefix='mrg cpu')
def basictest(f, steps, prefix=""): dt = 0.0 for i in xrange(steps): t0 = time.time() ival = f() dt += time.time() - t0 ival = numpy.asarray(ival) if i == 0: mean = numpy.array(ival, copy=True) else: alpha = 1.0 / (1+i) mean = alpha * ival + (1-alpha)*mean assert ival.min()>0 and ival.max()<1
borrow=True))
borrow=True), mode=mode)
def basictest(f, steps, prefix=""): dt = 0.0 for i in xrange(steps): t0 = time.time() ival = f() dt += time.time() - t0 ival = numpy.asarray(ival) if i == 0: mean = numpy.array(ival, copy=True) else: alpha = 1.0 / (1+i) mean = alpha * ival + (1-alpha)*mean assert ival.min()>0 and ival.max()<1
basictest(f, 1000, prefix='mrg ')
basictest(f, steps, prefix='mrg gpu')
def basictest(f, steps, prefix=""): dt = 0.0 for i in xrange(steps): t0 = time.time() ival = f() dt += time.time() - t0 ival = numpy.asarray(ival) if i == 0: mean = numpy.array(ival, copy=True) else: alpha = 1.0 / (1+i) mean = alpha * ival + (1-alpha)*mean assert ival.min()>0 and ival.max()<1
ff = theano.function([], uu)
ff = theano.function([], uu, mode=mode)
def basictest(f, steps, prefix=""): dt = 0.0 for i in xrange(steps): t0 = time.time() ival = f() dt += time.time() - t0 ival = numpy.asarray(ival) if i == 0: mean = numpy.array(ival, copy=True) else: alpha = 1.0 / (1+i) mean = alpha * ival + (1-alpha)*mean assert ival.min()>0 and ival.max()<1
f = theano.function([], n)
f = theano.function([], n, mode=mode)
def basictest(f, steps, target_avg, target_std, prefix=""): dt = 0.0 avg_std = 0.0 for i in xrange(steps): t0 = time.time() ival = f() dt += time.time() - t0 ival = numpy.asarray(ival) if i == 0: mean = numpy.array(ival, copy=True) avg_std = numpy.std(ival) else: alpha = 1.0 / (1+i) mean = alpha * ival + (1-alpha)*mean...
borrow=True))
borrow=True), mode=mode)
def basictest(f, steps, target_avg, target_std, prefix=""): dt = 0.0 avg_std = 0.0 for i in xrange(steps): t0 = time.time() ival = f() dt += time.time() - t0 ival = numpy.asarray(ival) if i == 0: mean = numpy.array(ival, copy=True) avg_std = numpy.std(ival) else: alpha = 1.0 / (1+i) mean = alpha * ival + (1-alpha)*mean...