idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
222,800 | def imsave ( path , img , channel_first = False , as_uint16 = False , auto_scale = True ) : img = _imsave_before ( img , channel_first , auto_scale ) if auto_scale : img = upscale_pixel_intensity ( img , as_uint16 ) img = check_type_and_cast_if_necessary ( img , as_uint16 ) bitdepth = 8 if img . dtype == np . uint8 else 16 grayscale = True if len ( img . shape ) == 2 or ( len ( img . shape ) == 3 and img . shape [ - 1 ] == 1 ) else False writer = png . Writer ( img . shape [ 1 ] , img . shape [ 0 ] , greyscale = grayscale , bitdepth = bitdepth ) writer . write ( open ( path , "wb" ) , img . reshape ( img . shape [ 0 ] , - 1 ) ) | Save image by pypng module . | 204 | 8 |
222,801 | def context_scope ( ctx ) : global current_ctx global context_level context_level += 1 prev_context = current_ctx current_ctx = ctx try : yield finally : context_level -= 1 current_ctx = prev_context | Context as Python context . | 52 | 5 |
222,802 | def generate_scalar_constant ( output_name , tensor_name , scalar ) : t = onnx . helper . make_tensor ( tensor_name , data_type = TensorProto . FLOAT , dims = [ 1 ] , vals = [ scalar ] ) c = onnx . helper . make_node ( "Constant" , [ ] , [ output_name ] , value = t ) return c | Convert a scalar value to a Constant buffer . This is mainly used for xxScalar operators . | 101 | 22 |
222,803 | def replace_negative_size_with_batch_size ( shape , batch_size ) : sl = [ ] for d in shape . dim : if d < 0 : # Negative size means batch size sl . append ( batch_size ) else : sl . append ( d ) out_shape = nnabla_pb2 . Shape ( ) out_shape . dim . extend ( sl ) return out_shape | Replace all dimensions with negative values to batch size | 87 | 10 |
222,804 | def BinarySigmoid ( self , func ) : n = onnx . helper . make_node ( 'HardSigmoid' , func . input , func . output , alpha = 1.0 , beta = 0.0 ) return [ n ] | Currently caffe2 does not support this function . | 54 | 9 |
222,805 | def convert ( self , vroot , entry_variables ) : for converter in self . converters : vroot = converter . convert ( vroot , entry_variables ) return vroot | Convert a given graph . | 40 | 6 |
222,806 | def calc_normal_std_he_forward ( inmaps , outmaps , kernel = ( 1 , 1 ) ) : return np . sqrt ( 2. / ( np . prod ( kernel ) * inmaps ) ) | r Calculates the standard deviation proposed by He et al . | 47 | 12 |
222,807 | def calc_normal_std_glorot ( inmaps , outmaps , kernel = ( 1 , 1 ) ) : return np . sqrt ( 2. / ( np . prod ( kernel ) * inmaps + outmaps ) ) | r Calculates the standard deviation proposed by Glorot et al . | 50 | 14 |
222,808 | def calc_uniform_lim_glorot ( inmaps , outmaps , kernel = ( 1 , 1 ) ) : d = np . sqrt ( 6. / ( np . prod ( kernel ) * inmaps + outmaps ) ) return - d , d | r Calculates the lower bound and the upper bound of the uniform distribution proposed by Glorot et al . | 57 | 22 |
222,809 | def _get_unique_function_name ( function_type , functions ) : function_name = function_name_base = function_type count = 2 while function_name in functions : function_name = '{}_{}' . format ( function_name_base , count ) count += 1 return function_name | Get a unique function name . | 68 | 6 |
222,810 | def _get_unique_variable_name ( vname , variables ) : count = 2 vname_base = vname while vname in variables : vname = '{}_{}' . format ( vname_base , count ) count += 1 return vname | Get a unique variable name . | 57 | 6 |
222,811 | def sum ( x , axis = None , keepdims = False ) : from . function_bases import sum as sum_base if axis is None : axis = range ( x . ndim ) elif not hasattr ( axis , '__iter__' ) : axis = [ axis ] return sum_base ( x , axis , keepdims ) | Reduction along axes with sum operation . | 75 | 8 |
222,812 | def mean ( x , axis = None , keepdims = False ) : from . function_bases import mean as mean_base if axis is None : axis = range ( x . ndim ) elif not hasattr ( axis , '__iter__' ) : axis = [ axis ] return mean_base ( x , axis , keepdims ) | Reduction along axes with mean operation . | 75 | 8 |
222,813 | def prod ( x , axis = None , keepdims = False ) : from . function_bases import prod as prod_base if axis is None : axis = range ( x . ndim ) elif not hasattr ( axis , '__iter__' ) : axis = [ axis ] return prod_base ( x , axis , keepdims ) | Reduction along axes with product operation . | 75 | 8 |
222,814 | def reduce ( x , op = 'sum' ) : import warnings warnings . warn ( "Deprecated API. Use ``sum`` or ``mean`` instead." , DeprecationWarning ) from . function_bases import reduce_sum , reduce_mean if op == 'sum' : return reduce_sum ( x ) elif op == 'mean' : return reduce_mean ( x ) raise ValueError ( ) | Reduction function with given operation . | 87 | 7 |
222,815 | def split ( x , axis = 0 ) : from . function_bases import split as split_base return split_base ( x , axis , x . shape [ axis ] ) | Split arrays at the specified axis . | 38 | 7 |
222,816 | def batch_normalization ( x , beta , gamma , mean , variance , axes = [ 1 ] , decay_rate = 0.9 , eps = 1e-05 , batch_stat = True , output_stat = False , n_outputs = None ) : from . function_bases import batch_normalization as batch_normalization_base n_outputs = 3 if output_stat else 1 assert batch_stat or ( not output_stat ) if batch_stat and ( mean . parent or variance . parent ) is not None : raise ValueError ( "if batch_stat is True, mean and variable must not have a parent function" ) if len ( axes ) == 1 : return batch_normalization_base ( x , beta , gamma , mean , variance , axes = axes , decay_rate = decay_rate , eps = eps , batch_stat = batch_stat , n_outputs = n_outputs ) def transpose_and_reshape ( x , axes ) : transposed = transpose ( x , transpose_axes ) return reshape ( transposed , [ rd ( lambda x , y : x * y , transposed . shape [ : len ( axes ) ] ) ] + list ( transposed . shape [ len ( axes ) : ] ) ) , transposed . shape def inverse_transpose_and_reshape ( x , axes , variable_shape ) : un_reshaped = reshape ( x , list ( variable_shape [ : len ( axes ) ] + variable_shape [ len ( axes ) : ] ) ) return transpose ( un_reshaped , inv_transpose_axes ) def get_tranpose_args ( ndim , axes ) : transpose_axes = [ i for i in list ( axes ) ] + [ i for i in range ( ndim ) if i not in list ( axes ) ] inv_transpose_axes = np . argsort ( transpose_axes ) . tolist ( ) return transpose_axes , inv_transpose_axes transpose_axes , inv_transpose_axes = get_tranpose_args ( len ( x . shape ) , axes ) inp , transposed_inp_shape = transpose_and_reshape ( x , axes ) beta , transposed_beta_shape = transpose_and_reshape ( beta , axes ) gamma , transposed_gamma_shape = transpose_and_reshape ( gamma , axes ) mean , transposed_mean_shape = transpose_and_reshape ( mean , axes ) variance , transposed_variance_shape = transpose_and_reshape ( variance , axes ) if n_outputs == 1 : out = batch_normalization_base ( inp , beta , gamma , mean , variance , axes = [ 0 ] , decay_rate = decay_rate , eps = eps , batch_stat = batch_stat , n_outputs = n_outputs ) return inverse_transpose_and_reshape ( out , axes , transposed_inp_shape ) out , mean , variance = batch_normalization_base ( inp , beta , gamma , mean , variance , axes = [ 0 ] , decay_rate = decay_rate , eps = eps , batch_stat = batch_stat , n_outputs = n_outputs ) out = inverse_transpose_and_reshape ( out , axes , transposed_inp_shape ) mean = inverse_transpose_and_reshape ( mean , axes , transposed_mean_shape ) variance = inverse_transpose_and_reshape ( variance , axes , transposed_variance_shape ) return out , mean , variance | r Batch normalization . | 813 | 6 |
222,817 | def fixed_point_quantize ( x , sign = True , n = 8 , delta = 2 ** - 4 , quantize = True , ste_fine_grained = True , outputs = None ) : from . function_bases import fixed_point_quantize as fixed_point_quantize_base if not quantize : return x return fixed_point_quantize_base ( x , sign , n , delta , ste_fine_grained , outputs = outputs ) | r Fixed Point Quantize | 102 | 5 |
222,818 | def pow2_quantize ( x , sign = True , with_zero = True , n = 8 , m = 1 , quantize = True , ste_fine_grained = True , outputs = None ) : from . function_bases import pow2_quantize as pow2_quantize_base if not quantize : return x return pow2_quantize_base ( x , sign , with_zero , n , m , ste_fine_grained , outputs = outputs ) | r Pow2 Quantize | 105 | 5 |
222,819 | def clip_by_value ( x , min , max ) : from . function_bases import maximum2 as maximum2_base from . function_bases import minimum2 as minimum2_base return minimum2_base ( maximum2_base ( x , min ) , max ) | r Clip inputs by values . | 60 | 6 |
222,820 | def interpolate ( x , scale = None , output_size = None , mode = 'linear' , align_corners = None ) : from . function_bases import interpolate as interpolate_base import math if scale is None and output_size is None : raise ValueError ( 'Either scale or output_size must be given' ) elif output_size is None : output_size = [ int ( math . floor ( s * d ) ) for d , s in zip ( x . shape [ - len ( scale ) : ] , scale ) ] if align_corners is None : if mode == 'linear' : align_corners = True else : align_corners = False return interpolate_base ( x , output_size , mode , align_corners ) | Resize an ND array with interpolation . | 167 | 9 |
222,821 | def sort ( x , axis = - 1 , reverse = False , with_index = False , only_index = False ) : from . function_bases import sort as sort_base n_outputs = 2 if with_index and not only_index else 1 return sort_base ( x , axis , reverse , with_index , only_index , n_outputs ) | Sorts the elements of x along a given axis in ascending order by value . A negative axis counts from the last dimension of x so the default of - 1 sorts along the last dimension . If reverse is True then the elements are soreted in descending order . | 80 | 52 |
222,822 | def download ( url , output_file = None , open_file = True , allow_overwrite = False ) : filename = url . split ( '/' ) [ - 1 ] if output_file is None : cache = os . path . join ( get_data_home ( ) , filename ) else : cache = output_file if os . path . exists ( cache ) and not allow_overwrite : logger . info ( "> {} already exists." . format ( cache ) ) logger . info ( "> If you have any issue when using this file, " ) logger . info ( "> manually remove the file and try download again." ) else : r = request . urlopen ( url ) try : if six . PY2 : content_length = int ( r . info ( ) . dict [ 'content-length' ] ) elif six . PY3 : content_length = int ( r . info ( ) [ 'Content-Length' ] ) except : content_length = 0 unit = 1000000 content = b'' with tqdm ( total = content_length , desc = filename , unit = 'B' , unit_scale = True , unit_divisor = 1024 ) as t : while True : data = r . read ( unit ) l = len ( data ) t . update ( l ) if l == 0 : break content += data with open ( cache , 'wb' ) as f : f . write ( content ) if not open_file : return return open ( cache , 'rb' ) | Download a file from URL . | 323 | 6 |
222,823 | def imread ( path , grayscale = False , size = None , interpolate = "bilinear" , channel_first = False , as_uint16 = False , num_channels = - 1 ) : _imread_before ( grayscale , num_channels ) r_mode = cv2 . IMREAD_GRAYSCALE if grayscale else cv2 . IMREAD_UNCHANGED img = _imread_helper ( path , r_mode ) if as_uint16 and img . dtype != np . uint16 : if img . dtype == np . uint8 : logger . warning ( "You want to read image as uint16, but the original bit-depth is 8 bit." "All pixel values are simply increased by 256 times." ) img = img . astype ( np . uint16 ) * 256 else : raise ValueError ( "casting {} to uint16 is not safe." . format ( img . dtype ) ) img = _cvtColor_helper ( img , num_channels ) img = _imread_after ( img , size , interpolate , channel_first , imresize ) return img | Read image by cv2 module . | 251 | 8 |
222,824 | def get_learning_rate ( self , iter ) : return self . init_lr * ( ( 1.0 - iter * 1.0 / self . max_iter ) ** self . power ) | Get learning rate with polymomial decay based on current iteration . | 42 | 13 |
222,825 | def get_learning_rate ( self , iter ) : return self . init_lr * ( ( math . cos ( iter * 1.0 / ( self . max_iter ) * math . pi ) + 1.0 ) * 0.5 ) | Get learning rate with cosine decay based on current iteration . | 53 | 12 |
222,826 | def affine ( inp , n_outmaps , base_axis = 1 , w_init = None , b_init = None , fix_parameters = False , rng = None , with_bias = True , apply_w = None , apply_b = None ) : if not hasattr ( n_outmaps , '__iter__' ) : n_outmaps = [ n_outmaps ] n_outmaps = list ( n_outmaps ) n_outmap = int ( np . prod ( n_outmaps ) ) if w_init is None : inmaps = np . prod ( inp . shape [ base_axis : ] ) w_init = UniformInitializer ( calc_uniform_lim_glorot ( inmaps , n_outmap ) , rng = rng ) if with_bias and b_init is None : b_init = ConstantInitializer ( ) w = get_parameter_or_create ( "W" , [ int ( np . prod ( inp . shape [ base_axis : ] ) ) ] + n_outmaps , w_init , True , not fix_parameters ) if apply_w is not None : w = apply_w ( w ) b = None if with_bias : b = get_parameter_or_create ( "b" , n_outmaps , b_init , True , not fix_parameters ) if apply_b is not None : b = apply_b ( b ) return F . affine ( inp , w , b , base_axis ) | The affine layer also known as the fully connected layer . Computes | 342 | 14 |
222,827 | def binary_weight_affine ( inp , n_outmaps , base_axis = 1 , quantize_zero_to = 1.0 , w_init = None , wb_init = None , b_init = None , fix_parameters = False , rng = None , with_bias = True ) : if not hasattr ( n_outmaps , '__iter__' ) : n_outmaps = [ n_outmaps ] n_outmaps = list ( n_outmaps ) n_outmap = int ( np . prod ( n_outmaps ) ) if w_init is None : fan_in = np . prod ( inp . shape [ base_axis : ] ) w_init = UniformInitializer ( calc_uniform_lim_glorot ( fan_in , n_outmap ) , rng = rng ) if wb_init is None : fan_in = np . prod ( inp . shape [ base_axis : ] ) wb_init = UniformInitializer ( calc_uniform_lim_glorot ( fan_in , n_outmap ) , rng = rng ) if b_init is None : b_init = ConstantInitializer ( ) w = get_parameter_or_create ( "W" , [ int ( np . prod ( inp . shape [ base_axis : ] ) ) ] + n_outmaps , w_init , True , not fix_parameters ) wb = get_parameter_or_create ( "Wb" , [ int ( np . prod ( inp . shape [ base_axis : ] ) ) ] + n_outmaps , wb_init , False ) alpha = get_parameter_or_create ( "alpha" , n_outmaps , ConstantInitializer ( 0 ) , False ) b = None if with_bias : b = get_parameter_or_create ( "b" , n_outmaps , b_init , True , not fix_parameters ) return F . binary_weight_affine ( inp , w , wb , alpha , b , base_axis , quantize_zero_to ) | Binary Weight Affine multiplier - less inner - product with a scale factor . | 475 | 16 |
222,828 | def inq_affine ( inp , n_outmaps , base_axis = 1 , num_bits = 4 , inq_iterations = ( ) , selection_algorithm = 'random' , seed = - 1 , w_init = None , i_init = None , b_init = None , fix_parameters = False , rng = None , with_bias = True ) : if not hasattr ( n_outmaps , '__iter__' ) : n_outmaps = [ n_outmaps ] n_outmaps = list ( n_outmaps ) n_outmap = int ( np . prod ( n_outmaps ) ) if w_init is None : fan_in = np . prod ( inp . shape [ base_axis : ] ) w_init = UniformInitializer ( calc_uniform_lim_glorot ( fan_in , n_outmap ) , rng = rng ) if i_init is None : fan_in = np . prod ( inp . shape [ base_axis : ] ) i_init = ConstantInitializer ( ) if b_init is None : b_init = ConstantInitializer ( ) w = get_parameter_or_create ( "W" , [ int ( np . prod ( inp . shape [ base_axis : ] ) ) ] + n_outmaps , w_init , True , not fix_parameters ) i = get_parameter_or_create ( "I" , [ int ( np . prod ( inp . shape [ base_axis : ] ) ) ] + n_outmaps , i_init , False ) b = None if with_bias : b = get_parameter_or_create ( "b" , n_outmaps , b_init , True , not fix_parameters ) return F . inq_affine ( inp , w , i , b , base_axis , num_bits , inq_iterations , selection_algorithm , seed ) | Incremental Network Quantization Affine Layer | 437 | 8 |
222,829 | def binary_connect_convolution ( inp , outmaps , kernel , pad = None , stride = None , dilation = None , group = 1 , quantize_zero_to = 1.0 , w_init = None , wb_init = None , b_init = None , base_axis = 1 , fix_parameters = False , rng = None , with_bias = True ) : if w_init is None : w_init = UniformInitializer ( calc_uniform_lim_glorot ( inp . shape [ base_axis ] , outmaps , tuple ( kernel ) ) , rng = rng ) if wb_init is None : wb_init = UniformInitializer ( calc_uniform_lim_glorot ( inp . shape [ base_axis ] , outmaps , tuple ( kernel ) ) , rng = rng ) if b_init is None : b_init = ConstantInitializer ( ) w = get_parameter_or_create ( "W" , ( outmaps , inp . shape [ base_axis ] ) + tuple ( kernel ) , w_init , True , not fix_parameters ) wb = get_parameter_or_create ( "Wb" , ( outmaps , inp . shape [ base_axis ] ) + tuple ( kernel ) , wb_init , False ) b = None if with_bias : b = get_parameter_or_create ( "b" , ( outmaps , ) , b_init , True , not fix_parameters ) return F . binary_connect_convolution ( inp , w , wb , b , base_axis , pad , stride , dilation , group , quantize_zero_to ) | Binary Connect Convolution multiplier - less inner - product . | 382 | 12 |
222,830 | def inq_convolution ( inp , outmaps , kernel , pad = None , stride = None , dilation = None , group = 1 , num_bits = 4 , inq_iterations = ( ) , selection_algorithm = 'random' , seed = - 1 , w_init = None , i_init = None , b_init = None , base_axis = 1 , fix_parameters = False , rng = None , with_bias = True ) : if w_init is None : w_init = UniformInitializer ( calc_uniform_lim_glorot ( inp . shape [ base_axis ] , outmaps , tuple ( kernel ) ) , rng = rng ) if i_init is None : i_init = ConstantInitializer ( ) if b_init is None : b_init = ConstantInitializer ( ) w = get_parameter_or_create ( "W" , ( outmaps , inp . shape [ base_axis ] ) + tuple ( kernel ) , w_init , True , not fix_parameters ) i = get_parameter_or_create ( "I" , ( outmaps , inp . shape [ base_axis ] ) + tuple ( kernel ) , i_init , False ) b = None if with_bias : b = get_parameter_or_create ( "b" , ( outmaps , ) , b_init , True , not fix_parameters ) return F . inq_convolution ( inp , w , i , b , base_axis , pad , stride , dilation , group , num_bits , inq_iterations , selection_algorithm , seed ) | Incremental Network Quantization Convolution Layer | 366 | 8 |
222,831 | def depthwise_convolution ( inp , kernel , pad = None , stride = None , dilation = None , multiplier = 1 , w_init = None , b_init = None , base_axis = 1 , fix_parameters = False , rng = None , with_bias = True ) : if w_init is None : w_init = UniformInitializer ( calc_uniform_lim_glorot ( inp . shape [ base_axis ] * multiplier , inp . shape [ base_axis ] , tuple ( kernel ) ) , rng = rng ) if with_bias and b_init is None : b_init = ConstantInitializer ( ) w = get_parameter_or_create ( "W" , ( inp . shape [ base_axis ] * multiplier , ) + tuple ( kernel ) , w_init , True , not fix_parameters ) b = None if with_bias : b = get_parameter_or_create ( "b" , ( inp . shape [ base_axis ] * multiplier , ) , b_init , True , not fix_parameters ) return F . depthwise_convolution ( inp , w , b , base_axis , pad , stride , dilation , multiplier ) | N - D Depthwise Convolution with a bias term . | 275 | 12 |
222,832 | def batch_normalization ( inp , axes = [ 1 ] , decay_rate = 0.9 , eps = 1e-5 , batch_stat = True , output_stat = False , fix_parameters = False , param_init = None ) : shape_stat = [ 1 for _ in inp . shape ] for i in range ( len ( axes ) ) : shape_stat [ axes [ i ] ] = inp . shape [ axes [ i ] ] if param_init is None : param_init = { } beta_init = param_init . get ( 'beta' , ConstantInitializer ( 0 ) ) gamma_init = param_init . get ( 'gamma' , ConstantInitializer ( 1 ) ) mean_init = param_init . get ( 'mean' , ConstantInitializer ( 0 ) ) var_init = param_init . get ( 'var' , ConstantInitializer ( 1 ) ) beta = get_parameter_or_create ( "beta" , shape_stat , beta_init , True , not fix_parameters ) gamma = get_parameter_or_create ( "gamma" , shape_stat , gamma_init , True , not fix_parameters ) mean = get_parameter_or_create ( "mean" , shape_stat , mean_init , False ) var = get_parameter_or_create ( "var" , shape_stat , var_init , False ) return F . batch_normalization ( inp , beta , gamma , mean , var , axes , decay_rate , eps , batch_stat , output_stat ) | Batch normalization layer . | 349 | 6 |
222,833 | def mean_subtraction ( inp , base_axis = 1 , update_running_mean = True , fix_parameters = False ) : assert len ( inp . shape ) >= base_axis shape = inp . shape [ base_axis : ] mean = get_parameter_or_create ( "mean" , shape , ConstantInitializer ( 0 ) , False ) t = get_parameter_or_create ( "t" , ( 1 , ) , ConstantInitializer ( 0 ) , False ) return F . mean_subtraction ( inp , mean , t , base_axis = base_axis , update_running_mean = update_running_mean ) | Mean subtraction layer . | 147 | 6 |
222,834 | def prelu ( inp , base_axis = 1 , shared = True , fix_parameters = False ) : shape = tuple ( ) if shared else ( inp . shape [ base_axis ] , ) w = get_parameter_or_create ( "slope" , shape , ConstantInitializer ( - 1 ) , True , not fix_parameters ) return F . prelu ( inp , w , base_axis ) | Parametrized Rectified Linear Unit function defined as | 94 | 11 |
222,835 | def fixed_point_quantized_affine ( inp , n_outmaps , base_axis = 1 , w_init = None , b_init = None , fix_parameters = False , rng = None , with_bias = True , quantize_w = True , sign_w = True , n_w = 8 , delta_w = 2 ** - 4 , ste_fine_grained_w = True , quantize_b = True , sign_b = True , n_b = 8 , delta_b = 2 ** - 4 , ste_fine_grained_b = True ) : if not hasattr ( n_outmaps , '__iter__' ) : n_outmaps = [ n_outmaps ] n_outmaps = list ( n_outmaps ) n_outmap = int ( np . prod ( n_outmaps ) ) if w_init is None : inmaps = np . prod ( inp . shape [ base_axis : ] ) w_init = UniformInitializer ( calc_uniform_lim_glorot ( inmaps , n_outmap ) , rng = rng ) if with_bias and b_init is None : b_init = ConstantInitializer ( ) # Floating Weight w = get_parameter_or_create ( "W" , [ int ( np . prod ( inp . shape [ base_axis : ] ) ) ] + n_outmaps , w_init , True , not fix_parameters ) # Quantized Weight if quantize_w : w_q = get_parameter_or_create ( "W_q" , [ int ( np . prod ( inp . shape [ base_axis : ] ) ) ] + n_outmaps , w_init , False ) # Link computation graph real_w_q = F . fixed_point_quantize ( w , quantize = quantize_w , sign = sign_w , n = n_w , delta = delta_w , ste_fine_grained = ste_fine_grained_w , outputs = [ w_q . data ] ) real_w_q . persistent = True else : real_w_q = w # Bias # Floating b = None b_q = None real_b_q = None if with_bias : b = get_parameter_or_create ( "b" , n_outmaps , b_init , True , not fix_parameters ) if quantize_b : b_q = get_parameter_or_create ( "b_q" , n_outmaps , b_init , False ) # Link computation graph real_b_q = F . fixed_point_quantize ( b , quantize = quantize_b , sign = sign_b , n = n_b , delta = delta_b , ste_fine_grained = ste_fine_grained_b , outputs = [ b_q . data ] ) real_b_q . persistent = True else : real_b_q = b return F . affine ( inp , real_w_q , real_b_q , base_axis ) | Fixed - Point Quantized Affine . | 690 | 8 |
222,836 | def fixed_point_quantized_convolution ( inp , outmaps , kernel , pad = None , stride = None , dilation = None , group = 1 , w_init = None , b_init = None , base_axis = 1 , fix_parameters = False , rng = None , with_bias = True , quantize_w = True , sign_w = True , n_w = 8 , delta_w = 2 ** - 4 , ste_fine_grained_w = True , quantize_b = True , sign_b = True , n_b = 8 , delta_b = 2 ** - 4 , ste_fine_grained_b = True , ) : if w_init is None : w_init = UniformInitializer ( calc_uniform_lim_glorot ( inp . shape [ base_axis ] , outmaps , tuple ( kernel ) ) , rng = rng ) if with_bias and b_init is None : b_init = ConstantInitializer ( ) # Floating Weight w = get_parameter_or_create ( "W" , ( outmaps , inp . shape [ base_axis ] // group ) + tuple ( kernel ) , w_init , True , not fix_parameters ) # Quantized Weight if quantize_w : w_q = get_parameter_or_create ( "W_q" , ( outmaps , inp . shape [ base_axis ] // group ) + tuple ( kernel ) , w_init , False ) # Link computation graph real_w_q = F . fixed_point_quantize ( w , quantize = quantize_w , sign = sign_w , n = n_w , delta = delta_w , ste_fine_grained = ste_fine_grained_w , outputs = [ w_q . data ] ) real_w_q . persistent = True else : real_w_q = w # Bias # Floating b = None b_q = None real_b_q = None if with_bias : b = get_parameter_or_create ( "b" , ( outmaps , ) , b_init , True , not fix_parameters ) if quantize_b : b_q = get_parameter_or_create ( "b_q" , ( outmaps , ) , b_init , False ) # Link computation graph real_b_q = F . fixed_point_quantize ( b , quantize = quantize_b , sign = sign_b , n = n_b , delta = delta_b , ste_fine_grained = ste_fine_grained_b , outputs = [ b_q . data ] ) real_b_q . persistent = True else : real_b_q = b return F . convolution ( inp , real_w_q , real_b_q , base_axis , pad , stride , dilation , group ) | Fixed - Point Quantized Convolution . | 646 | 8 |
222,837 | def pow2_quantized_affine ( inp , n_outmaps , base_axis = 1 , w_init = None , b_init = None , fix_parameters = False , rng = None , with_bias = True , quantize_w = True , sign_w = True , with_zero_w = False , n_w = 8 , m_w = 2 , ste_fine_grained_w = True , quantize_b = True , sign_b = True , with_zero_b = False , n_b = 8 , m_b = 2 , ste_fine_grained_b = True ) : if not hasattr ( n_outmaps , '__iter__' ) : n_outmaps = [ n_outmaps ] n_outmaps = list ( n_outmaps ) n_outmap = int ( np . prod ( n_outmaps ) ) if w_init is None : inmaps = np . prod ( inp . shape [ base_axis : ] ) w_init = UniformInitializer ( calc_uniform_lim_glorot ( inmaps , n_outmap ) , rng = rng ) if with_bias and b_init is None : b_init = ConstantInitializer ( ) # Floating Weight w = get_parameter_or_create ( "W" , [ int ( np . prod ( inp . shape [ base_axis : ] ) ) ] + n_outmaps , w_init , True , not fix_parameters ) # Quantized Weight if quantize_w : w_q = get_parameter_or_create ( "W_q" , [ int ( np . prod ( inp . shape [ base_axis : ] ) ) ] + n_outmaps , w_init , False ) # Link computation graph real_w_q = F . pow2_quantize ( w , quantize = quantize_w , sign = sign_w , with_zero = with_zero_w , n = n_w , m = m_w , ste_fine_grained = ste_fine_grained_w , outputs = [ w_q . data ] ) real_w_q . persistent = True else : real_w_q = w # Bias # Floating b = None b_q = None real_b_q = None if with_bias : b = get_parameter_or_create ( "b" , n_outmaps , b_init , True , not fix_parameters ) if quantize_b : b_q = get_parameter_or_create ( "b_q" , n_outmaps , b_init , False ) real_b_q = F . pow2_quantize ( b , quantize = quantize_b , sign = sign_b , with_zero = with_zero_b , n = n_b , m = m_b , ste_fine_grained = ste_fine_grained_b , outputs = [ b_q . data ] ) real_b_q . persistent = True else : real_b_q = b return F . affine ( inp , real_w_q , real_b_q , base_axis ) | Pow2 Quantized Affine . | 713 | 8 |
222,838 | def pow2_quantized_convolution ( inp , outmaps , kernel , pad = None , stride = None , dilation = None , group = 1 , w_init = None , b_init = None , base_axis = 1 , fix_parameters = False , rng = None , with_bias = True , quantize_w = True , with_zero_w = False , sign_w = True , n_w = 8 , m_w = 2 , ste_fine_grained_w = True , quantize_b = True , with_zero_b = False , sign_b = True , n_b = 8 , m_b = 2 , ste_fine_grained_b = True , ) : if w_init is None : w_init = UniformInitializer ( calc_uniform_lim_glorot ( inp . shape [ base_axis ] , outmaps , tuple ( kernel ) ) , rng = rng ) if with_bias and b_init is None : b_init = ConstantInitializer ( ) # Floating Weight w = get_parameter_or_create ( "W" , ( outmaps , inp . shape [ base_axis ] // group ) + tuple ( kernel ) , w_init , True , not fix_parameters ) # Quantized Weight if quantize_w : w_q = get_parameter_or_create ( "W_q" , ( outmaps , inp . shape [ base_axis ] // group ) + tuple ( kernel ) , w_init , False ) # Link computation graph real_w_q = F . pow2_quantize ( w , quantize = quantize_w , sign = sign_w , with_zero = with_zero_w , n = n_w , m = m_w , ste_fine_grained = ste_fine_grained_w , outputs = [ w_q . data ] ) real_w_q . persistent = True else : real_w_q = w # Bias # Floating b = None b_q = None real_b_q = None if with_bias : b = get_parameter_or_create ( "b" , ( outmaps , ) , b_init , True , not fix_parameters ) if quantize_b : b_q = get_parameter_or_create ( "b_q" , ( outmaps , ) , b_init , False ) # Link computation graph real_b_q = F . pow2_quantize ( b , quantize = quantize_b , sign = sign_b , with_zero = with_zero_b , n = n_b , m = m_b , ste_fine_grained = ste_fine_grained_b , outputs = [ b_q . data ] ) real_b_q . persistent = True else : real_b_q = b return F . convolution ( inp , real_w_q , real_b_q , base_axis , pad , stride , dilation , group ) | Pow2 Quantized Convolution . | 673 | 8 |
222,839 | def pruned_affine ( inp , n_outmaps , base_axis = 1 , w_init = None , b_init = None , fix_parameters = False , rng = None , with_bias = True , prune_w = True , rate_w = 0.9 , prune_b = True , rate_b = 0.9 ) : if not hasattr ( n_outmaps , '__iter__' ) : n_outmaps = [ n_outmaps ] n_outmaps = list ( n_outmaps ) n_outmap = int ( np . prod ( n_outmaps ) ) if w_init is None : inmaps = np . prod ( inp . shape [ base_axis : ] ) w_init = UniformInitializer ( calc_uniform_lim_glorot ( inmaps , n_outmap ) , rng = rng ) if with_bias and b_init is None : b_init = ConstantInitializer ( ) # Floating Weight w = get_parameter_or_create ( "W" , [ int ( np . prod ( inp . shape [ base_axis : ] ) ) ] + n_outmaps , w_init , True , not fix_parameters ) # sparsed Weight if prune_w : w_q = get_parameter_or_create ( "W_q" , [ int ( np . prod ( inp . shape [ base_axis : ] ) ) ] + n_outmaps , w_init , False ) # Link computation graph real_w_q = F . prune ( w , rate = rate_w , outputs = [ w_q . data ] ) real_w_q . persistent = True else : real_w_q = w # Bias # Floating real_b_q = None if with_bias : b = get_parameter_or_create ( "b" , n_outmaps , b_init , True , not fix_parameters ) if prune_b : b_q = get_parameter_or_create ( "b_q" , n_outmaps , b_init , False ) # Link computation graph real_b_q = F . prune ( b , rate = rate_b , outputs = [ b_q . data ] ) real_b_q . persistent = True else : real_b_q = b return F . affine ( inp , real_w_q , real_b_q , base_axis ) | Pruned Affine . | 551 | 6 |
222,840 | def pruned_convolution ( inp , outmaps , kernel , pad = None , stride = None , dilation = None , group = 1 , w_init = None , b_init = None , base_axis = 1 , fix_parameters = False , rng = None , with_bias = True , prune_w = True , rate_w = 0.9 , prune_b = True , rate_b = 0.9 ) : if w_init is None : w_init = UniformInitializer ( calc_uniform_lim_glorot ( inp . shape [ base_axis ] , outmaps , tuple ( kernel ) ) , rng = rng ) if with_bias and b_init is None : b_init = ConstantInitializer ( ) # Floating Weight w = get_parameter_or_create ( "W" , ( outmaps , inp . shape [ base_axis ] // group ) + tuple ( kernel ) , w_init , True , not fix_parameters ) # Quantized Weight if prune_w : w_q = get_parameter_or_create ( "W_q" , ( outmaps , inp . shape [ base_axis ] // group ) + tuple ( kernel ) , w_init , False ) # Link computation graph real_w_q = F . prune ( w , rate = rate_w , outputs = [ w_q . data ] ) real_w_q . persistent = True else : real_w_q = w # Bias # Floating real_b_q = None if with_bias : b = get_parameter_or_create ( "b" , ( outmaps , ) , b_init , True , not fix_parameters ) if prune_b : b_q = get_parameter_or_create ( "b_q" , ( outmaps , ) , b_init , False ) # Link computation graph real_b_q = F . prune ( b , rate = rate_b , outputs = [ b_q . data ] ) real_b_q . persistent = True else : real_b_q = b return F . convolution ( inp , real_w_q , real_b_q , base_axis , pad , stride , dilation , group ) | Pruned Convolution . | 505 | 6 |
222,841 | def lstm_cell ( x , h , c , state_size , w_init = None , b_init = None , fix_parameters = False ) : xh = F . concatenate ( * ( x , h ) , axis = 1 ) iofc = affine ( xh , ( 4 , state_size ) , w_init = w_init , b_init = b_init , fix_parameters = fix_parameters ) i_t , o_t , f_t , gate = F . split ( iofc , axis = 1 ) c_t = F . sigmoid ( f_t ) * c + F . sigmoid ( i_t ) * F . tanh ( gate ) h_t = F . sigmoid ( o_t ) * F . tanh ( c_t ) return h_t , c_t | Long Short - Term Memory . | 192 | 6 |
222,842 | def spectral_norm ( w , dim = 0 , itr = 1 , eps = 1e-12 , test = False , u_init = None , fix_parameters = True ) : assert ( 0 <= dim and dim < len ( w . shape ) ) , "`dim` must be `0 <= dim and dim < len(w.shape)`." assert 0 < itr , "`itr` must be greater than 0." assert 0 < eps , "`eps` must be greater than 0." if dim == len ( w . shape ) - 1 : w_sn = _spectral_norm_outer_most_dim ( w , dim = dim , itr = itr , eps = eps , test = test , u_init = u_init , fix_parameters = fix_parameters ) else : w_sn = _spectral_norm ( w , dim = dim , itr = itr , eps = eps , test = test , u_init = u_init , fix_parameters = fix_parameters ) return w_sn | Spectral Normalization . | 236 | 5 |
222,843 | def reset_state ( self ) : self . h . data . zero ( ) self . c . data . zero ( ) | Resets states h and c to zero . | 26 | 9 |
222,844 | def lap ( self ) : now = time . time ( ) lap_time = now - self . lap_time total_time = now - self . start self . lap_time = now return lap_time , total_time | Calculate lap time . | 48 | 6 |
222,845 | def write ( self , fb ) : print ( '[{}.{}]' . format ( fb . module , fb . func . __name__ ) , file = self . file ) print ( 'class = {}' . format ( fb . func_ins . name ) , file = self . file ) print ( 'inspecs = {}' . format ( repr ( fb . inspecs ) ) , file = self . file ) print ( 'func_args = {}' . format ( repr ( fb . func_args ) ) , file = self . file ) print ( 'func_kwargs = {}' . format ( repr ( fb . func_kwargs ) ) , file = self . file ) print ( 'ext = ({}, {})' . format ( repr ( fb . ext ) , repr ( fb . ext_kwargs ) ) , file = self . file ) if self . setup_stat is not None : self . _write_a_stat ( 'setup' , self . setup_stat ) if self . foward_stat is not None : self . _write_a_stat ( 'forward' , self . forward_stat ) if self . backward_stat is not None : self . _write_a_stat ( 'backward' , self . backward_stat ) | Write a single function benchmark . | 283 | 6 |
222,846 | def _setup ( self , delete = True ) : if delete : self . clear ( ) with nn . context_scope ( self . ctx ) : outputs = self . func ( * ( self . inputs_f + self . func_args ) , * * self . func_kwargs ) if not hasattr ( outputs , '__iter__' ) : self . outputs = [ outputs ] else : self . outputs = outputs self . func_ins = self . outputs [ 0 ] . parent self . inputs = self . func_ins . inputs | Create a function instance and execute setup . | 116 | 8 |
222,847 | def benchmark_setup ( self ) : def f ( ) : self . _setup ( ) self . mod_ext . synchronize ( * * self . ext_kwargs ) f ( ) # Ignore first self . setup_stat = self . _calc_benchmark_stat ( f ) | Benchmark setup execution . | 62 | 5 |
222,848 | def benchmark_forward ( self ) : self . _setup ( ) def f ( ) : self . _forward ( ) self . mod_ext . synchronize ( * * self . ext_kwargs ) f ( ) # Ignore first self . forward_stat = self . _calc_benchmark_stat ( f ) | Benchmark forward execution . | 68 | 5 |
222,849 | def benchmark_backward ( self ) : try : self . _benchmark_backward ( ) except RuntimeError as e : # Seems like not implemented. print ( e ) self . mod_ext . synchronize ( * * self . ext_kwargs ) self . backward_stat = None | Benchmark backward execution . | 62 | 5 |
222,850 | def context ( type_config = 'float' , * * kw ) : backends = [ 'cpu:float' ] if type_config == 'half' : backends = [ 'cpu:half' , 'cpu:float' ] elif type_config == 'float' : pass else : raise ValueError ( "Unknown data type config is given %s" % type_config ) return nn . Context ( backends , array_classes ( ) [ 0 ] , '' ) | CPU Context . | 104 | 3 |
222,851 | def revise_buffer_size ( info , settings ) : size_mapping = { 'FLOAT32' : 4 , 'FIXED16' : 2 , 'FIXED8' : 1 } var_dict = settings [ 'variables' ] buffer_index = 0 info . _variable_sizes = [ ] info . _variable_buffer_index = collections . OrderedDict ( ) info . _variable_buffer_size = collections . OrderedDict ( ) info . _buffer_ids = { } for n , v in enumerate ( info . _network . variable ) : byte_per_item = size_mapping . get ( var_dict . get ( v . name , 'FLOAT32' ) . split ( '_' ) [ 0 ] , 4 ) size = nnabla . utils . converter . calc_shape_size ( v . shape , info . _batch_size ) * byte_per_item info . _variable_sizes . append ( size ) if v . type == 'Buffer' : info . _variable_buffer_index [ buffer_index ] = [ n ] for vid in info . _variable_buffer_index [ buffer_index ] : info . _buffer_ids [ vid ] = buffer_index info . _variable_buffer_size [ buffer_index ] = size buffer_index += 1 | This function is used to revise buffer size use byte as its unit instead of data item . This is only used for nnb not for csrc . When settings contains user customized data type not pure FLOAT32 it affects the memory consumption . | 296 | 49 |
222,852 | def category_names ( self ) : if hasattr ( self , '_category_names' ) : return self . _category_names with open ( os . path . join ( os . path . dirname ( __file__ ) , 'category_names.txt' ) , 'r' ) as fd : self . _category_names = fd . read ( ) . splitlines ( ) return self . _category_names | Returns category names of 1000 ImageNet classes . | 92 | 9 |
222,853 | def write ( self ) : writer = csv . writer ( self . file ) for f , b in zip ( self . gb . result [ "forward" ] , self . gb . result [ "backward" ] ) : f = f . _asdict ( ) b = b . _asdict ( ) if not self . check_same ( f , b ) : raise AssertionError ( ) args_info = ", " . join ( [ "{}: {}" . format ( k , v ) for k , v in f [ "args_info" ] ] ) out = [ f [ "parameter_scope" ] , f [ "function_name" ] , f [ "inputs_shape" ] , args_info , f [ "mean_time" ] , b [ "mean_time" ] , f [ "n_run" ] , b [ "n_run" ] ] writer . writerow ( out ) writer . writerow ( [ ] ) writer . writerow ( [ "forward all" , self . gb . result [ "forward_all" ] ] ) writer . writerow ( [ "forward_all_n_run" , self . gb . result [ "n_run_forward_all" ] ] ) writer . writerow ( [ ] ) writer . writerow ( [ "backward all" , self . gb . result [ "backward_all" ] ] ) writer . writerow ( [ "backward_all_n_run" , self . gb . result [ "n_run_backward_all" ] ] ) if set ( self . gb . result . keys ( ) ) >= { "training" , "n_run_training" } : writer . writerow ( [ ] ) writer . writerow ( [ "training(forward + backward + update)" , self . gb . result [ "training" ] ] ) writer . writerow ( [ "training_n_run" , self . gb . result [ "n_run_training" ] ] ) | Write result to the file . The output file is specified by file . | 442 | 14 |
222,854 | def plot_series ( filename , plot_kwargs = None ) : import matplotlib . pyplot as plt if plot_kwargs is None : plot_kwargs = { } data = np . genfromtxt ( filename , dtype = 'i8,f4' , names = [ 'k' , 'v' ] ) index = data [ 'k' ] values = data [ 'v' ] plt . plot ( index , values , * * plot_kwargs ) | Plot series data from MonitorSeries output text file . | 105 | 10 |
222,855 | def plot_time_elapsed ( filename , elapsed = False , unit = 's' , plot_kwargs = None ) : import matplotlib . pyplot as plt if plot_kwargs is None : plot_kwargs = { } data_column = 3 if elapsed else 1 data = np . genfromtxt ( filename , dtype = 'i8,f4' , usecols = ( 0 , data_column ) , names = [ 'k' , 'v' ] ) index = data [ 'k' ] values = data [ 'v' ] if unit == 's' : pass elif unit == 'm' : values /= 60 elif unit == 'h' : values /= 3600 elif unit == 'd' : values /= 3600 * 24 else : raise ValueError ( 'The argument `unit` must be chosen from {s|m|h|d}.' ) plt . plot ( index , values , * * plot_kwargs ) | Plot series data from MonitorTimeElapsed output text file . | 214 | 12 |
222,856 | def add ( self , index , value ) : self . buf . append ( value ) if ( index - self . flush_at ) < self . interval : return value = np . mean ( self . buf ) if self . verbose : logger . info ( "iter={} {{{}}}={}" . format ( index , self . name , value ) ) if self . fd is not None : print ( "{} {:g}" . format ( index , value ) , file = self . fd ) self . flush_at = index self . buf = [ ] | Add a value to the series . | 119 | 7 |
222,857 | def add ( self , index ) : if ( index - self . flush_at ) < self . interval : return now = time . time ( ) elapsed = now - self . lap elapsed_total = now - self . start it = index - self . flush_at self . lap = now if self . verbose : logger . info ( "iter={} {{{}}}={}[sec/{}iter] {}[sec]" . format ( index , self . name , elapsed , it , elapsed_total ) ) if self . fd is not None : print ( "{} {} {} {}" . format ( index , elapsed , it , elapsed_total ) , file = self . fd ) self . flush_at = index | Calculate time elapsed from the point previously called this method or this object is created to this is called . | 154 | 22 |
222,858 | def add ( self , index , var ) : import nnabla as nn from nnabla . utils . image_utils import imsave if index != 0 and ( index + 1 ) % self . interval != 0 : return if isinstance ( var , nn . Variable ) : data = var . d . copy ( ) elif isinstance ( var , nn . NdArray ) : data = var . data . copy ( ) else : assert isinstance ( var , np . ndarray ) data = var . copy ( ) assert data . ndim > 2 channels = data . shape [ - 3 ] data = data . reshape ( - 1 , * data . shape [ - 3 : ] ) data = data [ : min ( data . shape [ 0 ] , self . num_images ) ] data = self . normalize_method ( data ) if channels > 3 : data = data [ : , : 3 ] elif channels == 2 : data = np . concatenate ( [ data , np . ones ( ( data . shape [ 0 ] , 1 ) + data . shape [ - 2 : ] ) ] , axis = 1 ) path_tmpl = os . path . join ( self . save_dir , '{:06d}-{}.png' ) for j in range ( min ( self . num_images , data . shape [ 0 ] ) ) : img = data [ j ] . transpose ( 1 , 2 , 0 ) if img . shape [ - 1 ] == 1 : img = img [ ... , 0 ] path = path_tmpl . format ( index , '{:03d}' . format ( j ) ) imsave ( path , img ) if self . verbose : logger . info ( "iter={} {{{}}} are written to {}." . format ( index , self . name , path_tmpl . format ( index , '*' ) ) ) | Add a minibatch of images to the monitor . | 409 | 11 |
222,859 | def data_iterator_simple ( load_func , num_examples , batch_size , shuffle = False , rng = None , with_memory_cache = True , with_file_cache = True , cache_dir = None , epoch_begin_callbacks = [ ] , epoch_end_callbacks = [ ] ) : return data_iterator ( SimpleDataSource ( load_func , num_examples , shuffle = shuffle , rng = rng ) , batch_size = batch_size , with_memory_cache = with_memory_cache , with_file_cache = with_file_cache , cache_dir = cache_dir , epoch_begin_callbacks = epoch_begin_callbacks , epoch_end_callbacks = epoch_end_callbacks ) | A generator that yield s minibatch data as a tuple as defined in load_func . It can unlimitedly yield minibatches at your request queried from the provided data . | 169 | 37 |
222,860 | def data_iterator_csv_dataset ( uri , batch_size , shuffle = False , rng = None , normalize = True , with_memory_cache = True , with_file_cache = True , cache_dir = None , epoch_begin_callbacks = [ ] , epoch_end_callbacks = [ ] ) : ds = CsvDataSource ( uri , shuffle = shuffle , rng = rng , normalize = normalize ) return data_iterator ( ds , batch_size = batch_size , with_memory_cache = with_memory_cache , with_file_cache = with_file_cache , cache_dir = cache_dir , epoch_begin_callbacks = epoch_begin_callbacks , epoch_end_callbacks = epoch_end_callbacks ) | data_iterator_csv_dataset Get data directly from a dataset provided as a CSV file . | 178 | 21 |
222,861 | def data_iterator_cache ( uri , batch_size , shuffle = False , rng = None , normalize = True , with_memory_cache = True , epoch_begin_callbacks = [ ] , epoch_end_callbacks = [ ] ) : ds = CacheDataSource ( uri , shuffle = shuffle , rng = rng , normalize = normalize ) return data_iterator ( ds , batch_size = batch_size , with_memory_cache = with_memory_cache , epoch_begin_callbacks = epoch_begin_callbacks , epoch_end_callbacks = epoch_end_callbacks ) | data_iterator_cache Get data from the cache directory . | 139 | 12 |
222,862 | def data_iterator_concat_datasets ( data_source_list , batch_size , shuffle = False , rng = None , with_memory_cache = True , with_file_cache = False , cache_dir = None , epoch_begin_callbacks = [ ] , epoch_end_callbacks = [ ] ) : ds = ConcatDataSource ( data_source_list , shuffle = shuffle , rng = rng ) return data_iterator ( ds , batch_size = batch_size , with_memory_cache = with_memory_cache , with_file_cache = with_file_cache , epoch_begin_callbacks = epoch_begin_callbacks , epoch_end_callbacks = epoch_end_callbacks ) | data_iterator_concat_datasets Get data from multiple datasets . | 166 | 16 |
222,863 | def slice ( self , rng , num_of_slices = None , slice_pos = None , slice_start = None , slice_end = None , cache_dir = None ) : if num_of_slices is not None and slice_pos is not None and slice_start is None and slice_end is None : size = self . _size // num_of_slices amount = self . _size % num_of_slices slice_start = slice_pos * size if slice_pos < amount : slice_start += slice_pos else : slice_start += amount slice_end = slice_start + size if slice_end > self . _size : slice_start -= ( slice_end - self . _size ) slice_end = self . _size elif num_of_slices is None and slice_pos is None and slice_start is not None and slice_end is not None : pass else : logger . critical ( 'You must specify position(num_of_slice and slice_pos) or range(slice_start and slice_end).' ) return None if cache_dir is None : ds = self . _data_source while '_data_source' in dir ( ds ) : if '_cache_dir' in dir ( ds ) : cache_dir = ds . _cache_dir ds = ds . _data_source if cache_dir is None : return DataIterator ( DataSourceWithMemoryCache ( SlicedDataSource ( self . _data_source , self . _data_source . shuffle , slice_start = slice_start , slice_end = slice_end ) , shuffle = self . _shuffle , rng = rng ) , self . _batch_size ) else : return DataIterator ( DataSourceWithMemoryCache ( DataSourceWithFileCache ( SlicedDataSource ( self . _data_source , self . _data_source . shuffle , slice_start = slice_start , slice_end = slice_end ) , cache_dir = cache_dir , cache_file_name_prefix = 'cache_sliced_{:08d}_{:08d}' . format ( slice_start , slice_end ) , shuffle = self . _shuffle , rng = rng ) , shuffle = self . _shuffle , rng = rng ) , self . _batch_size ) | Slices the data iterator so that newly generated data iterator has access to limited portion of the original data . | 525 | 22 |
222,864 | def auto_forward ( auto = True ) : global __auto_forward_state prev = __auto_forward_state __auto_forward_state = auto yield __auto_forward_state = prev | Context for dynamic graph execution mode . | 42 | 7 |
222,865 | def print_stats ( self , reset = True ) : if not self . ncalls : return stats = self . stats code = self . fn . __code__ print ( '--- Function Profiling ---' ) print ( 'File "{}", line {}, function {}' . format ( code . co_filename , code . co_firstlineno , self . fn . __name__ ) ) stats . sort_stats ( * self . sort_keys ) stats . print_stats ( * self . print_restrictions ) print ( '--------------------------' ) if reset : self . reset_stats ( ) | Manually print profiling result . | 129 | 6 |
222,866 | def get_model_home ( ) : d = os . path . join ( get_data_home ( ) , 'nnp_models' ) if not os . path . isdir ( d ) : os . makedirs ( d ) return d | Returns a root folder path for downloading models . | 54 | 9 |
222,867 | def get_model_url_base ( ) : url_base = get_model_url_base_from_env ( ) if url_base is not None : logger . info ( 'NNBLA_MODELS_URL_BASE is set as {}.' . format ( url_base ) ) else : url_base = 'https://nnabla.org/pretrained-models/nnp_models/' return url_base | Returns a root folder for models . | 95 | 7 |
222,868 | def load_image_imread ( file , shape = None , max_range = 1.0 ) : img255 = imread ( file ) # return value is from zero to 255 (even if the image has 16-bitdepth.) if len ( img255 . shape ) == 2 : # gray image height , width = img255 . shape if shape is None : out_height , out_width , out_n_color = height , width , 1 else : out_n_color , out_height , out_width = shape assert ( out_n_color == 1 ) if out_height != height or out_width != width : # imresize returns 0 to 255 image. img255 = imresize ( img255 , ( out_height , out_width ) ) img255 = img255 . reshape ( ( out_n_color , out_height , out_width ) ) elif len ( img255 . shape ) == 3 : # RGB image height , width , n_color = img255 . shape if shape is None : out_height , out_width , out_n_color = height , width , n_color else : out_n_color , out_height , out_width = shape assert ( out_n_color == n_color ) if out_height != height or out_width != width or out_n_color != n_color : # imresize returns 0 to 255 image. img255 = imresize ( img255 , ( out_height , out_width , out_n_color ) ) img255 = img255 . transpose ( 2 , 0 , 1 ) if max_range < 0 or max_range == 255.0 : return img255 else : return img255 * ( max_range / 255.0 ) | Load image from file like object . | 380 | 7 |
222,869 | def load_csv ( file , shape = None , normalize = False ) : value_list = [ ] if six . PY2 : for row in csv . reader ( file ) : value_list . append ( list ( map ( float , row ) ) ) elif six . PY34 : for row in csv . reader ( [ l . decode ( 'utf-8' ) for l in file . readlines ( ) ] ) : value_list . append ( list ( map ( float , row ) ) ) if shape is None : return numpy . array ( value_list ) else : return numpy . array ( value_list ) . reshape ( shape ) | Load CSV file . | 145 | 4 |
222,870 | def save ( self , vleaf , fpath , cleanup = False , format = None ) : graph = self . create_graphviz_digraph ( vleaf , format = format ) graph . render ( fpath , cleanup = cleanup ) | Save the graph to a given file path . | 51 | 9 |
222,871 | def view ( self , vleaf , fpath = None , cleanup = True , format = None ) : graph = self . create_graphviz_digraph ( vleaf , format = format ) graph . view ( fpath , cleanup = cleanup ) | View the graph . | 53 | 4 |
222,872 | def get_modules ( self , memo = None , prefix = "" ) : if memo is None : memo = set ( ) if self not in memo : memo . add ( self ) yield prefix , self for k , v in self . __dict__ . items ( ) : if not isinstance ( v , Module ) : continue name , module = k , v submodule_prefix = "{}/{}" . format ( prefix , name ) if prefix != "" else name for m in module . get_modules ( memo , submodule_prefix ) : yield m | Get modules . | 117 | 3 |
222,873 | def get_prep_value ( self , value ) : if value is None or value == "" : return None if isinstance ( value , six . string_types ) : value = _hex_string_to_unsigned_integer ( value ) if _using_signed_storage ( ) : value = _unsigned_to_signed_integer ( value ) return value | Return the integer value to be stored from the hex string | 76 | 11 |
222,874 | def from_db_value ( self , value , expression , connection , context ) : if value is None : return value if _using_signed_storage ( ) : value = _signed_to_unsigned_integer ( value ) return value | Return an unsigned int representation from all db backends | 50 | 10 |
222,875 | def to_python ( self , value ) : if isinstance ( value , six . string_types ) : return value if value is None : return value return _unsigned_integer_to_hex_string ( value ) | Return a str representation of the hexadecimal | 46 | 10 |
222,876 | def apns_send_bulk_message ( registration_ids , alert , application_id = None , certfile = None , * * kwargs ) : results = _apns_send ( registration_ids , alert , batch = True , application_id = application_id , certfile = certfile , * * kwargs ) inactive_tokens = [ token for token , result in results . items ( ) if result == "Unregistered" ] models . APNSDevice . objects . filter ( registration_id__in = inactive_tokens ) . update ( active = False ) return results | Sends an APNS notification to one or more registration_ids . The registration_ids argument needs to be a list . | 130 | 25 |
222,877 | def _cm_send_request ( registration_ids , data , cloud_type = "GCM" , application_id = None , use_fcm_notifications = True , * * kwargs ) : payload = { "registration_ids" : registration_ids } if registration_ids else { } data = data . copy ( ) # If using FCM, optionnally autodiscovers notification related keys # https://firebase.google.com/docs/cloud-messaging/concept-options#notifications_and_data_messages if cloud_type == "FCM" and use_fcm_notifications : notification_payload = { } if "message" in data : notification_payload [ "body" ] = data . pop ( "message" , None ) for key in FCM_NOTIFICATIONS_PAYLOAD_KEYS : value_from_extra = data . pop ( key , None ) if value_from_extra : notification_payload [ key ] = value_from_extra value_from_kwargs = kwargs . pop ( key , None ) if value_from_kwargs : notification_payload [ key ] = value_from_kwargs if notification_payload : payload [ "notification" ] = notification_payload if data : payload [ "data" ] = data # Attach any additional non falsy keyword args (targets, options) # See ref : https://firebase.google.com/docs/cloud-messaging/http-server-ref#table1 payload . update ( { k : v for k , v in kwargs . items ( ) if v and ( k in FCM_TARGETS_KEYS or k in FCM_OPTIONS_KEYS ) } ) # Sort the keys for deterministic output (useful for tests) json_payload = json . dumps ( payload , separators = ( "," , ":" ) , sort_keys = True ) . encode ( "utf-8" ) # Sends requests and handles the response if cloud_type == "GCM" : response = json . loads ( _gcm_send ( json_payload , "application/json" , application_id = application_id ) ) elif cloud_type == "FCM" : response = json . loads ( _fcm_send ( json_payload , "application/json" , application_id = application_id ) ) else : raise ImproperlyConfigured ( "cloud_type must be FCM or GCM not %s" % str ( cloud_type ) ) return _cm_handle_response ( registration_ids , response , cloud_type , application_id ) | Sends a FCM or GCM notification to one or more registration_ids as json data . The registration_ids needs to be a list . | 584 | 30 |
222,878 | def _cm_handle_canonical_id ( canonical_id , current_id , cloud_type ) : devices = GCMDevice . objects . filter ( cloud_message_type = cloud_type ) if devices . filter ( registration_id = canonical_id , active = True ) . exists ( ) : devices . filter ( registration_id = current_id ) . update ( active = False ) else : devices . filter ( registration_id = current_id ) . update ( registration_id = canonical_id ) | Handle situation when FCM server response contains canonical ID | 111 | 10 |
222,879 | def _validate_applications ( self , apps ) : for application_id , application_config in apps . items ( ) : self . _validate_config ( application_id , application_config ) application_config [ "APPLICATION_ID" ] = application_id | Validate the application collection | 61 | 5 |
222,880 | def _validate_apns_certificate ( self , certfile ) : try : with open ( certfile , "r" ) as f : content = f . read ( ) check_apns_certificate ( content ) except Exception as e : raise ImproperlyConfigured ( "The APNS certificate file at %r is not readable: %s" % ( certfile , e ) ) | Validate the APNS certificate at startup . | 85 | 9 |
222,881 | def _validate_allowed_settings ( self , application_id , application_config , allowed_settings ) : for setting_key in application_config . keys ( ) : if setting_key not in allowed_settings : raise ImproperlyConfigured ( "Platform {}, app {} does not support the setting: {}." . format ( application_config [ "PLATFORM" ] , application_id , setting_key ) ) | Confirm only allowed settings are present . | 91 | 8 |
222,882 | def _validate_required_settings ( self , application_id , application_config , required_settings ) : for setting_key in required_settings : if setting_key not in application_config . keys ( ) : raise ImproperlyConfigured ( MISSING_SETTING . format ( application_id = application_id , setting = setting_key ) ) | All required keys must be present | 77 | 6 |
222,883 | def _get_application_settings ( self , application_id , platform , settings_key ) : if not application_id : conf_cls = "push_notifications.conf.AppConfig" raise ImproperlyConfigured ( "{} requires the application_id be specified at all times." . format ( conf_cls ) ) # verify that the application config exists app_config = self . _settings . get ( "APPLICATIONS" ) . get ( application_id , None ) if app_config is None : raise ImproperlyConfigured ( "No application configured with application_id: {}." . format ( application_id ) ) # fetch a setting for the incorrect type of platform if app_config . get ( "PLATFORM" ) != platform : raise ImproperlyConfigured ( SETTING_MISMATCH . format ( application_id = application_id , platform = app_config . get ( "PLATFORM" ) , setting = settings_key ) ) # finally, try to fetch the setting if settings_key not in app_config : raise ImproperlyConfigured ( MISSING_SETTING . format ( application_id = application_id , setting = settings_key ) ) return app_config . get ( settings_key ) | Walks through PUSH_NOTIFICATIONS_SETTINGS to find the correct setting value or raises ImproperlyConfigured . | 269 | 27 |
222,884 | def _wns_authenticate ( scope = "notify.windows.com" , application_id = None ) : client_id = get_manager ( ) . get_wns_package_security_id ( application_id ) client_secret = get_manager ( ) . get_wns_secret_key ( application_id ) if not client_id : raise ImproperlyConfigured ( 'You need to set PUSH_NOTIFICATIONS_SETTINGS["WNS_PACKAGE_SECURITY_ID"] to use WNS.' ) if not client_secret : raise ImproperlyConfigured ( 'You need to set PUSH_NOTIFICATIONS_SETTINGS["WNS_SECRET_KEY"] to use WNS.' ) headers = { "Content-Type" : "application/x-www-form-urlencoded" , } params = { "grant_type" : "client_credentials" , "client_id" : client_id , "client_secret" : client_secret , "scope" : scope , } data = urlencode ( params ) . encode ( "utf-8" ) request = Request ( SETTINGS [ "WNS_ACCESS_URL" ] , data = data , headers = headers ) try : response = urlopen ( request ) except HTTPError as err : if err . code == 400 : # One of your settings is probably jacked up. # https://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh868245 raise WNSAuthenticationError ( "Authentication failed, check your WNS settings." ) raise err oauth_data = response . read ( ) . decode ( "utf-8" ) try : oauth_data = json . loads ( oauth_data ) except Exception : # Upstream WNS issue raise WNSAuthenticationError ( "Received invalid JSON data from WNS." ) access_token = oauth_data . get ( "access_token" ) if not access_token : # Upstream WNS issue raise WNSAuthenticationError ( "Access token missing from WNS response." ) return access_token | Requests an Access token for WNS communication . | 474 | 10 |
222,885 | def _wns_send ( uri , data , wns_type = "wns/toast" , application_id = None ) : access_token = _wns_authenticate ( application_id = application_id ) content_type = "text/xml" if wns_type == "wns/raw" : content_type = "application/octet-stream" headers = { # content_type is "text/xml" (toast/badge/tile) | "application/octet-stream" (raw) "Content-Type" : content_type , "Authorization" : "Bearer %s" % ( access_token ) , "X-WNS-Type" : wns_type , # wns/toast | wns/badge | wns/tile | wns/raw } if type ( data ) is str : data = data . encode ( "utf-8" ) request = Request ( uri , data , headers ) # A lot of things can happen, let them know which one. try : response = urlopen ( request ) except HTTPError as err : if err . code == 400 : msg = "One or more headers were specified incorrectly or conflict with another header." elif err . code == 401 : msg = "The cloud service did not present a valid authentication ticket." elif err . code == 403 : msg = "The cloud service is not authorized to send a notification to this URI." elif err . code == 404 : msg = "The channel URI is not valid or is not recognized by WNS." elif err . code == 405 : msg = "Invalid method. Only POST or DELETE is allowed." elif err . code == 406 : msg = "The cloud service exceeded its throttle limit" elif err . code == 410 : msg = "The channel expired." elif err . code == 413 : msg = "The notification payload exceeds the 500 byte limit." elif err . code == 500 : msg = "An internal failure caused notification delivery to fail." elif err . code == 503 : msg = "The server is currently unavailable." else : raise err raise WNSNotificationResponseError ( "HTTP %i: %s" % ( err . code , msg ) ) return response . read ( ) . decode ( "utf-8" ) | Sends a notification data and authentication to WNS . | 497 | 11 |
222,886 | def _wns_prepare_toast ( data , * * kwargs ) : root = ET . Element ( "toast" ) visual = ET . SubElement ( root , "visual" ) binding = ET . SubElement ( visual , "binding" ) binding . attrib [ "template" ] = kwargs . pop ( "template" , "ToastText01" ) if "text" in data : for count , item in enumerate ( data [ "text" ] , start = 1 ) : elem = ET . SubElement ( binding , "text" ) elem . text = item elem . attrib [ "id" ] = str ( count ) if "image" in data : for count , item in enumerate ( data [ "image" ] , start = 1 ) : elem = ET . SubElement ( binding , "img" ) elem . attrib [ "src" ] = item elem . attrib [ "id" ] = str ( count ) return ET . tostring ( root ) | Creates the xml tree for a toast notification | 222 | 9 |
222,887 | def wns_send_bulk_message ( uri_list , message = None , xml_data = None , raw_data = None , application_id = None , * * kwargs ) : res = [ ] if uri_list : for uri in uri_list : r = wns_send_message ( uri = uri , message = message , xml_data = xml_data , raw_data = raw_data , application_id = application_id , * * kwargs ) res . append ( r ) return res | WNS doesn t support bulk notification so we loop through each uri . | 121 | 15 |
222,888 | def _add_sub_elements_from_dict ( parent , sub_dict ) : for key , value in sub_dict . items ( ) : if isinstance ( value , list ) : for repeated_element in value : sub_element = ET . SubElement ( parent , key ) _add_element_attrs ( sub_element , repeated_element . get ( "attrs" , { } ) ) children = repeated_element . get ( "children" , None ) if isinstance ( children , dict ) : _add_sub_elements_from_dict ( sub_element , children ) elif isinstance ( children , str ) : sub_element . text = children else : sub_element = ET . SubElement ( parent , key ) _add_element_attrs ( sub_element , value . get ( "attrs" , { } ) ) children = value . get ( "children" , None ) if isinstance ( children , dict ) : _add_sub_elements_from_dict ( sub_element , children ) elif isinstance ( children , str ) : sub_element . text = children | Add SubElements to the parent element . | 243 | 9 |
222,889 | def _add_element_attrs ( elem , attrs ) : for attr , value in attrs . items ( ) : elem . attrib [ attr ] = value return elem | Add attributes to the given element . | 43 | 7 |
222,890 | def login ( self , host_spec = "" , username = "" , password = "" ) : warnings . warn ( "shouldn't use this function anymore ! use connect which handles" "handles authentication directly." , DeprecationWarning ) scheme = "http" if not host_spec : u = urlparse ( self . endpoint ) host_spec = u . netloc if u . scheme == "wss" : scheme = "https" if self . username : username = self . username if self . password : password = self . password auth = Authenticate ( host_spec , scheme = scheme , username = username , password = password ) try : auth . login ( ) cookie = 'authtok={}' . format ( auth . authtok ) if self . cookies : self . cookies . append ( cookie ) else : self . cookies = [ cookie , ] return True except Exception : return False | Authenticate with infrastructure via the Skydive analyzer | 189 | 11 |
222,891 | def _sdkmanager ( self , * args , * * kwargs ) : # Use the android-sdk dir as cwd by default kwargs [ 'cwd' ] = kwargs . get ( 'cwd' , self . android_sdk_dir ) command = self . sdkmanager_path + ' ' + ' ' . join ( args ) return_child = kwargs . pop ( 'return_child' , False ) if return_child : return self . buildozer . cmd_expect ( command , * * kwargs ) else : kwargs [ 'get_stdout' ] = kwargs . get ( 'get_stdout' , True ) return self . buildozer . cmd ( command , * * kwargs ) | Call the sdkmanager in our Android SDK with the given arguments . | 170 | 14 |
222,892 | def _android_get_installed_platform_tools_version ( self ) : platform_tools_dir = os . path . join ( self . android_sdk_dir , 'platform-tools' ) if not os . path . exists ( platform_tools_dir ) : return None data_file = os . path . join ( platform_tools_dir , 'source.properties' ) if not os . path . exists ( data_file ) : return None with open ( data_file , 'r' ) as fileh : lines = fileh . readlines ( ) for line in lines : if line . startswith ( 'Pkg.Revision=' ) : break else : self . buildozer . error ( 'Read {} but found no Pkg.Revision' . format ( data_file ) ) # Don't actually exit, in case the build env is # okay. Something else will fault if it's important. return None revision = line . split ( '=' ) [ 1 ] . strip ( ) return revision | Crudely parse out the installed platform - tools version | 218 | 11 |
222,893 | def _android_update_sdk ( self , * sdkmanager_commands ) : auto_accept_license = self . buildozer . config . getbooldefault ( 'app' , 'android.accept_sdk_license' , False ) if auto_accept_license : # `SIGPIPE` is not being reported somehow, but `EPIPE` is. # This leads to a stderr "Broken pipe" message which is harmless, # but doesn't look good on terminal, hence redirecting to /dev/null yes_command = 'yes 2>/dev/null' command = '{} | {} --licenses' . format ( yes_command , self . sdkmanager_path ) self . buildozer . cmd ( command , cwd = self . android_sdk_dir ) self . _sdkmanager ( * sdkmanager_commands ) | Update the tools and package - tools if possible | 197 | 9 |
222,894 | def cmd_logcat ( self , * args ) : self . check_requirements ( ) serial = self . serials [ 0 : ] if not serial : return filters = self . buildozer . config . getrawdefault ( "app" , "android.logcat_filters" , "" , section_sep = ":" , split_char = " " ) filters = " " . join ( filters ) self . buildozer . environ [ 'ANDROID_SERIAL' ] = serial [ 0 ] self . buildozer . cmd ( '{adb} logcat {filters}' . format ( adb = self . adb_cmd , filters = filters ) , cwd = self . buildozer . global_platform_dir , show_output = True ) self . buildozer . environ . pop ( 'ANDROID_SERIAL' , None ) | Show the log from the device | 193 | 6 |
222,895 | def path_or_git_url ( self , repo , owner = 'kivy' , branch = 'master' , url_format = 'https://github.com/{owner}/{repo}.git' , platform = None , squash_hyphen = True ) : if squash_hyphen : key = repo . replace ( '-' , '_' ) else : key = repo if platform : key = "{}.{}" . format ( platform , key ) config = self . buildozer . config path = config . getdefault ( 'app' , '{}_dir' . format ( key ) , None ) if path is not None : path = join ( self . buildozer . root_dir , path ) url = None branch = None else : branch = config . getdefault ( 'app' , '{}_branch' . format ( key ) , branch ) default_url = url_format . format ( owner = owner , repo = repo , branch = branch ) url = config . getdefault ( 'app' , '{}_url' . format ( key ) , default_url ) if branch != 'master' : url = "--branch {} {}" . format ( branch , url ) return path , url , branch | Get source location for a git checkout | 269 | 7 |
222,896 | def install_or_update_repo ( self , repo , * * kwargs ) : cmd = self . buildozer . cmd install_dir = join ( self . buildozer . platform_dir , repo ) custom_dir , clone_url , clone_branch = self . path_or_git_url ( repo , * * kwargs ) if not self . buildozer . file_exists ( install_dir ) : if custom_dir : cmd ( 'mkdir -p "{}"' . format ( install_dir ) ) cmd ( 'cp -a "{}"/* "{}"/' . format ( custom_dir , install_dir ) ) else : cmd ( 'git clone {}' . format ( clone_url ) , cwd = self . buildozer . platform_dir ) elif self . platform_update : if custom_dir : cmd ( 'cp -a "{}"/* "{}"/' . format ( custom_dir , install_dir ) ) else : cmd ( 'git clean -dxf' , cwd = install_dir ) cmd ( 'git pull origin {}' . format ( clone_branch ) , cwd = install_dir ) return install_dir | Install or update a git repository into the platform directory . | 260 | 11 |
222,897 | def set_config_token_from_env ( section , token , config ) : env_var_name = '' . join ( [ section . upper ( ) , '_' , token . upper ( ) . replace ( '.' , '_' ) ] ) env_var = os . environ . get ( env_var_name ) if env_var is None : return False config . set ( section , token , env_var ) return True | Given a config section and token checks for an appropriate environment variable . If the variable exists sets the config entry to its value . | 96 | 25 |
222,898 | def prepare_for_build ( self ) : assert ( self . target is not None ) if hasattr ( self . target , '_build_prepared' ) : return self . info ( 'Preparing build' ) self . info ( 'Check requirements for {0}' . format ( self . targetname ) ) self . target . check_requirements ( ) self . info ( 'Install platform' ) self . target . install_platform ( ) self . info ( 'Check application requirements' ) self . check_application_requirements ( ) self . info ( 'Check garden requirements' ) self . check_garden_requirements ( ) self . info ( 'Compile platform' ) self . target . compile_platform ( ) # flag to prevent multiple build self . target . _build_prepared = True | Prepare the build . | 173 | 5 |
222,899 | def build ( self ) : assert ( self . target is not None ) assert ( hasattr ( self . target , '_build_prepared' ) ) if hasattr ( self . target , '_build_done' ) : return # increment the build number self . build_id = int ( self . state . get ( 'cache.build_id' , '0' ) ) + 1 self . state [ 'cache.build_id' ] = str ( self . build_id ) self . info ( 'Build the application #{}' . format ( self . build_id ) ) self . build_application ( ) self . info ( 'Package the application' ) self . target . build_package ( ) # flag to prevent multiple build self . target . _build_done = True | Do the build . | 169 | 4 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.