idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
33,800
def allconcat_ring ( xs , devices , concat_axis ) : n = len ( xs ) if n == 1 : return xs parts = [ [ xs [ target ] if target == source else None for source in xrange ( n ) ] for target in xrange ( n ) ] for distance in xrange ( 1 , n // 2 + 1 ) : for target in xrange ( n ) : source = ( target + distance ) % n if parts ...
Concatenate all Tensors everywhere .
33,801
def Print ( self , x , data , message , ** kwargs ) : tf . logging . info ( "PlacementMeshImpl::Print" ) new_slices = x . tensor_list [ : ] with tf . device ( self . _devices [ 0 ] ) : new_slices [ 0 ] = tf . Print ( new_slices [ 0 ] , [ t for d in data for t in d . tensor_list ] , message , ** kwargs ) return self . L...
call tf . Print .
33,802
def alltoall ( self , x , mesh_axis , split_axis , concat_axis ) : return self . _collective_with_groups ( x , [ mesh_axis ] , functools . partial ( alltoall_ring , split_axis = split_axis , concat_axis = concat_axis ) )
Grouped alltoall .
33,803
def import_tf_tensor ( self , x , tf_x ) : return self . LaidOutTensor ( self . make_slices ( tf_x , x . shape ) )
Import a tf . Tensor producing a LaidOutTensor .
33,804
def attention ( q , k , v , memory_length_dim , key_dim , value_dim , mask = None , dropout_rate = 0.0 , dropout_broadcast_dims = None , extra_logit = None ) : logits = mtf . einsum ( [ q , k ] , reduced_dims = [ key_dim ] ) if mask is not None : logits += mask weights = mtf . softmax ( logits , memory_length_dim , ext...
Dot - product attention - doesn t use positional dimensions .
33,805
def attention_params_simple ( mesh , io_dim , kv_dim , heads_dim , variable_dtype ) : return AttentionParams ( mesh , query_input_dim = io_dim , memory_input_dim = io_dim , output_dim = io_dim , key_dim = kv_dim , value_dim = kv_dim , query_heads_dims = [ heads_dim ] , memory_heads_dims = [ heads_dim ] , variable_dtype...
Common case attention parameters .
33,806
def local_attention_1d ( q , k , v , length_dim , key_dim , value_dim , autoregressive = True , length_dim_num_splits = 1 , radius = 128 , sequence_id = 1 , attention_kwargs = None ) : length_per_split = length_dim . size // length_dim_num_splits block_length = max ( radius , 128 ) while length_per_split % block_length...
Attention to the a neighborood around the source .
33,807
def compute_q ( self , query_antecedent ) : ret = mtf . einsum ( [ query_antecedent , self . wq ] , reduced_dims = [ self . query_input_dim ] ) if self . combine_dims : ret = mtf . replace_dimensions ( ret , ret . shape . dims [ - 1 ] , self . q_dims ) return ret
Compute query Tensor q .
33,808
def compute_k ( self , memory_antecedent ) : if self . shared_kv : raise ValueError ( "compute_k cannot be called with shared_kv" ) ret = mtf . einsum ( [ memory_antecedent , self . wk ] , reduced_dims = [ self . memory_input_dim ] ) if self . combine_dims : ret = mtf . replace_dimensions ( ret , ret . shape . dims [ -...
Compute key Tensor k .
33,809
def compute_v ( self , memory_antecedent ) : if self . shared_kv : raise ValueError ( "compute_v cannot be called with shared_kv" ) ret = mtf . einsum ( [ memory_antecedent , self . wv ] , reduced_dims = [ self . memory_input_dim ] ) if self . combine_dims : ret = mtf . replace_dimensions ( ret , ret . shape . dims [ -...
Compute value Tensor v .
33,810
def compute_output ( self , o , output_shape = None ) : if self . combine_dims : o = mtf . transpose ( o , o . shape - self . o_dims + self . o_dims ) o = mtf . replace_dimensions ( o , self . o_dims , self . wo . shape . dims [ 0 ] ) reduced_dims = [ self . wo . shape . dims [ 0 ] ] else : reduced_dims = self . o_dims...
Compute output of multihead attention .
33,811
def encode_tf ( self , s ) : ids = subword_text_encoder_ops . subword_text_encoder_encode ( s , self . _filepath ) return ids [ : - 1 ]
Encode a tf . Scalar string to a tf . Tensor .
33,812
def simple_layer_stack ( include_encdec_attention , num_layers = 6 , d_ff = 2048 , num_heads = 8 , d_kv = 128 , dropout_rate = 0.1 ) : ret = [ ] for _ in xrange ( num_layers ) : ret . append ( transformer_layers . SelfAttention ( num_heads = num_heads , key_value_size = d_kv , attention_kwargs = { "dropout_rate" : drop...
Create a layer stack .
33,813
def toy_model ( features , mesh ) : batch_dim = mtf . Dimension ( 'batch' , FLAGS . batch_size ) io_dim = mtf . Dimension ( 'io' , FLAGS . io_size ) master_dtype = tf . as_dtype ( FLAGS . master_dtype ) slice_dtype = tf . as_dtype ( FLAGS . slice_dtype ) activation_dtype = tf . as_dtype ( FLAGS . activation_dtype ) x =...
A toy model implemented by mesh tensorlfow .
33,814
def run_toy_model_tpu ( ) : tpu_cluster_resolver = tf . contrib . cluster_resolver . TPUClusterResolver ( FLAGS . tpu , zone = FLAGS . tpu_zone , project = FLAGS . gcp_project ) iterations_per_loop = FLAGS . iterations mesh_shape = mtf . convert_to_shape ( FLAGS . mesh_shape ) config = tpu_config . RunConfig ( cluster ...
Run a toy model on TPU .
33,815
def mnist_model ( image , labels , mesh ) : batch_dim = mtf . Dimension ( "batch" , FLAGS . batch_size ) row_blocks_dim = mtf . Dimension ( "row_blocks" , 4 ) col_blocks_dim = mtf . Dimension ( "col_blocks" , 4 ) rows_dim = mtf . Dimension ( "rows_size" , 7 ) cols_dim = mtf . Dimension ( "cols_size" , 7 ) classes_dim =...
The model .
33,816
def run_mnist ( ) : mnist_classifier = tf . estimator . Estimator ( model_fn = model_fn , model_dir = FLAGS . model_dir ) def train_input_fn ( ) : ds = dataset . train ( FLAGS . data_dir ) ds_batched = ds . cache ( ) . shuffle ( buffer_size = 50000 ) . batch ( FLAGS . batch_size ) ds = ds_batched . repeat ( FLAGS . epo...
Run MNIST training and eval loop .
33,817
def call ( self , context , x , losses = None ) : has_length_dim = context . length_dim in x . shape . dims if not has_length_dim : x_shape = x . shape shape_with_length = mtf . Shape ( x_shape . dims [ : - 1 ] + [ mtf . Dimension ( "length" , 1 ) ] + x_shape . dims [ - 1 : ] ) x = mtf . reshape ( x , shape_with_length...
Call the layer .
33,818
def print_solution ( model , solver ) : model_proto = model . Proto ( ) response_proto = solver . ResponseProto ( ) variables_in_objective_map = { } maximization = False if model_proto . HasField ( 'objective' ) : objective = model_proto . objective for i in range ( len ( objective . vars ) ) : variables_in_objective_m...
Prints the solution associated with solver .
33,819
def _local_var_name ( splittable_dimensions , assignment ) : assignment_string = [ ] for splittable in sorted ( splittable_dimensions ) : if splittable in assignment : assignment_string . append ( "{}:{}" . format ( splittable , assignment [ splittable ] ) ) else : assignment_string . append ( "{}" . format ( splittabl...
Name for a local variable .
33,820
def _generate_assignments ( splittable_dimensions , mesh_dimension_to_size ) : assignments = [ ] for assignment_size in six . moves . xrange ( 1 + min ( len ( splittable_dimensions ) , len ( mesh_dimension_to_size ) ) ) : for s_dims_chosen in itertools . combinations ( splittable_dimensions , assignment_size ) : for m_...
Generates all ways to map splittable dimensions to mesh dimensions .
33,821
def _preprocess_input ( self ) : self . _operation_name_to_mtf_dimension_set = { } self . _tensor_name_to_mtf_dimension_set = { } for operation_name in self . _graph . get_all_operation_names ( ) : self . _operation_name_to_mtf_dimension_set [ operation_name ] = frozenset ( set ( self . _graph . get_operation_mtf_dimen...
Computing useful input data structures to ease IP construction .
33,822
def _initialize_variables ( self ) : self . _global_vars = { } for mtf_dimension_name in ( self . _layout_validator . splittable_mtf_dimension_names ) : for mesh_dimension_name in ( self . _layout_validator . mesh_dimension_name_to_size ) : name = _global_var_name ( mtf_dimension_name , mesh_dimension_name ) self . _gl...
Initializing the variables of the IP .
33,823
def _add_constraints ( self ) : for mesh_dimension_name in ( self . _layout_validator . mesh_dimension_name_to_size ) : for mtf_dimension_set in self . _operation_mtf_dimension_sets : self . _model . Add ( sum ( self . _global_vars [ ( mtf_dimension_name , mesh_dimension_name ) ] for mtf_dimension_name in mtf_dimension...
Adding constraints to the IP .
33,824
def _get_memory_contents ( self ) : if self . _memory_contents is not None : return self . _memory_contents schedule = scheduler . minimize_peak_memory ( self . _graph , self . _scheduler_alg ) self . _memory_contents = self . _graph . compute_memory_contents_under_schedule ( schedule ) return self . _memory_contents
Runs the scheduler to determine memory contents at every point in time .
33,825
def solve ( self , print_solution = False ) : self . _cp_solver = cp_model . CpSolver ( ) status = self . _cp_solver . Solve ( self . _model ) if status != cp_model . OPTIMAL : if status == cp_model . FEASIBLE : logging . warning ( "A potentially suboptimal solution was found." ) else : logging . error ( "Solver return...
Solves the current integer program and returns the computed layout .
33,826
def evaluate_layout ( self , layout ) : layout_dict = { } if layout : for pair in layout . split ( ";" ) : mtf_dimension_name , mesh_dimension_name = pair . split ( ":" , 1 ) if ( mtf_dimension_name in self . _layout_validator . splittable_mtf_dimension_names ) : layout_dict [ mtf_dimension_name ] = mesh_dimension_name...
The current objective value for the given layout .
33,827
def device_function ( self , var ) : if var . type not in ( 'Variable' , 'VariableV2' , 'VarHandleOp' ) : tf . logging . debug ( 'Place {} on last device: {}.' . format ( var . name , self . _last_device ) ) return self . _last_device shape = tf . TensorShape ( var . get_attr ( 'shape' ) ) assert shape . num_elements (...
Choose a device for the input variable .
33,828
def greedy_decode ( logits_fn , initial_ids , temperature = 0.0 , initial_states = None , eos_id = EOS_ID , forced_ids = None , use_tpu = True ) : length_dim = initial_ids . shape . dims [ - 1 ] mesh = initial_ids . mesh num_steps = mtf . constant ( mesh , length_dim . size , dtype = tf . int32 ) def cond_fn ( step_num...
Greedy decoding .
33,829
def pack_and_batch ( dataset , batch_size , length , pack = True ) : if pack : dataset = pack_dataset ( dataset , length = length ) dataset = dataset . map ( functools . partial ( trim_and_pad_all_features , length = length ) , num_parallel_calls = tf . data . experimental . AUTOTUNE ) dataset = dataset . batch ( batch...
Create a tf . data . Dataset which emits training batches .
33,830
def encode_dataset ( dataset , vocabulary ) : def encode ( features ) : return { k : vocabulary . encode_tf ( v ) for k , v in features . items ( ) } return dataset . map ( encode , num_parallel_calls = tf . data . experimental . AUTOTUNE )
Encode from strings to token ids .
33,831
def packed_parallel_tsv_dataset ( filenames = gin . REQUIRED , dataset_split = gin . REQUIRED , batch_size = gin . REQUIRED , sequence_length = gin . REQUIRED , vocabulary = gin . REQUIRED , append_eos = True , shuffle_buffer_size = 10000 , eos_id = 1 ) : dataset = tf . data . TextLineDataset ( filenames ) if dataset_s...
Reads parallel tab - separated text file . One example per line .
33,832
def supervised_to_dict ( dataset , text2self ) : def my_fn ( inputs , targets ) : if text2self : return { "targets" : targets } else : return { "inputs" : inputs , "targets" : targets } return dataset . map ( my_fn , num_parallel_calls = tf . data . experimental . AUTOTUNE )
Turns a supervised dataset into a dataset with a feature dictionary .
33,833
def encode_all_features ( dataset , vocabulary ) : def my_fn ( features ) : ret = { } for k , v in features . items ( ) : v = vocabulary . encode_tf ( v ) v = tf . concat ( [ tf . to_int64 ( v ) , [ 1 ] ] , 0 ) ret [ k ] = v return ret return dataset . map ( my_fn , num_parallel_calls = tf . data . experimental . AUTOT...
Encode all features .
33,834
def pretokenized_tfrecord_dataset ( filenames , text2self , eos_included , repeat , batch_size , sequence_length ) : dataset = tf . data . TFRecordDataset ( filenames , buffer_size = 64 * 1024 * 1024 ) if repeat : dataset = dataset . repeat ( ) keys = [ "targets" ] if text2self else [ "inputs" , "targets" ] def decode_...
Reads tensor2tensor - style data files .
33,835
def pretokenized_t2t_dataset ( dataset_name = gin . REQUIRED , text2self = False , data_dir = gin . REQUIRED , dataset_split = "train" , batch_size = gin . REQUIRED , sequence_length = gin . REQUIRED , vocabulary = None ) : del vocabulary filepattern = os . path . join ( data_dir , dataset_name + "-" + dataset_split + ...
Loads the Tensor2tensor dataset specified by dataset_name .
33,836
def pack_dataset ( dataset , length , keys = None , use_custom_ops = False ) : shapes = dataset . output_shapes if keys is None : keys = shapes . keys ( ) for k in keys : if k not in shapes : raise ValueError ( "Key %s not found in dataset. Available keys are %s" % ( k , shapes . keys ( ) ) ) if not shapes [ k ] . is_...
Creates a packed version of a dataset on - the - fly .
33,837
def trim_and_pad_all_features ( features , length ) : return { k : _trim_and_pad ( v , length ) for k , v in features . items ( ) }
Trim and pad first dimension of all features to size length .
33,838
def convert_to_dimension ( d ) : if d is None : return None if isinstance ( d , Dimension ) : if not isinstance ( d . name , str ) or not isinstance ( d . size , int ) : raise ValueError ( "Bad dimension %s" % ( d , ) ) return d name , size = d if isinstance ( name , str ) and isinstance ( size , int ) : return Dimensi...
Converts input to a Dimension .
33,839
def convert_to_shape ( x ) : if x is None : return None if isinstance ( x , Shape ) : return x if isinstance ( x , str ) : x = _parse_string_to_list_of_pairs ( x , seconds_to_int = True ) return Shape ( x )
Converts input to a Shape .
33,840
def convert_to_layout_rules ( x ) : if isinstance ( x , LayoutRules ) : return x if isinstance ( x , str ) : x = _parse_string_to_list_of_pairs ( x ) return LayoutRules ( x )
Converts input to a LayoutRules .
33,841
def convert_args_to_laid_out_tensors ( xs ) : ret = [ ] for x in xs : if hasattr ( x , "to_laid_out_tensor" ) : ret . append ( x . to_laid_out_tensor ( ) ) else : ret . append ( x ) return ret
Convert list elements to laid - out - tensors when possible .
33,842
def slicewise ( tf_fn , xs , output_shape = None , output_dtype = None , splittable_dims = None , grad_function = None , name = None ) : multiple_outputs = isinstance ( output_dtype , list ) output_shapes = output_shape if multiple_outputs else [ output_shape ] output_dtypes = output_dtype if multiple_outputs else [ ou...
Slice - wise call to any tensorflow function .
33,843
def cwise ( tf_fn , xs , output_dtype = None , grad_function = None , name = None ) : return slicewise ( tf_fn , xs , output_dtype = output_dtype , splittable_dims = xs [ 0 ] . shape . dims , grad_function = grad_function , name = name or "cwise" )
Component - wise operation with no broadcasting .
33,844
def binary_arguments_to_tensors ( x1 , x2 ) : if not isinstance ( x1 , Tensor ) and not isinstance ( x2 , Tensor ) : raise ValueError ( "at least one of x1 and x2 must be an mtf Tensor" ) elif isinstance ( x1 , Tensor ) and isinstance ( x2 , Tensor ) : return x1 , x2 elif isinstance ( x1 , Tensor ) : return x1 , import...
Convert argument of a binary operation to Tensors .
33,845
def minimum ( x1 , x2 , output_shape = None , name = None ) : output_shape = convert_to_shape ( output_shape ) with tf . name_scope ( name , default_name = "minimum" ) : x1 , x2 = binary_arguments_to_tensors ( x1 , x2 ) return MinMaxOperation ( tf . minimum , x1 , x2 , output_shape = _infer_binary_broadcast_shape ( x1 ...
Binary minimum with broadcsting .
33,846
def split ( x , split_dim , num_or_size_splits , name = None ) : return SplitOperation ( x , split_dim , num_or_size_splits , name = name ) . outputs
Like tf . split .
33,847
def stack ( xs , dim_name , axis = 0 , name = None ) : ret = StackOperation ( xs , dim_name , axis , name ) . outputs [ 0 ] return ret
Stack multiple Tensors to make a new dimension .
33,848
def cumsum ( x , dim , exclusive = False ) : with tf . variable_scope ( "cumsum" ) : new_name = "tmp_dim_cumsum" new_dim = Dimension ( new_name , dim . size ) new_shape = x . shape . rename_dimension ( dim . name , new_name ) comparator = less if exclusive else less_equal m = cast ( comparator ( mtf_range ( x . mesh , ...
Cumulative sum .
33,849
def shift ( x , offset , dim , wrap , name = None ) : return ShiftOperation ( x , offset , dim , wrap , name = name ) . outputs [ 0 ]
Shift operation .
33,850
def import_laid_out_tensor ( mesh , laid_out_tensor , shape , name = None ) : return ImportLaidOutTensorOperation ( mesh , laid_out_tensor , convert_to_shape ( shape ) , name = name ) . outputs [ 0 ]
Import a laid_out_tensor .
33,851
def get_variable ( mesh , name , shape , dtype = tf . float32 , master_dtype = None , slice_dtype = None , activation_dtype = None , initializer = None , trainable = True , ** kwargs ) : if dtype is None : dtype = VariableDType ( master_dtype , slice_dtype , activation_dtype ) elif isinstance ( dtype , tf . DType ) : d...
Create a new variable or retrieve an already - created one .
33,852
def assign ( var , new_val , assign_fn = assign_slice ) : if isinstance ( var , Tensor ) : var = var . operation if not isinstance ( var , Variable ) : raise ValueError ( "var must be a mtf.Variable or its output Tensor." ) return Assign ( [ var ] , [ new_val ] , assign_fn = assign_fn )
Assign a new value to a variable .
33,853
def Print ( x , data , message , ** kwargs ) : return PrintOperation ( x , data , message , ** kwargs ) . outputs [ 0 ]
Call tf . Print .
33,854
def rename_dimension ( x , old_name , new_name ) : return reshape ( x , x . shape . rename_dimension ( old_name , new_name ) )
Reshape a Tensor renaming one dimension .
33,855
def replace_dimensions ( tensor_or_shape , old_dim_or_dims , new_dim_or_dims ) : if isinstance ( tensor_or_shape , Tensor ) : return reshape ( tensor_or_shape , replace_dimensions ( tensor_or_shape . shape , old_dim_or_dims , new_dim_or_dims ) ) if not isinstance ( tensor_or_shape , Shape ) : raise ValueError ( "tensor...
Replace dimensions in a Tensor or Shape .
33,856
def einsum ( xs , output_shape = None , reduced_dims = None , name = None ) : output_shape = convert_to_shape ( output_shape ) input_dim_count = collections . defaultdict ( int ) input_dims = [ ] for x in xs : for d in x . shape . dims : if d not in input_dim_count : input_dims . append ( d ) input_dim_count [ d ] += 1...
Einstein summation .
33,857
def _reduction_output_shape ( x , output_shape , reduced_dim ) : if output_shape is None : if reduced_dim is None : return Shape ( [ ] ) else : if reduced_dim not in x . shape . dims : raise ValueError ( "reduced_dim=%s not in x.shape.dims=%s" % ( reduced_dim , x . shape ) ) return x . shape - reduced_dim if reduced_di...
Helper function to reduce_sum etc .
33,858
def top_1 ( x , reduced_dim , dtype = tf . int32 , name = None ) : reduced_dim = convert_to_dimension ( reduced_dim ) with tf . name_scope ( name , default_name = "top_1" ) : max_val = reduce_max ( x , reduced_dim = reduced_dim ) is_max = to_float ( equal ( x , max_val ) ) pos = mtf_range ( x . mesh , reduced_dim , tf ...
Argmax and Max .
33,859
def top_k ( x , reduced_dim , new_dim , dtype = tf . int32 , name = None ) : reduced_dim = convert_to_dimension ( reduced_dim ) new_dim = convert_to_dimension ( new_dim ) indices = [ ] values = [ ] k = new_dim . size with tf . name_scope ( name , default_name = "top_k" ) : for i in xrange ( k ) : max_index , max_val = ...
Like tf . top_k .
33,860
def add ( x1 , x2 , output_shape = None , name = None ) : output_shape = convert_to_shape ( output_shape ) if not isinstance ( x2 , Tensor ) : return ScalarAddOperation ( x1 , x2 ) . outputs [ 0 ] with tf . name_scope ( name , default_name = "add" ) : x1 , x2 = binary_arguments_to_tensors ( x1 , x2 ) return AddOperatio...
Binary addition with broadcsting .
33,861
def sub ( x1 , x2 , output_shape = None , name = None ) : output_shape = convert_to_shape ( output_shape ) if not isinstance ( x2 , Tensor ) : return ScalarAddOperation ( x1 , - x2 ) . outputs [ 0 ] with tf . name_scope ( name , default_name = "sub" ) : x1 , x2 = binary_arguments_to_tensors ( x1 , x2 ) return add ( x1 ...
Binary subtraction with broadcsting .
33,862
def multiply ( x1 , x2 , output_shape = None , name = None ) : if not isinstance ( x2 , Tensor ) : return ScalarMultiplyOperation ( x1 , x2 ) . outputs [ 0 ] with tf . name_scope ( name , default_name = "mul" ) : x1 , x2 = binary_arguments_to_tensors ( x1 , x2 ) return einsum ( [ x1 , x2 ] , output_shape = _infer_binar...
Binary multiplication with broadcasting .
33,863
def divide ( x1 , x2 , output_shape = None , name = None ) : output_shape = convert_to_shape ( output_shape ) if not isinstance ( x2 , Tensor ) : return ScalarMultiplyOperation ( x1 , 1.0 / x2 ) . outputs [ 0 ] with tf . name_scope ( name , default_name = "divide" ) : x1 , x2 = binary_arguments_to_tensors ( x1 , x2 ) r...
Binary division with broadcasting .
33,864
def one_hot ( indices , output_dim , on_value = 1.0 , off_value = 0.0 , dtype = tf . float32 , name = None ) : return OneHotOperation ( indices , output_dim , on_value , off_value , dtype , name = name ) . outputs [ 0 ]
One hot operation .
33,865
def gradients ( ys , xs , grad_ys = None ) : graph = ys [ 0 ] . graph if not grad_ys : grad_ys = [ Constant ( y . mesh , 1.0 , y . shape , y . dtype ) . outputs [ 0 ] for y in ys ] downstream = set ( xs ) for op in graph . operations : if op . has_gradient : if set ( op . inputs ) & downstream : downstream |= set ( op ...
Compute gradients in dtf .
33,866
def _infer_binary_broadcast_shape ( shape1 , shape2 , given_output_shape = None ) : shape1 = convert_to_shape ( shape1 ) shape2 = convert_to_shape ( shape2 ) given_output_shape = convert_to_shape ( given_output_shape ) if given_output_shape is not None : return given_output_shape if is_subsequence ( shape1 . dims , sha...
Infer shape of the output of a binary op with broadcasting .
33,867
def _expand_dims ( x , input_shape , output_shape ) : verify_no_new_dims ( [ output_shape ] , input_shape ) if input_shape == output_shape or input_shape . ndims == 0 : return x perm = [ input_shape . dims . index ( d ) for d in output_shape . dims if d in input_shape . dims ] x = tf . transpose ( x , perm ) for i , d ...
Expand dimensions and transpose if necessary .
33,868
def _einsum_equation ( input_shapes , output_shape ) : ret = [ ] next_letter = ord ( "a" ) dim_to_letter = { } for shape_num , shape in enumerate ( input_shapes + [ output_shape ] ) : if shape_num == len ( input_shapes ) : ret . append ( "->" ) elif shape_num > 0 : ret . append ( "," ) for d in shape . dims : if d not ...
Turn shapes into an einsum equation .
33,869
def is_subsequence ( short_seq , long_seq ) : if not short_seq : return True pos = 0 for x in long_seq : if pos == len ( short_seq ) : return True if short_seq [ pos ] == x : pos += 1 if pos == len ( short_seq ) : return True return False
Is short_seq a subsequence of long_seq .
33,870
def verify_no_new_dims ( input_shapes , output_shape ) : all_input_dims = set ( sum ( [ s . dims for s in input_shapes ] , [ ] ) ) all_output_dims = set ( output_shape . dims ) if not all_output_dims . issubset ( all_input_dims ) : raise ValueError ( "No new dimensions allowed in output" " input_shapes = %s output_shap...
Verifies that all dimensions in the output are in at least one input .
33,871
def pnum_to_processor_coordinates ( mesh_shape , pnum ) : ret = [ ] for dimsize in mesh_shape . to_integer_list [ : : - 1 ] : ret . append ( pnum % dimsize ) pnum //= dimsize return ret [ : : - 1 ]
Coordinates of a processor in the mesh .
33,872
def processor_coordinates_to_pnum ( mesh_shape , coord ) : ret = 0 multiplier = 1 for c , d in zip ( coord [ : : - 1 ] , mesh_shape . to_integer_list [ : : - 1 ] ) : ret += multiplier * c multiplier *= d return ret
Inverse of pnum_to_processor_coordinates .
33,873
def pnum_to_group ( mesh_shape , group_dims , pnum ) : coord = pnum_to_processor_coordinates ( mesh_shape , pnum ) remaining_shape = Shape ( [ d for i , d in enumerate ( mesh_shape ) if i not in group_dims ] ) remaining_coord = [ d for i , d in enumerate ( coord ) if i not in group_dims ] return processor_coordinates_t...
Group number for grouped allreduce .
33,874
def processor_groups ( mesh_shape , group_dims ) : group_numbers = [ pnum_to_group ( mesh_shape , group_dims , pnum ) for pnum in xrange ( mesh_shape . size ) ] ret = [ ] for pnum , g in enumerate ( group_numbers ) : while len ( ret ) <= g : ret . append ( [ ] ) ret [ g ] . append ( pnum ) return ret
Groups of processors which differ only in the given dimensions .
33,875
def mtf_range ( mesh , dim , dtype , name = None ) : dim = convert_to_dimension ( dim ) with tf . variable_scope ( name , default_name = "range" ) : if dtype == tf . bfloat16 : tf_range = tf . cast ( tf . range ( dim . size ) , tf . bfloat16 ) else : tf_range = tf . range ( dim . size , dtype = dtype ) return import_tf...
Create a 1d mesh tensor with a range from [ 0 dim . size ) .
33,876
def pretty_print_counters ( counters ) : totals = collections . defaultdict ( int ) for ( name , val ) in counters : prefixes = [ name [ : i ] for i in xrange ( len ( name ) ) if name [ i ] == "/" ] + [ name ] for p in prefixes : totals [ p ] += val parts = [ ] for name , val in sorted ( six . iteritems ( totals ) ) : ...
print counters hierarchically .
33,877
def _parse_string_to_list_of_pairs ( s , seconds_to_int = False ) : r ret = [ ] for p in [ s . split ( ":" ) for s in re . sub ( "[,.;]" , " " , s ) . split ( ) ] : if len ( p ) != 2 : raise ValueError ( "bad input to _parse_string_to_list_of_pairs %s" % s ) if seconds_to_int : ret . append ( ( p [ 0 ] , int ( p [ 1 ] ...
r Parses a string into a list of pairs .
33,878
def parallel ( devices , fn , * args , ** kwargs ) : if not isinstance ( devices , list ) : raise ValueError ( "devices must be a list" ) for x in list ( args ) + list ( six . itervalues ( kwargs ) ) : if not isinstance ( x , list ) or len ( x ) != len ( devices ) : raise ValueError ( "Argument not a list with same len...
Call a function once on each device .
33,879
def random_uniform ( mesh , shape , ** kwargs ) : shape = convert_to_shape ( shape ) return RandomOperation ( mesh , shape , tf . random . uniform , ** kwargs ) . outputs [ 0 ]
Random uniform .
33,880
def dropout ( x , keep_prob , noise_shape = None , name = None ) : noise_shape = convert_to_shape ( noise_shape ) if noise_shape is None : noise_shape = x . shape with tf . variable_scope ( name , default_name = "dropout" ) : if keep_prob == 1.0 : return x noise = cast ( less ( random_uniform ( x . mesh , noise_shape ,...
Dropout layer .
33,881
def _cumprod ( l ) : ret = [ 1 ] for item in l : ret . append ( ret [ - 1 ] * item ) return ret
Cumulative product of a list .
33,882
def while_loop ( cond_fn , body_fn , inputs , num_loop_vars = None , has_accumulators = False , ** kwargs ) : if num_loop_vars is None : return WhileLoopOperation ( cond_fn , body_fn , inputs , tf_kwargs = kwargs , has_accumulators = has_accumulators ) . outputs assert num_loop_vars > 0 extra_inputs = inputs [ num_loop...
While Loop .
33,883
def _shape_union ( shapes ) : return Shape ( sorted ( list ( set ( sum ( [ s . dims for s in shapes ] , [ ] ) ) ) ) )
A shape containing the union of all dimensions in the input shapes .
33,884
def _tf_flatten_batch_dims ( x , num_nonbatch_dims ) : shape = x . shape . as_list ( ) assert None not in shape new_shape = ( [ list_product ( shape [ : - num_nonbatch_dims ] ) ] + shape [ - num_nonbatch_dims : ] ) if new_shape != shape : x = tf . reshape ( x , new_shape ) return x
Flatten all but last num_nonbatch_dims into one dimension .
33,885
def _tf_restore_batch_dims ( x , num_nonbatch_dims , prototype ) : assert x . shape . ndims == 1 + num_nonbatch_dims new_shape = ( prototype . shape . as_list ( ) [ : - num_nonbatch_dims ] + x . shape . as_list ( ) [ 1 : ] ) assert None not in new_shape if new_shape != x . shape . as_list ( ) : x = tf . reshape ( x , n...
Reverse op of _tf_flatten_batch_dims .
33,886
def halo_exchange ( x , blocks_dim , block_size_dim , halo_size , wrap = False ) : if halo_size == 0 : return x block_size = block_size_dim . size partial_size = halo_size % block_size num_complete_blocks = halo_size // block_size parts = [ x ] for i in xrange ( 1 , num_complete_blocks + 1 ) : parts = ( [ shift ( x , i...
Concat each block with the margins of adjacent blocks .
33,887
def conv2d_with_blocks ( conv_input , conv_filter , strides , padding , h_blocks_dim = None , w_blocks_dim = None , name = None ) : filter_h_dim , filter_w_dim = conv_filter . shape . dims [ : 2 ] assert filter_h_dim . size % 2 == 1 assert filter_w_dim . size % 2 == 1 h_dim , w_dim = conv_input . shape . dims [ - 3 : -...
conv2d operation with spatial partitioning .
33,888
def tensor_dim_to_mesh_dim_size ( layout , mesh_shape , tensor_dim ) : layout_rules = convert_to_layout_rules ( layout ) mesh_shape = convert_to_shape ( mesh_shape ) mesh_axis = layout_rules . tensor_dimension_to_mesh_axis ( tensor_dim , mesh_shape ) if mesh_axis is None : return 1 else : return mesh_shape . dims [ mes...
How many ways does a tensor dimension get split .
33,889
def serialize_training_step ( features , model_fn , batch_dim , num_splits ) : for v in features . values ( ) : mesh = v . mesh graph = v . graph microbatch_dim = Dimension ( "microbatch" , num_splits ) smaller_batch_dim = Dimension ( batch_dim . name , batch_dim . size // num_splits ) cache = { } def select ( t , micr...
Break the training batch into multiple microbatches .
33,890
def rename_dimension ( self , old_name , new_name ) : if old_name not in self . dimension_names : raise ValueError ( "Shape %s does not have dimension named %s" % ( self , old_name ) ) return Shape ( [ Dimension ( new_name , d . size ) if d . name == old_name else d for d in self . dims ] )
Returns a copy where one dimension is renamed .
33,891
def resize_dimension ( self , name , new_size ) : if name not in self . dimension_names : raise ValueError ( "Shape %s does not have dimension named %s" % ( self , name ) ) return Shape ( [ Dimension ( name , new_size ) if d . name == name else d for d in self . dims ] )
Returns a copy where one dimension has a different size .
33,892
def tensor_layout ( self , tensor_shape , mesh_shape ) : ret = [ self . tensor_dimension_to_mesh_axis ( d , mesh_shape ) for d in tensor_shape ] not_nones = [ a for a in ret if a is not None ] if len ( not_nones ) != len ( set ( not_nones ) ) : raise ValueError ( "Two Tensor Dimensions may not map to the same Mesh Dime...
Computes TensorLayout given a Tensor Shape and a Mesh Shape .
33,893
def mesh_axis_to_tensor_axis ( self , mesh_ndims ) : ta2ma = self . _tensor_axis_to_mesh_axis return tuple ( [ ta2ma . index ( mesh_axis ) if mesh_axis in ta2ma else None for mesh_axis in xrange ( mesh_ndims ) ] )
For each mesh axis which Tensor axis maps to it .
33,894
def unique_name ( self , name , mark_as_used = True ) : scope_name = tf . get_variable_scope ( ) . name if scope_name : name = scope_name + "/" + name name_key = name . lower ( ) i = self . _names_in_use . get ( name_key , 0 ) if mark_as_used : self . _names_in_use [ name_key ] = i + 1 if i > 0 : base_name_key = name_k...
Like tf . Graph . unique_name returns a unique operation name for name .
33,895
def combine_assignments ( self , assignments ) : group_by_fn = collections . defaultdict ( list ) for a in assignments : if not isinstance ( a , Assign ) : raise ValueError ( "ops should be instances of mtf.Assign" ) group_by_fn [ a . assign_fn ] . append ( a ) assignments_set = set ( assignments ) self . _operations =...
Rewrite the current graph to combine Assign operations .
33,896
def tensor_layout ( self , arg ) : if isinstance ( arg , Tensor ) : arg = arg . shape return self . layout_rules . tensor_layout ( arg , self . shape )
Compute TensorLayout for a Tensor or a Shape .
33,897
def mesh_axis_to_cumprod ( self , tensor_shape ) : tensor_layout = self . tensor_layout ( tensor_shape ) ma2ta = tensor_layout . mesh_axis_to_tensor_axis ( self . ndims ) ta2cumprod = tensor_shape . cumprod return [ None if ta is None else ta2cumprod [ ta ] for ta in ma2ta ]
For each mesh axis give the product of previous tensor axes .
33,898
def slice_shape ( self , tensor_shape ) : tensor_layout = self . tensor_layout ( tensor_shape ) ret = [ ] for tensor_dim , mesh_axis in zip ( tensor_shape , tensor_layout . tensor_axis_to_mesh_axis ) : if mesh_axis is None : ret . append ( tensor_dim . size ) else : mesh_dim = self . shape [ mesh_axis ] if tensor_dim ....
Shape of each slice of the Tensor .
33,899
def slice_begin ( self , tensor_shape , pnum ) : tensor_layout = self . tensor_layout ( tensor_shape ) coordinates = pnum_to_processor_coordinates ( self . shape , pnum ) ret = [ ] for dim_size , mesh_axis in zip ( tensor_shape . to_integer_list , tensor_layout . tensor_axis_to_mesh_axis ) : if mesh_axis is None : ret ...
Begin position for the tensor slice for the given processor .