idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
33,700
def get_index_node ( self , idx ) : idx = self . node_index . index ( idx ) return self . nodes [ idx ]
get node with iterindex idx
33,701
def start ( self ) : self . update_device_info ( ) self . get_device_status ( 0 ) self . hook ( ) self . thread = threading . Thread ( target = self . _run ) self . thread . start ( ) self . running = True
start running in background .
33,702
def analyze_frames ( cls , workdir ) : record = cls ( None , workdir ) obj = { } with open ( os . path . join ( workdir , 'frames' , 'frames.json' ) ) as f : obj = json . load ( f ) record . device_info = obj [ 'device' ] record . frames = obj [ 'frames' ] record . analyze_all ( ) record . save ( )
generate draft from recorded frames
33,703
def process_casefile ( cls , workdir ) : record = cls ( None , workdir ) obj = { } with open ( os . path . join ( workdir , 'frames' , 'frames.json' ) ) as f : obj = json . load ( f ) record . device_info = obj [ 'device' ] record . frames = obj [ 'frames' ] casedir = os . path . join ( workdir , 'case' ) with open ( o...
generate code from case . json
33,704
def adb_path ( cls ) : if cls . __adb_cmd is None : if "ANDROID_HOME" in os . environ : filename = "adb.exe" if os . name == 'nt' else "adb" adb_dir = os . path . join ( os . environ [ "ANDROID_HOME" ] , "platform-tools" ) adb_cmd = os . path . join ( adb_dir , filename ) if not os . path . exists ( adb_cmd ) : raise E...
return adb binary full path
33,705
def connect ( self , addr ) : if addr . find ( ':' ) == - 1 : addr += ':5555' output = self . run_cmd ( 'connect' , addr ) return 'unable to connect' not in output
Call adb connect Return true when connect success
33,706
def main ( host = None , port = None , serial = None , scale = 1.0 , out = 'screenshot.png' , method = 'minicap' ) : print ( 'Started screencap' ) start = time . time ( ) client = adbkit . Client ( host = host , port = port ) device = client . device ( serial ) im = device . screenshot ( scale = scale ) im . save ( out...
If minicap not avaliable then use uiautomator instead Disable scale for now . Because - s scale is conflict of - s serial
33,707
def rotation ( self ) : if self . screen_rotation in range ( 4 ) : return self . screen_rotation return self . adb_device . rotation ( ) or self . info [ 'displayRotation' ]
Rotaion of the phone
33,708
def properties ( self ) : props = { } for line in self . adb_shell ( [ 'getprop' ] ) . splitlines ( ) : m = _PROP_PATTERN . match ( line ) if m : props [ m . group ( 'key' ) ] = m . group ( 'value' ) return props
Android Properties extracted from adb shell getprop
33,709
def type ( self , s , enter = False , clear = False ) : if clear : self . clear_text ( ) self . _uiauto . send_keys ( s ) if enter : self . keyevent ( 'KEYCODE_ENTER' )
Input some text this method has been tested not very stable on some device . Hi world maybe spell into H iworld
33,710
def input_methods ( self ) : imes = [ ] for line in self . adb_shell ( [ 'ime' , 'list' , '-s' , '-a' ] ) . splitlines ( ) : line = line . strip ( ) if re . match ( '^.+/.+$' , line ) : imes . append ( line ) return imes
Get all input methods
33,711
def current_ime ( self ) : dumpout = self . adb_shell ( [ 'dumpsys' , 'input_method' ] ) m = _INPUT_METHOD_RE . search ( dumpout ) if m : return m . group ( 1 )
Get current input method
33,712
def open_as_pillow ( filename ) : with __sys_open ( filename , 'rb' ) as f : data = BytesIO ( f . read ( ) ) return Image . open ( data )
This way can delete file immediately
33,713
def from_pillow ( pil_image ) : pil_image = pil_image . convert ( 'RGB' ) cv2_image = np . array ( pil_image ) cv2_image = cv2_image [ : , : , : : - 1 ] . copy ( ) return cv2_image
Convert from pillow image to opencv
33,714
def url_to_image ( url , flag = cv2 . IMREAD_COLOR ) : resp = urlopen ( url ) image = np . asarray ( bytearray ( resp . read ( ) ) , dtype = "uint8" ) image = cv2 . imdecode ( image , flag ) return image
download the image convert it to a NumPy array and then read it into OpenCV format
33,715
def mark_point ( img , x , y ) : overlay = img . copy ( ) output = img . copy ( ) alpha = 0.5 radius = max ( 5 , min ( img . shape [ : 2 ] ) // 15 ) center = int ( x ) , int ( y ) color = ( 0 , 0 , 255 ) cv2 . circle ( overlay , center , radius , color , - 1 ) cv2 . addWeighted ( overlay , alpha , output , 1 - alpha , ...
Mark a point
33,716
def display ( self ) : w , h = self . session . window_size ( ) return Display ( w * self . scale , h * self . scale )
Get screen width and height
33,717
def forward ( self , device_port , local_port = None ) : if local_port is None : for s , lp , rp in self . forward_list ( ) : if s == self . device_serial ( ) and rp == 'tcp:%d' % device_port : return int ( lp [ 4 : ] ) return self . forward ( device_port , next_local_port ( self . server_host ) ) else : self . cmd ( "...
adb port forward . return local_port
33,718
def touch2screen ( w , h , o , x , y ) : if o == 0 : return x , y elif o == 1 : return y , w - x elif o == 2 : return w - x , h - y elif o == 3 : return h - y , x return x , y
convert touch position
33,719
def patch_wda ( self ) : import wda def _click ( that ) : rawx , rawy = that . bounds . center x , y = self . d . scale * rawx , self . d . scale * rawy screen_before = self . _save_screenshot ( ) orig_click = pt . get_original ( wda . Selector , 'click' ) screen_after = self . _save_screenshot ( ) self . add_step ( 'c...
Record steps of WebDriverAgent
33,720
def _take_screenshot ( self , screenshot = False , name_prefix = 'unknown' ) : if isinstance ( screenshot , bool ) : if not screenshot : return return self . _save_screenshot ( name_prefix = name_prefix ) if isinstance ( screenshot , Image . Image ) : return self . _save_screenshot ( screen = screenshot , name_prefix =...
This is different from _save_screenshot . The return value maybe None or the screenshot path
33,721
def _add_assert ( self , ** kwargs ) : screenshot = kwargs . get ( 'screenshot' ) is_success = kwargs . get ( 'success' ) screenshot = ( not is_success ) if screenshot is None else screenshot kwargs [ 'screenshot' ] = self . _take_screenshot ( screenshot = screenshot , name_prefix = 'assert' ) action = kwargs . pop ( '...
if screenshot is None only failed case will take screenshot
33,722
def plot_chain ( chain , joints , ax , target = None , show = False ) : nodes = [ ] axes = [ ] transformation_matrixes = chain . forward_kinematics ( joints , full_kinematics = True ) for ( index , link ) in enumerate ( chain . links ) : ( node , rotation ) = geometry_utils . from_transformation_matrix ( transformation...
Plots the chain
33,723
def plot_target ( target , ax ) : ax . scatter ( target [ 0 ] , target [ 1 ] , target [ 2 ] , c = "red" , s = 80 )
Ajoute la target au plot
33,724
def Rx_matrix ( theta ) : return np . array ( [ [ 1 , 0 , 0 ] , [ 0 , np . cos ( theta ) , - np . sin ( theta ) ] , [ 0 , np . sin ( theta ) , np . cos ( theta ) ] ] )
Rotation matrix around the X axis
33,725
def Rz_matrix ( theta ) : return np . array ( [ [ np . cos ( theta ) , - np . sin ( theta ) , 0 ] , [ np . sin ( theta ) , np . cos ( theta ) , 0 ] , [ 0 , 0 , 1 ] ] )
Rotation matrix around the Z axis
33,726
def symbolic_Rz_matrix ( symbolic_theta ) : return sympy . Matrix ( [ [ sympy . cos ( symbolic_theta ) , - sympy . sin ( symbolic_theta ) , 0 ] , [ sympy . sin ( symbolic_theta ) , sympy . cos ( symbolic_theta ) , 0 ] , [ 0 , 0 , 1 ] ] )
Matrice symbolique de rotation autour de l axe Z
33,727
def Ry_matrix ( theta ) : return np . array ( [ [ np . cos ( theta ) , 0 , np . sin ( theta ) ] , [ 0 , 1 , 0 ] , [ - np . sin ( theta ) , 0 , np . cos ( theta ) ] ] )
Rotation matrix around the Y axis
33,728
def rpy_matrix ( roll , pitch , yaw ) : return np . dot ( Rz_matrix ( yaw ) , np . dot ( Ry_matrix ( pitch ) , Rx_matrix ( roll ) ) )
Returns a rotation matrix described by the extrinsinc roll pitch yaw coordinates
33,729
def cartesian_to_homogeneous ( cartesian_matrix , matrix_type = "numpy" ) : dimension_x , dimension_y = cartesian_matrix . shape if matrix_type == "numpy" : homogeneous_matrix = np . eye ( dimension_x + 1 ) elif matrix_type == "sympy" : homogeneous_matrix = sympy . eye ( dimension_x + 1 ) homogeneous_matrix [ : - 1 , :...
Converts a cartesian matrix to an homogenous matrix
33,730
def cartesian_to_homogeneous_vectors ( cartesian_vector , matrix_type = "numpy" ) : dimension_x = cartesian_vector . shape [ 0 ] if matrix_type == "numpy" : homogeneous_vector = np . zeros ( dimension_x + 1 ) homogeneous_vector [ - 1 ] = 1 homogeneous_vector [ : - 1 ] = cartesian_vector return homogeneous_vector
Converts a cartesian vector to an homogenous vector
33,731
def find_next_joint ( root , current_link , next_joint_name ) : has_next = False next_joint = None search_by_name = True current_link_name = None if next_joint_name is None : search_by_name = False current_link_name = current_link . attrib [ "name" ] for joint in root . iter ( "joint" ) : if search_by_name : if joint ....
Find the next joint in the URDF tree
33,732
def find_next_link ( root , current_joint , next_link_name ) : has_next = False next_link = None if next_link_name is None : next_link_name = current_joint . find ( "child" ) . attrib [ "link" ] for urdf_link in root . iter ( "link" ) : if urdf_link . attrib [ "name" ] == next_link_name : next_link = urdf_link has_next...
Find the next link in the URDF tree
33,733
def get_urdf_parameters ( urdf_file , base_elements = None , last_link_vector = None , base_element_type = "link" ) : tree = ET . parse ( urdf_file ) root = tree . getroot ( ) base_elements = list ( base_elements ) if base_elements is None : base_elements = [ "base_link" ] elif base_elements is [ ] : raise ValueError (...
Returns translated parameters from the given URDF file
33,734
def _convert_angle_limit ( angle , joint , ** kwargs ) : angle_pypot = angle if joint [ "orientation" ] == "indirect" : angle_pypot = 1 * angle_pypot return angle_pypot * np . pi / 180
Converts the limit angle of the PyPot JSON file to the internal format
33,735
def follow_hand ( poppy , delta ) : right_arm_position = poppy . l_arm_chain . end_effector + delta poppy . r_arm_chain . goto ( right_arm_position , 0.5 , wait = True )
Tell the right hand to follow the left hand
33,736
def inverse_kinematic_optimization ( chain , target_frame , starting_nodes_angles , regularization_parameter = None , max_iter = None ) : target = target_frame [ : 3 , 3 ] if starting_nodes_angles is None : raise ValueError ( "starting_nodes_angles must be specified" ) def optimize_target ( x ) : y = chain . active_to_...
Computes the inverse kinematic on the specified target with an optimization method
33,737
def forward_kinematics ( self , joints , full_kinematics = False ) : frame_matrix = np . eye ( 4 ) if full_kinematics : frame_matrixes = [ ] if len ( self . links ) != len ( joints ) : raise ValueError ( "Your joints vector length is {} but you have {} links" . format ( len ( joints ) , len ( self . links ) ) ) for ind...
Returns the transformation matrix of the forward kinematics
33,738
def inverse_kinematics ( self , target , initial_position = None , ** kwargs ) : target = np . array ( target ) if target . shape != ( 4 , 4 ) : raise ValueError ( "Your target must be a 4x4 transformation matrix" ) if initial_position is None : initial_position = [ 0 ] * len ( self . links ) return ik . inverse_kinema...
Computes the inverse kinematic on the specified target
33,739
def plot ( self , joints , ax , target = None , show = False ) : from . import plot_utils if ax is None : ax = plot_utils . init_3d_figure ( ) plot_utils . plot_chain ( self , joints , ax ) plot_utils . plot_basis ( ax , self . _length ) if target is not None : plot_utils . plot_target ( target , ax ) if show : plot_ut...
Plots the Chain using Matplotlib
33,740
def from_urdf_file ( cls , urdf_file , base_elements = None , last_link_vector = None , base_element_type = "link" , active_links_mask = None , name = "chain" ) : if base_elements is None : base_elements = [ "base_link" ] links = URDF_utils . get_urdf_parameters ( urdf_file , base_elements = base_elements , last_link_v...
Creates a chain from an URDF file
33,741
def check_internet_off ( secrets_file_path ) : while True : if internet_on ( ) is False and os . path . exists ( secrets_file_path ) : break else : print ( "Turn off your internet and plug in your USB to continue..." ) time . sleep ( 10 ) return True
If internet off and USB plugged in returns true . Else continues to wait ...
33,742
def check_internet_on ( secrets_file_path ) : while True : if internet_on ( ) is True and not os . path . exists ( secrets_file_path ) : break else : print ( "Turn on your internet and unplug your USB to continue..." ) time . sleep ( 10 ) return True
If internet on and USB unplugged returns true . Else continues to wait ...
33,743
def verify_signature ( uid , signed_cert_file_name , issuing_address ) : logging . info ( 'verifying signature for certificate with uid=%s:' , uid ) with open ( signed_cert_file_name ) as in_file : signed_cert = in_file . read ( ) signed_cert_json = json . loads ( signed_cert ) to_verify = uid signature = signed_cert_j...
Verify the certificate signature matches the expected . Double - check the uid field in the certificate and use VerifyMessage to confirm that the signature in the certificate matches the issuing_address .
33,744
def get_balance ( self , address , api_token ) : broadcast_url = self . base_url + '?module=account&action=balance' broadcast_url += '&address=%s' % address broadcast_url += '&tag=latest' if api_token : '&apikey=%s' % api_token response = requests . get ( broadcast_url ) if int ( response . status_code ) == 200 : balan...
returns the balance in wei with some inspiration from PyWallet
33,745
def get_address_nonce ( self , address , api_token ) : broadcast_url = self . base_url + '?module=proxy&action=eth_getTransactionCount' broadcast_url += '&address=%s' % address broadcast_url += '&tag=latest' if api_token : '&apikey=%s' % api_token response = requests . get ( broadcast_url , ) if int ( response . status...
Looks up the address nonce of this address Neccesary for the transaction creation
33,746
def _dense_var_to_tensor ( self , dtype = None , name = None , as_ref = False ) : if _enclosing_tpu_context ( ) is None : if hasattr ( self . _primary_var , '_dense_var_to_tensor' ) : return self . _primary_var . _dense_var_to_tensor ( dtype , name , as_ref ) else : return ops . convert_to_tensor ( self . _primary_var ...
Converts a variable to a tensor .
33,747
def _compute_layout_validator ( self ) : self . _layout_validator = valid_layouts . LayoutValidator ( self . mtf_graph , self . mesh_shape )
Computes self . _layout_validator .
33,748
def _compute_graph_interface ( self ) : self . _graph_interface = graph_interface . GraphInterface ( self . mtf_graph ) for mtf_output in self . mtf_outputs : self . _graph_interface . set_tensor_final ( mtf_output . name )
Computes self . _graph_interface .
33,749
def make_layer_stack ( layers = gin . REQUIRED , num_layers = 6 ) : return LayerStack ( [ cls ( ) for cls in layers ] * num_layers )
Configurable layer stack .
33,750
def make_bitransformer ( input_vocab_size = gin . REQUIRED , output_vocab_size = gin . REQUIRED , layout = None , mesh_shape = None ) : with gin . config_scope ( "encoder" ) : encoder = Unitransformer ( layer_stack = make_layer_stack ( ) , input_vocab_size = input_vocab_size , output_vocab_size = None , autoregressive ...
Gin - configurable bitransformer constructor .
33,751
def get_states ( self , n ) : return self . states [ len ( self . new_states ) : len ( self . new_states ) + n ]
Get the next n recurrent states .
33,752
def get_constant_state ( self ) : ret = self . constant_states [ self . next_constant_state ] self . next_constant_state += 1 return ret
Read state that was written in first_part mode .
33,753
def nonpadding ( self ) : if self . sequence_id is None : return None if self . sequence_id == 1 : return 1 else : return mtf . cast ( mtf . not_equal ( self . sequence_id , 0 ) , self . activation_dtype )
Tensor with zeros in padding positions and ones elsewhere .
33,754
def sequence_accuracy ( labels , outputs ) : all_correct = tf . reduce_all ( tf . logical_or ( tf . equal ( labels , outputs ) , tf . equal ( labels , 0 ) ) , axis = - 1 ) return tf . metrics . mean ( all_correct )
Compute the sequence - level accuracy .
33,755
def get_operation_input_names ( self , operation_name ) : for input_tensor in self . _name_to_operation ( operation_name ) . inputs : yield input_tensor . name
Generates the names of all input tensors of an operation .
33,756
def get_operation_output_names ( self , operation_name ) : for output_tensor in self . _name_to_operation ( operation_name ) . outputs : yield output_tensor . name
Generates the names of all output tensors of an operation .
33,757
def get_tensor_shape ( self , tensor_name ) : tensor = self . _name_to_tensor ( tensor_name ) if isinstance ( tensor , mtf . Tensor ) : return tf . TensorShape ( tensor . shape . to_integer_list ) else : return tensor . shape
The tf . TensorShape of a tensor .
33,758
def get_tensor_num_entries ( self , tensor_name , partial_layout = None , mesh_dimension_to_size = None ) : shape = self . get_tensor_shape ( tensor_name ) num_entries = 1 for dim in shape . dims : num_entries = num_entries * dim . value if not partial_layout : return num_entries for mtf_dimension_name in self . get_te...
The number of entries in a tensor .
33,759
def get_tensor_size ( self , tensor_name , partial_layout = None , mesh_dimension_to_size = None ) : return ( self . get_tensor_dtype ( tensor_name ) . size * self . get_tensor_num_entries ( tensor_name , partial_layout , mesh_dimension_to_size ) )
The size of a tensor in bytes .
33,760
def get_tensor_device ( self , tensor_name ) : tensor = self . _name_to_tensor ( tensor_name ) if isinstance ( tensor , tf . Tensor ) : return tensor . device else : return None
The device of a tensor .
33,761
def get_operation_device ( self , operation_name ) : operation = self . _name_to_operation ( operation_name ) if isinstance ( operation , tf . Operation ) : return operation . device else : return None
The device of an operation .
33,762
def get_tensor_mtf_dimension_names ( self , tensor_name ) : tensor = self . _name_to_tensor ( tensor_name ) if isinstance ( tensor , mtf . Tensor ) : return tensor . shape . dimension_names else : return [ ]
The Mesh TensorFlow dimensions associated with a tensor .
33,763
def get_operation_mtf_dimension_names ( self , operation_name ) : mtf_dimension_names = set ( ) for tensor_name in self . get_operation_input_names ( operation_name ) : mtf_dimension_names . update ( self . get_tensor_mtf_dimension_names ( tensor_name ) ) for tensor_name in self . get_operation_output_names ( operation...
The Mesh TensorFlow dimensions associated with an operation .
33,764
def set_tensor_final ( self , tensor_name ) : tensor = self . _name_to_tensor ( tensor_name ) self . _final_tensors . add ( tensor )
Denotes a tensor as a final output of the computation .
33,765
def is_tensor_final ( self , tensor_name ) : tensor = self . _name_to_tensor ( tensor_name ) return tensor in self . _final_tensors
Whether a tensor is a final output of the computation .
33,766
def compute_cost_graph ( self , devices = None ) : cost_graph_def = cost_graph_pb2 . CostGraphDef ( ) for i , operation_name in enumerate ( self . get_all_operation_names ( ) ) : node = cost_graph_def . node . add ( name = operation_name , device = self . get_operation_device ( operation_name ) , id = i ) for input_nam...
Computes a CostGraphDef protobuf based on this graph .
33,767
def compute_memory_contents_under_schedule ( self , schedule ) : out_degree = self . _compute_initial_out_degree ( ) curr_memory_contents = set ( ) memory_contents_for_each_operation = [ ] for operation_id in schedule : operation_name = self . _operations [ operation_id ] . name for output_name in self . get_operation_...
The in - memory tensors present when executing each operation in schedule .
33,768
def _initialize_operations ( self ) : if isinstance ( self . _graph , tf . Graph ) : return self . _graph . get_operations ( ) elif isinstance ( self . _graph , mtf . Graph ) : return self . _graph . operations else : raise TypeError ( 'Graph is not tf.Graph or mtf.Graph: {}' . format ( type ( self . _graph ) ) )
Initializer for _operations .
33,769
def _initialize_operation_name_to_id ( self ) : operation_name_to_id = { } for i , operation in enumerate ( self . _operations ) : operation_name_to_id [ operation . name ] = i return operation_name_to_id
Initializer for _operation_name_to_id .
33,770
def _initialize_tensor_name_to_ids ( self ) : tensor_name_to_ids = { } for i , operation in enumerate ( self . _operations ) : for j , tensor in enumerate ( operation . outputs ) : tensor_name_to_ids [ tensor . name ] = ( i , j ) return tensor_name_to_ids
Initializer for _tensor_name_to_ids .
33,771
def _name_to_tensor ( self , tensor_name ) : id1 , id2 = self . _tensor_name_to_ids [ tensor_name ] return self . _operations [ id1 ] . outputs [ id2 ]
The tensor with the given name .
33,772
def _compute_initial_out_degree ( self ) : out_degree = collections . defaultdict ( int ) for tensor_name in self . get_all_tensor_names ( ) : if self . is_tensor_final ( tensor_name ) : out_degree [ tensor_name ] = 1 for operation_name in self . get_all_operation_names ( ) : for input_name in self . get_operation_inpu...
The number of operations which use each tensor as input .
33,773
def layer_norm ( x , dim , epsilon = 1e-6 , name = "layer_prepostprocess" ) : with tf . variable_scope ( name + "/layer_norm" ) : scale = mtf . get_variable ( x . mesh , "layer_norm_scale" , mtf . Shape ( [ dim ] ) , initializer = tf . ones_initializer ( ) , activation_dtype = x . dtype ) bias = mtf . get_variable ( x ...
Layer normalization over dimension dim .
33,774
def softmax_cross_entropy_with_logits ( logits , targets , vocab_dim , z_loss = 0.0 ) : if logits . shape != targets . shape : raise ValueError ( "logits shape must equal targets shape" "logits=%s targets=%s" % ( logits . to_string , targets . to_string ) ) if vocab_dim not in logits . shape . dims : raise ValueError (...
Per - example softmax loss .
33,775
def sigmoid_cross_entropy_with_logits ( logits , targets ) : if logits . shape != targets . shape : raise ValueError ( "logits shape must equal targets shape" "logits=%s targets=%s" % ( logits . to_string , targets . to_string ) ) x = logits z = targets return mtf . relu ( x ) - x * z + mtf . log ( 1 + mtf . exp ( - mt...
Sigmoid cross - entropy loss .
33,776
def dense_relu_dense ( x , hidden_channels , dropout = 0.0 , dropout_broadcast_dims = None , master_dtype = tf . float32 , slice_dtype = tf . float32 , name = None ) : with tf . variable_scope ( name , default_name = "dense_relu_dense" ) : io_channels = x . shape . dims [ - 1 ] h = dense ( x , hidden_channels , use_bia...
Hidden layer with ReLU activation followed by linear projection .
33,777
def local_1d_halo_exchange ( k , v , num_w_blocks , w_dim , mask_right ) : if num_w_blocks is not None : if mask_right : k = mtf . left_halo_exchange ( k , num_w_blocks , w_dim , w_dim . size ) v = mtf . left_halo_exchange ( v , num_w_blocks , w_dim , w_dim . size ) else : k = mtf . halo_exchange ( k , num_w_blocks , w...
Halo exchange for keys and values for Local 1D attention .
33,778
def local_2d_halo_exchange ( k , v , num_h_blocks , h_dim , num_w_blocks , w_dim , mask_right ) : for blocks_dim , block_size_dim , halo_size in [ ( num_h_blocks , h_dim , h_dim . size ) , ( num_w_blocks , w_dim , w_dim . size ) ] : if halo_size > 0 : if blocks_dim is not None : if mask_right : k = mtf . left_halo_exch...
Halo exchange for keys and values for Local 2D attention .
33,779
def local_2d_self_attention_spatial_blocks ( query_antecedent , kv_channels , heads , memory_h_dim = None , memory_w_dim = None , mask_right = False , master_dtype = tf . float32 , slice_dtype = tf . float32 , name = None ) : with tf . variable_scope ( name , default_name = "multihead_attention" , values = [ query_ante...
Attention to the source position and a neighborhood to the left or right .
33,780
def multihead_attention_vars ( mesh , heads , io_channels , kv_channels , master_dtype , slice_dtype , activation_dtype ) : return multihead_attention_params ( mesh , heads , io_channels , kv_channels , mtf . VariableDType ( master_dtype , slice_dtype , activation_dtype ) , combine = True )
Deprecated version of multihead_attention_params with combine = True .
33,781
def multihead_attention_params ( mesh , heads , io_channels , kv_channels , variable_dtype , combine = False ) : qkvo = mtf . Dimension ( "qkvo" , 4 ) qk_stddev = ( io_channels . size ** - 0.5 ) * ( kv_channels . size ** - 0.25 ) v_stddev = io_channels . size ** - 0.5 o_stddev = ( io_channels . size * heads . size ) **...
Create Parameters for Multihead Attention .
33,782
def attention_mask_ignore_padding ( inputs , dtype = tf . float32 ) : inputs = rename_length_to_memory_length ( inputs ) return mtf . cast ( mtf . equal ( inputs , 0 ) , dtype ) * - 1e9
Bias for encoder - decoder attention .
33,783
def attention_mask_autoregressive ( query_pos , dtype = tf . float32 ) : memory_pos = rename_length_to_memory_length ( query_pos ) return mtf . cast ( mtf . less ( query_pos , memory_pos ) , dtype ) * - 1e9
Bias for self - attention where attention to the right is disallowed .
33,784
def attention_mask_same_segment ( query_segment , memory_segment = None , dtype = tf . float32 ) : memory_segment = rename_length_to_memory_length ( memory_segment or query_segment ) return mtf . cast ( mtf . not_equal ( query_segment , memory_segment ) , dtype ) * - 1e9
Bias for attention where attention between segments is disallowed .
33,785
def multiplicative_jitter ( x , epsilon = 1e-2 ) : if epsilon == 0 : return x return x * mtf . random_uniform ( x . mesh , x . shape , minval = 1.0 - epsilon , maxval = 1.0 + epsilon , dtype = x . dtype )
Multiply values by a random number between 1 - epsilon and 1 + epsilon .
33,786
def multihead_self_attention_memory_compressed ( x , mask_right , compression_factor , kv_channels , heads , dropout = 0.0 , dropout_broadcast_dims = None , master_dtype = tf . float32 , slice_dtype = tf . float32 , name = "multihead_attention" ) : batch_dims = x . shape . dims [ : - 2 ] length , io_channels = x . shap...
Memory - compressed self - attention .
33,787
def compress_mean ( x , dim , compression_factor ) : dims = x . shape . dims pos = dims . index ( dim ) compressed_dim = mtf . Dimension ( dim . name , dim . size // compression_factor ) compression_factor_dim = mtf . Dimension ( "compression_factor" , compression_factor ) new_shape = ( dims [ : pos ] + [ compressed_di...
Compress by taking group means .
33,788
def embedding ( indices , vocab_dim , output_dim , variable_dtype , name = "embedding" ) : weights = embedding_weights ( indices . mesh , vocab_dim , output_dim , variable_dtype , name ) return mtf . gather ( weights , indices , vocab_dim )
Embedding layer .
33,789
def attention_params ( context , kv_dim , num_heads , num_memory_heads = 0 , shared_kv = False ) : if num_heads == 1 : query_heads_dims = None memory_heads_dims = None elif num_memory_heads == 0 : query_heads_dims = [ mtf . Dimension ( "heads" , num_heads ) ] memory_heads_dims = query_heads_dims elif num_memory_heads =...
Attention Parameters for Transformer Layers .
33,790
def get_metric_fns ( metric_names , labels , outputs ) : metric_fns = { } for metric_name in metric_names : metric_fn_name = metric_name . split ( "/" ) [ - 1 ] if hasattr ( metrics , metric_fn_name ) : metric_fn = getattr ( metrics , metric_fn_name ) metric_fns [ metric_name ] = metric_fn ( labels , outputs ) else : r...
Generate a dictionary of metric name to metric function .
33,791
def minimize_peak_memory ( graph , scheduler_alg ) : if scheduler_alg == 'NAIVE' : return _minimize_peak_memory_naive ( graph ) elif scheduler_alg == 'LIST' : return _minimize_peak_memory_list ( graph ) else : raise NotImplementedError ( '{} is not a scheduler algorithm. It should be ' 'one of NAIVE or LIST.' . format ...
Computes a schedule to minimize peak memory .
33,792
def _minimize_peak_memory_list ( graph ) : schedule = [ ] bytes_freed = { } users_of = collections . defaultdict ( set ) in_degree = collections . defaultdict ( int ) operation_id = { } priority_queue = [ ] for i , operation_name in enumerate ( graph . get_all_operation_names ( ) ) : operation_id [ operation_name ] = i...
Computes schedule according to the greedy list heuristic .
33,793
def layout ( mtf_graph , mesh_shape , mtf_outputs = ( ) ) : mesh_shape = mtf . convert_to_shape ( mesh_shape ) estimator = memory_estimator . MemoryEstimator ( mtf_graph , mesh_shape , mtf_outputs ) optimizer = layout_optimizer . LayoutOptimizer ( estimator ) return mtf . convert_to_layout_rules ( optimizer . solve ( )...
Compute layout rules based on a computational graph and mesh shape .
33,794
def apply_grads ( self , grads , variables ) : ops = [ ] for grad , var in zip ( grads , variables ) : ops . extend ( self . apply_grad ( grad , var ) ) if not ops : return ops return variables [ 0 ] . graph . combine_assignments ( ops )
Apply gradients to variables .
33,795
def _factored_dims ( self , shape ) : if not self . _factored or shape . ndims < 2 : return None sorted_dims = sorted ( shape . dims , key = lambda d : - d . size ) if sorted_dims [ 1 ] . size < self . _min_dim_size_to_factor : return None return sorted_dims [ : 2 ]
Should we use a factored second moment estimator .
33,796
def is_valid_assignment ( self , mtf_dimension_name , mesh_dimension_name ) : return ( ( mtf_dimension_name in self . _splittable_mtf_dimension_names ) and ( self . _mtf_dimension_name_to_size_gcd [ mtf_dimension_name ] % self . _mesh_dimension_name_to_size [ mesh_dimension_name ] == 0 ) )
Whether this MTF dimension may be assigned to this mesh dimension .
33,797
def _initialize_splittable_dimensions ( self , mtf_graph ) : all_mtf_dimension_names = set ( ) for mtf_operation in mtf_graph . operations : for mtf_tensor in mtf_operation . outputs : for mtf_dimension in mtf_tensor . shape . dims : if not re . match ( r"_anonymous_\d*" , mtf_dimension . name ) : all_mtf_dimension_nam...
Initializer for self . _splittable_mtf_dimension_names .
33,798
def _initialize_mtf_dimension_name_to_size_gcd ( self , mtf_graph ) : mtf_dimension_name_to_size_gcd = { } for mtf_operation in mtf_graph . operations : for mtf_tensor in mtf_operation . outputs : for mtf_dimension in mtf_tensor . shape . dims : mtf_dimension_name_to_size_gcd [ mtf_dimension . name ] = fractions . gcd ...
Initializer for self . _mtf_dimension_name_to_size_gcd .
33,799
def _initialize_mesh_dimension_name_to_size ( self , mesh_shape ) : mesh_dimension_name_to_size = { } for mesh_dimension in mesh_shape . dims : mesh_dimension_name_to_size [ mesh_dimension . name ] = mesh_dimension . size return mesh_dimension_name_to_size
Initializer for self . _mesh_dimension_name_to_size .