rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
print ' Theano Op time (included in fct call, Time spent running thunks) %.3fs %.1f%%(of total) %.1f%%(of fct call)'% (local_time,local_time/total_time*100,local_time/total_fct_time*100)
print ' Theano Op time (included in fct call, Time spent running thunks) %.3fs %.1f%%(of total) %.1f%%(of fct call)'% (local_time,local_time/total_time*100, time_pr_in_fct)
def print_summary_(fct_name, local_time, compile_time, fct_call_time, fct_call, apply_time, apply_call, 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.
print '%i Theano fct call, %.3fs per call'%(total_fct_call, total_fct_time/total_fct_call)
print '%i Theano fct call, %.3fs per call'%(total_fct_call, time_per_call)
def print_summary_(fct_name, local_time, compile_time, fct_call_time, fct_call, apply_time, apply_call, 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.
return tensor.hashtype(self) ^ hash(self.val.value)
return tensor.hashtype(self) ^ hash(self.val.data)
def __hash__(self): return tensor.hashtype(self) ^ hash(self.val.value)
return hash(self.message) ^ hash(self.attrs)
return hash(self.message) ^ hash(str(self.attrs))
def __hash__(self): return hash(self.message) ^ hash(self.attrs)
raise RuntimeError(('A C Op raised an exception. PerformLinker cannot'
raise RuntimeError(('A C Op raised an exception. PROFILE_MODE cannot'
def blah(i, node, th): if hasattr(th, 'cthunk'): t0 = time.time() failure = run_cthunk(th.cthunk) dt = time.time() - t0 if failure: raise RuntimeError(('A C Op raised an exception. PerformLinker cannot' ' tell you what it was though. Use a standard mode such as' ' FAST_RUN_NOGC to correct the problem.')) else: t0 = t...
print outputs_info
def scan(fn, sequences=[], outputs_info=[], non_sequences=[], 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 Given variables representing all the slices of input an...
print n_outs print outs_info
def scan(fn, sequences=[], outputs_info=[], non_sequences=[], 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 Given variables representing all the slices of input an...
print shape, 'adding ', a0.size, 'cpu', cpu_dt, 'advantage', cpu_dt / gpu_dt
print shape, 'adding ', a0.size, 'cpu', cpu_dt, 'advantage', advantage(cpu_dt, gpu_dt)
def test_add_iadd_idiv(): for shape in ((), (0,), (3,), (2,3), (1,10000000),(10,1000000), (100,100000), (1000,10000),(10000,1000), (4100,33,34),(33,4100,34),(33,34,4100), (4100,33,3,6),(33,4100,3,6),(33,3,4100,6),(33,3,6,4100), (4100,3,34,6),(3,4100,34,6),(3,34,4100,6),(3,34,6,4100), (4100,3,4,36),(3,4100,4,36),(3,4,41...
print shape, 'adding ', a0.size, 'cpu', cpu_dt, 'advantage', cpu_dt / gpu_dt
print shape, 'adding ', a0.size, 'cpu', cpu_dt, 'advantage', advantage(cpu_dt, gpu_dt)
def test_exp(): print >>sys.stdout, 'starting test_exp' for shape in ((), (3,), (2,3), (1,10000000),(10,1000000), (100,100000),(1000,10000),(10000,1000)): a0 = theano._asarray(numpy.random.rand(*shape), dtype='float32') a1 = a0.copy() b0 = cuda_ndarray.CudaNdarray(a0) b1 = cuda_ndarray.CudaNdarray(a1) t0 = time.time() ...
path = os.path.split()[:-1]
path = os.path.split(path)[0]
def debug(*msg): _logger.debug(_logger_name+'DEBUG: '+' '.join(str(m) for m in msg))
outs_info = [outputs_info]
outs_info = outputs_info
def reduce(fn, sequences, outputs_info, non_sequences = [], go_backwards = False, mode = 'FAST_RUN'): ''' Similar behaviour as python reduce :param fn: the function to be applied over the elements in sequences ( see scan `fn` for more info) :param outputs_info: information about outputs (mainly the initial state of e...
repl.tag = copy(node.tag)
repl.tag = copy.copy(node.tag)
def transform(self, node): if node.op != self.op1: return False repl = self.op2.make_node(*node.inputs) if self.transfer_tags: repl.tag = copy(node.tag) for output, new_output in zip(node.outputs, repl.outputs): new_output.tag = copy(output.tag) return repl.outputs
new_output.tag = copy(output.tag)
new_output.tag = copy.copy(output.tag)
def transform(self, node): if node.op != self.op1: return False repl = self.op2.make_node(*node.inputs) if self.transfer_tags: repl.tag = copy(node.tag) for output, new_output in zip(node.outputs, repl.outputs): new_output.tag = copy(output.tag) return repl.outputs
denominators.remove(den) numerators.remove(den.owner.inputs[0]) numerators.append(T.sgn(den.owner.inputs[0]))
if den.owner.inputs[0].type.dtype.startswith('complex'): pass else: denominators.remove(den) numerators.remove(den.owner.inputs[0]) numerators.append(T.sgn(den.owner.inputs[0]))
def check_for_x_over_absX(numerators, denominators): # TODO: this function should dig/search through dimshuffles # This won't catch a dimshuffled absolute value for den in list(denominators): if den.owner and den.owner.op == T.abs_ and den.owner.inputs[0] in numerators: denominators.remove(den) numerators.remove(den.ow...
print [printing.pp(x) for x in dummy_args]
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...
message=""
def __init__(self, linker=config.linker, optimizer=config.optimizer): apply_time = {} op_cimpl = {} compile_time = 0 #time passed in theano.function() fct_call_time = {}#time passed inside theano fct call including op time. fct_call = {}
compile_time, fct_call_time, fct_call))
compile_time, fct_call_time, fct_call, message))
def __init__(self, linker=config.linker, optimizer=config.optimizer): apply_time = {} op_cimpl = {} compile_time = 0 #time passed in theano.function() fct_call_time = {}#time passed inside theano fct call including op time. fct_call = {}
self.op_cimpl, self.compile_time, self.fct_call_time, self.fct_call)
self.op_cimpl, self.compile_time, self.fct_call_time, self.fct_call, self.message)
def __getstate__(self): #print "__getstate__",self.provided_linker,self.provided_optimizer return (self.provided_linker, self.provided_optimizer, self.apply_time, self.op_cimpl, self.compile_time, self.fct_call_time, self.fct_call)
compile_time, fct_call_time, fct_call)):
compile_time, fct_call_time, fct_call, message)):
def __setstate__(self, (linker, optimizer, apply_time, op_cimpl, compile_time, fct_call_time, fct_call)): self.apply_time = apply_time self.op_cimpl = op_cimpl self.compile_time = compile_time self.fct_call_time = fct_call_time self.fct_call = fct_call self.call_time = 0 self.fn_time = 0
message = self.message
def print_summary(self, n_apply_to_print=config.ProfileMode.n_apply_to_print, n_ops_to_print=config.ProfileMode.n_ops_to_print): """ Print 3 summary that show where the time is spend. The first show an Apply-wise summary, the second show an Op-wise summary, the third show an type-Op-wise summary.
apply_time, op_cimpl,
apply_time, op_cimpl, message,
def print_summary(self, n_apply_to_print=config.ProfileMode.n_apply_to_print, n_ops_to_print=config.ProfileMode.n_ops_to_print): """ Print 3 summary that show where the time is spend. The first show an Apply-wise summary, the second show an Op-wise summary, the third show an type-Op-wise summary.
apply_time, op_cimpl,
apply_time, op_cimpl, message,
def diff_dict(a_time,b_time_): r = {} b_time = copy.copy(b_time_) for a,ta in a_time.items(): r.setdefault(a,0) tb = b_time.pop(a,0) r[a]+=ta-tb #they are missing in a for a,t in b_time.items(): r.setdefault(a,0) r[a]+=t return r
apply_time, op_cimpl,
apply_time, op_cimpl, message,
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.
print 'ProfileMode.%s()'%(fct_name)
print 'ProfileMode.%s(%s)'%(fct_name,message)
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.
vlen = 10 * 30 * 768 iters = 1000
vlen = 10 * 30 * 70 iters = 10
def test_using_gpu_1(self): # I'm checking if this compiles and runs from theano import function, config, shared, sandbox import theano.tensor as T import numpy import time
vlen = 10 * 30 * 768 iters = 1000
vlen = 10 * 30 * 70 iters = 10
def test_using_gpu_2(self):
vlen = 10 * 30 * 768 iters = 1000
vlen = 10 * 30 * 70 iters = 10
def test_using_gpu_3(self):
self.mode = theano.compile.mode.get_default_mode().including('canonicalize').including('fast_run').excluding('fusion').excluding('gpu')
def setUp(self): self.mode = theano.compile.mode.get_default_mode().including('canonicalize').including('fast_run').excluding('fusion').excluding('gpu')
f = theano.function([condition[0],x[0],c],[y])
f = theano.function([condition[0],x[0],c],[y], mode='FAST_RUN')
def test_local_mul_switch_sink(self): c = T.dscalar() idx = 0 for condition in [(T.dmatrix('cond'),self.condm),(T.dvector('cond'),self.condv),(T.dscalar('cond'),self.conds)]: for x in [(T.dmatrix('x'),self.xm),(T.dvector('x'),self.xv),(T.dscalar('x'),self.xs)]: y = T.mul(T.switch(condition[0]>0,1.*x[0],0.*x[0]),T.switc...
f = theano.function([condition[0],x[0],c],[y])
f = theano.function([condition[0],x[0],c],[y], mode='FAST_RUN')
def test_local_div_switch_sink(self): c = T.dscalar() idx = 0 for condition in [(T.dmatrix('cond'),self.condm),(T.dvector('cond'),self.condv),(T.dscalar('cond'),self.conds)]: for x in [(T.dmatrix('x'),self.xm),(T.dvector('x'),self.xv),(T.dscalar('x'),self.xs)]: y = T.true_div(T.switch(condition[0]>0,1.*x[0],0.*x[0]),T....
return Apply(self, [ten4, neib_shape], [ten4.type()])
return Apply(self, [ten4, neib_shape], [T.matrix(dtype=ten4.type.dtype)])
def make_node(self, ten4, neib_shape): ten4 = T.as_tensor_variable(ten4) neib_shape = T.as_tensor_variable(neib_shape) return Apply(self, [ten4, neib_shape], [ten4.type()])
return Apply(self, [ten4, neib_shape], [ten4.type()])
return Apply(self, [ten4, neib_shape], [CudaNdarrayType(broadcastable=(False,False), dtype=ten4.type.dtype)()])
def make_node(self, ten4, neib_shape): assert ten4.dtype == 'float32' #assert neib_shape.dtype == 'float32' if not isinstance(ten4.type, CudaNdarrayType): raise TypeError('pvals must be cudandarray', ten4) #if not isinstance(neib_shape.type, CudaNdarrayType): # raise TypeError('unis must be cudandarray', neib_shape)...
return (2,)
v = super(ScalarSigmoid, self).c_code_cache_version() if v: return (2,) + v else: return v
def c_code_cache_version(self): return (2,)
return (2,)
v = super(ScalarSoftplus, self).c_code_cache_version() if v: return (2,) + v else: return v
def c_code_cache_version(self): return (2,)
print 'x_in =', x_in print 'x_in.type =', x_in.type print 'x_in.broadcastable =', x_in.broadcastable
def local_softmax_with_bias(node): """Try to turn softmax(sum_of_stuff) -> softmax_w_bias(matrix, bias) """ if node.op == softmax: x, = node.inputs if x.owner and x.owner.op == tensor.add: vectors = [] non_vectors = [] for x_in in x.owner.inputs: print 'x_in =', x_in print 'x_in.type =', x_in.type print 'x_in.broadcast...
const int threadCount = blockDim.x * blockDim.y * blockDim.y;
const int threadCount = blockDim.x * blockDim.y * blockDim.z;
def _k_init(self, *args): return """ const int threadCount = blockDim.x * blockDim.y * blockDim.y; const int threadNum = threadIdx.z * blockDim.x * blockDim.y + threadIdx.y * blockDim.x + threadIdx.x; extern __shared__ float buf[]; float mysum = 0.0f;
theano.printing.debugprint(specify_shape_fct)
def test_specify_shape_partial(self): dtype = self.dtype if dtype is None: dtype = theano.config.floatX
assert len(topo_specify)==6
assert len(topo_specify)==4
def test_specify_shape_partial(self): dtype = self.dtype if dtype is None: dtype = theano.config.floatX
theano.printing.debugprint(shape_constant_fct)
def test_specify_shape_partial(self): dtype = self.dtype if dtype is None: dtype = theano.config.floatX
assert len(topo_cst)==6
assert len(topo_cst)==2
def test_specify_shape_partial(self): dtype = self.dtype if dtype is None: dtype = theano.config.floatX
theano.printing.debugprint(f)
def test_exp_over_1_plus_exp(self): m = theano.config.mode if m == 'FAST_COMPILE': m = 'FAST_RUN'
T.mul]
T.mul, T.inplace.neg_inplace]
def test_exp_over_1_plus_exp(self): m = theano.config.mode if m == 'FAST_COMPILE': m = 'FAST_RUN'
if a<0:
if not isinstance(a, TensorVariable) and a<0:
def make_node(self, x, axis=None): x = _as_tensor_variable(x) if axis is None: axis = x.type.ndim - 1 if isinstance(axis,int): axis = [axis] #we make the axis all positive to make the infer_shape work with negative axis if x.type.ndim>0: for id,a in enumerate(axis): if a<0: if -a>x.type.ndim: raise ValueError('axis out...
def debugprint(r, prefix='', depth=-1, done=None, print_type=False, file=sys.stdout):
def debugprint(r, prefix='', depth=-1, done=None, print_type=False, file=sys.stdout, print_destroy_map=False, print_view_map=False):
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 ...
:param print_destroy_map: wether to print the op destroy_map after ofther info :param print_view_map: wether to print the op view_map after ofther info
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]%s \'%s\'' % (prefix, a.op, id(r), \ type_str, r_name)
print >> file, '%s%s [@%i]%s \'%s\' %s %s' % (prefix, a.op, id(r), type_str, r_name, destroy_map_str, view_map_str)
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 \'%s\'' % (prefix, a.op, \ a.outputs.index(r), id(r), type_str, r_name)
print >> file, '%s%s.%i [@%i]%s \'%s\' %s %s' % (prefix, a.op, a.outputs.index(r), id(r), type_str, r_name, destroy_map_str, view_map_str)
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 ...
import logging logging_default_handler = logging.StreamHandler() logging.getLogger("theano").addHandler(logging_default_handler) logging.getLogger("theano").setLevel(logging.WARNING)
def dot(l, r): """Return a symbolic matrix/dot product between l and r """ rval = NotImplemented e0, e1 = None, None if rval == NotImplemented and hasattr(l, '__dot__'): try: rval = l.__dot__(r) except Exception, e0: rval = NotImplemented if rval == NotImplemented and hasattr(r, '__rdot__'): try: rval = r.__rdot__(l) ...
(fx-theano.tensor.true_div(fy,2),(fx,fy,fz),(fxv,fyv,fzv),1,fxv-(fyv/2),'float32'), (fx-theano.tensor.true_div(fy,fz),(fx,fy,fz),(fxv,fyv,fzv),1,fxv-(fyv/fzv),'float32'), (fx-theano.tensor.int_div(ix*100,iy*1000),(fx,ix,iy),(fxv,ixv,iyv),4,fxv-((ixv*100)//(iyv*1000)),'float64'), (fx-(fy/2),(fx,fy,fz),(fxv,fyv,fzv),1,fx...
(fx-theano.tensor.true_div(fy,2),(fx,fy),(fxv,fyv),1,fxv-(fyv/2),'float32'), (fx-theano.tensor.true_div(fy,fz),(fx,fy,fz),(fxv,fyv,fzv),1,fxv-(fyv/fzv),'float32'), (fx-theano.tensor.int_div(ix*100,iy*1000),(fx,ix,iy),(fxv,ixv,iyv),4,fxv-((ixv*100)//(iyv*1000)),'float64'), (fx-(fy/2),(fx,fy),(fxv,fyv),1,fxv-(fyv/2),'flo...
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
(fx-(fy>=fz),(fx,fy,fz),(fxv,fyv,fzv),1,fxv-(fyv>=fzv),'float32'), (fx-(fy<fz),(fx,fy,fz),(fxv,fyv,fzv),1,fxv-(fyv<fzv),'float32'), (fx-(fy<=fz),(fx,fy,fz),(fxv,fyv,fzv),1,fxv-(fyv<=fzv),'float32'), (fx-(fy==fz),(fx,fy,fz),(fxv,fyv,fzv),1,fxv-(fyv==fzv),'float32'), (fx-(fy!=fz),(fx,fy,fz),(fxv,fyv,fzv),1,fxv-(fyv!=fzv)...
(fx-(fy>=fz),(fx,fy,fz),(fxv,fyv,fzv),1,fxv-(fyv>=fzv),'float32'), (fx-(fy<fz),(fx,fy,fz),(fxv,fyv,fzv),1,fxv-(fyv<fzv),'float32'), (fx-(fy<=fz),(fx,fy,fz),(fxv,fyv,fzv),1,fxv-(fyv<=fzv),'float32'), (fx-T.eq(fy,fz),(fx,fy,fz),(fxv,fyv,fzv),1,fxv-(fyv==fzv),'float32'), (fx-T.neq(fy,fz),(fx,fy,fz),(fxv,fyv,fzv),1,fxv-(fy...
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
import theano_cuda_ndarray as tcn topo_ = [x for x in topo if not isinstance(x.op,tcn.basic_ops.GpuFromHost)] gpu_ = [x for x in topo if isinstance(x.op,tcn.basic_ops.GpuFromHost)]
import theano.sandbox.cuda as cuda topo_ = [x for x in topo if not isinstance(x.op,cuda.basic_ops.GpuFromHost) and not isinstance(x.op,cuda.basic_ops.HostFromGpu)] gpu_ = [x for x in topo if isinstance(x.op,cuda.basic_ops.GpuFromHost)]
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
import theano.sandbox.cuda as tcn self.do(mode, tcn.shared_constructor, shp, gpu=True)
mode = theano.compile.mode.get_mode(mode).including('gpu') import theano.sandbox.cuda as cuda self.do(mode, cuda.float32_shared_constructor, shp, gpu=True)
def gpu_fusion(self): shp=(5,5) #we need the optimisation enabled, debug do this. mode=compile.mode.predefined_modes['FAST_COMPILE'] mode=compile.mode.predefined_modes['FAST_RUN'] mode=compile.mode.predefined_modes['DEBUG_MODE'] import theano.sandbox.cuda as tcn self.do(mode, tcn.shared_constructor, shp, gpu=True)
import theano_cuda_ndarray as tcn self.speed_fusion(shared_fn=tcn.shared_constructor, gpu=True, s=slice(0,15))
import theano.sandbox.cuda as cuda self.speed_fusion(shared_fn=tcn.float32_shared_constructor, gpu=True, s=slice(0,15))
def speed_fusion_gpu(self): import theano_cuda_ndarray as tcn self.speed_fusion(shared_fn=tcn.shared_constructor, gpu=True, s=slice(0,15))
if all(theano.tensor.constant(pattern).value==expr.value):
if numpy.all(theano.tensor.constant(pattern).value==expr.value):
def retry_with_equiv(): expr_equiv = self.skip_identities(expr) if expr_equiv is None: return False #TODO: Not sure how to handle multiple_clients flag ###print 'retrying match', pattern, expr_equiv return match(pattern, expr_equiv, u, allow_multiple_clients=allow_multiple_clients)
^ self.kshp
^ hash(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 \ ^ self.kshp
f = function([start, stop, step], out.shape, mode=compile.mode.get_default_mode().excluding('fusion'))
mode = theano.config.mode if mode == 'FAST_COMPILE': mode = 'FAST_RUN' mode = compile.mode.get_mode(mode).excluding('fusion') f = function([start, stop, step], out.shape, mode=mode)
def test_infer_shape(self): start, stop, step = iscalars('start', 'stop', 'step') out = arange(start, stop, step) f = function([start, stop, step], out.shape, mode=compile.mode.get_default_mode().excluding('fusion')) assert len(f.maker.env.toposort())==7
f = function([start, stop], out.shape, mode=compile.mode.get_default_mode().excluding('fusion'))
f = function([start, stop], out.shape, mode=mode)
def test_infer_shape(self): start, stop, step = iscalars('start', 'stop', 'step') out = arange(start, stop, step) f = function([start, stop, step], out.shape, mode=compile.mode.get_default_mode().excluding('fusion')) assert len(f.maker.env.toposort())==7
f = function([stop], out.shape, mode=compile.mode.get_default_mode().excluding('fusion'))
f = function([stop], out.shape, mode=mode)
def test_infer_shape(self): start, stop, step = iscalars('start', 'stop', 'step') out = arange(start, stop, step) f = function([start, stop, step], out.shape, mode=compile.mode.get_default_mode().excluding('fusion')) assert len(f.maker.env.toposort())==7
o_shapes = default_infer_shape(node, [self.shape_of[r] for r in node.inputs])
o_shapes = self.default_infer_shape(node, [self.shape_of[r] for r in node.inputs])
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
for (shpnode, idx) in r.clients:
for (shpnode, idx) in (r.clients + [(node, i)]):
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.
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]))
continue 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]))
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.
self.failUnless(z is new_z)
def cmp_linker(z, a, x, y, b, l): z,a,x,y,b = [numpy.asarray(p) for p in z,a,x,y,b] z_orig = z.copy() tz,ta,tx,ty,tb = [as_tensor_variable(p).type() for p in z,a,x,y,b]
self.failUnless(_approx_eq(z_after, z), (z_orig, z_after, z, z_after - z))
self.failUnless(_approx_eq(z_after, tz.value), (z_orig, z_after, z, z_after - z))
def t(z,x,y,a=1.0, b=0.0,l='c|py',dt='float64'): z,a,x,y,b = [theano._asarray(p,dtype=dt) for p in z,a,x,y,b] z_orig = z.copy() z_after = self._gemm(z, a, x, y, b)
assert numpy.all(tz.value == z)
def t(z,x,y,a=1.0, b=0.0,l='c|py',dt='float64'): z,a,x,y,b = [theano._asarray(p,dtype=dt) for p in z,a,x,y,b] z_orig = z.copy() z_after = self._gemm(z, a, x, y, b)
self.failUnless(_approx_eq(z_after, z.T))
self.failUnless(_approx_eq(z_after, tz.value.T))
def t(z,x,y,a=1.0, b=0.0,l='c|py',dt='float64'): z,a,x,y,b = [theano._asarray(p,dtype=dt) for p in z,a,x,y,b] z_orig = z.copy() z_after = self._gemm(z, a, x, y, b)
class BROKEN_ON_PURPOSE_StructuredDotCSC(gof.Op):
class BROKEN_ON_PURPOSE_Add(gof.Op):
def test0(): x = theano.tensor.dvector() f = theano.function([x], (2.*x + 7) / 2., mode=debugmode.DebugMode()) print f([1,2])
def make_node(self, a_val, a_ind, a_ptr, a_nrows, b): a_nrows = theano.tensor.as_tensor_variable(a_nrows) assert a_val.type.dtype == b.type.dtype r = gof.Apply(self, [a_val, a_ind, a_ptr, a_nrows, b], [theano.tensor.tensor(a_val.type.dtype, (False, False))])
def make_node(self, a, b): a = theano.tensor.as_tensor_variable(a) b = theano.tensor.as_tensor_variable(b) assert a.type.dtype == 'float64' assert a.type.dtype == b.type.dtype assert a.type.ndim==1 r = gof.Apply(self, [a, b], [a.type()])
def make_node(self, a_val, a_ind, a_ptr, a_nrows, b): a_nrows = theano.tensor.as_tensor_variable(a_nrows) assert a_val.type.dtype == b.type.dtype r = gof.Apply(self, [a_val, a_ind, a_ptr, a_nrows, b], [theano.tensor.tensor(a_val.type.dtype, (False, False))]) return r
def perform(self, node, (a_val, a_ind, a_ptr, a_nrows, b), (out,)): a = scipy.sparse.csc_matrix((a_val, a_ind, a_ptr), (a_nrows, b.shape[0]), copy = False) z = a * b
def perform(self, node, (a, b), (out,)): z = a+b
def perform(self, node, (a_val, a_ind, a_ptr, a_nrows, b), (out,)): a = scipy.sparse.csc_matrix((a_val, a_ind, a_ptr), (a_nrows, b.shape[0]), copy = False)
def c_code(self, node, name, (a_val, a_ind, a_ptr, a_nrows, b), (z,), sub):
def c_code(self, node, name, (a, b), (z,), sub):
def c_code(self, node, name, (a_val, a_ind, a_ptr, a_nrows, b), (z,), sub): return """ if (%(a_val)s->nd != 1) {PyErr_SetString(PyExc_NotImplementedError, "rank(a_val) != 1"); %(fail)s;} if (%(a_ind)s->nd != 1) {PyErr_SetString(PyExc_NotImplementedError, "rank(a_ind) != 1"); %(fail)s;} if (%(a_ptr)s->nd != 1) {PyErr_Se...
if (%(a_val)s->nd != 1) {PyErr_SetString(PyExc_NotImplementedError, "rank(a_val) != 1"); %(fail)s;} if (%(a_ind)s->nd != 1) {PyErr_SetString(PyExc_NotImplementedError, "rank(a_ind) != 1"); %(fail)s;} if (%(a_ptr)s->nd != 1) {PyErr_SetString(PyExc_NotImplementedError, "rank(a_ptr) != 1"); %(fail)s;} if (%(a_nrows)s->nd ...
if (%(a)s->nd != 1) {PyErr_SetString(PyExc_NotImplementedError, "rank(a) != 1"); %(fail)s;} if (%(b)s->nd != 1) {PyErr_SetString(PyExc_NotImplementedError, "rank(b) != 1"); %(fail)s;} if (%(a)s->descr->type_num != PyArray_DOUBLE) {PyErr_SetString(PyExc_NotImplementedError, "a dtype not NPY_DOUBLE"); %(fail)s;}
def c_code(self, node, name, (a_val, a_ind, a_ptr, a_nrows, b), (z,), sub): return """ if (%(a_val)s->nd != 1) {PyErr_SetString(PyExc_NotImplementedError, "rank(a_val) != 1"); %(fail)s;} if (%(a_ind)s->nd != 1) {PyErr_SetString(PyExc_NotImplementedError, "rank(a_ind) != 1"); %(fail)s;} if (%(a_ptr)s->nd != 1) {PyErr_Se...
if (%(a_val)s->dimensions[0] != %(a_ind)s->dimensions[0]) {PyErr_SetString(PyExc_NotImplementedError, "a_val and a_ind have different lengths"); %(fail)s;} if (%(a_ptr)s->dimensions[0] != %(b)s->dimensions[0]+1) {PyErr_SetString(PyExc_NotImplementedError, "a's number of columns doesn't match b's rows"); %(fail)s;}
if (%(a)s->dimensions[0] != %(b)s->dimensions[0]) {PyErr_SetString(PyExc_NotImplementedError, "a and b have different lengths"); %(fail)s;}
def c_code(self, node, name, (a_val, a_ind, a_ptr, a_nrows, b), (z,), sub): return """ if (%(a_val)s->nd != 1) {PyErr_SetString(PyExc_NotImplementedError, "rank(a_val) != 1"); %(fail)s;} if (%(a_ind)s->nd != 1) {PyErr_SetString(PyExc_NotImplementedError, "rank(a_ind) != 1"); %(fail)s;} if (%(a_ptr)s->nd != 1) {PyErr_Se...
|| (%(z)s->dimensions[0] != ((npy_int32 *)%(a_nrows)s->data)[0]) || (%(z)s->dimensions[1] != %(b)s->dimensions[1])
|| (%(z)s->dimensions[0] != %(b)s->dimensions[0])
def c_code(self, node, name, (a_val, a_ind, a_ptr, a_nrows, b), (z,), sub): return """ if (%(a_val)s->nd != 1) {PyErr_SetString(PyExc_NotImplementedError, "rank(a_val) != 1"); %(fail)s;} if (%(a_ind)s->nd != 1) {PyErr_SetString(PyExc_NotImplementedError, "rank(a_ind) != 1"); %(fail)s;} if (%(a_ptr)s->nd != 1) {PyErr_Se...
npy_intp dims[] = {0,0}; dims[0] = ((npy_int32 *)%(a_nrows)s->data)[0]; dims[1] = %(b)s->dimensions[1]; %(z)s = (PyArrayObject*) PyArray_SimpleNew(2, dims, %(b)s->descr->type_num);
npy_intp dims[] = {0}; dims[0] = %(b)s->dimensions[0]; %(z)s = (PyArrayObject*) PyArray_SimpleNew(1, dims, %(b)s->descr->type_num);
def c_code(self, node, name, (a_val, a_ind, a_ptr, a_nrows, b), (z,), sub): return """ if (%(a_val)s->nd != 1) {PyErr_SetString(PyExc_NotImplementedError, "rank(a_val) != 1"); %(fail)s;} if (%(a_ind)s->nd != 1) {PyErr_SetString(PyExc_NotImplementedError, "rank(a_ind) != 1"); %(fail)s;} if (%(a_ptr)s->nd != 1) {PyErr_Se...
//the output array has size M x N npy_intp M = %(z)s->dimensions[0]; npy_intp N = %(z)s->dimensions[1]; npy_intp K = %(b)s->dimensions[0]; npy_intp Szm = %(z)s->strides[0] / %(z)s->descr->elsize; npy_intp Szn = %(z)s->strides[1] / %(z)s->descr->elsize; //npy_intp Sbm = %(b)s->strides[0] / %(b)s->descr->elsize; npy_intp...
for (npy_intp m = 0; m < %(z)s->dimensions[0]; ++m)
def c_code(self, node, name, (a_val, a_ind, a_ptr, a_nrows, b), (z,), sub): return """ if (%(a_val)s->nd != 1) {PyErr_SetString(PyExc_NotImplementedError, "rank(a_val) != 1"); %(fail)s;} if (%(a_ind)s->nd != 1) {PyErr_SetString(PyExc_NotImplementedError, "rank(a_ind) != 1"); %(fail)s;} if (%(a_ptr)s->nd != 1) {PyErr_Se...
for (npy_intp n = 0; n < N; ++n) { //Dz[m*Szm + n*Szn] = 0.0; Dz[m*Szm + n*Szn] = 0.5; //here is the py_offset amount } } //iterate over the sparse array, making the most of an entry wherever we find it. // // Normal matrix matrix multiply: // for m // for n // for k // z[m,n] += a[m,k] * b[k,n] // Here ...
((double*)PyArray_GETPTR1(%(z)s, m))[0] = 0.5 + ((double*)PyArray_GETPTR1(%(a)s, m))[0] + ((double*)PyArray_GETPTR1(%(b)s, m))[0] ;
def c_code(self, node, name, (a_val, a_ind, a_ptr, a_nrows, b), (z,), sub): return """ if (%(a_val)s->nd != 1) {PyErr_SetString(PyExc_NotImplementedError, "rank(a_val) != 1"); %(fail)s;} if (%(a_ind)s->nd != 1) {PyErr_SetString(PyExc_NotImplementedError, "rank(a_ind) != 1"); %(fail)s;} if (%(a_ptr)s->nd != 1) {PyErr_Se...
inconsistent = BROKEN_ON_PURPOSE_StructuredDotCSC(False)
inconsistent = BROKEN_ON_PURPOSE_Add(False)
def c_code(self, node, name, (a_val, a_ind, a_ptr, a_nrows, b), (z,), sub): return """ if (%(a_val)s->nd != 1) {PyErr_SetString(PyExc_NotImplementedError, "rank(a_val) != 1"); %(fail)s;} if (%(a_ind)s->nd != 1) {PyErr_SetString(PyExc_NotImplementedError, "rank(a_ind) != 1"); %(fail)s;} if (%(a_ptr)s->nd != 1) {PyErr_Se...
off_by_half = BROKEN_ON_PURPOSE_StructuredDotCSC(True)
off_by_half = BROKEN_ON_PURPOSE_Add(True)
def c_code(self, node, name, (a_val, a_ind, a_ptr, a_nrows, b), (z,), sub): return """ if (%(a_val)s->nd != 1) {PyErr_SetString(PyExc_NotImplementedError, "rank(a_val) != 1"); %(fail)s;} if (%(a_ind)s->nd != 1) {PyErr_SetString(PyExc_NotImplementedError, "rank(a_ind) != 1"); %(fail)s;} if (%(a_ptr)s->nd != 1) {PyErr_Se...
This op can be inplace if behaviour is times1_inplace This op can be destructive if behaviour is times2_inplace
This op can be inplace if behaviour is 'times1_inplace' This op can be destructive if behaviour is 'times2_inplace'
def c_code(self, node, name, (a_val, a_ind, a_ptr, a_nrows, b), (z,), sub): return """ if (%(a_val)s->nd != 1) {PyErr_SetString(PyExc_NotImplementedError, "rank(a_val) != 1"); %(fail)s;} if (%(a_ind)s->nd != 1) {PyErr_SetString(PyExc_NotImplementedError, "rank(a_ind) != 1"); %(fail)s;} if (%(a_ptr)s->nd != 1) {PyErr_Se...
vals = theano.tensor.dvector() inds = theano.tensor.ivector() ptrs = theano.tensor.ivector() nrows = theano.tensor.iscalar() b = theano.tensor.dmatrix() f_good = theano.function([vals, inds, ptrs, nrows, b], theano.sparse.StructuredDotCSC()(vals, inds, ptrs, nrows, b),
a = theano.tensor.dvector() b = theano.tensor.dvector() f_good = theano.function([a, b], off_by_half(a, b),
def test_badclinkeroutput(): vals = theano.tensor.dvector() inds = theano.tensor.ivector() ptrs = theano.tensor.ivector() nrows = theano.tensor.iscalar() b = theano.tensor.dmatrix() f_good = theano.function([vals, inds, ptrs, nrows, b], theano.sparse.StructuredDotCSC()(vals, inds, ptrs, nrows, b), mode=debugmode.Deb...
f_inconsistent = theano.function([vals, inds, ptrs, nrows, b], inconsistent(vals, inds, ptrs, nrows, b),
f_inconsistent = theano.function([a,b], inconsistent(a, b),
def test_badclinkeroutput(): vals = theano.tensor.dvector() inds = theano.tensor.ivector() ptrs = theano.tensor.ivector() nrows = theano.tensor.iscalar() b = theano.tensor.dmatrix() f_good = theano.function([vals, inds, ptrs, nrows, b], theano.sparse.StructuredDotCSC()(vals, inds, ptrs, nrows, b), mode=debugmode.Deb...
rval_good = f_good([1.0, 2.0, 3.0], [0,1,2], [0,1,2,3], 3, numpy.asarray([[0.,1.,2.],[3.,4.,5.],[6.,7.,8.]]))
f_good([1.0, 2.0, 3.0], [2,3,4])
def test_badclinkeroutput(): vals = theano.tensor.dvector() inds = theano.tensor.ivector() ptrs = theano.tensor.ivector() nrows = theano.tensor.iscalar() b = theano.tensor.dmatrix() f_good = theano.function([vals, inds, ptrs, nrows, b], theano.sparse.StructuredDotCSC()(vals, inds, ptrs, nrows, b), mode=debugmode.Deb...
rval = f_inconsistent([1.0, 2.0, 3.0], [0,1,2], [0,1,2,3], 3, numpy.asarray([[0.,1.,2.],[3.,4.,5.],[6.,7.,8.]]))
f_inconsistent([1.0, 2.0, 3.0], [2,3,4])
def test_badclinkeroutput(): vals = theano.tensor.dvector() inds = theano.tensor.ivector() ptrs = theano.tensor.ivector() nrows = theano.tensor.iscalar() b = theano.tensor.dmatrix() f_good = theano.function([vals, inds, ptrs, nrows, b], theano.sparse.StructuredDotCSC()(vals, inds, ptrs, nrows, b), mode=debugmode.Deb...
@gof.local_optimizer([theano.sparse.sd_csc]) def insert_broken_csc(node): if node.op == theano.sparse.sd_csc:
@gof.local_optimizer([theano.tensor.add]) def insert_broken_add(node): if node.op == theano.tensor.add:
def test_badoptimization(): @gof.local_optimizer([theano.sparse.sd_csc]) def insert_broken_csc(node): if node.op == theano.sparse.sd_csc: return [off_by_half(*node.inputs)] return False edb = gof.EquilibriumDB() edb.register('insert_broken_csc', insert_broken_csc, 'all') opt = edb.query('+all') vals = theano.tensor.dv...
edb.register('insert_broken_csc', insert_broken_csc, 'all')
edb.register('insert_broken_add', insert_broken_add, 'all')
def insert_broken_csc(node): if node.op == theano.sparse.sd_csc: return [off_by_half(*node.inputs)] return False
vals = theano.tensor.dvector() inds = theano.tensor.ivector() ptrs = theano.tensor.ivector() nrows = theano.tensor.iscalar() b = theano.tensor.dmatrix() f = theano.function([vals, inds, ptrs, nrows, b], theano.sparse.sd_csc(vals, inds, ptrs, nrows, b),
a = theano.tensor.dvector() b = theano.tensor.dvector() f = theano.function([a, b], a+b,
def insert_broken_csc(node): if node.op == theano.sparse.sd_csc: return [off_by_half(*node.inputs)] return False
rval = f([1.0, 2.0, 3.0], [0,1,2], [0,1,2,3], 3, numpy.asarray([[0.,1.,2.],[3.,4.,5.],[6.,7.,8.]]))
rval = f([1.0, 2.0, 3.0], [2,3,4],)
def insert_broken_csc(node): if node.op == theano.sparse.sd_csc: return [off_by_half(*node.inputs)] return False
assert str(e.reason) == 'insert_broken_csc'
assert str(e.reason) == 'insert_broken_add'
def insert_broken_csc(node): if node.op == theano.sparse.sd_csc: return [off_by_half(*node.inputs)] return False
@gof.local_optimizer([theano.sparse.sd_csc]) def insert_broken_csc_sometimes(node): if node.op == theano.sparse.sd_csc:
@gof.local_optimizer([theano.tensor.add]) def insert_broken_add_sometimes(node): if node.op == theano.tensor.add:
def test_stochasticoptimization(): # this optimization alternates between triggering and not triggering. last_time_replaced=[False] @gof.local_optimizer([theano.sparse.sd_csc]) def insert_broken_csc_sometimes(node): if node.op == theano.sparse.sd_csc: last_time_replaced[0] = not last_time_replaced[0] if last_time_rep...
edb.register('insert_broken_csc_sometimes', insert_broken_csc_sometimes, 'all')
edb.register('insert_broken_add_sometimes', insert_broken_add_sometimes, 'all')
def insert_broken_csc_sometimes(node): if node.op == theano.sparse.sd_csc: last_time_replaced[0] = not last_time_replaced[0] if last_time_replaced[0]: return [off_by_half(*node.inputs)] return False
vals = theano.tensor.dvector() inds = theano.tensor.ivector() ptrs = theano.tensor.ivector() nrows = theano.tensor.iscalar() b = theano.tensor.dmatrix()
a = theano.tensor.dvector() b = theano.tensor.dvector()
def insert_broken_csc_sometimes(node): if node.op == theano.sparse.sd_csc: last_time_replaced[0] = not last_time_replaced[0] if last_time_replaced[0]: return [off_by_half(*node.inputs)] return False
f = theano.function([vals, inds, ptrs, nrows, b], theano.sparse.sd_csc(vals, inds, ptrs, nrows, b),
f = theano.function([a, b], theano.tensor.add(a, b),
def insert_broken_csc_sometimes(node): if node.op == theano.sparse.sd_csc: last_time_replaced[0] = not last_time_replaced[0] if last_time_replaced[0]: return [off_by_half(*node.inputs)] return False
rval, rshapes = get_constant_value(val) return rval, rshapes + [shape]
return get_constant_value(val)
def get_constant_value(v): """return the constant scalar(0-D) value underlying variable `v` If v is the output of dimshuffles, fills, 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 in the code, but I'm not su...
random = RandomStreams(234)
random = RandomStreams(utt.fetch_seed())
def test_basics(self): random = RandomStreams(234) fn = function([], random.uniform((2,2)), updates=random.updates()) gn = function([], random.normal((2,2)), updates=random.updates())
rng_seed = numpy.random.RandomState(234).randint(2**30)
rng_seed = numpy.random.RandomState(utt.fetch_seed()).randint(2**30)
def test_basics(self): random = RandomStreams(234) fn = function([], random.uniform((2,2)), updates=random.updates()) gn = function([], random.normal((2,2)), updates=random.updates())
random.seed(888) fn_val0 = fn() fn_val1 = fn() rng_seed = numpy.random.RandomState(888).randint(2**30)
random.seed(utt.fetch_seed()) fn_val0 = fn() fn_val1 = fn() rng_seed = numpy.random.RandomState(utt.fetch_seed()).randint(2**30)
def test_seed_fn(self): random = RandomStreams(234) fn = function([], random.uniform((2,2)), updates=random.updates())
random.seed(888)
random.seed(utt.fetch_seed())
def test_getitem(self):
rng = numpy.random.RandomState(823874) random[out.rng] = numpy.random.RandomState(823874)
rng = numpy.random.RandomState(utt.fetch_seed()) random[out.rng] = numpy.random.RandomState(utt.fetch_seed())
def test_setitem(self):
random = RandomStreams(234)
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. random = RandomStreams(234) fn = function([], random.permutation((20,), 10), updates=random.updates())
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. random = RandomStreams(234) fn = function([], random.permutation((20,), 10), updates=random.updates())
random = RandomStreams(234)
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. random = RandomStreams(234) fn = function([], random.multinomial((4,4), 1, [0.1]*10), updates=random.updates())