rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
ff = theano.function([], nn)
ff = theano.function([], nn, 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...
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(self): dtype = self.dtype if dtype is None: dtype = theano.config.floatX
assert len(topo_cst)==0
if theano.config.mode!='FAST_COMPILE': assert len(topo_cst)==0
def test_specify_shape(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(self): dtype = self.dtype if dtype is None: dtype = theano.config.floatX
assert sum([isinstance(node.op,tensor.blas.Gemm) or node.op.__class__.__name__=="GpuGemm"for node in topo])==1 assert all(node.op == tensor.blas.gemm_inplace for node in topo if isinstance(node.op,tensor.blas.Gemm))
if theano.config.mode!='FAST_COMPILE': assert sum([node.op.__class__.__name__ in ["Gemm","GpuGemm","StructuredDot"] for node in topo])==1 assert all(node.op == tensor.blas.gemm_inplace for node in topo if isinstance(node.op,tensor.blas.Gemm)) assert all(node.op.inplace for node in topo if node.op.__class__.__name__ == ...
def test_specify_shape_inplace(self): #test that specify_shape don't break inserting inplace op
debug(i, "DEBUGMODE running thunk_py")
def f(): debug("starting a DebugMode call") for x in no_recycling: x[0] = None
out[0] = variable
out[0] = theano._asarray(variable, str(variable.dtype))
def perform(self, node, (a,b), (out,)): if a.shape[1] != b.shape[0]: raise ValueError('shape mismatch in StructuredDot.perform', (a.shape, b.shape))
f = function([n], tensor.max_and_argmax(n,0)[0])
f = function([n], tensor.max_and_argmax(n,0)[0], mode=mode)
def test_optimization(self): #If we use only the max output, we should replace this op with a faster one. data = numpy.asarray(numpy.random.rand(2,3),dtype=config.floatX) n = tensor.matrix()
f = function([n], tensor.max_and_argmax(n,0))
f = function([n], tensor.max_and_argmax(n,0), mode=mode)
def test_optimization(self): #If we use only the max output, we should replace this op with a faster one. data = numpy.asarray(numpy.random.rand(2,3),dtype=config.floatX) n = tensor.matrix()
f = function([n],tensor.max(n,0))
f = function([n],tensor.max(n,0), mode=self.mode)
def test_optimization_max(self): data = numpy.asarray(numpy.random.rand(2,3),dtype=config.floatX) n = tensor.matrix()
f = function([n],tensor.max(-n,0))
f = function([n],tensor.max(-n,0), mode=self.mode)
def test_optimization_max(self): data = numpy.asarray(numpy.random.rand(2,3),dtype=config.floatX) n = tensor.matrix()
f = function([n],-tensor.max(n,0))
f = function([n],-tensor.max(n,0), mode=self.mode)
def test_optimization_max(self): data = numpy.asarray(numpy.random.rand(2,3),dtype=config.floatX) n = tensor.matrix()
f = function([n],-tensor.max(-n,0))
f = function([n],-tensor.max(-n,0), mode=self.mode)
def test_optimization_max(self): data = numpy.asarray(numpy.random.rand(2,3),dtype=config.floatX) n = tensor.matrix()
f = function([n],tensor.min(n,0))
f = function([n],tensor.min(n,0), mode=self.mode)
def test_optimization_min(self): data = numpy.asarray(numpy.random.rand(2,3),dtype=config.floatX) n = tensor.matrix()
f = function([n],tensor.min(-n,0))
f = function([n],tensor.min(-n,0), mode=self.mode)
def test_optimization_min(self): data = numpy.asarray(numpy.random.rand(2,3),dtype=config.floatX) n = tensor.matrix()
f = function([n],-tensor.min(n,0))
f = function([n],-tensor.min(n,0), mode=self.mode)
def test_optimization_min(self): data = numpy.asarray(numpy.random.rand(2,3),dtype=config.floatX) n = tensor.matrix()
f = function([n],-tensor.min(-n,0))
f = function([n],-tensor.min(-n,0), mode=self.mode)
def test_optimization_min(self): data = numpy.asarray(numpy.random.rand(2,3),dtype=config.floatX) n = tensor.matrix()
@gof.local_optimizer([T.Alloc])
@gof.local_optimizer([T.Elemwise])
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...
if not isinstance(mode,ProfileMode):
if not isinstance(mode,ProfileMode) or not mode.fct_call.has_key(fct):
def pydotprint(fct, outfile=os.path.join(config.compiledir,'theano.pydotprint.png'), compact=True, mode=None): """ print to a file in png format the graph of op of a compile theano fct. :param fct: the theano fct returned by theano.function. :param outfile: the output file where to put the graph. :param compact: if Tr...
def __str__(self): return self.__class__.__name__
def make_node(self, input): input = as_cuda_ndarray_variable(input) return Apply(self, [input], [input.type()])
y = y[0]
try: y = y[0] except IndexError: pass
def local_pow_specialize_device(node): """ This optimization is not the same on all device. We do it only on cpu here. """ if node.op == T.pow: #the idea here is that we have pow(x, y) odtype = node.outputs[0].dtype xsym = node.inputs[0] ysym = node.inputs[1] y = local_mul_canonizer.get_constant(ysym) #the next line i...
_logger.debug(' '.join(msg))
_logger.debug(' '.join([ str(x) for x in msg]))
def _debug(*msg): _logger.debug(' '.join(msg))
_logger.warn(' '.join(msg))
_logger.warn(' '.join([ str(x) for x in msg]))
def _warn(*msg): _logger.warn(' '.join(msg))
"""
"""% d
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)
global cuda_enabled
global cuda_enabled, cuda_initialization_error_message
def use(device, force=False): global cuda_enabled if force and not cuda_available and device.startswith('gpu'): raise EnvironmentError("You forced use of device %s, but CUDA initialization failed " "with error:\n%s" % (device, cuda_initialization_error_message)) if not cuda_available: warning('CUDA is installed, but de...
(theano.tensor.pow(fx*fy+fz,fx*fy),(fx,fy,fz),(fxv,fyv,fzv),2,numpy.power(fxv*fyv+fzv,fxv*fyv),'float32'),
(theano.tensor.pow(fx*fy+fz,fx*fy),(fx,fy,fz),(fxv,fyv,fzv),1,numpy.power(fxv*fyv+fzv,fxv*fyv),'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
dim3 n_blocks(CudaNdarray_HOST_DIMS(%(x)s)[0]);
dim3 n_blocks(std::min(CudaNdarray_HOST_DIMS(%(x)s)[0],NUM_VECTOR_OP_BLOCKS));
def c_code_reduce_01X(self, sio, node, name, x, z, fail, N): """ :param N: the number of 1 in the pattern N=1 -> 01, N=2 -> 011 N=3 ->0111 Work for N=1,2,3 """ assert N in [1,2,3] makecall = self._makecall(node, name, x, z, fail) N_pattern = ''.join(['1']*N) param_dim = ",".join(["CudaNdarray_HOST_DIMS(%(x)s)[%(i)s]"%l...
@gof.local_optimizer([None, None]) def local_shape_i_lift(node): """ "Lifts" DimShuffle through Elemwise operations and merges consecutive DimShuffles. Basically, applies the following transformations on the whole graph: DimShuffle(Elemwise(x, y)) => Elemwise(DimShuffle(x), DimShuffle(y)) DimShuffle(DimShuffle(x)) => ...
def apply(self, env): pass
print >> sys.stderr, "REPLACING SOMETHING", replacement, shape_feature.shape_of[replacement]
def local_track_shape_i(node): try: shape_feature = node.env.shape_feature except: return if node in shape_feature.scheduled: assert isinstance(node.op, Shape_i) replacement = shape_feature.scheduled[node] #if len(shape_feature.shape_of[replacement])!=1: #import pdb;pdb.set_trace() print >> sys.stderr, "REPLACING SOMET...
updated_env_inputs = [env_i for i, env_i in zip(inputs, env.inputs) if getattr(i, 'update', False)] for i in xrange(len(env.outputs)):
updated_env_inputs = [env_i for ii, env_i in zip(inputs, env.inputs) if getattr(ii, 'update', False)] for out_i in xrange(len(env.outputs)):
def __init__(self, inputs, outputs, optimizer, mode, accept_inplace = False, function_builder = Function): """ :type inputs: a list of SymbolicInput instances
view_tree_set(alias_root(env.outputs[i]), views_of_output_i)
view_tree_set(alias_root(env.outputs[out_i]), views_of_output_i)
def __init__(self, inputs, outputs, optimizer, mode, accept_inplace = False, function_builder = Function): """ :type inputs: a list of SymbolicInput instances
for j in xrange(i+1, len(env.outputs)):
for j in xrange(out_i+1, len(env.outputs)):
def __init__(self, inputs, outputs, optimizer, mode, accept_inplace = False, function_builder = Function): """ :type inputs: a list of SymbolicInput instances
env.change_input('output', i, deep_copy_op(env.outputs[i]))
env.change_input('output', out_i, deep_copy_op(env.outputs[out_i]))
def __init__(self, inputs, outputs, optimizer, mode, accept_inplace = False, function_builder = Function): """ :type inputs: a list of SymbolicInput instances
if 0:
if 1:
def assert_optimizer_worked(expr): f = theano.function([x,y], expr, mode='FAST_RUN') if 0: for i, node in enumerate(f.maker.env.toposort()): print i, node f(x_val, y_val) assert len(f.maker.env.toposort()) == 4
assert len(g.maker.env.toposort()) == 2
assert len(f.maker.env.toposort()) == 2
def assert_optimizer_worked(expr): f = theano.function([x,y], expr, mode='FAST_RUN') if 0: for i, node in enumerate(f.maker.env.toposort()): print i, node f(x_val, y_val) assert len(f.maker.env.toposort()) == 4
assert no_broad_idx>0
assert no_broad_idx>=0
def local_alloc_elemwise(node): """ elemwise(alloc(x, shp), ..., y.TensorType(BROADCAST CONDITION)) -> elemwise(x, y.TensorType(no broadcast flag)) elemwise(dimshuffle(alloc(x, shp)),... ,y.TensorType(BROADCAST CONDITION)) -> elemwise(x, y.TensorType(no broadcast flag)) BROADCAST CONDITION: the condition is that the ...
xshp, ind1shp, ind2shp = ishapes return [ind2shp]
if len(ishapes) == 3: xshp, ind1shp, ind2shp = ishapes if len(xshp) == 2 and len(ind1shp) == 1 and len(ind2shp) == 1: if node.inputs[2].owner is None: return [ind2shp] else: return [ind1shp] return node.env.shape_feature.default_infer_shape(node, ishapes)
def infer_shape(self, node, ishapes): xshp, ind1shp, ind2shp = ishapes return [ind2shp]
if axis == ():
if len(axis) == 0:
def _c_all(self, node, name, inames, onames, sub):
version = [2]
version = [3]
def c_code_cache_version_apply(self, node): version = [2] # the version corresponding to the c code in this Op
if device=="-1" or device=="CPU":
if device<0:
def use(device=config.device): if device.startswith('gpu'): device = int(device[3:]) elif device == 'cpu': device = -1 else: raise ValueError("Invalid device identifier", device) if use.device_number is None: # No successful call to use() has been made yet if device=="-1" or device=="CPU": return if device in [None,""]...
debug("starting f")
debug("starting a DebugMode call")
def f(): debug("starting f") for x in no_recycling: x[0] = None
thunk_c()
try: thunk_c() except: raise_with_op(node)
def f(): debug("starting f") for x in no_recycling: x[0] = None
from theano.tensor import TensorType TensorType.filter_checks_isfinite = mode.check_isfinite
def __init__(self, inputs, outputs, optimizer, mode, accept_inplace = False, function_builder = Function): """ :type inputs: a list of SymbolicInput instances
import pdb;pdb.set_trace()
def __call__(self, *inputs, **kwargs): """ Don't generate alloc that do nothing. If you always want an Alloc node, call make_node. """ ret = super(Alloc,self).__call__(*inputs,**kwargs) import pdb;pdb.set_trace() if inputs[0].type == ret.type: return inputs[0] else: return ret
node.tag.trace = traceback.extract_stack(limit=limit)[:-1] r.tag.trace = traceback.extract_stack(limit)[:-1]
r.tag.trace = traceback.extract_stack(limit=limit)[:-1]
def __call__(self, name = None): """Return a new `Variable` instance of Type `self`.
T.inplace.neg_inplace]
theano.tensor.inplace.neg_inplace]
def test_exp_over_1_plus_exp(self): m = theano.config.mode if m == 'FAST_COMPILE': m = 'FAST_RUN' m = theano.compile.mode.get_mode(m) m = m.excluding('local_elemwise_fusion')
T.mul, T.inplace.neg_inplace]
T.mul, theano.tensor.inplace.neg_inplace]
def test_exp_over_1_plus_exp(self): m = theano.config.mode if m == 'FAST_COMPILE': m = 'FAST_RUN' m = theano.compile.mode.get_mode(m) m = m.excluding('local_elemwise_fusion')
and abs(a-b).sum() < (1e-6 * a.nnz)
and ((abs(a-b).sum() < (1e-6 * a.nnz)) or (a.nnz==0 and b.nnz==0))
def values_eq_approx(self, a, b, eps=1e-6): #WARNING: equality comparison of sparse matrices is not fast or easy # we definitely do not want to be doing this un-necessarily during # a FAST_RUN computation.. return scipy.sparse.issparse(a) \ and scipy.sparse.issparse(b) \ and abs(a-b).sum() < (1e-6 * a.nnz)
if isinstance(num[0], gof.Variable): return num[0] else: return T.as_tensor_variable(num[0])
assert isinstance(num[0], gof.Variable) return num[0]
def merge_num_denum(self, num, denum): """ Utility function which takes two lists, num and denum, and returns something which is equivalent to inverse(main(*num), main(*denum)), but depends on the length of num and the length of denum (in order to minimize the number of operations).
if orig_num and len(numct) == 1 and len(denumct) == 0 and ct and N.all(ct == self.get_constant(orig_num[0])):
ct = [T.constant(c, dtype=out_type.dtype) for c in ct] if orig_num and len(numct) == 1 and len(denumct) == 0 and ct and\ N.all([c.data for c in ct] == self.get_constant(orig_num[0])):
def simplify_constants(self, orig_num, orig_denum): """
if num: first = num[0] else: first = denum[0] one = N.asarray(first).dtype.type(1)
out_dtype = scalar.upcast(*[v.dtype for v in (num+denum)])
def mul_calculate(num, denum, aslist=False, out_type=None): if not num and not denum: # Smallest 1 possible. if aslist: return [] else: return N.int8(1) #return [] if aslist else N.int8(1) # Make sure we do not accidently upcast data types. if out_type is None: # TODO: remove this error-causing heuristic if num: first...
one = theano._asarray(1, dtype=out_type.dtype)
out_dtype = out_type.dtype one = theano._asarray(1, dtype=out_dtype)
def mul_calculate(num, denum, aslist=False, out_type=None): if not num and not denum: # Smallest 1 possible. if aslist: return [] else: return N.int8(1) #return [] if aslist else N.int8(1) # Make sure we do not accidently upcast data types. if out_type is None: # TODO: remove this error-causing heuristic if num: first...
'''sum(a / dimshuffle{...}(b), axis=l) -> sum(a, axis=l) / b,
'''sum(a / dimshuffle{...}(b), axis=l) -> sum(a, axis={...}) / b,
def local_sum_div_dimshuffle(node): '''sum(a / dimshuffle{...}(b), axis=l) -> sum(a, axis=l) / b, if dimension l of the DimShuffle is 'x'.''' # TODO: extend it to product, and quotient of products if isinstance(node.op, T.Sum): axis = node.op.axis if axis is None: axis = range(node.inputs[0].ndim) #print 'axis =', axi...
if isinstance(numerator.owner.op, T.DimShuffle):
if numerator.owner and isinstance(numerator.owner.op, T.DimShuffle):
def local_sum_div_dimshuffle(node): '''sum(a / dimshuffle{...}(b), axis=l) -> sum(a, axis=l) / b, if dimension l of the DimShuffle is 'x'.''' # TODO: extend it to product, and quotient of products if isinstance(node.op, T.Sum): axis = node.op.axis if axis is None: axis = range(node.inputs[0].ndim) #print 'axis =', axi...
if isinstance(denominator.owner.op, T.DimShuffle):
if denominator.owner and isinstance(denominator.owner.op, T.DimShuffle):
def local_sum_div_dimshuffle(node): '''sum(a / dimshuffle{...}(b), axis=l) -> sum(a, axis=l) / b, if dimension l of the DimShuffle is 'x'.''' # TODO: extend it to product, and quotient of products if isinstance(node.op, T.Sum): axis = node.op.axis if axis is None: axis = range(node.inputs[0].ndim) #print 'axis =', axi...
and self.version
and self.version == other.version
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...
_log("return imshp!=imshp_logical or self.kshp != self.kshp_logical shape version")
_debug("return imshp!=imshp_logical or self.kshp != self.kshp_logical shape version")
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)
_log("return unroll patch version. all_shape=", all_shape)
_debug("return unroll patch version. all_shape=", 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)
_debug("return unrolled batch (%i) and kern code (%i)", self.unroll_batch, self.unroll_kern)
_debug("return unrolled batch (%s) and kern code (%s)", str(self.unroll_batch), str(self.unroll_kern))
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)
:returns: str if `file`=='str', else file arg
:returns: string if `file` == 'str', else file arg
def debugprint(obj, depth=-1, print_type=False, file=None): """Print a computation graph to file :type obj: Variable, Apply, or Function instance :param obj: symbolic thing to print :type depth: integer :param depth: print graph to this depth (-1 for unlimited) :type print_type: boolean :param print_type: wether to pr...
imshp = imshp[1:]
imshp = image_shape[1:]
def conv2d(input, filters, border_mode='valid', subsample=(1,1), image_shape=None, filter_shape=None, **kargs): """ This function returns an instanciated ConvOp through a simple interface. We do this instead of changing the ConvOp interface so as not to change previous code based on the ConvOp. :type input: symbolic 4...
print 'imshp = ', imshp print 'kshp = ', kshp print 'nkern = ', nkern print 'bsize = ', bsize
def conv2d(input, filters, border_mode='valid', subsample=(1,1), image_shape=None, filter_shape=None, **kargs): """ This function returns an instanciated ConvOp through a simple interface. We do this instead of changing the ConvOp interface so as not to change previous code based on the ConvOp. :type input: symbolic 4...
imval = rng.rand(4,7)
imval = rng.rand(4,5)
def test_max_pool2D_2D(self): rng = numpy.random.RandomState(utt.fetch_seed())
assert len(topo)==0
assert len(topo)==1 assert topo[0].op==theano.compile.function_module.deep_copy_op
def test1(self): #remove assert that are always true mode = theano.config.mode if mode == 'FAST_COMPILE': mode = 'FAST_RUN' mode = compile.mode.get_mode(mode)
assert len(topo)==1
assert len(topo)==2
def test2(self): #remove assert condition that are always true mode = theano.config.mode if mode == 'FAST_COMPILE': mode = 'FAST_RUN' mode = compile.mode.get_mode(mode)
assert len(topo)==1
assert len(topo)==2
def test3(self): #don't remove assert condition that are always false mode = theano.config.mode if mode == 'FAST_COMPILE': mode = 'FAST_RUN' mode = compile.mode.get_mode(mode)
assert nodes == []
nodes == [theano.compile.function_module.deep_copy_op]
def test_local_mul_specialize(): # test a few cases to make sure that the basics are covered # mode = theano.config.mode if mode == 'FAST_COMPILE': mode = 'FAST_RUN' mode = compile.mode.get_mode(mode) mode = mode.excluding('fusion') v = T.vector() m = T.vector() f = function([v,m], v*1, mode=mode) nodes = [node.op ...
assert nodes == []
nodes == [theano.compile.function_module.deep_copy_op]
def test_local_pow_specialize(): # test a few cases to make sure that the basics are covered # mode = theano.config.mode if mode == 'FAST_COMPILE': mode = 'FAST_RUN' mode = compile.mode.get_mode(mode) mode = mode.excluding('fusion') v = T.vector() val = numpy.arange(10,dtype=theano.config.floatX) val_no0 = numpy.ara...
assert len(topo)==0
assert len(topo)==1 assert topo[0].op==theano.compile.function_module.deep_copy_op
def test_mul(self): x=T.dmatrix() y=T.dmatrix() f=theano.function([x],T.mul(x), mode=self.mode) vx=numpy.random.rand(5,4) vy=numpy.random.rand(5,4) f(vx) topo = f.maker.env.toposort() assert len(topo)==0 f2=theano.function([x,y],T.mul(x,y), mode=self.mode) assert numpy.all(f2(vx,vy)==vx*vy) topo2 = f2.maker.env.toposor...
assert len(topo)==0
assert len(topo)==1 assert topo[0].op==theano.compile.function_module.deep_copy_op
def test_add(self): x=T.dmatrix() y=T.dmatrix() f=theano.function([x],T.add(x), mode=self.mode) vx=numpy.random.rand(5,4) vy=numpy.random.rand(5,4) f(vx) topo = f.maker.env.toposort() assert len(topo)==0 f2=theano.function([x,y],T.add(x,y), mode=self.mode) assert numpy.all(f2(vx,vy)==vx+vy) topo2 = f2.maker.env.toposor...
assert len(o_shapes) == len(node.outputs)
if len(o_shapes) != len(node.outputs): raise Exception('len(o_shapes) = '+str(len(o_shapes))+' != len(node.outputs) = '+str(len(node.outputs)))
def on_import(self, env, node): if node.outputs[0] in self.shape_of: # this is a revert, not really an import for r in node.outputs + node.inputs: assert r in self.shape_of return
return numpy.max(errs), numpy.argmax(errs)
if numpy.all(numpy.isfinite(errs)): return numpy.max(errs), numpy.argmax(errs) else: return float('inf'), 0
def max_err(self, g_pt): """Return the biggest relative error between g_pt and self.gf""" if len(g_pt) != len(self.gf): raise ValueError('argument has wrong number of elements', len(g_pt)) errs = [] for i, (a, b) in enumerate(zip(g_pt, self.gf)): if a.shape != b.shape: raise ValueError('argument element %i has wrong sh...
cmp = numpy_values == theano_values assert numpy.all(cmp)
assert numpy.allclose(numpy_values,theano_values)
def f_pow2(x_tm1): return 2*x_tm1
if v.owner.inputs[0].owner and isinstance(v.owner.inputs[0].owner.op, Join):
if (v.owner.inputs[0].owner and isinstance(v.owner.inputs[0].owner.op, Join) and all(var.ndim==0 for var in v.owner.inputs[0].owner.inputs)): assert len(v.owner.op.idx_list) == 1
def get_constant_value(v): """return the constant scalar(0-D) value underlying variable `v` If v is the output of dimshuffles, fills, allocs, rebroadcasts, cast this function digs through them. If `v` is not some view of constant data, then raise a TypeError. :note: There may be another function similar to this one ...
return numpy.asarray(ret, dtype=v.type.dtype)
return theano._asarray(ret, dtype=v.type.dtype)
def get_constant_value(v): """return the constant scalar(0-D) value underlying variable `v` If v is the output of dimshuffles, fills, allocs, rebroadcasts, cast this function digs through them. If `v` is not some view of constant data, then raise a TypeError. :note: There may be another function similar to this one ...
changed = False rval2 = theano.tensor.opt.local_useless_rebroadcast.transform(rval.owner) if rval2: assert len(rval2)==1 rval = rval2[0] changed = True if rval.owner: rval2 = theano.tensor.opt.local_rebroadcast_lift.transform(rval.owner)
changed = False rval2 = theano.tensor.opt.local_useless_rebroadcast.transform(rval.owner)
def apply_rebroadcast_opt(rval): """ Apply as many times as required the optimization local_useless_rebroadcast and local_rebroadcast_lift. :param rval: a Variable :retrun: a Variable. The same if not optimisation can be applied. """ changed = True while changed and rval.owner: changed = False rval2 = theano.tensor.o...
assert len(rval2)==1 rval = rval2[0] changed = True
assert len(rval2)==1 rval = rval2[0] changed = True if rval.owner: rval2 = theano.tensor.opt.local_rebroadcast_lift.transform(rval.owner) if rval2: assert len(rval2)==1 rval = rval2[0] changed = True
def apply_rebroadcast_opt(rval): """ Apply as many times as required the optimization local_useless_rebroadcast and local_rebroadcast_lift. :param rval: a Variable :retrun: a Variable. The same if not optimisation can be applied. """ changed = True while changed and rval.owner: changed = False rval2 = theano.tensor.o...
if (mode == FULL) { dim_zz[0] = (int)ceil((dim_im[0]+dim_ker[0]-1)/float(%(self_dx)s)); dim_zz[1] = (int)ceil((dim_im[1]+dim_ker[1]-1)/float(%(self_dy)s)); } else { dim_zz[0] = (int)ceil((dim_im[0]-dim_ker[0]+1)/float(%(self_dx)s)); dim_zz[1] = (int)ceil((dim_im[1]-dim_ker[1]+1)/float(%(self_dy)s)); }
%(dim_zz_affect)s
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"
print 'asdfasdf'
def local_dot_to_dot22(node): if node.op != T.dot: return x,y = node.inputs if y.type.dtype != x.type.dtype: # TODO: upcast one so the types match info('Not optimizing dot with inputs', x, y, x.type, y.type) return print 'asdfasdf' if y.type.dtype.startswith('float'): if _is_real_matrix(x) and _is_real_matrix(y): retu...
r = numpy.int32(numpy.int64(a*b + c) % m)
r = numpy.int32((numpy.int64(a)*b + c) % m)
def mulmod(a, b, c, m): r = numpy.int32(numpy.int64(a*b + c) % m) return r if r >= 0 else r+m
print >> sys.stderr, 'SCHEDULING SOMETHING', self.scheduled
def on_change_input(self, env, node, i, r, new_r): # TODO: # This tells us that r and new_r must have the same shape # if we didn't know that the shapes are related, now we do.
print>> sys.stderr, 'UNSCHEDULING SOMETHING', self.scheduled
def on_change_input(self, env, node, i, r, new_r): # TODO: # This tells us that r and new_r must have the same shape # if we didn't know that the shapes are related, now we do.
if len(node.env.shape_feature.shape_of[replacement])!=1: import pdb;pdb.set_trace() print >> sys.stderr, "REPLACING SOMETHING", replacement, node.env.shape_feature.shape_of[replacement]
def local_track_shape_i(node): try: shape_feature = node.env.shape_feature except: return if node in node.env.shape_feature.scheduled: assert isinstance(node.op, Shape_i) replacement = node.env.shape_feature.scheduled[node] if len(node.env.shape_feature.shape_of[replacement])!=1: import pdb;pdb.set_trace() print >> sys...
varstr = '%s [%s]'% (str(var.data) , str(var.type))
dstr = str(var.data) if '\n' in dstr: dstr = dstr[:dstr.index('\n')] if len(dstr) > 30: dstr = dstr[:27]+'...' varstr = '%s [%s]'% (dstr, str(var.type))
def var_name(var): if var in var_str: return var_str[var] if var.name is not None: varstr = var.name elif isinstance(var,gof.Constant): varstr = '%s [%s]'% (str(var.data) , str(var.type)) elif var in input_update and input_update[var].variable.name is not None: varstr = input_update[var].variable.name else: #a var id ...
preargs.extend(['-m{0}'.format(n_bits)]) debug("OS X: compiling for {0} bit architecture".format(n_bits))
preargs.extend(['-m%s' % n_bits]) debug("OS X: compiling for %s bit architecture" % 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...
BoolParam(True))
BoolParam(default_warn))
def warning(*msg): _logger.warning('WARNING theano.configdefaults: '+' '.join(msg))
import pdb;pdb.set_trace()
def may_share_memory(a,b): import pdb;pdb.set_trace() #when this is called with a an ndarray and b #a sparce matrix, numpy.may_share_memory fail. if a.__class__ is b.__class__: return numpy.may_share_memory(a,b) else: return False
return ' '.join('-l%s'%l for l in numpy.distutils.__config__.blas_opt_info['libraries']+ '-L%s'%l for l in numpy.distutils.__config__.blas_opt_info['library_dirs']) except:
return ' '.join( ['-l%s'%l for l in numpy.distutils.__config__.blas_opt_info['libraries']]) except KeyError:
def default_blas_ldflags(): try: return ' '.join('-l%s'%l for l in numpy.distutils.__config__.blas_opt_info['libraries']+ '-L%s'%l for l in numpy.distutils.__config__.blas_opt_info['library_dirs']) except: return "-lblas"
[tensor.max(softmax(tensor.exp(tensor.tanh(sigmoid(x)))))])
[tensor.argmax(softmax(tensor.exp(tensor.tanh(sigmoid(x)))))])
def test_argmax_pushdown(): x = tensor.dmatrix() env = gof.Env( [x], [tensor.max(softmax(tensor.exp(tensor.tanh(sigmoid(x)))))]) 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()) == 2 # an output_guar...
[tensor.max(softmax_with_bias(x, b))])
[tensor.argmax(softmax_with_bias(x, b))])
def test_argmax_pushdown_bias(): x = tensor.dmatrix() b = tensor.dvector() env = gof.Env( [x,b], [tensor.max(softmax_with_bias(x, b))]) 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()) == 4 assert isins...
print 'NEW INPUTS', new_inputs
def local_fill_cut(node): """ f(fill(a,b), c) -> f(b, c) If c.type == a.type. """ # this optimization is essentially for getting broadcasting to replace fill. # This is always possible when using a Compound Elemwise operation, # but it is not always possible without one (consider filling a large matrix with a scalar, ...
_cmp(numpy.asarray(_a[1]), a[1]) _cmp(numpy.asarray(_a[-1]), a[-1])
def _cmpfV(x,*y): try: if len(y)==1: x.__getitem__(*y) else: x.__getitem__(y)
exp = [(1,100000),(1e1,100000),(1e2,100000),(1e3,100000), (5e3,50000),
exp = [(1e3,100000),(5e3,50000), \
def exec_timeit_2vector(expr, nb_call_scal=1, fname=None, do_unalign=False, do_amd=True): time=[] exp = [(1,100000),(1e1,100000),(1e2,100000),(1e3,100000), (5e3,50000), (1e4,10000),(5e4,5000),(1e5,2000),(1e6,200),(1e7,10) ] for nb_e, nb_c in exp: time.append(timeit_2vector(nb_element=nb_e, nb_repeat=3, nb_call=nb_c*nb...
pylab.xlabel('Nb element')
pylab.xlabel('Dimension of real valued vectors a and b')
def exec_timeit_2vector(expr, nb_call_scal=1, fname=None, do_unalign=False, do_amd=True): time=[] exp = [(1,100000),(1e1,100000),(1e2,100000),(1e3,100000), (5e3,50000), (1e4,10000),(5e4,5000),(1e5,2000),(1e6,200),(1e7,10) ] for nb_e, nb_c in exp: time.append(timeit_2vector(nb_element=nb_e, nb_repeat=3, nb_call=nb_c*nb...
pylab.title('Speed up Numexpr and Theano vs NumPy for "%(expr)s"'%locals())
def exec_timeit_2vector(expr, nb_call_scal=1, fname=None, do_unalign=False, do_amd=True): time=[] exp = [(1,100000),(1e1,100000),(1e2,100000),(1e3,100000), (5e3,50000), (1e4,10000),(5e4,5000),(1e5,2000),(1e6,200),(1e7,10) ] for nb_e, nb_c in exp: time.append(timeit_2vector(nb_element=nb_e, nb_repeat=3, nb_call=nb_c*nb...
exp = [(1,10000),(1e1,10000),(1e2,100000),(1e3,100000), (5e3,50000),
exp = [(1e3,100000),(5e3,50000), \
def execs_timeit_2vector(exprs, fname=None): """ exprs is a list of list of expr to evaluate The first level of list is put into different graph section in the same graph. The second level is the expression to put in each section """ exp = [(1,10000),(1e1,10000),(1e2,100000),(1e3,100000), (5e3,50000), (1e4,10000),(5e4,...
for idx,graph in enumerate(exprs): legend=[] plot = fig.add_subplot(1,len(exprs),idx) for time,expr,color in zip(times,str_expr,colors): speedup = [t[0].min()/t[1].min() for t in time] plot.semilogx(nb_calls, speedup, linewidth=1.0, linestyle='--', color=color) speedup = [t[0].min()/t[2].min() for t in time] plot.semil...
for idx,(time,expr) in enumerate(zip(times,str_expr)): pylab.subplot(220+idx+1) pylab.subplots_adjust(wspace=0.25, hspace=0.25) speedup = [t[0].min()/t[1].min() for t in time] pylab.semilogx(nb_calls, speedup, linewidth=1.0, linestyle = '--', color='r') speedup = [t[0].min()/t[2].min() for t in time] pylab.semilogx(n...
def execs_timeit_2vector(exprs, fname=None): """ exprs is a list of list of expr to evaluate The first level of list is put into different graph section in the same graph. The second level is the expression to put in each section """ exp = [(1,10000),(1e1,10000),(1e2,100000),(1e3,100000), (5e3,50000), (1e4,10000),(5e4,...
pylab.title('Speed up Numexpr and Theano vs NumPy') pylab.grid(True) pylab.xlabel('Nb element') pylab.ylabel('Speed up vs NumPy') pylab.axhline(y=1, linewidth=1.0, color='black') pylab.legend(legend,loc='upper left')
def execs_timeit_2vector(exprs, fname=None): """ exprs is a list of list of expr to evaluate The first level of list is put into different graph section in the same graph. The second level is the expression to put in each section """ exp = [(1,10000),(1e1,10000),(1e2,100000),(1e3,100000), (5e3,50000), (1e4,10000),(5e4,...
],fname="multiple_graph.png"
],fname="multiple_graph.pdf"
def execs_timeit_2vector(exprs, fname=None): """ exprs is a list of list of expr to evaluate The first level of list is put into different graph section in the same graph. The second level is the expression to put in each section """ exp = [(1,10000),(1e1,10000),(1e2,100000),(1e3,100000), (5e3,50000), (1e4,10000),(5e4,...
``outputs_info``. ``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``
``outputs_info``). ``updates`` is a dictionary specifying the update rules for all shared variables used in the scan operation. This dictionary should be passed to ``theano.function``
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:...