rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
int verbose = 0; dim3 n_threads(std::min(32,CudaNdarray_HOST_DIMS(%(x)s)[2])); while(n_threads.x*(n_threads.y+1)<=512 && n_threads.y<CudaNdarray_HOST_DIMS(%(x)s)[1]){ n_threads.y++; } dim3 n_blocks(std::min(CudaNdarray_HOST_DIMS(%(x)s)[0], (int)NUM_VECTOR_OP_BLOCKS)); n_blocks.y = std::min( ceil_intdiv(CudaNdarray_HO...
//int n_summations = CudaNdarray_HOST_DIMS(%(x)s)[0] * CudaNdarray_HOST_DIMS(%(x)s)[2]; //if ((n_summations >= 15 * 32) && (CudaNdarray_HOST_DIMS(%(x)s)[2]>=16)) if (1) // if the alternative is less buggy, consider not using this branch { // If there are a lot of summations to do, then we can use simple parallelizatio...
def c_code_reduce_010(self, sio, node, name, x, z, fail): makecall = self._makecall(node, name, x, z, fail) makecall_inner = self._makecall(node, name, x, z, fail, pattern="010_inner") pattern = ''.join(str(i) for i in self.reduce_mask) print >> sio, """ { int verbose = 0;
return (17,)
return (18,)
def c_code_cache_version(self): return (17,)
float mysum = 0.0f;
def c_support_code_apply(self, node, nodename): sio = StringIO.StringIO() nd_in = len(self.reduce_mask) if all(i==1 for i in self.reduce_mask): #this kernel is ok for up to a few thousand elements, but # it only runs on ONE multiprocessor reducebuf = self._k_reduce_buf('Z[0]') print >> sio, """ static __global__ void k...
def mp(input): return max_pool2D(input, maxpoolshp, ignore_border) utt.verify_grad(mp, [imval], rng=rng)
def mp(input): return max_pool2D(input, maxpoolshp, ignore_border)
"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.",
"If 'None', we warn about all Theano bugs found by default. If 'all', we don't warn about Theano bugs found by default. If a version, we print only the warnings relative to Theano bugs found after that version. Warning for specific bugs can be configured with specific [warn] flags.",
def warning(*msg): _logger.warning('WARNING theano.configdefaults: '+' '.join(msg))
elif config.warn.ignore_bug_before=='All':
elif config.warn.ignore_bug_before == 'all':
def warning(*msg): _logger.warning('WARNING theano.configdefaults: '+' '.join(msg))
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))
assert abs(numpy.mean(mean) - target_avg) < mean_rtol, 'bad mean? %f %f'%(mean, target_avg)
assert abs(numpy.mean(mean) - target_avg) < mean_rtol, 'bad mean? %f %f'%(numpy.mean(mean), target_avg)
def basictest(f, steps, sample_size, prefix="", allow_01=False, inputs=[], target_avg=0.5, target_std=None, mean_rtol=0.01): dt = 0.0 avg_std = 0.0 for i in xrange(steps): t0 = time.time() ival = f(*inputs) dt += time.time() - t0 ival = numpy.asarray(ival) if i == 0: mean = numpy.array(ival, copy=True) avg_std = numpy...
basictest(f, steps, sample_size, prefix='mrg cpu', inputs=input, allow_01=True, mean = mean)
basictest(f, steps, sample_size, prefix='mrg cpu', inputs=input, allow_01=True, target_avg = mean)
def test_binomial():
basictest(f, steps, sample_size, prefix='mrg gpu', inputs=input, allow_01=True, mean = mean)
basictest(f, steps, sample_size, prefix='mrg gpu', inputs=input, allow_01=True, target_avg = mean)
def test_binomial():
basictest(ff, steps, sample_size, prefix='numpy', allow_01=True, inputs=input, mean = mean)
basictest(ff, steps, sample_size, prefix='numpy', allow_01=True, inputs=input, target_avg = mean)
def test_binomial():
assert any([isinstance(node.op,GpuImages2Neibs) for node in f.maker.env.toposort()])
f_gpu = function([], images2neibs(images,neib_shape), mode=mode_with_gpu) assert any([isinstance(node.op,GpuImages2Neibs) for node in f_gpu.maker.env.toposort()])
def test_neibs_gpu(): if cuda.cuda_available == False: raise SkipTest('Optional package cuda disabled') shape = (100,40,18,18) images = shared(numpy.arange(numpy.prod(shape), dtype='float32').reshape(shape)) neib_shape = T.as_tensor_variable((2,2))#(array((2,2), dtype='float32')) from theano.sandbox.cuda.basic_ops im...
res1=[[[[ 0., 1., 4., 5.], [ 2., 3., 6., 7.], [ 8., 9., 12., 13.], [ 10., 11., 14., 15.], [ 16., 17., 20., 21.], [ 18., 19., 22., 23.], [ 24., 25., 28., 29.], [ 26., 27., 30., 31.], [ 32., 33., 36., 37.], [ 34., 35., 38., 39.], [ 40., 41., 44., 45.], [ 42., 43., 46., 47.], ...
neibs = numpy.asarray(f_gpu()) assert numpy.allclose(neibs,f())
def test_neibs_gpu(): if cuda.cuda_available == False: raise SkipTest('Optional package cuda disabled') shape = (100,40,18,18) images = shared(numpy.arange(numpy.prod(shape), dtype='float32').reshape(shape)) neib_shape = T.as_tensor_variable((2,2))#(array((2,2), dtype='float32')) from theano.sandbox.cuda.basic_ops im...
else: return
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_...
help="only check indentation if the file was previously correctly indented (or is new)"
help="only block on newly introduced indentation problems; ignore all others" ) parser.add_argument("-p", "--incremental-with-patch", action="store_const", default=False, const=True, help="only block on newly introduced indentation problems; propose a patch for all others"
def main(argv=None): if argv is None: argv = sys.argv[1:] parser = argparse.ArgumentParser(description="Pretxncommit hook for Mercurial to check for whitespace issues") parser.add_argument("-n", "--no-indentation", action="store_const", default=False, const=True, help="don't check indentation, just basic parsing" ) pa...
if args.incremental and filename in changed_filenames: old_file_contents = get_file_contents(filename, revision=parent_commit()) check_indentation = get_correct_indentation_diff(old_file_contents, "") is None else: check_indentation = True
was_clean = None if args.incremental or args.incremental_with_patch: if filename in changed_filenames: old_file_contents = get_file_contents(filename, revision=parent_commit()) was_clean = get_correct_indentation_diff(old_file_contents, "") is None else: was_clean = True check_indentation = was_clean or not args.incr...
def main(argv=None): if argv is None: argv = sys.argv[1:] parser = argparse.ArgumentParser(description="Pretxncommit hook for Mercurial to check for whitespace issues") parser.add_argument("-n", "--no-indentation", action="store_const", default=False, const=True, help="don't check indentation, just basic parsing" ) pa...
block_commit = True
if was_clean or not args.incremental_with_patch: block_commit = True
def main(argv=None): if argv is None: argv = sys.argv[1:] parser = argparse.ArgumentParser(description="Pretxncommit hook for Mercurial to check for whitespace issues") parser.add_argument("-n", "--no-indentation", action="store_const", default=False, const=True, help="don't check indentation, just basic parsing" ) pa...
if not (-size <= i < size): raise IndexError
def __delitem__(self, i): size = len(self) if not (-size <= i < size): raise IndexError data = self.data if i < 0: i += size for j in xrange(self.left+i, self.right-1): data[j] = data[j+1] self.pop()
non_seq_copy = non_seq.type()
if n_fixed_steps not in [-1,1]: non_seq_copy = non_seq.type() else: non_seq_copy = non_seq
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...
f = theano.function([x,y,x2], [c.sum(), tensor.grad(c, x)])
f = theano.function([x,y,x2], [c.sum(), tensor.grad(c.sum(), x)], mode='FAST_RUN')
def test_asymptotic_32(): """ This test makes sure that our functions behave sensibly when huge values are present """ for dtype in 'float32', 'float64': if dtype == 'float32': x = tensor.fmatrix() x2 = tensor.fvector() else: x = tensor.dmatrix() x2 = tensor.dvector() y = tensor.lvector() c = categorical_crossentropy(...
return [host_from_gpu(new_op(*(gpu_from_host(i) for i in node.inputs)))] upcastable = set(['float32', 'int8', 'int16', 'uint8', 'uint16']) if numpy.all([i.type.dtype in upcastable for i in node.inputs]):
gpu_elemwise = new_op(*(gpu_from_host(i) for i in node.inputs)) elif numpy.all([i.type.dtype in upcastable for i in node.inputs]):
def local_gpu_elemwise_0(node): """elemwise(..., host_from_gpu, ...) -> host_from_gpu(elemwise(gpu_from_host, ..., gpu_from_host) """ if isinstance(node.op, tensor.Elemwise): if numpy.any([i.owner and isinstance(i.owner.op, HostFromGpu) for i in node.inputs]): if numpy.all([o.type.dtype == 'float32' for o in node.outpu...
return [host_from_gpu(new_op(*new_inputs))]
gpu_elemwise = new_op(*new_inputs) else: return False else: return False gpu_elemwise = split_huge_add_or_mul(gpu_elemwise.owner).outputs[0] return [host_from_gpu(gpu_elemwise)]
def local_gpu_elemwise_0(node): """elemwise(..., host_from_gpu, ...) -> host_from_gpu(elemwise(gpu_from_host, ..., gpu_from_host) """ if isinstance(node.op, tensor.Elemwise): if numpy.any([i.owner and isinstance(i.owner.op, HostFromGpu) for i in node.inputs]): if numpy.all([o.type.dtype == 'float32' for o in node.outpu...
return [new_op(*[gpu_from_host(i) for i in elemwise_node.inputs])]
gpu_elemwise = new_op(*[gpu_from_host(i) for i in elemwise_node.inputs]) gpu_elemwise = split_huge_add_or_mul(gpu_elemwise.owner).outputs[0] return [gpu_elemwise]
def local_gpu_elemwise_1(node): """ gpu_from_host(Elemwise)) -> GpuElemwise(gpu_from_host(...)) """ if node.op == gpu_from_host: host_i, = node.inputs if host_i.owner and isinstance(host_i.owner.op, tensor.Elemwise) and len(host_i.clients)==1: elemwise_node = host_i.owner #don't set any inplace pattern. gpu_insert_inpl...
@register_opt() @local_optimizer([]) def local_gpu_huge_add_or_mul(node): """ The gpu code generator for elemwise fusion knows when there are too many inputs, but add doesn't. So there's this workaround. The CUDA c compiler limits the number of arguments to 256 bytes' worth or something. """ if isinstance(node.op, Gp...
def max_inputs_to_GpuElemwise(node): """ return the maximum number of input this Apply node to an GpuElemwise can accept. This is needed as currently their is a limit of 256 bytes of paramter for the gpu function. This mesure the number of paramter we put in our gpu function and compute the maximum number of inputs tha...
def local_gpualloc(node): replace=False if node.op == tensor.alloc: if node.inputs[0].owner and node.inputs[0].owner.op==host_from_gpu:#if the input was on the gpu replace = True if all([c!='output' and c.op == gpu_from_host for c,idx in node.outputs[0].clients]):#if all clients are on gpu replace=True if all([c!='outp...
:param fn: Function that describes the operations involved in one step of scan Given variables representing all the slices of input and past values of outputs and other non sequences parameters, ``fn`` should produce variables describing the output of one time step of scan. The order in which the argument to this funct...
:param fn: Function that describes the operations involved in one step of scan Given variables representing all the slices of input and past values of outputs and other non sequences parameters, ``fn`` should produce variables describing the output of one time step of scan. The order in which the argument to this funct...
def scan(fn, sequences, initial_states, non_sequences, inplace_map={}, \ sequences_taps={}, outputs_taps = {}, n_steps = 0, \ truncate_gradient = -1, go_backwards = False, mode = None): '''Function that constructs and applies a Scan op :param fn: Function that describes the operations involved in one step of scan Give...
``inplace_map`` is a dictionary where keys are output indexes, and values are sequence indexes. Assigning a value ``j`` to a key ``i`` means that output number ``j`` will be computed inplace (in the same memory buffer) as the input number ``i``. :param sequences_taps: Dictionary describing what slices of the input seq...
``inplace_map`` is a dictionary where keys are output indexes, and values are sequence indexes. Assigning a value ``j`` to a key ``i`` means that output number ``j`` will be computed inplace (in the same memory buffer) as the input number ``i``. :param sequences_taps: Dictionary describing what slices of the input sequ...
def scan(fn, sequences, initial_states, non_sequences, inplace_map={}, \ sequences_taps={}, outputs_taps = {}, n_steps = 0, \ truncate_gradient = -1, go_backwards = False, mode = None): '''Function that constructs and applies a Scan op :param fn: Function that describes the operations involved in one step of scan Give...
:return: tuple of the form (outputs, updates) ``outputs`` is either a Theano variable or a list of Theano variables representing the outputs of scan. ``updates`` is a dictionary specifying the updates rules for all shared variables used in the scan operation; this dictionary should be pass to ``theano.function``
:return: tuple of the form (outputs, updates); ``outputs`` is either a Theano variable or a list of Theano variables representing the outputs of scan. ``updates`` is a dictionary specifying the updates rules for all shared variables used in the scan operation; this dictionary should be pass to ``theano.function``
def scan(fn, sequences, initial_states, non_sequences, inplace_map={}, \ sequences_taps={}, outputs_taps = {}, n_steps = 0, \ truncate_gradient = -1, go_backwards = False, mode = None): '''Function that constructs and applies a Scan op :param fn: Function that describes the operations involved in one step of scan Give...
:param (inputs,outputs): inputs and outputs Theano variables that describe the function that is applied recursively :param n_seqs: number of sequences over which scan will have to iterate
:param (inputs,outputs, givens): inputs and outputs Theano variables that describe the function that is applied recursively; givens list is used to replace shared variables with not shared ones :param n_seqs: number of sequences over which scan will have to iterate
def __init__(self,(inputs, outputs, givens),n_seqs, n_outs, inplace_map={}, seqs_taps={}, outs_taps={}, truncate_gradient = -1, go_backwards = False, stored_steps_output = {}, mode = 'FAST_RUN', inplace=False): ''' :param (inputs,outputs): inputs and outputs Theano variables that describe the function that is applied ...
elif isinstance(v, SharedVariable) and v not in clone_d:
elif isinstance(v, SharedVariable):
def clone_v_get_shared_updates(v): '''Clone a variable and its inputs recursively until all are in clone_d. Also appends all shared variables met along the way to shared_inputs, and their default_update (if applicable) to update_d and update_expr. ''' # this method co-recurses with clone_a assert v is not None if v.own...
def get_first_node(node, dtype): if node is None: return None if any([getattr(o.type, 'dtype', 'nodtype') != dtype for o in node.outputs]): for i in node.inputs: n = get_first_node(i.owner, dtype) if n is not None: return n return node else: return None raise TypeError('an update must have the same type as the origina...
err_msg = 'an update must have the same type as the original shared variable(dest, dest.type, update_val, update_val.type)' err_arg = (store_into, store_into.type, update_val, update_val.type) raise TypeError(err_msg, err_arg )
def clone_a(a): # this method co-recurses with clone_v_get_shared_updates if a is None: return None if a not in clone_d: for i in a.inputs: clone_v_get_shared_updates(i) clone_d[a] = a.clone_with_new_inputs([clone_d[i] for i in a.inputs]) for old_o, new_o in zip(a.outputs, clone_d[a].outputs): clone_d.setdefault(old_o,...
special = dict(middle_dot = "\dot", big_sigma = "\Sigma") greek = dict(alpha = "\alpha", beta = "\beta", gamma = "\gamma", delta = "\delta", epsilon = "\epsilon")
special = dict(middle_dot = "\\dot", big_sigma = "\\Sigma") greek = dict(alpha = "\\alpha", beta = "\\beta", gamma = "\\gamma", delta = "\\delta", epsilon = "\\epsilon")
def __call__(self, *args): if len(args) == 1: return self.process(*args) elif len(args) == 2 and isinstance(args[1], (PrinterState, dict)): return self.process(*args) elif len(args) > 2: return self.process_graph(*args) else: raise TypeError('Not enough arguments to call.')
print >> file, '%s%s [@%i]%s' % (prefix, a.op, id(r), type_str)
print >> file, '%s%s [@%i]%s \'%s\'' % (prefix, a.op, id(r), \ type_str, r_name)
def debugprint(r, prefix='', depth=-1, done=None, print_type=False, file=sys.stdout): """Print the graph leading to `r` to given depth. :param r: Variable instance :param prefix: prefix to each line (typically some number of spaces) :param depth: maximum recursion depth (Default -1 for unlimited). :param done: set of ...
print >> file, '%s%s.%i [@%i]%s' % (prefix, a.op, a.outputs.index(r), id(r), type_str)
print >> file, '%s%s.%i [@%i]%s \'%s\'' % (prefix, a.op, \ a.outputs.index(r), id(r), type_str, r_name)
def debugprint(r, prefix='', depth=-1, done=None, print_type=False, file=sys.stdout): """Print the graph leading to `r` to given depth. :param r: Variable instance :param prefix: prefix to each line (typically some number of spaces) :param depth: maximum recursion depth (Default -1 for unlimited). :param done: set of ...
nodelist = list(env.nodes)
nodelist = env.toposort()
def apply(self, env): did_something = True while did_something: nodelist = list(env.nodes) did_something = False for node in nodelist: if node.op == T._max_and_argmax: if len(node.outputs[1].clients)==0: try: axis=get_constant_value(node.inputs[1]) except ValueError: return False
for i, val in enumerate(node.outputs[0].type.broadcastable): if val: final_shape[i] = -1 rval = cuda_ndarray.cuda_ndarray.CudaNdarray.zeros_with_pattern(final_shape)
for i, bcastable in enumerate(node.outputs[0].type.broadcastable): assert not bcastable or final_shape[i] == 1, "Broadcastable dimension but dim != 1, this is invalid" rval = cuda_ndarray.cuda_ndarray.CudaNdarray.zeros(final_shape)
def perform(self, node, axis_and_tensors, (out, )): axis, cndas = axis_and_tensors[0], axis_and_tensors[1:]
CAReduce(maximum) -> sum
CAReduce(maximum) -> max
# def elemwise_to_scal(env):
if i.type.dtype=='float64':
if hasattr(i.type, 'dtype') and i.type.dtype=='float64':
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.
cval_i = get_constant_value(i) if all((not b for b in i.broadcastable)):
cval_i = get_constant_value(i) if all(i.broadcastable):
def local_upcast_elemwise_constant_inputs(node): """This explicitly upcasts constant inputs to elemwise Ops, when those Ops do implicit upcasting anyway. Rationale: it helps merge things like (1-x) and (1.0 - x). """ if len(node.outputs)>1: return try: shape_i = node.env.shape_feature.shape_i except AttributeError: sh...
unittest_tools.seed_rng()
from theano import tests as theano_tests theano_tests.unittest_tools.seed_rng()
def verify_grad(op, pt, n_tests=2, rng=None, eps=None, tol=None, mode=None, cast_to_output_type=False): """ WRITEME Raises an Exception if the difference between the analytic gradient and numerical gradient (computed through the Finite Difference Method) exceeds the given tolerance. :param op: something that behaves ...
for l in numpy.distutils.__config__.blas_opt_info['libraries'])
for l in numpy.distutils.__config__.blas_opt_info['libraries']+ '-L%s'%l for l in numpy.distutils.__config__.blas_opt_info['library_dirs'])
def default_blas_ldflags(): try: return ' '.join('-l%s'%l for l in numpy.distutils.__config__.blas_opt_info['libraries']) except: return "-lblas"
if __name__ == '__main__':
def mrg_random_make_inplace(node): op = node.op if isinstance(op, mrg_uniform) and not op.inplace: # op might be gpu version new_op = op.__class__(op.output_type, inplace=True) return new_op.make_node(*node.inputs).outputs return False
def __init__(self, node, idx, old_val, new_val):
def __init__(self, node, idx, old_val, new_val, perform):
def __init__(self, node, idx, old_val, new_val): super(BadDestroyMap, self).__init__() self.node = node self.idx = idx self.old_val = old_val self.new_val = new_val
def _check_inputs(node, storage_map, r_vals, dr_vals, active_nodes, clobber_dr_vals=True):
def _check_inputs(node, storage_map, r_vals, dr_vals, active_nodes, clobber_dr_vals=True, perform=None):
def _check_inputs(node, storage_map, r_vals, dr_vals, active_nodes, clobber_dr_vals=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(): destroyed_idx_list.extend(i_pos_list) destroyed_re...
raise BadDestroyMap(node, r_idx, r_vals[r], storage_map[r][0])
raise BadDestroyMap(node, r_idx, r_vals[r], storage_map[r][0], perform)
def _check_inputs(node, storage_map, r_vals, dr_vals, active_nodes, clobber_dr_vals=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(): destroyed_idx_list.extend(i_pos_list) destroyed_re...
clobber_dr_vals=True)
clobber_dr_vals=True, perform='py')
def f(): debug("starting a DebugMode call") for x in no_recycling: x[0] = None
clobber_dr_vals=False)
clobber_dr_vals=False, perform='c')
def f(): debug("starting a DebugMode call") for x in no_recycling: x[0] = None
assert isinstance(env.toposort()[2].op, tensor.MaxAndArgmax)
assert isinstance(env.toposort()[2].op, tensor.CAReduce) assert isinstance(env.toposort()[2].op.scalar_op, theano.scalar.Maximum)
def test_argmax_pushdown(): x = tensor.dmatrix() #test that the max_and_argmax is pushed down if the max is not used out = tensor.max_and_argmax(softmax(tensor.exp(tensor.tanh(sigmoid(x)))))[1] env = gof.Env( [x], [out]) theano.compile.mode.optdb.query( theano.compile.mode.OPT_FAST_RUN).optimize(env) #print 'AFTER' ...
assert isinstance(env.toposort()[1].op, tensor.MaxAndArgmax)
assert isinstance(env.toposort()[1].op, tensor.CAReduce) assert isinstance(env.toposort()[1].op.scalar_op, theano.scalar.Maximum)
def test_argmax_pushdown_bias(): x = tensor.dmatrix() b = tensor.dvector() out = tensor.argmax(softmax_with_bias(x, b)) env = gof.Env( [x,b], [out]) theano.compile.mode.optdb.query( theano.compile.mode.OPT_FAST_RUN).optimize(env) #print 'AFTER' #for node in env.toposort(): # print node.op assert len(env.toposort(...
new_node = host_from_gpu(gpu_alloc(val2, *shp)) return [new_node]
new_out = host_from_gpu(gpu_alloc(val2, *shp)) if new_out.type != old_out.type: assert new_out.type.ndim == old_out.type.ndim assert new_out.type.dtype == old_out.type.dtype for b_old,b_new in zip(old_out.type.broadcastable, new_out.type.broadcastable): assert b_new or (not b_old) new_out = tensor.patternbroadca...
def local_gpualloc(node): replace=False if node.op == tensor.alloc: if node.inputs[0].owner and node.inputs[0].owner.op==host_from_gpu:#if the input was on the gpu replace = True if all([c!='output' and c.op == gpu_from_host for c,idx in node.outputs[0].clients]):#if all clients are on gpu replace=True if all([c!='outp...
if gpu and out_dtype!='float32':
if gpu and (out_dtype!='float32' or any(i.dtype != 'float32' for i in g.owner.inputs)):
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
PyErr_SetString(PyExc_NotImplementedError, "expected an aligned array");
PyErr_Format(PyExc_NotImplementedError, "expected an aligned array of type %%d (%(type_num)s), got non-aligned array of type %%d", %(type_num)s, type_num_%(name)s);
def c_extract(self, name, sub): """Override `CLinkerOp.c_extract` """ # TODO: make the error message print out the dtype of the # input received. return """ %(name)s = NULL; if (py_%(name)s == Py_None) { // We can either fail here or set %(name)s to NULL and rely on Ops using // tensors to handle the NULL case, but if ...
type_num_%(name)s = ((PyArrayObject*)py_%(name)s)->descr->type_num; //we expect %(type_num)s
def c_extract(self, name, sub): """Override `CLinkerOp.c_extract` """ # TODO: make the error message print out the dtype of the # input received. return """ %(name)s = NULL; if (py_%(name)s == Py_None) { // We can either fail here or set %(name)s to NULL and rely on Ops using // tensors to handle the NULL case, but if ...
perform=None):
perform=None, warn_input_not_reused=True):
def _check_inputs(node, storage_map, r_vals, dr_vals, active_nodes, clobber_dr_vals=True, perform=None): """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(): destroyed_idx_list.extend(i_pos_list...
clobber_dr_vals=True, perform='py')
clobber_dr_vals=True, perform='py', warn_input_not_reused=config.DebugMode.warn_input_not_reused)
def f(): debug("starting a DebugMode call") for x in no_recycling: x[0] = None
clobber_dr_vals=clobber, perform='c')
clobber_dr_vals=clobber, perform='c', warn_input_not_reused=config.DebugMode.warn_input_not_reused)
def f(): debug("starting a DebugMode call") for x in no_recycling: x[0] = None
scal_name = 'maximum'
def _c_all(self, node, name, inames, onames, sub):
scal_name = 'minimum'
def _c_all(self, node, name, inames, onames, sub):
_logger.warning('ERROR (%s): '% ( _logger_name, ' '.join(str(m) for m in msg)))
_logger.warning('ERROR (%s): %s'% ( _logger_name, ' '.join(str(m) for m in msg)))
def error(*msg): _logger.warning('ERROR (%s): '% ( _logger_name, ' '.join(str(m) for m in msg)))
_logger.warning('WARNING (%s): '% ( _logger_name, ' '.join(str(m) for m in msg)))
_logger.warning('WARNING (%s): %s'% ( _logger_name, ' '.join(str(m) for m in msg)))
def warning(*msg): _logger.warning('WARNING (%s): '% ( _logger_name, ' '.join(str(m) for m in msg)))
_logger.warning('INFO (%s): '% ( _logger_name, ' '.join(str(m) for m in msg)))
_logger.warning('INFO (%s): %s'% ( _logger_name, ' '.join(str(m) for m in msg)))
def info(*msg): _logger.warning('INFO (%s): '% ( _logger_name, ' '.join(str(m) for m in msg)))
_logger.warning('DEBUG (%s): '% ( _logger_name, ' '.join(str(m) for m in msg)))
_logger.warning('DEBUG (%s): %s'% ( _logger_name, ' '.join(str(m) for m in msg)))
def debug(*msg): _logger.warning('DEBUG (%s): '% ( _logger_name, ' '.join(str(m) for m in msg)))
for arg in args:
for arg_index, arg in enumerate(args):
def __call__(self, *args, **kwargs): t0 = time.time()
e.args = tuple(list(e.args)+["Bad input argument at index %d"%(list(args).index(arg))])
e.args = tuple(list(e.args)+["Bad input argument at index %d" % arg_index])
def __call__(self, *args, **kwargs): t0 = time.time()
y_shape = (n_steps,)+args[i+n_seqs].shape[1:]
y_shape = (n_steps,)+arg_shape
def scan(self,fn, args, n_seqs, n_outs, seqs_taps, outs_taps, n_steps, go_backwards, inplace_map):
y_shape = args[i+n_seqs].shape[1:]
y_shape = arg_shape
def scan(self,fn, args, n_seqs, n_outs, seqs_taps, outs_taps, n_steps, go_backwards, inplace_map):
y_shape = (self.stored_steps_output[i],)+args[i+n_seqs].shape[1:]
y_shape = (self.stored_steps_output[i],)+arg_shape
def scan(self,fn, args, n_seqs, n_outs, seqs_taps, outs_taps, n_steps, go_backwards, inplace_map):
print 'perform args'
def perform(self, node, args, storage): print 'perform args' # get scan inputs n_steps = args[0]
print 'seqs' print seqs print 'outInfo' print outInfo print 'non_Seqs' print non_seqs
def perform(self, node, args, storage): print 'perform args' # get scan inputs n_steps = args[0]
print 'g_outs' print g_outs print 'outs' print outs print 'steps' print args[0]
def perform(self, node, args, storage): print 'perform args' # get scan inputs n_steps = args[0]
print 'g_seqs' print g_seqs print 'g_outInfo' print g_outInfo print 'g_non_seqs' print g_non_seqs
def perform(self, node, args, storage): print 'perform args' # get scan inputs n_steps = args[0]
mode = theano.compile.mode.get_default_mode().excluding("local_elemwise_fusion")
if theano.config.mode=='FAST_COMPILE': mode = theano.compile.mode.get_mode('FAST_RUN').excluding("local_elemwise_fusion") else: mode = theano.compile.mode.get_default_mode().excluding("local_elemwise_fusion")
def test_abs_mul_div(self): """ test that if we have 4 * x / abs(2*x) it get simplifier during canonicalisation. """
f(0)
def test_abs_mul_div(self): """ test that if we have 4 * x / abs(2*x) it get simplifier during canonicalisation. """
assert len(f.maker.env.toposort())==2 f=theano.function([x],[(4*x)/abs(2/x)], mode = mode)
if not isinstance(mode,theano.compile.debugmode.DebugMode): assert numpy.isfinite(f(0)) assert len(f.maker.env.toposort())==3 assert f.maker.env.toposort()[0].op==T.sgn f=theano.function([x],[(4*x)/abs(x/2)], mode = mode)
def test_abs_mul_div(self): """ test that if we have 4 * x / abs(2*x) it get simplifier during canonicalisation. """
assert f.maker.env.toposort()[0].op==T.abs_
assert f.maker.env.toposort()[0].op==T.sgn
def test_abs_mul_div(self): """ test that if we have 4 * x / abs(2*x) it get simplifier during canonicalisation. """
try: return get_constant_value(v) except TypeError: return None
if isinstance(v, Variable): try: return get_constant_value(v) except TypeError: return None else: return v
def get_constant(v): """ Returns a numeric constant if v is a gof.Constant or, well, a numeric constant. If v is a plain Variable, returns None. """ try: return get_constant_value(v) except TypeError: return None
if type(a) is not SparseVariable and type(a) is not SparseConstant:
if not _is_sparse_variable(a):
def make_node(self, a, b): if type(a) is not SparseVariable and type(a) is not SparseConstant: raise TypeError('First argument must be of type SparseVariable or SparseConstant'); dtype_out = scalar.upcast(a.type.dtype, b.type.dtype) if b.type.ndim != 2: raise NotImplementedError('non-matrix b') return gof.Apply(self, [...
if verbose:
if self.verbose:
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)
else: for client in var.clients: edge = pd.Edge(astr,apply_name(client[0])) g.add_edge(edge) g.set_simplify(True)
def apply_name(node): return str(node.op).replace(':','_')+' '+str(topo.index(node))
raise IndexError('cannot remove from empty deque')
raise ValueError('cannot remove from empty deque')
def remove(self, x): if self.left == self.right: raise IndexError('cannot remove from empty deque') for i in xrange(self.left, self.right-1): elem = self.data[i] if elem==x: self.__delitem__(i) break
if type(s_i) is int:
if type(s_i) is int or isinstance(s_i, numpy.integer):
def unpack(self, s_i): # unpack the s_i that the Op returned assert s_i is not None if s_i == 1: # don't make the optimizer merge a zillion ones together return self.lscalar_one if type(s_i) is int: # this shape is a constant assert s_i >= 0 return T.constant(s_i, dtype='int64') if type(s_i) in (tuple,list): # this dim...
assert isinstance(idx, old_idx)
assert idx.type == old_idx
def local_subtensor_make_vector(node): # replace all subtensor(make_vector) like: # [a,b,c][0] -> a # [a,b,c][0:2] -> [a,b] # we can do this for constant indexes if isinstance(node.op, T.Subtensor): shape_feature = node.env.shape_feature x = node.inputs[0] if x.owner and x.owner.op == make_vector: try: idx, = node.op.i...
f([[1,2],[3,4]],[5,6],[[[7,8],[9,10]],[[11,12],[13,14]]],15)
f(a_val, b_val, c_val, d_val)
def test_local_sum_div_dimshuffle(self): a = T.matrix('a') b = T.vector('b') c = T.tensor3('c') d = T.scalar('d') sums = [ sum(a/d), sum(a/d.dimshuffle('x','x')), sum(a/d.dimshuffle('x','x'), axis=0), sum(a/d.dimshuffle('x','x'), axis=1), sum(b/d), sum(b/d.dimshuffle('x')), sum(c/d), sum(c/d.dimshuffle('x','x','x')), s...
assert [node.op for node in f.maker.env.toposort()] == [sigmoid, T.inplace.neg_inplace]
assert len(f.maker.env.toposort())==1 assert str(f.maker.env.toposort()[0].op)=='Elemwise{Composite{scalar_sigmoid,neg}}'
def test_exp_over_1_plus_exp(self): m = theano.config.mode if m == 'FAST_COMPILE': m = 'FAST_RUN'
assert [node.op for node in f.maker.env.toposort()] == [sigmoid, T.mul, T.inplace.neg_inplace]
assert len(f.maker.env.toposort())==2 assert f.maker.env.toposort()[0].op == sigmoid assert str(f.maker.env.toposort()[1].op)=='Elemwise{Composite{mul,neg}}'
def test_exp_over_1_plus_exp(self): m = theano.config.mode if m == 'FAST_COMPILE': m = 'FAST_RUN'
a = theano.shared(_a) b = theano.shared(_b)
a = cuda_ndarray.shared_constructor(_a) b = cuda_ndarray.shared_constructor(_b)
def test_opt_gpujoin_onlyajoin(): # from a bug in normal sampling _a = numpy.asarray([[1,2],[3,4]],dtype='float32') _b = numpy.asarray([[5,6,7],[8,9,10]],dtype='float32') a = theano.shared(_a) b = theano.shared(_b) c = tensor.join(1,a,b) f = theano.function([], c) #theano.printing.debugprint(f) f() graph_nodes = f...
f = theano.function([], c)
f = theano.function([], c, mode=mode_with_gpu)
def test_opt_gpujoin_onlyajoin(): # from a bug in normal sampling _a = numpy.asarray([[1,2],[3,4]],dtype='float32') _b = numpy.asarray([[5,6,7],[8,9,10]],dtype='float32') a = theano.shared(_a) b = theano.shared(_b) c = tensor.join(1,a,b) f = theano.function([], c) #theano.printing.debugprint(f) f() graph_nodes = f...
a = theano.shared(_a) b = theano.shared(_b)
a = cuda_ndarray.shared_constructor(_a) b = cuda_ndarray.shared_constructor(_b)
def test_opt_gpujoin_joinvectors_elemwise_then_minusone(): # from a bug in gpu normal sampling _a = numpy.asarray([1,2,3,4],dtype='float32') _b = numpy.asarray([5,6,7,8],dtype='float32') a = theano.shared(_a) b = theano.shared(_b) a_prime = tensor.cos(a) b_prime = tensor.sin(b) c = tensor.join(0,a_prime,b_prime) d =...
f = theano.function([], d)
f = theano.function([], d, mode=mode_with_gpu)
def test_opt_gpujoin_joinvectors_elemwise_then_minusone(): # from a bug in gpu normal sampling _a = numpy.asarray([1,2,3,4],dtype='float32') _b = numpy.asarray([5,6,7,8],dtype='float32') a = theano.shared(_a) b = theano.shared(_b) a_prime = tensor.cos(a) b_prime = tensor.sin(b) c = tensor.join(0,a_prime,b_prime) d =...
not isinstance(i,gof.Constant)
not isinstance(i,graph.Constant)
def fast_inplace_check(inputs): """ Return the variables in inputs that are posible candidate for as inputs of inplace operation :type inputs: list :param inputs: inputs Variable that you want to use as inplace destination """ env = inputs[0].env protected_inputs = [f.protected for f in env._features if isinstance(f,t...
^ hash(self.version)
^ self.version
def __hash__(self): 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) \ ^ hash(self.version)
cmd.extend(config.gcc.cxxflags.split(' '))
if config.gcc.cxxflags: cmd.extend(config.gcc.cxxflags.split(' '))
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...
if True:
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...
import pdb;pdb.set_trace()
def get_default_mode(): global instanciated_default_mode if config.mode in ['Mode','ProfileMode','DebugMode']: if instanciated_default_mode: return instanciated_default_mode #need to import later to break circular dependency. from profilemode import ProfileMode,prof_mode_instance_to_print from debugmode import DebugMod...
require_matching_strides=None):
require_matching_strides=None, linker=None):
def __init__(self, optimizer='fast_run', stability_patience=None, check_c_code=None, check_py_code=None, check_isfinite=None, require_matching_strides=None): """Initialize member variables.
return (7,)
return (8,)
def c_code_cache_version(self): #return () return (7,)
buf[threadNum] = mysum; __syncthreads(); // rest of function is handled by one warp if (threadNum < warpSize) { for (int i = threadNum + warpSize; i < threadCount; i += warpSize) { mysum += buf[i]; } buf[threadNum] = mysum; if (threadNum < 16) { //reduce so that threadNum 0 has the sum of everything if(threadNum + 16 ...
%(reducebuf)s
def c_support_code_apply(self, node, nodename): sio = StringIO.StringIO() if self.reduce_mask == (1,): #this kernel is ok for up to a few thousand elements, but # it only runs on ONE multiprocessor print >> sio, """ static __global__ void kernel_reduce_sum_1_%(nodename)s( const unsigned int d0, const float *A, const in...
== [inplace.log1p_inplace, alloc]
== [T.log1p, alloc]
def test_log1p(): m = theano.config.mode if m == 'FAST_COMPILE': m = 'FAST_RUN' m = compile.mode.get_mode(m) m = m.excluding('fusion') # 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) ...
if os.path.join(config.compiledir,'cuda_ndarray','cuda_ndarray.so')!=cuda_ndarray.cuda_ndarray.__file__: _logger.warning("WARNING: cuda_ndarray was loaded from",cuda_ndarray.cuda_ndarray.__file__,"This is not expected as theano should compile it automatically for you. Do you have a directory called cuda_ndarray in your...
from theano.gof.cmodule import get_lib_extension if os.path.join(config.compiledir,'cuda_ndarray','cuda_ndarray.'+get_lib_extension())!=cuda_ndarray.cuda_ndarray.__file__: warning("WARNING: cuda_ndarray was loaded from",cuda_ndarray.cuda_ndarray.__file__,"This is not expected as theano should compile it automatically ...
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...
else if (threadNum < 16)
else */ if (threadNum < 16)
def _k_reduce_buf(self, z_pos): return """ buf[threadNum] = mysum; __syncthreads();
return (10,)
return (11,)
def c_code_cache_version(self): #return () return (10,)