code
stringlengths
87
55.2k
code_codestyle
int64
0
349
style_context
stringlengths
135
49.1k
style_context_codestyle
int64
0
349
label
int64
0
1
def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> float: if digit_amount > 0: return round(number - int(lowerCamelCase__ ) , lowerCamelCase__ ) return number - int(lowerCamelCase__ ) if __name__ == "__main__": print(decimal_isolate(1.53, 0)) print(decimal_isolate(35.3_45, 1)) print(decimal_isolate(35.3_45, 2)) print(decimal_isolate(35.3_45, 3)) print(decimal_isolate(-14.7_89, 3)) print(decimal_isolate(0, 2)) print(decimal_isolate(-14.1_23, 1)) print(decimal_isolate(-14.1_23, 2)) print(decimal_isolate(-14.1_23, 3))
73
import re import warnings from contextlib import contextmanager from ...processing_utils import ProcessorMixin class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : Any = ['''image_processor''', '''tokenizer'''] _UpperCAmelCase : List[Any] = '''AutoImageProcessor''' _UpperCAmelCase : Dict = '''AutoTokenizer''' def __init__( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : Optional[int]=None ,SCREAMING_SNAKE_CASE__ : List[Any]=None ,**SCREAMING_SNAKE_CASE__ : Union[str, Any]): __lowerCamelCase : List[str] = None if "feature_extractor" in kwargs: warnings.warn( 'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`' ' instead.' ,SCREAMING_SNAKE_CASE__ ,) __lowerCamelCase : Union[str, Any] = kwargs.pop('feature_extractor') __lowerCamelCase : Dict = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('You need to specify an `image_processor`.') if tokenizer is None: raise ValueError('You need to specify a `tokenizer`.') super().__init__(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Dict = self.image_processor __lowerCamelCase : Optional[int] = False def __call__( self : int ,*SCREAMING_SNAKE_CASE__ : Union[str, Any] ,**SCREAMING_SNAKE_CASE__ : Union[str, Any]): # For backward compatibility if self._in_target_context_manager: return self.current_processor(*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[int] = kwargs.pop('images' ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Union[str, Any] = kwargs.pop('text' ,SCREAMING_SNAKE_CASE__) if len(SCREAMING_SNAKE_CASE__) > 0: __lowerCamelCase : int = args[0] __lowerCamelCase : List[str] = args[1:] if images is None and text is None: raise ValueError('You need to specify either an `images` or `text` input to process.') if images is not None: __lowerCamelCase : Optional[int] = self.image_processor(SCREAMING_SNAKE_CASE__ ,*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) if text is not None: __lowerCamelCase : List[Any] = self.tokenizer(SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) if text is None: return inputs elif images is None: return encodings else: __lowerCamelCase : Optional[Any] = encodings['input_ids'] return inputs def lowerCAmelCase ( self : int ,*SCREAMING_SNAKE_CASE__ : Union[str, Any] ,**SCREAMING_SNAKE_CASE__ : Dict): return self.tokenizer.batch_decode(*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Optional[Any] ,*SCREAMING_SNAKE_CASE__ : List[Any] ,**SCREAMING_SNAKE_CASE__ : Any): return self.tokenizer.decode(*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) @contextmanager def lowerCAmelCase ( self : Tuple): warnings.warn( '`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your ' 'labels by using the argument `text` of the regular `__call__` method (either in the same call as ' 'your images inputs, or in a separate call.') __lowerCamelCase : List[Any] = True __lowerCamelCase : str = self.tokenizer yield __lowerCamelCase : Tuple = self.image_processor __lowerCamelCase : Tuple = False def lowerCAmelCase ( self : Any ,SCREAMING_SNAKE_CASE__ : str ,SCREAMING_SNAKE_CASE__ : int=False ,SCREAMING_SNAKE_CASE__ : List[Any]=None): if added_vocab is None: __lowerCamelCase : str = self.tokenizer.get_added_vocab() __lowerCamelCase : Union[str, Any] = {} while tokens: __lowerCamelCase : Tuple = re.search(R'<s_(.*?)>' ,SCREAMING_SNAKE_CASE__ ,re.IGNORECASE) if start_token is None: break __lowerCamelCase : Dict = start_token.group(1) __lowerCamelCase : List[str] = re.search(RF"</s_{key}>" ,SCREAMING_SNAKE_CASE__ ,re.IGNORECASE) __lowerCamelCase : Optional[int] = start_token.group() if end_token is None: __lowerCamelCase : List[Any] = tokens.replace(SCREAMING_SNAKE_CASE__ ,'') else: __lowerCamelCase : Tuple = end_token.group() __lowerCamelCase : int = re.escape(SCREAMING_SNAKE_CASE__) __lowerCamelCase : str = re.escape(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Union[str, Any] = re.search(F"{start_token_escaped}(.*?){end_token_escaped}" ,SCREAMING_SNAKE_CASE__ ,re.IGNORECASE) if content is not None: __lowerCamelCase : List[Any] = content.group(1).strip() if r"<s_" in content and r"</s_" in content: # non-leaf node __lowerCamelCase : str = self.tokenajson(SCREAMING_SNAKE_CASE__ ,is_inner_value=SCREAMING_SNAKE_CASE__ ,added_vocab=SCREAMING_SNAKE_CASE__) if value: if len(SCREAMING_SNAKE_CASE__) == 1: __lowerCamelCase : Tuple = value[0] __lowerCamelCase : int = value else: # leaf nodes __lowerCamelCase : Tuple = [] for leaf in content.split(R'<sep/>'): __lowerCamelCase : List[Any] = leaf.strip() if leaf in added_vocab and leaf[0] == "<" and leaf[-2:] == "/>": __lowerCamelCase : str = leaf[1:-2] # for categorical special tokens output[key].append(SCREAMING_SNAKE_CASE__) if len(output[key]) == 1: __lowerCamelCase : Dict = output[key][0] __lowerCamelCase : Dict = tokens[tokens.find(SCREAMING_SNAKE_CASE__) + len(SCREAMING_SNAKE_CASE__) :].strip() if tokens[:6] == r"<sep/>": # non-leaf nodes return [output] + self.tokenajson(tokens[6:] ,is_inner_value=SCREAMING_SNAKE_CASE__ ,added_vocab=SCREAMING_SNAKE_CASE__) if len(SCREAMING_SNAKE_CASE__): return [output] if is_inner_value else output else: return [] if is_inner_value else {"text_sequence": tokens} @property def lowerCAmelCase ( self : List[str]): warnings.warn( '`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.' ,SCREAMING_SNAKE_CASE__ ,) return self.image_processor_class @property def lowerCAmelCase ( self : List[Any]): warnings.warn( '`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.' ,SCREAMING_SNAKE_CASE__ ,) return self.image_processor
73
1
import os import unicodedata from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging a =logging.get_logger(__name__) a ={"""vocab_file""": """spiece.model"""} a ={ """vocab_file""": { """albert-base-v1""": """https://huggingface.co/albert-base-v1/resolve/main/spiece.model""", """albert-large-v1""": """https://huggingface.co/albert-large-v1/resolve/main/spiece.model""", """albert-xlarge-v1""": """https://huggingface.co/albert-xlarge-v1/resolve/main/spiece.model""", """albert-xxlarge-v1""": """https://huggingface.co/albert-xxlarge-v1/resolve/main/spiece.model""", """albert-base-v2""": """https://huggingface.co/albert-base-v2/resolve/main/spiece.model""", """albert-large-v2""": """https://huggingface.co/albert-large-v2/resolve/main/spiece.model""", """albert-xlarge-v2""": """https://huggingface.co/albert-xlarge-v2/resolve/main/spiece.model""", """albert-xxlarge-v2""": """https://huggingface.co/albert-xxlarge-v2/resolve/main/spiece.model""", } } a ={ """albert-base-v1""": 512, """albert-large-v1""": 512, """albert-xlarge-v1""": 512, """albert-xxlarge-v1""": 512, """albert-base-v2""": 512, """albert-large-v2""": 512, """albert-xlarge-v2""": 512, """albert-xxlarge-v2""": 512, } a ="""▁""" class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : List[Any] = VOCAB_FILES_NAMES _UpperCAmelCase : List[str] = PRETRAINED_VOCAB_FILES_MAP _UpperCAmelCase : Optional[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self : str ,SCREAMING_SNAKE_CASE__ : Optional[int] ,SCREAMING_SNAKE_CASE__ : Tuple=True ,SCREAMING_SNAKE_CASE__ : str=True ,SCREAMING_SNAKE_CASE__ : List[str]=False ,SCREAMING_SNAKE_CASE__ : Any="[CLS]" ,SCREAMING_SNAKE_CASE__ : Optional[int]="[SEP]" ,SCREAMING_SNAKE_CASE__ : Optional[Any]="<unk>" ,SCREAMING_SNAKE_CASE__ : Any="[SEP]" ,SCREAMING_SNAKE_CASE__ : Optional[int]="<pad>" ,SCREAMING_SNAKE_CASE__ : Any="[CLS]" ,SCREAMING_SNAKE_CASE__ : Union[str, Any]="[MASK]" ,SCREAMING_SNAKE_CASE__ : Optional[Dict[str, Any]] = None ,**SCREAMING_SNAKE_CASE__ : Dict ,): # Mask token behave like a normal word, i.e. include the space before it and # is included in the raw text, there should be a match in a non-normalized sentence. __lowerCamelCase : Dict = ( AddedToken(SCREAMING_SNAKE_CASE__ ,lstrip=SCREAMING_SNAKE_CASE__ ,rstrip=SCREAMING_SNAKE_CASE__ ,normalized=SCREAMING_SNAKE_CASE__) if isinstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) else mask_token ) __lowerCamelCase : str = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( do_lower_case=SCREAMING_SNAKE_CASE__ ,remove_space=SCREAMING_SNAKE_CASE__ ,keep_accents=SCREAMING_SNAKE_CASE__ ,bos_token=SCREAMING_SNAKE_CASE__ ,eos_token=SCREAMING_SNAKE_CASE__ ,unk_token=SCREAMING_SNAKE_CASE__ ,sep_token=SCREAMING_SNAKE_CASE__ ,pad_token=SCREAMING_SNAKE_CASE__ ,cls_token=SCREAMING_SNAKE_CASE__ ,mask_token=SCREAMING_SNAKE_CASE__ ,sp_model_kwargs=self.sp_model_kwargs ,**SCREAMING_SNAKE_CASE__ ,) __lowerCamelCase : Any = do_lower_case __lowerCamelCase : Union[str, Any] = remove_space __lowerCamelCase : Tuple = keep_accents __lowerCamelCase : Dict = vocab_file __lowerCamelCase : str = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.Load(SCREAMING_SNAKE_CASE__) @property def lowerCAmelCase ( self : Optional[Any]): return len(self.sp_model) def lowerCAmelCase ( self : Optional[Any]): __lowerCamelCase : Optional[int] = {self.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__): i for i in range(self.vocab_size)} vocab.update(self.added_tokens_encoder) return vocab def __getstate__( self : Union[str, Any]): __lowerCamelCase : str = self.__dict__.copy() __lowerCamelCase : Tuple = None return state def __setstate__( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : str): __lowerCamelCase : List[str] = d # for backward compatibility if not hasattr(self ,'sp_model_kwargs'): __lowerCamelCase : List[str] = {} __lowerCamelCase : int = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.Load(self.vocab_file) def lowerCAmelCase ( self : Dict ,SCREAMING_SNAKE_CASE__ : List[Any]): if self.remove_space: __lowerCamelCase : Dict = ' '.join(inputs.strip().split()) else: __lowerCamelCase : Optional[Any] = inputs __lowerCamelCase : Tuple = outputs.replace('``' ,'"').replace('\'\'' ,'"') if not self.keep_accents: __lowerCamelCase : List[str] = unicodedata.normalize('NFKD' ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : str = ''.join([c for c in outputs if not unicodedata.combining(SCREAMING_SNAKE_CASE__)]) if self.do_lower_case: __lowerCamelCase : Optional[Any] = outputs.lower() return outputs def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : str): __lowerCamelCase : Tuple = self.preprocess_text(SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = self.sp_model.encode(SCREAMING_SNAKE_CASE__ ,out_type=SCREAMING_SNAKE_CASE__) __lowerCamelCase : Tuple = [] for piece in pieces: if len(SCREAMING_SNAKE_CASE__) > 1 and piece[-1] == str(',') and piece[-2].isdigit(): __lowerCamelCase : int = self.sp_model.EncodeAsPieces(piece[:-1].replace(SCREAMING_SNAKE_CASE__ ,'')) if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE: if len(cur_pieces[0]) == 1: __lowerCamelCase : Union[str, Any] = cur_pieces[1:] else: __lowerCamelCase : Dict = cur_pieces[0][1:] cur_pieces.append(piece[-1]) new_pieces.extend(SCREAMING_SNAKE_CASE__) else: new_pieces.append(SCREAMING_SNAKE_CASE__) return new_pieces def lowerCAmelCase ( self : Any ,SCREAMING_SNAKE_CASE__ : List[str]): return self.sp_model.PieceToId(SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : str ,SCREAMING_SNAKE_CASE__ : Any): return self.sp_model.IdToPiece(SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Tuple ,SCREAMING_SNAKE_CASE__ : int): __lowerCamelCase : Optional[Any] = [] __lowerCamelCase : int = '' __lowerCamelCase : Optional[int] = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(SCREAMING_SNAKE_CASE__) + token __lowerCamelCase : List[Any] = True __lowerCamelCase : Any = [] else: current_sub_tokens.append(SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = False out_string += self.sp_model.decode(SCREAMING_SNAKE_CASE__) return out_string.strip() def lowerCAmelCase ( self : Dict ,SCREAMING_SNAKE_CASE__ : List[int] ,SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None): __lowerCamelCase : Union[str, Any] = [self.sep_token_id] __lowerCamelCase : int = [self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def lowerCAmelCase ( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : List[int] ,SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ,SCREAMING_SNAKE_CASE__ : bool = False): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=SCREAMING_SNAKE_CASE__ ,token_ids_a=SCREAMING_SNAKE_CASE__ ,already_has_special_tokens=SCREAMING_SNAKE_CASE__) if token_ids_a is not None: return [1] + ([0] * len(SCREAMING_SNAKE_CASE__)) + [1] + ([0] * len(SCREAMING_SNAKE_CASE__)) + [1] return [1] + ([0] * len(SCREAMING_SNAKE_CASE__)) + [1] def lowerCAmelCase ( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : List[int] ,SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None): __lowerCamelCase : Tuple = [self.sep_token_id] __lowerCamelCase : List[Any] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep) * [0] return len(cls + token_ids_a + sep) * [0] + len(token_ids_a + sep) * [1] def lowerCAmelCase ( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : str ,SCREAMING_SNAKE_CASE__ : Optional[str] = None): if not os.path.isdir(SCREAMING_SNAKE_CASE__): logger.error(F"Vocabulary path ({save_directory}) should be a directory") return __lowerCamelCase : List[str] = os.path.join( SCREAMING_SNAKE_CASE__ ,(filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file']) if os.path.abspath(self.vocab_file) != os.path.abspath(SCREAMING_SNAKE_CASE__) and os.path.isfile(self.vocab_file): copyfile(self.vocab_file ,SCREAMING_SNAKE_CASE__) elif not os.path.isfile(self.vocab_file): with open(SCREAMING_SNAKE_CASE__ ,'wb') as fi: __lowerCamelCase : str = self.sp_model.serialized_model_proto() fi.write(SCREAMING_SNAKE_CASE__) return (out_vocab_file,)
73
def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> int: __lowerCamelCase : Optional[int] = 0 __lowerCamelCase : Dict = len(lowerCamelCase__ ) - 1 while left <= right: # avoid divided by 0 during interpolation if sorted_collection[left] == sorted_collection[right]: if sorted_collection[left] == item: return left else: return None __lowerCamelCase : str = left + ((item - sorted_collection[left]) * (right - left)) // ( sorted_collection[right] - sorted_collection[left] ) # out of range check if point < 0 or point >= len(lowerCamelCase__ ): return None __lowerCamelCase : Tuple = sorted_collection[point] if current_item == item: return point else: if point < left: __lowerCamelCase : List[Any] = left __lowerCamelCase : Tuple = point elif point > right: __lowerCamelCase : Dict = right __lowerCamelCase : str = point else: if item < current_item: __lowerCamelCase : Dict = point - 1 else: __lowerCamelCase : Dict = point + 1 return None def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> Any: # avoid divided by 0 during interpolation if sorted_collection[left] == sorted_collection[right]: if sorted_collection[left] == item: return left else: return None __lowerCamelCase : Optional[int] = left + ((item - sorted_collection[left]) * (right - left)) // ( sorted_collection[right] - sorted_collection[left] ) # out of range check if point < 0 or point >= len(lowerCamelCase__ ): return None if sorted_collection[point] == item: return point elif point < left: return interpolation_search_by_recursion(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) elif point > right: return interpolation_search_by_recursion(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) else: if sorted_collection[point] > item: return interpolation_search_by_recursion( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , point - 1 ) else: return interpolation_search_by_recursion( lowerCamelCase__ , lowerCamelCase__ , point + 1 , lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Optional[Any]: if collection != sorted(lowerCamelCase__ ): raise ValueError('Collection must be ascending sorted' ) return True if __name__ == "__main__": import sys a =0 if debug == 1: a =[10, 30, 40, 45, 50, 66, 77, 93] try: __assert_sorted(collection) except ValueError: sys.exit("""Sequence must be ascending sorted to apply interpolation search""") a =67 a =interpolation_search(collection, target) if result is not None: print(F"""{target} found at positions: {result}""") else: print("""Not found""")
73
1
from random import shuffle import tensorflow as tf from numpy import array def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> Optional[Any]: __lowerCamelCase : Optional[Any] = int(lowerCamelCase__ ) assert noofclusters < len(lowerCamelCase__ ) # Find out the dimensionality __lowerCamelCase : Optional[int] = len(vectors[0] ) # Will help select random centroids from among the available vectors __lowerCamelCase : Union[str, Any] = list(range(len(lowerCamelCase__ ) ) ) shuffle(lowerCamelCase__ ) # GRAPH OF COMPUTATION # We initialize a new graph and set it as the default during each run # of this algorithm. This ensures that as this function is called # multiple times, the default graph doesn't keep getting crowded with # unused ops and Variables from previous function calls. __lowerCamelCase : Optional[Any] = tf.Graph() with graph.as_default(): # SESSION OF COMPUTATION __lowerCamelCase : Tuple = tf.Session() ##CONSTRUCTING THE ELEMENTS OF COMPUTATION ##First lets ensure we have a Variable vector for each centroid, ##initialized to one of the vectors from the available data points __lowerCamelCase : Optional[Any] = [ tf.Variable(vectors[vector_indices[i]] ) for i in range(lowerCamelCase__ ) ] ##These nodes will assign the centroid Variables the appropriate ##values __lowerCamelCase : Optional[Any] = tf.placeholder('float64' , [dim] ) __lowerCamelCase : Optional[int] = [] for centroid in centroids: cent_assigns.append(tf.assign(lowerCamelCase__ , lowerCamelCase__ ) ) ##Variables for cluster assignments of individual vectors(initialized ##to 0 at first) __lowerCamelCase : List[Any] = [tf.Variable(0 ) for i in range(len(lowerCamelCase__ ) )] ##These nodes will assign an assignment Variable the appropriate ##value __lowerCamelCase : Tuple = tf.placeholder('int32' ) __lowerCamelCase : str = [] for assignment in assignments: cluster_assigns.append(tf.assign(lowerCamelCase__ , lowerCamelCase__ ) ) ##Now lets construct the node that will compute the mean # The placeholder for the input __lowerCamelCase : Optional[int] = tf.placeholder('float' , [None, dim] ) # The Node/op takes the input and computes a mean along the 0th # dimension, i.e. the list of input vectors __lowerCamelCase : Dict = tf.reduce_mean(lowerCamelCase__ , 0 ) ##Node for computing Euclidean distances # Placeholders for input __lowerCamelCase : int = tf.placeholder('float' , [dim] ) __lowerCamelCase : Optional[Any] = tf.placeholder('float' , [dim] ) __lowerCamelCase : List[Any] = tf.sqrt(tf.reduce_sum(tf.pow(tf.sub(lowerCamelCase__ , lowerCamelCase__ ) , 2 ) ) ) ##This node will figure out which cluster to assign a vector to, ##based on Euclidean distances of the vector from the centroids. # Placeholder for input __lowerCamelCase : str = tf.placeholder('float' , [noofclusters] ) __lowerCamelCase : Optional[Any] = tf.argmin(lowerCamelCase__ , 0 ) ##INITIALIZING STATE VARIABLES ##This will help initialization of all Variables defined with respect ##to the graph. The Variable-initializer should be defined after ##all the Variables have been constructed, so that each of them ##will be included in the initialization. __lowerCamelCase : List[str] = tf.initialize_all_variables() # Initialize all variables sess.run(lowerCamelCase__ ) ##CLUSTERING ITERATIONS # Now perform the Expectation-Maximization steps of K-Means clustering # iterations. To keep things simple, we will only do a set number of # iterations, instead of using a Stopping Criterion. __lowerCamelCase : Optional[int] = 1_0_0 for _ in range(lowerCamelCase__ ): ##EXPECTATION STEP ##Based on the centroid locations till last iteration, compute ##the _expected_ centroid assignments. # Iterate over each vector for vector_n in range(len(lowerCamelCase__ ) ): __lowerCamelCase : Any = vectors[vector_n] # Compute Euclidean distance between this vector and each # centroid. Remember that this list cannot be named #'centroid_distances', since that is the input to the # cluster assignment node. __lowerCamelCase : Dict = [ sess.run(lowerCamelCase__ , feed_dict={va: vect, va: sess.run(lowerCamelCase__ )} ) for centroid in centroids ] # Now use the cluster assignment node, with the distances # as the input __lowerCamelCase : int = sess.run( lowerCamelCase__ , feed_dict={centroid_distances: distances} ) # Now assign the value to the appropriate state variable sess.run( cluster_assigns[vector_n] , feed_dict={assignment_value: assignment} ) ##MAXIMIZATION STEP # Based on the expected state computed from the Expectation Step, # compute the locations of the centroids so as to maximize the # overall objective of minimizing within-cluster Sum-of-Squares for cluster_n in range(lowerCamelCase__ ): # Collect all the vectors assigned to this cluster __lowerCamelCase : Union[str, Any] = [ vectors[i] for i in range(len(lowerCamelCase__ ) ) if sess.run(assignments[i] ) == cluster_n ] # Compute new centroid location __lowerCamelCase : str = sess.run( lowerCamelCase__ , feed_dict={mean_input: array(lowerCamelCase__ )} ) # Assign value to appropriate variable sess.run( cent_assigns[cluster_n] , feed_dict={centroid_value: new_location} ) # Return centroids and assignments __lowerCamelCase : int = sess.run(lowerCamelCase__ ) __lowerCamelCase : int = sess.run(lowerCamelCase__ ) return centroids, assignments
73
import json import os import subprocess import unittest from ast import literal_eval import pytest from parameterized import parameterized, parameterized_class from . import is_sagemaker_available if is_sagemaker_available(): from sagemaker import Session, TrainingJobAnalytics from sagemaker.huggingface import HuggingFace @pytest.mark.skipif( literal_eval(os.getenv('''TEST_SAGEMAKER''' , '''False''' ) ) is not True , reason='''Skipping test because should only be run when releasing minor transformers version''' , ) @pytest.mark.usefixtures('''sm_env''' ) @parameterized_class( [ { '''framework''': '''pytorch''', '''script''': '''run_glue_model_parallelism.py''', '''model_name_or_path''': '''roberta-large''', '''instance_type''': '''ml.p3dn.24xlarge''', '''results''': {'''train_runtime''': 1_600, '''eval_accuracy''': 0.3, '''eval_loss''': 1.2}, }, { '''framework''': '''pytorch''', '''script''': '''run_glue.py''', '''model_name_or_path''': '''roberta-large''', '''instance_type''': '''ml.p3dn.24xlarge''', '''results''': {'''train_runtime''': 1_600, '''eval_accuracy''': 0.3, '''eval_loss''': 1.2}, }, ] ) class A_ ( unittest.TestCase ): def lowerCAmelCase ( self : Union[str, Any]): if self.framework == "pytorch": subprocess.run( F"cp ./examples/pytorch/text-classification/run_glue.py {self.env.test_path}/run_glue.py".split() ,encoding='utf-8' ,check=SCREAMING_SNAKE_CASE__ ,) assert hasattr(self ,'env') def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : int): # configuration for running training on smdistributed Model Parallel __lowerCamelCase : Any = { 'enabled': True, 'processes_per_host': 8, } __lowerCamelCase : List[Any] = { 'enabled': True, 'parameters': { 'microbatches': 4, 'placement_strategy': 'spread', 'pipeline': 'interleaved', 'optimize': 'speed', 'partitions': 4, 'ddp': True, }, } __lowerCamelCase : str = {'smdistributed': {'modelparallel': smp_options}, 'mpi': mpi_options} __lowerCamelCase : List[str] = 'trainer' if self.script == 'run_glue.py' else 'smtrainer' # creates estimator return HuggingFace( entry_point=self.script ,source_dir=self.env.test_path ,role=self.env.role ,image_uri=self.env.image_uri ,base_job_name=F"{self.env.base_job_name}-{instance_count}-smp-{name_extension}" ,instance_count=SCREAMING_SNAKE_CASE__ ,instance_type=self.instance_type ,debugger_hook_config=SCREAMING_SNAKE_CASE__ ,hyperparameters={ **self.env.hyperparameters, 'model_name_or_path': self.model_name_or_path, 'max_steps': 5_0_0, } ,metric_definitions=self.env.metric_definitions ,distribution=SCREAMING_SNAKE_CASE__ ,py_version='py36' ,) def lowerCAmelCase ( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : Any): TrainingJobAnalytics(SCREAMING_SNAKE_CASE__).export_csv(F"{self.env.test_path}/{job_name}_metrics.csv") @parameterized.expand([(1,)]) def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : Optional[Any]): # create estimator __lowerCamelCase : str = self.create_estimator(SCREAMING_SNAKE_CASE__) # run training estimator.fit() # result dataframe __lowerCamelCase : List[str] = TrainingJobAnalytics(estimator.latest_training_job.name).dataframe() # extract kpis __lowerCamelCase : Optional[int] = list(result_metrics_df[result_metrics_df.metric_name == 'eval_accuracy']['value']) __lowerCamelCase : Any = list(result_metrics_df[result_metrics_df.metric_name == 'eval_loss']['value']) # get train time from SageMaker job, this includes starting, preprocessing, stopping __lowerCamelCase : str = ( Session().describe_training_job(estimator.latest_training_job.name).get('TrainingTimeInSeconds' ,9_9_9_9_9_9) ) # assert kpis assert train_runtime <= self.results["train_runtime"] assert all(t >= self.results['eval_accuracy'] for t in eval_accuracy) assert all(t <= self.results['eval_loss'] for t in eval_loss) # dump tests result into json file to share in PR with open(F"{estimator.latest_training_job.name}.json" ,'w') as outfile: json.dump({'train_time': train_runtime, 'eval_accuracy': eval_accuracy, 'eval_loss': eval_loss} ,SCREAMING_SNAKE_CASE__)
73
1
from __future__ import annotations import time a =list[tuple[int, int]] a =[ [0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles [0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0], [1, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0], ] a =[[-1, 0], [0, -1], [1, 0], [0, 1]] # up, left, down, right class A_ : def __init__( self : List[str] ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : Node | None): __lowerCamelCase : Tuple = pos_x __lowerCamelCase : List[str] = pos_y __lowerCamelCase : str = (pos_y, pos_x) __lowerCamelCase : str = goal_x __lowerCamelCase : int = goal_y __lowerCamelCase : List[Any] = parent class A_ : def __init__( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : tuple[int, int] ,SCREAMING_SNAKE_CASE__ : tuple[int, int]): __lowerCamelCase : Any = Node(start[1] ,start[0] ,goal[1] ,goal[0] ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = Node(goal[1] ,goal[0] ,goal[1] ,goal[0] ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Union[str, Any] = [self.start] __lowerCamelCase : List[str] = False def lowerCAmelCase ( self : List[Any]): while self.node_queue: __lowerCamelCase : Any = self.node_queue.pop(0) if current_node.pos == self.target.pos: __lowerCamelCase : Dict = True return self.retrace_path(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Tuple = self.get_successors(SCREAMING_SNAKE_CASE__) for node in successors: self.node_queue.append(SCREAMING_SNAKE_CASE__) if not self.reached: return [self.start.pos] return None def lowerCAmelCase ( self : str ,SCREAMING_SNAKE_CASE__ : Node): __lowerCamelCase : Union[str, Any] = [] for action in delta: __lowerCamelCase : Optional[Any] = parent.pos_x + action[1] __lowerCamelCase : Optional[int] = parent.pos_y + action[0] if not (0 <= pos_x <= len(grid[0]) - 1 and 0 <= pos_y <= len(SCREAMING_SNAKE_CASE__) - 1): continue if grid[pos_y][pos_x] != 0: continue successors.append( Node(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,self.target.pos_y ,self.target.pos_x ,SCREAMING_SNAKE_CASE__)) return successors def lowerCAmelCase ( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : Node | None): __lowerCamelCase : List[Any] = node __lowerCamelCase : int = [] while current_node is not None: path.append((current_node.pos_y, current_node.pos_x)) __lowerCamelCase : int = current_node.parent path.reverse() return path class A_ : def __init__( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : int): __lowerCamelCase : int = BreadthFirstSearch(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = BreadthFirstSearch(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = False def lowerCAmelCase ( self : str): while self.fwd_bfs.node_queue or self.bwd_bfs.node_queue: __lowerCamelCase : Any = self.fwd_bfs.node_queue.pop(0) __lowerCamelCase : Any = self.bwd_bfs.node_queue.pop(0) if current_bwd_node.pos == current_fwd_node.pos: __lowerCamelCase : List[str] = True return self.retrace_bidirectional_path( SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = current_bwd_node __lowerCamelCase : int = current_fwd_node __lowerCamelCase : str = { self.fwd_bfs: self.fwd_bfs.get_successors(SCREAMING_SNAKE_CASE__), self.bwd_bfs: self.bwd_bfs.get_successors(SCREAMING_SNAKE_CASE__), } for bfs in [self.fwd_bfs, self.bwd_bfs]: for node in successors[bfs]: bfs.node_queue.append(SCREAMING_SNAKE_CASE__) if not self.reached: return [self.fwd_bfs.start.pos] return None def lowerCAmelCase ( self : Dict ,SCREAMING_SNAKE_CASE__ : Node ,SCREAMING_SNAKE_CASE__ : Node): __lowerCamelCase : List[Any] = self.fwd_bfs.retrace_path(SCREAMING_SNAKE_CASE__) __lowerCamelCase : str = self.bwd_bfs.retrace_path(SCREAMING_SNAKE_CASE__) bwd_path.pop() bwd_path.reverse() __lowerCamelCase : List[Any] = fwd_path + bwd_path return path if __name__ == "__main__": # all coordinates are given in format [y,x] import doctest doctest.testmod() a =(0, 0) a =(len(grid) - 1, len(grid[0]) - 1) for elem in grid: print(elem) a =time.time() a =BreadthFirstSearch(init, goal) a =bfs.search() a =time.time() - start_bfs_time print("""Unidirectional BFS computation time : """, bfs_time) a =time.time() a =BidirectionalBreadthFirstSearch(init, goal) a =bd_bfs.search() a =time.time() - start_bd_bfs_time print("""Bidirectional BFS computation time : """, bd_bfs_time)
73
import unittest import numpy as np from transformers import DistilBertConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask if is_flax_available(): import jax.numpy as jnp from transformers.models.distilbert.modeling_flax_distilbert import ( FlaxDistilBertForMaskedLM, FlaxDistilBertForMultipleChoice, FlaxDistilBertForQuestionAnswering, FlaxDistilBertForSequenceClassification, FlaxDistilBertForTokenClassification, FlaxDistilBertModel, ) class A_ ( unittest.TestCase ): def __init__( self : Tuple ,SCREAMING_SNAKE_CASE__ : List[str] ,SCREAMING_SNAKE_CASE__ : Any=1_3 ,SCREAMING_SNAKE_CASE__ : int=7 ,SCREAMING_SNAKE_CASE__ : str=True ,SCREAMING_SNAKE_CASE__ : Dict=True ,SCREAMING_SNAKE_CASE__ : str=True ,SCREAMING_SNAKE_CASE__ : Dict=True ,SCREAMING_SNAKE_CASE__ : List[Any]=9_9 ,SCREAMING_SNAKE_CASE__ : List[Any]=3_2 ,SCREAMING_SNAKE_CASE__ : int=5 ,SCREAMING_SNAKE_CASE__ : List[Any]=4 ,SCREAMING_SNAKE_CASE__ : Optional[Any]=3_7 ,SCREAMING_SNAKE_CASE__ : Union[str, Any]="gelu" ,SCREAMING_SNAKE_CASE__ : int=0.1 ,SCREAMING_SNAKE_CASE__ : Optional[int]=0.1 ,SCREAMING_SNAKE_CASE__ : Optional[int]=5_1_2 ,SCREAMING_SNAKE_CASE__ : Dict=1_6 ,SCREAMING_SNAKE_CASE__ : Dict=2 ,SCREAMING_SNAKE_CASE__ : Optional[int]=0.02 ,SCREAMING_SNAKE_CASE__ : Dict=4 ,): __lowerCamelCase : int = parent __lowerCamelCase : Dict = batch_size __lowerCamelCase : Union[str, Any] = seq_length __lowerCamelCase : List[Any] = is_training __lowerCamelCase : Tuple = use_attention_mask __lowerCamelCase : List[str] = use_token_type_ids __lowerCamelCase : Any = use_labels __lowerCamelCase : List[str] = vocab_size __lowerCamelCase : Any = hidden_size __lowerCamelCase : Tuple = num_hidden_layers __lowerCamelCase : Union[str, Any] = num_attention_heads __lowerCamelCase : Union[str, Any] = intermediate_size __lowerCamelCase : List[Any] = hidden_act __lowerCamelCase : int = hidden_dropout_prob __lowerCamelCase : int = attention_probs_dropout_prob __lowerCamelCase : Union[str, Any] = max_position_embeddings __lowerCamelCase : Union[str, Any] = type_vocab_size __lowerCamelCase : List[str] = type_sequence_label_size __lowerCamelCase : Tuple = initializer_range __lowerCamelCase : Optional[int] = num_choices def lowerCAmelCase ( self : Union[str, Any]): __lowerCamelCase : Dict = ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size) __lowerCamelCase : Union[str, Any] = None if self.use_attention_mask: __lowerCamelCase : Any = random_attention_mask([self.batch_size, self.seq_length]) __lowerCamelCase : str = DistilBertConfig( vocab_size=self.vocab_size ,dim=self.hidden_size ,n_layers=self.num_hidden_layers ,n_heads=self.num_attention_heads ,hidden_dim=self.intermediate_size ,hidden_act=self.hidden_act ,dropout=self.hidden_dropout_prob ,attention_dropout=self.attention_probs_dropout_prob ,max_position_embeddings=self.max_position_embeddings ,initializer_range=self.initializer_range ,tie_weights_=SCREAMING_SNAKE_CASE__ ,) return config, input_ids, attention_mask def lowerCAmelCase ( self : List[Any]): __lowerCamelCase : List[str] = self.prepare_config_and_inputs() __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : Dict = config_and_inputs __lowerCamelCase : Any = {'input_ids': input_ids, 'attention_mask': attention_mask} return config, inputs_dict @require_flax class A_ ( SCREAMING_SNAKE_CASE , unittest.TestCase ): _UpperCAmelCase : Dict = ( ( FlaxDistilBertModel, FlaxDistilBertForMaskedLM, FlaxDistilBertForMultipleChoice, FlaxDistilBertForQuestionAnswering, FlaxDistilBertForSequenceClassification, FlaxDistilBertForTokenClassification, FlaxDistilBertForQuestionAnswering, ) if is_flax_available() else () ) def lowerCAmelCase ( self : Optional[Any]): __lowerCamelCase : Tuple = FlaxDistilBertModelTester(self) @slow def lowerCAmelCase ( self : int): for model_class_name in self.all_model_classes: __lowerCamelCase : List[Any] = model_class_name.from_pretrained('distilbert-base-uncased') __lowerCamelCase : List[str] = model(np.ones((1, 1))) self.assertIsNotNone(SCREAMING_SNAKE_CASE__) @require_flax class A_ ( unittest.TestCase ): @slow def lowerCAmelCase ( self : str): __lowerCamelCase : Union[str, Any] = FlaxDistilBertModel.from_pretrained('distilbert-base-uncased') __lowerCamelCase : str = np.array([[0, 3_4_5, 2_3_2, 3_2_8, 7_4_0, 1_4_0, 1_6_9_5, 6_9, 6_0_7_8, 1_5_8_8, 2]]) __lowerCamelCase : List[Any] = np.array([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]) __lowerCamelCase : Union[str, Any] = model(SCREAMING_SNAKE_CASE__ ,attention_mask=SCREAMING_SNAKE_CASE__)[0] __lowerCamelCase : Optional[int] = (1, 1_1, 7_6_8) self.assertEqual(output.shape ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Union[str, Any] = np.array([[[-0.1639, 0.3299, 0.1648], [-0.1746, 0.3289, 0.1710], [-0.1884, 0.3357, 0.1810]]]) self.assertTrue(jnp.allclose(output[:, 1:4, 1:4] ,SCREAMING_SNAKE_CASE__ ,atol=1E-4))
73
1
import os import sys a =os.path.join(os.path.dirname(__file__), """src""") sys.path.append(SRC_DIR) from transformers import ( AutoConfig, AutoModel, AutoModelForCausalLM, AutoModelForMaskedLM, AutoModelForQuestionAnswering, AutoModelForSequenceClassification, AutoTokenizer, add_start_docstrings, ) a =[ """torch""", """numpy""", """tokenizers""", """filelock""", """requests""", """tqdm""", """regex""", """sentencepiece""", """sacremoses""", """importlib_metadata""", """huggingface_hub""", ] @add_start_docstrings(AutoConfig.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> int: return AutoConfig.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ ) @add_start_docstrings(AutoTokenizer.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> Optional[Any]: return AutoTokenizer.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ ) @add_start_docstrings(AutoModel.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> List[str]: return AutoModel.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ ) @add_start_docstrings(AutoModelForCausalLM.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> Any: return AutoModelForCausalLM.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ ) @add_start_docstrings(AutoModelForMaskedLM.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> List[str]: return AutoModelForMaskedLM.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ ) @add_start_docstrings(AutoModelForSequenceClassification.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> List[str]: return AutoModelForSequenceClassification.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ ) @add_start_docstrings(AutoModelForQuestionAnswering.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> Tuple: return AutoModelForQuestionAnswering.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ )
73
import csv import tweepy # Twitter API credentials a ="""""" a ="""""" a ="""""" a ="""""" def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> None: # authorize twitter, initialize tweepy __lowerCamelCase : Tuple = tweepy.OAuthHandler(lowerCamelCase__ , lowerCamelCase__ ) auth.set_access_token(lowerCamelCase__ , lowerCamelCase__ ) __lowerCamelCase : Optional[int] = tweepy.API(lowerCamelCase__ ) # initialize a list to hold all the tweepy Tweets __lowerCamelCase : str = [] # make initial request for most recent tweets (200 is the maximum allowed count) __lowerCamelCase : Union[str, Any] = api.user_timeline(screen_name=lowerCamelCase__ , count=2_0_0 ) # save most recent tweets alltweets.extend(lowerCamelCase__ ) # save the id of the oldest tweet less one __lowerCamelCase : Any = alltweets[-1].id - 1 # keep grabbing tweets until there are no tweets left to grab while len(lowerCamelCase__ ) > 0: print(F"getting tweets before {oldest}" ) # all subsequent requests use the max_id param to prevent duplicates __lowerCamelCase : str = api.user_timeline( screen_name=lowerCamelCase__ , count=2_0_0 , max_id=lowerCamelCase__ ) # save most recent tweets alltweets.extend(lowerCamelCase__ ) # update the id of the oldest tweet less one __lowerCamelCase : Optional[int] = alltweets[-1].id - 1 print(F"...{len(lowerCamelCase__ )} tweets downloaded so far" ) # transform the tweepy tweets into a 2D array that will populate the csv __lowerCamelCase : str = [[tweet.id_str, tweet.created_at, tweet.text] for tweet in alltweets] # write the csv with open(F"new_{screen_name}_tweets.csv" , 'w' ) as f: __lowerCamelCase : Any = csv.writer(lowerCamelCase__ ) writer.writerow(['id', 'created_at', 'text'] ) writer.writerows(lowerCamelCase__ ) if __name__ == "__main__": # pass in the username of the account you want to download get_all_tweets("""FirePing32""")
73
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_torch_available a ={ """configuration_gpt_neo""": ["""GPT_NEO_PRETRAINED_CONFIG_ARCHIVE_MAP""", """GPTNeoConfig""", """GPTNeoOnnxConfig"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a =[ """GPT_NEO_PRETRAINED_MODEL_ARCHIVE_LIST""", """GPTNeoForCausalLM""", """GPTNeoForQuestionAnswering""", """GPTNeoForSequenceClassification""", """GPTNeoForTokenClassification""", """GPTNeoModel""", """GPTNeoPreTrainedModel""", """load_tf_weights_in_gpt_neo""", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a =[ """FlaxGPTNeoForCausalLM""", """FlaxGPTNeoModel""", """FlaxGPTNeoPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_gpt_neo import GPT_NEO_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTNeoConfig, GPTNeoOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_gpt_neo import ( GPT_NEO_PRETRAINED_MODEL_ARCHIVE_LIST, GPTNeoForCausalLM, GPTNeoForQuestionAnswering, GPTNeoForSequenceClassification, GPTNeoForTokenClassification, GPTNeoModel, GPTNeoPreTrainedModel, load_tf_weights_in_gpt_neo, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_gpt_neo import FlaxGPTNeoForCausalLM, FlaxGPTNeoModel, FlaxGPTNeoPreTrainedModel else: import sys a =_LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
73
import numpy as np from scipy.spatial.distance import cdist from sklearn.metrics import fa_score import datasets a ="""\ @inproceedings{kakwani2020indicnlpsuite, title={{IndicNLPSuite: Monolingual Corpora, Evaluation Benchmarks and Pre-trained Multilingual Language Models for Indian Languages}}, author={Divyanshu Kakwani and Anoop Kunchukuttan and Satish Golla and Gokul N.C. and Avik Bhattacharyya and Mitesh M. Khapra and Pratyush Kumar}, year={2020}, booktitle={Findings of EMNLP}, } """ a ="""\ IndicGLUE is a natural language understanding benchmark for Indian languages. It contains a wide variety of tasks and covers 11 major Indian languages - as, bn, gu, hi, kn, ml, mr, or, pa, ta, te. """ a =""" Compute IndicGLUE evaluation metric associated to each IndicGLUE dataset. Args: predictions: list of predictions to score (as int64), except for 'cvit-mkb-clsr' where each prediction is a vector (of float32). references: list of ground truth labels corresponding to the predictions (as int64), except for 'cvit-mkb-clsr' where each reference is a vector (of float32). Returns: depending on the IndicGLUE subset, one or several of: \"accuracy\": Accuracy \"f1\": F1 score \"precision\": Precision@10 Examples: >>> indic_glue_metric = datasets.load_metric('indic_glue', 'wnli') # 'wnli' or any of [\"copa\", \"sna\", \"csqa\", \"wstp\", \"inltkh\", \"bbca\", \"iitp-mr\", \"iitp-pr\", \"actsa-sc\", \"md\"] >>> references = [0, 1] >>> predictions = [0, 1] >>> results = indic_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {'accuracy': 1.0} >>> indic_glue_metric = datasets.load_metric('indic_glue', 'wiki-ner') >>> references = [0, 1] >>> predictions = [0, 1] >>> results = indic_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {'accuracy': 1.0, 'f1': 1.0} >>> indic_glue_metric = datasets.load_metric('indic_glue', 'cvit-mkb-clsr') >>> references = [[0.5, 0.5, 0.5], [0.1, 0.2, 0.3]] >>> predictions = [[0.5, 0.5, 0.5], [0.1, 0.2, 0.3]] >>> results = indic_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {'precision@10': 1.0} """ def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> List[str]: return float((preds == labels).mean() ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> List[str]: __lowerCamelCase : Optional[Any] = simple_accuracy(lowerCamelCase__ , lowerCamelCase__ ) __lowerCamelCase : Tuple = float(fa_score(y_true=lowerCamelCase__ , y_pred=lowerCamelCase__ ) ) return { "accuracy": acc, "f1": fa, } def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> Optional[Any]: __lowerCamelCase : Any = np.array(lowerCamelCase__ ) __lowerCamelCase : List[Any] = np.array(lowerCamelCase__ ) __lowerCamelCase : Any = en_sentvecs.shape[0] # mean centering __lowerCamelCase : Union[str, Any] = en_sentvecs - np.mean(lowerCamelCase__ , axis=0 ) __lowerCamelCase : Dict = in_sentvecs - np.mean(lowerCamelCase__ , axis=0 ) __lowerCamelCase : Optional[int] = cdist(lowerCamelCase__ , lowerCamelCase__ , 'cosine' ) __lowerCamelCase : Optional[Any] = np.array(range(lowerCamelCase__ ) ) __lowerCamelCase : Dict = sim.argsort(axis=1 )[:, :1_0] __lowerCamelCase : Optional[int] = np.any(preds == actual[:, None] , axis=1 ) return float(matches.mean() ) @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class A_ ( datasets.Metric ): def lowerCAmelCase ( self : Optional[Any]): if self.config_name not in [ "wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", "cvit-mkb-clsr", "iitp-mr", "iitp-pr", "actsa-sc", "md", "wiki-ner", ]: raise KeyError( 'You should supply a configuration name selected in ' '["wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", ' '"cvit-mkb-clsr", "iitp-mr", "iitp-pr", "actsa-sc", "md", ' '"wiki-ner"]') return datasets.MetricInfo( description=_DESCRIPTION ,citation=_CITATION ,inputs_description=_KWARGS_DESCRIPTION ,features=datasets.Features( { 'predictions': datasets.Value('int64') if self.config_name != 'cvit-mkb-clsr' else datasets.Sequence(datasets.Value('float32')), 'references': datasets.Value('int64') if self.config_name != 'cvit-mkb-clsr' else datasets.Sequence(datasets.Value('float32')), }) ,codebase_urls=[] ,reference_urls=[] ,format='numpy' if self.config_name != 'cvit-mkb-clsr' else None ,) def lowerCAmelCase ( self : Any ,SCREAMING_SNAKE_CASE__ : Tuple ,SCREAMING_SNAKE_CASE__ : Optional[Any]): if self.config_name == "cvit-mkb-clsr": return {"precision@10": precision_at_aa(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__)} elif self.config_name in ["wiki-ner"]: return acc_and_fa(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) elif self.config_name in [ "wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", "iitp-mr", "iitp-pr", "actsa-sc", "md", ]: return {"accuracy": simple_accuracy(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__)} else: raise KeyError( 'You should supply a configuration name selected in ' '["wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", ' '"cvit-mkb-clsr", "iitp-mr", "iitp-pr", "actsa-sc", "md", ' '"wiki-ner"]')
73
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available a ={ """configuration_mvp""": ["""MVP_PRETRAINED_CONFIG_ARCHIVE_MAP""", """MvpConfig""", """MvpOnnxConfig"""], """tokenization_mvp""": ["""MvpTokenizer"""], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a =["""MvpTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a =[ """MVP_PRETRAINED_MODEL_ARCHIVE_LIST""", """MvpForCausalLM""", """MvpForConditionalGeneration""", """MvpForQuestionAnswering""", """MvpForSequenceClassification""", """MvpModel""", """MvpPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_mvp import MVP_PRETRAINED_CONFIG_ARCHIVE_MAP, MvpConfig, MvpOnnxConfig from .tokenization_mvp import MvpTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mvp_fast import MvpTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mvp import ( MVP_PRETRAINED_MODEL_ARCHIVE_LIST, MvpForCausalLM, MvpForConditionalGeneration, MvpForQuestionAnswering, MvpForSequenceClassification, MvpModel, MvpPreTrainedModel, ) else: import sys a =_LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
73
from __future__ import annotations from scipy.special import comb # type: ignore class A_ : def __init__( self : List[str] ,SCREAMING_SNAKE_CASE__ : list[tuple[float, float]]): __lowerCamelCase : Union[str, Any] = list_of_points # Degree determines the flexibility of the curve. # Degree = 1 will produce a straight line. __lowerCamelCase : int = len(SCREAMING_SNAKE_CASE__) - 1 def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : float): assert 0 <= t <= 1, "Time t must be between 0 and 1." __lowerCamelCase : list[float] = [] for i in range(len(self.list_of_points)): # basis function for each i output_values.append( comb(self.degree ,SCREAMING_SNAKE_CASE__) * ((1 - t) ** (self.degree - i)) * (t**i)) # the basis must sum up to 1 for it to produce a valid Bezier curve. assert round(sum(SCREAMING_SNAKE_CASE__) ,5) == 1 return output_values def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : float): assert 0 <= t <= 1, "Time t must be between 0 and 1." __lowerCamelCase : Tuple = self.basis_function(SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = 0.0 __lowerCamelCase : Optional[Any] = 0.0 for i in range(len(self.list_of_points)): # For all points, sum up the product of i-th basis function and i-th point. x += basis_function[i] * self.list_of_points[i][0] y += basis_function[i] * self.list_of_points[i][1] return (x, y) def lowerCAmelCase ( self : int ,SCREAMING_SNAKE_CASE__ : float = 0.01): from matplotlib import pyplot as plt # type: ignore __lowerCamelCase : list[float] = [] # x coordinates of points to plot __lowerCamelCase : list[float] = [] # y coordinates of points to plot __lowerCamelCase : Any = 0.0 while t <= 1: __lowerCamelCase : List[Any] = self.bezier_curve_function(SCREAMING_SNAKE_CASE__) to_plot_x.append(value[0]) to_plot_y.append(value[1]) t += step_size __lowerCamelCase : Optional[Any] = [i[0] for i in self.list_of_points] __lowerCamelCase : List[str] = [i[1] for i in self.list_of_points] plt.plot( SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,color='blue' ,label='Curve of Degree ' + str(self.degree) ,) plt.scatter(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,color='red' ,label='Control Points') plt.legend() plt.show() if __name__ == "__main__": import doctest doctest.testmod() BezierCurve([(1, 2), (3, 5)]).plot_curve() # degree 1 BezierCurve([(0, 0), (5, 5), (5, 0)]).plot_curve() # degree 2 BezierCurve([(0, 0), (5, 5), (5, 0), (2.5, -2.5)]).plot_curve() # degree 3
73
1
# Copyright 2021 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from packaging import version from .. import __version__ from .constants import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD from .doc import ( add_code_sample_docstrings, add_end_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, copy_func, replace_return_docstrings, ) from .generic import ( ContextManagers, ExplicitEnum, ModelOutput, PaddingStrategy, TensorType, add_model_info_to_auto_map, cached_property, can_return_loss, expand_dims, find_labels, flatten_dict, infer_framework, is_jax_tensor, is_numpy_array, is_tensor, is_tf_symbolic_tensor, is_tf_tensor, is_torch_device, is_torch_dtype, is_torch_tensor, reshape, squeeze, strtobool, tensor_size, to_numpy, to_py_obj, transpose, working_or_temp_dir, ) from .hub import ( CLOUDFRONT_DISTRIB_PREFIX, DISABLE_TELEMETRY, HF_MODULES_CACHE, HUGGINGFACE_CO_PREFIX, HUGGINGFACE_CO_RESOLVE_ENDPOINT, PYTORCH_PRETRAINED_BERT_CACHE, PYTORCH_TRANSFORMERS_CACHE, S3_BUCKET_PREFIX, TRANSFORMERS_CACHE, TRANSFORMERS_DYNAMIC_MODULE_NAME, EntryNotFoundError, PushToHubMixin, RepositoryNotFoundError, RevisionNotFoundError, cached_file, default_cache_path, define_sagemaker_information, download_url, extract_commit_hash, get_cached_models, get_file_from_repo, get_full_repo_name, has_file, http_user_agent, is_offline_mode, is_remote_url, move_cache, send_example_telemetry, try_to_load_from_cache, ) from .import_utils import ( ENV_VARS_TRUE_AND_AUTO_VALUES, ENV_VARS_TRUE_VALUES, TORCH_FX_REQUIRED_VERSION, USE_JAX, USE_TF, USE_TORCH, DummyObject, OptionalDependencyNotAvailable, _LazyModule, ccl_version, direct_transformers_import, get_torch_version, is_accelerate_available, is_apex_available, is_bitsandbytes_available, is_bsa_available, is_coloredlogs_available, is_cython_available, is_datasets_available, is_decord_available, is_detectrona_available, is_faiss_available, is_flax_available, is_ftfy_available, is_in_notebook, is_ipex_available, is_jieba_available, is_jumanpp_available, is_kenlm_available, is_keras_nlp_available, is_librosa_available, is_natten_available, is_ninja_available, is_onnx_available, is_openai_available, is_optimum_available, is_pandas_available, is_peft_available, is_phonemizer_available, is_protobuf_available, is_psutil_available, is_pyanvml_available, is_pyctcdecode_available, is_pytesseract_available, is_pytest_available, is_pytorch_quantization_available, is_rjieba_available, is_sacremoses_available, is_safetensors_available, is_sagemaker_dp_enabled, is_sagemaker_mp_enabled, is_scipy_available, is_sentencepiece_available, is_seqio_available, is_sklearn_available, is_soundfile_availble, is_spacy_available, is_speech_available, is_sudachi_available, is_tensorflow_probability_available, is_tensorflow_text_available, is_tfaonnx_available, is_tf_available, is_timm_available, is_tokenizers_available, is_torch_available, is_torch_bfaa_available, is_torch_bfaa_cpu_available, is_torch_bfaa_gpu_available, is_torch_compile_available, is_torch_cuda_available, is_torch_fx_available, is_torch_fx_proxy, is_torch_mps_available, is_torch_neuroncore_available, is_torch_tensorrt_fx_available, is_torch_tfaa_available, is_torch_tpu_available, is_torchaudio_available, is_torchdistx_available, is_torchdynamo_available, is_torchvision_available, is_training_run_on_sagemaker, is_vision_available, requires_backends, torch_only_method, ) a ="""pytorch_model.bin""" a ="""pytorch_model.bin.index.json""" a ="""adapter_config.json""" a ="""adapter_model.bin""" a ="""adapter_model.safetensors""" a ="""tf_model.h5""" a ="""tf_model.h5.index.json""" a ="""model.ckpt""" a ="""flax_model.msgpack""" a ="""flax_model.msgpack.index.json""" a ="""model.safetensors""" a ="""model.safetensors.index.json""" a ="""config.json""" a ="""preprocessor_config.json""" a =FEATURE_EXTRACTOR_NAME a ="""generation_config.json""" a ="""modelcard.json""" a ="""▁""" a =SENTENCEPIECE_UNDERLINE # Kept for backward compatibility a =[ [[0, 1, 0, 1], [1, 0, 0, 1]] ] * 2 # Needs to have 0s and 1s only since XLM uses it for langs too. a =[[7, 6, 0, 0, 1], [1, 2, 3, 0, 0], [0, 0, 0, 4, 5]] a =[[1, 1, 1, 1, 1], [1, 1, 1, 0, 0], [0, 0, 0, 1, 1]] def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> str: if version.parse(lowerCamelCase__ ) < version.parse(lowerCamelCase__ ): if "dev" in min_version: __lowerCamelCase : List[Any] = ( 'This example requires a source install from HuggingFace Transformers (see ' '`https://huggingface.co/docs/transformers/installation#install-from-source`),' ) else: __lowerCamelCase : Union[str, Any] = F"This example requires a minimum version of {min_version}," error_message += F" but the version found is {__version__}.\n" raise ImportError( error_message + 'Check out https://github.com/huggingface/transformers/tree/main/examples#important-note for the examples corresponding to other ' 'versions of HuggingFace Transformers.' )
73
from __future__ import annotations import time a =list[tuple[int, int]] a =[ [0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles [0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0], [1, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0], ] a =[[-1, 0], [0, -1], [1, 0], [0, 1]] # up, left, down, right class A_ : def __init__( self : List[str] ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : Node | None): __lowerCamelCase : Tuple = pos_x __lowerCamelCase : List[str] = pos_y __lowerCamelCase : str = (pos_y, pos_x) __lowerCamelCase : str = goal_x __lowerCamelCase : int = goal_y __lowerCamelCase : List[Any] = parent class A_ : def __init__( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : tuple[int, int] ,SCREAMING_SNAKE_CASE__ : tuple[int, int]): __lowerCamelCase : Any = Node(start[1] ,start[0] ,goal[1] ,goal[0] ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = Node(goal[1] ,goal[0] ,goal[1] ,goal[0] ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Union[str, Any] = [self.start] __lowerCamelCase : List[str] = False def lowerCAmelCase ( self : List[Any]): while self.node_queue: __lowerCamelCase : Any = self.node_queue.pop(0) if current_node.pos == self.target.pos: __lowerCamelCase : Dict = True return self.retrace_path(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Tuple = self.get_successors(SCREAMING_SNAKE_CASE__) for node in successors: self.node_queue.append(SCREAMING_SNAKE_CASE__) if not self.reached: return [self.start.pos] return None def lowerCAmelCase ( self : str ,SCREAMING_SNAKE_CASE__ : Node): __lowerCamelCase : Union[str, Any] = [] for action in delta: __lowerCamelCase : Optional[Any] = parent.pos_x + action[1] __lowerCamelCase : Optional[int] = parent.pos_y + action[0] if not (0 <= pos_x <= len(grid[0]) - 1 and 0 <= pos_y <= len(SCREAMING_SNAKE_CASE__) - 1): continue if grid[pos_y][pos_x] != 0: continue successors.append( Node(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,self.target.pos_y ,self.target.pos_x ,SCREAMING_SNAKE_CASE__)) return successors def lowerCAmelCase ( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : Node | None): __lowerCamelCase : List[Any] = node __lowerCamelCase : int = [] while current_node is not None: path.append((current_node.pos_y, current_node.pos_x)) __lowerCamelCase : int = current_node.parent path.reverse() return path class A_ : def __init__( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : int): __lowerCamelCase : int = BreadthFirstSearch(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = BreadthFirstSearch(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = False def lowerCAmelCase ( self : str): while self.fwd_bfs.node_queue or self.bwd_bfs.node_queue: __lowerCamelCase : Any = self.fwd_bfs.node_queue.pop(0) __lowerCamelCase : Any = self.bwd_bfs.node_queue.pop(0) if current_bwd_node.pos == current_fwd_node.pos: __lowerCamelCase : List[str] = True return self.retrace_bidirectional_path( SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = current_bwd_node __lowerCamelCase : int = current_fwd_node __lowerCamelCase : str = { self.fwd_bfs: self.fwd_bfs.get_successors(SCREAMING_SNAKE_CASE__), self.bwd_bfs: self.bwd_bfs.get_successors(SCREAMING_SNAKE_CASE__), } for bfs in [self.fwd_bfs, self.bwd_bfs]: for node in successors[bfs]: bfs.node_queue.append(SCREAMING_SNAKE_CASE__) if not self.reached: return [self.fwd_bfs.start.pos] return None def lowerCAmelCase ( self : Dict ,SCREAMING_SNAKE_CASE__ : Node ,SCREAMING_SNAKE_CASE__ : Node): __lowerCamelCase : List[Any] = self.fwd_bfs.retrace_path(SCREAMING_SNAKE_CASE__) __lowerCamelCase : str = self.bwd_bfs.retrace_path(SCREAMING_SNAKE_CASE__) bwd_path.pop() bwd_path.reverse() __lowerCamelCase : List[Any] = fwd_path + bwd_path return path if __name__ == "__main__": # all coordinates are given in format [y,x] import doctest doctest.testmod() a =(0, 0) a =(len(grid) - 1, len(grid[0]) - 1) for elem in grid: print(elem) a =time.time() a =BreadthFirstSearch(init, goal) a =bfs.search() a =time.time() - start_bfs_time print("""Unidirectional BFS computation time : """, bfs_time) a =time.time() a =BidirectionalBreadthFirstSearch(init, goal) a =bd_bfs.search() a =time.time() - start_bd_bfs_time print("""Bidirectional BFS computation time : """, bd_bfs_time)
73
1
a ={ """Pillow""": """Pillow<10.0.0""", """accelerate""": """accelerate>=0.20.3""", """av""": """av==9.2.0""", """beautifulsoup4""": """beautifulsoup4""", """black""": """black~=23.1""", """codecarbon""": """codecarbon==1.2.0""", """cookiecutter""": """cookiecutter==1.7.3""", """dataclasses""": """dataclasses""", """datasets""": """datasets!=2.5.0""", """decord""": """decord==0.6.0""", """deepspeed""": """deepspeed>=0.9.3""", """diffusers""": """diffusers""", """dill""": """dill<0.3.5""", """evaluate""": """evaluate>=0.2.0""", """fairscale""": """fairscale>0.3""", """faiss-cpu""": """faiss-cpu""", """fastapi""": """fastapi""", """filelock""": """filelock""", """flax""": """flax>=0.4.1,<=0.7.0""", """ftfy""": """ftfy""", """fugashi""": """fugashi>=1.0""", """GitPython""": """GitPython<3.1.19""", """hf-doc-builder""": """hf-doc-builder>=0.3.0""", """huggingface-hub""": """huggingface-hub>=0.14.1,<1.0""", """importlib_metadata""": """importlib_metadata""", """ipadic""": """ipadic>=1.0.0,<2.0""", """isort""": """isort>=5.5.4""", """jax""": """jax>=0.2.8,!=0.3.2,<=0.4.13""", """jaxlib""": """jaxlib>=0.1.65,<=0.4.13""", """jieba""": """jieba""", """kenlm""": """kenlm""", """keras-nlp""": """keras-nlp>=0.3.1""", """librosa""": """librosa""", """nltk""": """nltk""", """natten""": """natten>=0.14.6""", """numpy""": """numpy>=1.17""", """onnxconverter-common""": """onnxconverter-common""", """onnxruntime-tools""": """onnxruntime-tools>=1.4.2""", """onnxruntime""": """onnxruntime>=1.4.0""", """opencv-python""": """opencv-python""", """optuna""": """optuna""", """optax""": """optax>=0.0.8,<=0.1.4""", """packaging""": """packaging>=20.0""", """parameterized""": """parameterized""", """phonemizer""": """phonemizer""", """protobuf""": """protobuf""", """psutil""": """psutil""", """pyyaml""": """pyyaml>=5.1""", """pydantic""": """pydantic<2""", """pytest""": """pytest>=7.2.0""", """pytest-timeout""": """pytest-timeout""", """pytest-xdist""": """pytest-xdist""", """python""": """python>=3.8.0""", """ray[tune]""": """ray[tune]""", """regex""": """regex!=2019.12.17""", """requests""": """requests""", """rhoknp""": """rhoknp>=1.1.0,<1.3.1""", """rjieba""": """rjieba""", """rouge-score""": """rouge-score!=0.0.7,!=0.0.8,!=0.1,!=0.1.1""", """ruff""": """ruff>=0.0.241,<=0.0.259""", """sacrebleu""": """sacrebleu>=1.4.12,<2.0.0""", """sacremoses""": """sacremoses""", """safetensors""": """safetensors>=0.3.1""", """sagemaker""": """sagemaker>=2.31.0""", """scikit-learn""": """scikit-learn""", """sentencepiece""": """sentencepiece>=0.1.91,!=0.1.92""", """sigopt""": """sigopt""", """starlette""": """starlette""", """sudachipy""": """sudachipy>=0.6.6""", """sudachidict_core""": """sudachidict_core>=20220729""", """tensorflow-cpu""": """tensorflow-cpu>=2.6,<2.14""", """tensorflow""": """tensorflow>=2.6,<2.14""", """tensorflow-text""": """tensorflow-text<2.14""", """tf2onnx""": """tf2onnx""", """timeout-decorator""": """timeout-decorator""", """timm""": """timm""", """tokenizers""": """tokenizers>=0.11.1,!=0.11.3,<0.14""", """torch""": """torch>=1.9,!=1.12.0""", """torchaudio""": """torchaudio""", """torchvision""": """torchvision""", """pyctcdecode""": """pyctcdecode>=0.4.0""", """tqdm""": """tqdm>=4.27""", """unidic""": """unidic>=1.0.2""", """unidic_lite""": """unidic_lite>=1.0.7""", """urllib3""": """urllib3<2.0.0""", """uvicorn""": """uvicorn""", }
73
import qiskit def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> qiskit.result.counts.Counts: __lowerCamelCase : Optional[int] = qiskit.Aer.get_backend('aer_simulator' ) # Create a Quantum Circuit acting on the q register __lowerCamelCase : List[str] = qiskit.QuantumCircuit(lowerCamelCase__ , lowerCamelCase__ ) # Map the quantum measurement to the classical bits circuit.measure([0] , [0] ) # Execute the circuit on the simulator __lowerCamelCase : List[Any] = qiskit.execute(lowerCamelCase__ , lowerCamelCase__ , shots=1_0_0_0 ) # Return the histogram data of the results of the experiment. return job.result().get_counts(lowerCamelCase__ ) if __name__ == "__main__": print(F"""Total count for various states are: {single_qubit_measure(1, 1)}""")
73
1
import os import socket from contextlib import contextmanager import torch from ..commands.config.default import write_basic_config # noqa: F401 from ..state import PartialState from .dataclasses import DistributedType from .imports import is_deepspeed_available, is_tpu_available from .transformer_engine import convert_model from .versions import is_torch_version if is_deepspeed_available(): from deepspeed import DeepSpeedEngine if is_tpu_available(check_device=False): import torch_xla.core.xla_model as xm def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> str: if is_torch_version('<' , '2.0.0' ) or not hasattr(lowerCamelCase__ , '_dynamo' ): return False return isinstance(lowerCamelCase__ , torch._dynamo.eval_frame.OptimizedModule ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ = True ) -> str: __lowerCamelCase : Optional[Any] = (torch.nn.parallel.DistributedDataParallel, torch.nn.DataParallel) __lowerCamelCase : Dict = is_compiled_module(lowerCamelCase__ ) if is_compiled: __lowerCamelCase : str = model __lowerCamelCase : Tuple = model._orig_mod if is_deepspeed_available(): options += (DeepSpeedEngine,) while isinstance(lowerCamelCase__ , lowerCamelCase__ ): __lowerCamelCase : Optional[int] = model.module if not keep_fpaa_wrapper: __lowerCamelCase : Optional[Any] = getattr(lowerCamelCase__ , 'forward' ) __lowerCamelCase : Tuple = model.__dict__.pop('_original_forward' , lowerCamelCase__ ) if original_forward is not None: while hasattr(lowerCamelCase__ , '__wrapped__' ): __lowerCamelCase : Union[str, Any] = forward.__wrapped__ if forward == original_forward: break __lowerCamelCase : Tuple = forward if getattr(lowerCamelCase__ , '_converted_to_transformer_engine' , lowerCamelCase__ ): convert_model(lowerCamelCase__ , to_transformer_engine=lowerCamelCase__ ) if is_compiled: __lowerCamelCase : int = model __lowerCamelCase : Optional[Any] = compiled_model return model def SCREAMING_SNAKE_CASE__ ( ) -> str: PartialState().wait_for_everyone() def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> str: if PartialState().distributed_type == DistributedType.TPU: xm.save(lowerCamelCase__ , lowerCamelCase__ ) elif PartialState().local_process_index == 0: torch.save(lowerCamelCase__ , lowerCamelCase__ ) @contextmanager def SCREAMING_SNAKE_CASE__ ( **lowerCamelCase__ ) -> Union[str, Any]: for key, value in kwargs.items(): __lowerCamelCase : Union[str, Any] = str(lowerCamelCase__ ) yield for key in kwargs: if key.upper() in os.environ: del os.environ[key.upper()] def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Any: if not hasattr(lowerCamelCase__ , '__qualname__' ) and not hasattr(lowerCamelCase__ , '__name__' ): __lowerCamelCase : Tuple = getattr(lowerCamelCase__ , '__class__' , lowerCamelCase__ ) if hasattr(lowerCamelCase__ , '__qualname__' ): return obj.__qualname__ if hasattr(lowerCamelCase__ , '__name__' ): return obj.__name__ return str(lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> Optional[int]: for key, value in source.items(): if isinstance(lowerCamelCase__ , lowerCamelCase__ ): __lowerCamelCase : int = destination.setdefault(lowerCamelCase__ , {} ) merge_dicts(lowerCamelCase__ , lowerCamelCase__ ) else: __lowerCamelCase : Dict = value return destination def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ = None ) -> bool: if port is None: __lowerCamelCase : str = 2_9_5_0_0 with socket.socket(socket.AF_INET , socket.SOCK_STREAM ) as s: return s.connect_ex(('localhost', port) ) == 0
73
import os import sys a =os.path.join(os.path.dirname(__file__), """src""") sys.path.append(SRC_DIR) from transformers import ( AutoConfig, AutoModel, AutoModelForCausalLM, AutoModelForMaskedLM, AutoModelForQuestionAnswering, AutoModelForSequenceClassification, AutoTokenizer, add_start_docstrings, ) a =[ """torch""", """numpy""", """tokenizers""", """filelock""", """requests""", """tqdm""", """regex""", """sentencepiece""", """sacremoses""", """importlib_metadata""", """huggingface_hub""", ] @add_start_docstrings(AutoConfig.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> int: return AutoConfig.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ ) @add_start_docstrings(AutoTokenizer.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> Optional[Any]: return AutoTokenizer.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ ) @add_start_docstrings(AutoModel.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> List[str]: return AutoModel.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ ) @add_start_docstrings(AutoModelForCausalLM.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> Any: return AutoModelForCausalLM.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ ) @add_start_docstrings(AutoModelForMaskedLM.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> List[str]: return AutoModelForMaskedLM.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ ) @add_start_docstrings(AutoModelForSequenceClassification.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> List[str]: return AutoModelForSequenceClassification.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ ) @add_start_docstrings(AutoModelForQuestionAnswering.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> Tuple: return AutoModelForQuestionAnswering.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ )
73
1
import os import unittest from transformers import FunnelTokenizer, FunnelTokenizerFast from transformers.models.funnel.tokenization_funnel import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class A_ ( SCREAMING_SNAKE_CASE , unittest.TestCase ): _UpperCAmelCase : Dict = FunnelTokenizer _UpperCAmelCase : List[str] = FunnelTokenizerFast _UpperCAmelCase : str = True _UpperCAmelCase : Optional[int] = True def lowerCAmelCase ( self : Any): super().setUp() __lowerCamelCase : Union[str, Any] = [ '<unk>', '<cls>', '<sep>', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing', ',', 'low', 'lowest', ] __lowerCamelCase : Optional[Any] = os.path.join(self.tmpdirname ,VOCAB_FILES_NAMES['vocab_file']) with open(self.vocab_file ,'w' ,encoding='utf-8') as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in vocab_tokens])) def lowerCAmelCase ( self : Union[str, Any] ,**SCREAMING_SNAKE_CASE__ : List[Any]): return FunnelTokenizer.from_pretrained(self.tmpdirname ,**SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : List[Any] ,**SCREAMING_SNAKE_CASE__ : List[str]): return FunnelTokenizerFast.from_pretrained(self.tmpdirname ,**SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : str): __lowerCamelCase : Dict = 'UNwant\u00E9d,running' __lowerCamelCase : Tuple = 'unwanted, running' return input_text, output_text def lowerCAmelCase ( self : List[Any]): __lowerCamelCase : Tuple = self.tokenizer_class(self.vocab_file) __lowerCamelCase : Any = tokenizer.tokenize('UNwant\u00E9d,running') self.assertListEqual(SCREAMING_SNAKE_CASE__ ,['un', '##want', '##ed', ',', 'runn', '##ing']) self.assertListEqual(tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__) ,[7, 4, 5, 1_0, 8, 9]) def lowerCAmelCase ( self : Tuple): __lowerCamelCase : int = self.get_tokenizers(do_lower_case=SCREAMING_SNAKE_CASE__) for tokenizer in tokenizers: __lowerCamelCase : Dict = tokenizer('UNwant\u00E9d,running') __lowerCamelCase : int = len(inputs['input_ids']) - 1 self.assertListEqual(inputs['token_type_ids'] ,[2] + [0] * sentence_len) __lowerCamelCase : Dict = tokenizer('UNwant\u00E9d,running' ,'UNwant\u00E9d,running') self.assertListEqual(inputs['token_type_ids'] ,[2] + [0] * sentence_len + [1] * sentence_len)
73
from typing import Optional from urllib.parse import quote import huggingface_hub as hfh from packaging import version def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ = None ) -> str: if version.parse(hfh.__version__ ).release < version.parse('0.11.0' ).release: # old versions of hfh don't url-encode the file path __lowerCamelCase : int = quote(lowerCamelCase__ ) return hfh.hf_hub_url(lowerCamelCase__ , lowerCamelCase__ , repo_type='dataset' , revision=lowerCamelCase__ )
73
1
import json import os import subprocess import unittest from ast import literal_eval import pytest from parameterized import parameterized, parameterized_class from . import is_sagemaker_available if is_sagemaker_available(): from sagemaker import Session, TrainingJobAnalytics from sagemaker.huggingface import HuggingFace @pytest.mark.skipif( literal_eval(os.getenv('''TEST_SAGEMAKER''' , '''False''' ) ) is not True , reason='''Skipping test because should only be run when releasing minor transformers version''' , ) @pytest.mark.usefixtures('''sm_env''' ) @parameterized_class( [ { '''framework''': '''pytorch''', '''script''': '''run_glue_model_parallelism.py''', '''model_name_or_path''': '''roberta-large''', '''instance_type''': '''ml.p3dn.24xlarge''', '''results''': {'''train_runtime''': 1_600, '''eval_accuracy''': 0.3, '''eval_loss''': 1.2}, }, { '''framework''': '''pytorch''', '''script''': '''run_glue.py''', '''model_name_or_path''': '''roberta-large''', '''instance_type''': '''ml.p3dn.24xlarge''', '''results''': {'''train_runtime''': 1_600, '''eval_accuracy''': 0.3, '''eval_loss''': 1.2}, }, ] ) class A_ ( unittest.TestCase ): def lowerCAmelCase ( self : Union[str, Any]): if self.framework == "pytorch": subprocess.run( F"cp ./examples/pytorch/text-classification/run_glue.py {self.env.test_path}/run_glue.py".split() ,encoding='utf-8' ,check=SCREAMING_SNAKE_CASE__ ,) assert hasattr(self ,'env') def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : int): # configuration for running training on smdistributed Model Parallel __lowerCamelCase : Any = { 'enabled': True, 'processes_per_host': 8, } __lowerCamelCase : List[Any] = { 'enabled': True, 'parameters': { 'microbatches': 4, 'placement_strategy': 'spread', 'pipeline': 'interleaved', 'optimize': 'speed', 'partitions': 4, 'ddp': True, }, } __lowerCamelCase : str = {'smdistributed': {'modelparallel': smp_options}, 'mpi': mpi_options} __lowerCamelCase : List[str] = 'trainer' if self.script == 'run_glue.py' else 'smtrainer' # creates estimator return HuggingFace( entry_point=self.script ,source_dir=self.env.test_path ,role=self.env.role ,image_uri=self.env.image_uri ,base_job_name=F"{self.env.base_job_name}-{instance_count}-smp-{name_extension}" ,instance_count=SCREAMING_SNAKE_CASE__ ,instance_type=self.instance_type ,debugger_hook_config=SCREAMING_SNAKE_CASE__ ,hyperparameters={ **self.env.hyperparameters, 'model_name_or_path': self.model_name_or_path, 'max_steps': 5_0_0, } ,metric_definitions=self.env.metric_definitions ,distribution=SCREAMING_SNAKE_CASE__ ,py_version='py36' ,) def lowerCAmelCase ( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : Any): TrainingJobAnalytics(SCREAMING_SNAKE_CASE__).export_csv(F"{self.env.test_path}/{job_name}_metrics.csv") @parameterized.expand([(1,)]) def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : Optional[Any]): # create estimator __lowerCamelCase : str = self.create_estimator(SCREAMING_SNAKE_CASE__) # run training estimator.fit() # result dataframe __lowerCamelCase : List[str] = TrainingJobAnalytics(estimator.latest_training_job.name).dataframe() # extract kpis __lowerCamelCase : Optional[int] = list(result_metrics_df[result_metrics_df.metric_name == 'eval_accuracy']['value']) __lowerCamelCase : Any = list(result_metrics_df[result_metrics_df.metric_name == 'eval_loss']['value']) # get train time from SageMaker job, this includes starting, preprocessing, stopping __lowerCamelCase : str = ( Session().describe_training_job(estimator.latest_training_job.name).get('TrainingTimeInSeconds' ,9_9_9_9_9_9) ) # assert kpis assert train_runtime <= self.results["train_runtime"] assert all(t >= self.results['eval_accuracy'] for t in eval_accuracy) assert all(t <= self.results['eval_loss'] for t in eval_loss) # dump tests result into json file to share in PR with open(F"{estimator.latest_training_job.name}.json" ,'w') as outfile: json.dump({'train_time': train_runtime, 'eval_accuracy': eval_accuracy, 'eval_loss': eval_loss} ,SCREAMING_SNAKE_CASE__)
73
def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , ) -> float: __lowerCamelCase : Dict = [redshift, radiation_density, matter_density, dark_energy] if any(p < 0 for p in parameters ): raise ValueError('All input parameters must be positive' ) if any(p > 1 for p in parameters[1:4] ): raise ValueError('Relative densities cannot be greater than one' ) else: __lowerCamelCase : Dict = 1 - (matter_density + radiation_density + dark_energy) __lowerCamelCase : Union[str, Any] = ( radiation_density * (redshift + 1) ** 4 + matter_density * (redshift + 1) ** 3 + curvature * (redshift + 1) ** 2 + dark_energy ) __lowerCamelCase : List[Any] = hubble_constant * e_a ** (1 / 2) return hubble if __name__ == "__main__": import doctest # run doctest doctest.testmod() # demo LCDM approximation a =0.3 print( hubble_parameter( hubble_constant=68.3, radiation_density=1E-4, matter_density=matter_density, dark_energy=1 - matter_density, redshift=0, ) )
73
1
from typing import Any import numpy as np def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> bool: return np.array_equal(lowerCamelCase__ , matrix.conjugate().T ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> Any: __lowerCamelCase : Any = v.conjugate().T __lowerCamelCase : Optional[int] = v_star.dot(lowerCamelCase__ ) assert isinstance(lowerCamelCase__ , np.ndarray ) return (v_star_dot.dot(lowerCamelCase__ )) / (v_star.dot(lowerCamelCase__ )) def SCREAMING_SNAKE_CASE__ ( ) -> None: __lowerCamelCase : str = np.array([[2, 2 + 1j, 4], [2 - 1j, 3, 1j], [4, -1j, 1]] ) __lowerCamelCase : Optional[int] = np.array([[1], [2], [3]] ) assert is_hermitian(lowerCamelCase__ ), F"{a} is not hermitian." print(rayleigh_quotient(lowerCamelCase__ , lowerCamelCase__ ) ) __lowerCamelCase : Any = np.array([[1, 2, 4], [2, 3, -1], [4, -1, 1]] ) assert is_hermitian(lowerCamelCase__ ), F"{a} is not hermitian." assert rayleigh_quotient(lowerCamelCase__ , lowerCamelCase__ ) == float(3 ) if __name__ == "__main__": import doctest doctest.testmod() tests()
73
from typing import List, Optional, Union from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : Optional[Any] = ['''image_processor''', '''tokenizer'''] _UpperCAmelCase : Union[str, Any] = '''Pix2StructImageProcessor''' _UpperCAmelCase : Any = ('''T5Tokenizer''', '''T5TokenizerFast''') def __init__( self : List[str] ,SCREAMING_SNAKE_CASE__ : str ,SCREAMING_SNAKE_CASE__ : int): __lowerCamelCase : List[Any] = False super().__init__(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) def __call__( self : str ,SCREAMING_SNAKE_CASE__ : Any=None ,SCREAMING_SNAKE_CASE__ : Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None ,SCREAMING_SNAKE_CASE__ : bool = True ,SCREAMING_SNAKE_CASE__ : Union[bool, str, PaddingStrategy] = False ,SCREAMING_SNAKE_CASE__ : Union[bool, str, TruncationStrategy] = None ,SCREAMING_SNAKE_CASE__ : Optional[int] = None ,SCREAMING_SNAKE_CASE__ : Optional[int] = 2_0_4_8 ,SCREAMING_SNAKE_CASE__ : int = 0 ,SCREAMING_SNAKE_CASE__ : Optional[int] = None ,SCREAMING_SNAKE_CASE__ : Optional[bool] = None ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = True ,SCREAMING_SNAKE_CASE__ : Optional[Union[str, TensorType]] = None ,**SCREAMING_SNAKE_CASE__ : Dict ,): if images is None and text is None: raise ValueError('You have to specify either images or text.') # Get only text if images is None and not self.image_processor.is_vqa: __lowerCamelCase : Tuple = self.tokenizer __lowerCamelCase : Dict = self.tokenizer( text=SCREAMING_SNAKE_CASE__ ,add_special_tokens=SCREAMING_SNAKE_CASE__ ,padding=SCREAMING_SNAKE_CASE__ ,truncation=SCREAMING_SNAKE_CASE__ ,max_length=SCREAMING_SNAKE_CASE__ ,stride=SCREAMING_SNAKE_CASE__ ,pad_to_multiple_of=SCREAMING_SNAKE_CASE__ ,return_attention_mask=SCREAMING_SNAKE_CASE__ ,return_overflowing_tokens=SCREAMING_SNAKE_CASE__ ,return_special_tokens_mask=SCREAMING_SNAKE_CASE__ ,return_offsets_mapping=SCREAMING_SNAKE_CASE__ ,return_token_type_ids=SCREAMING_SNAKE_CASE__ ,return_length=SCREAMING_SNAKE_CASE__ ,verbose=SCREAMING_SNAKE_CASE__ ,return_tensors=SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__ ,) return text_encoding if not self.image_processor.is_vqa: # add pixel_values __lowerCamelCase : List[Any] = self.image_processor( SCREAMING_SNAKE_CASE__ ,return_tensors=SCREAMING_SNAKE_CASE__ ,max_patches=SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) else: # add pixel_values and bbox __lowerCamelCase : List[Any] = self.image_processor( SCREAMING_SNAKE_CASE__ ,return_tensors=SCREAMING_SNAKE_CASE__ ,max_patches=SCREAMING_SNAKE_CASE__ ,header_text=SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) if text is not None and not self.image_processor.is_vqa: __lowerCamelCase : List[Any] = self.tokenizer( text=SCREAMING_SNAKE_CASE__ ,add_special_tokens=SCREAMING_SNAKE_CASE__ ,padding=SCREAMING_SNAKE_CASE__ ,truncation=SCREAMING_SNAKE_CASE__ ,max_length=SCREAMING_SNAKE_CASE__ ,stride=SCREAMING_SNAKE_CASE__ ,pad_to_multiple_of=SCREAMING_SNAKE_CASE__ ,return_attention_mask=SCREAMING_SNAKE_CASE__ ,return_overflowing_tokens=SCREAMING_SNAKE_CASE__ ,return_special_tokens_mask=SCREAMING_SNAKE_CASE__ ,return_offsets_mapping=SCREAMING_SNAKE_CASE__ ,return_token_type_ids=SCREAMING_SNAKE_CASE__ ,return_length=SCREAMING_SNAKE_CASE__ ,verbose=SCREAMING_SNAKE_CASE__ ,return_tensors=SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__ ,) if "attention_mask" in text_encoding: __lowerCamelCase : List[Any] = text_encoding.pop('attention_mask') if "input_ids" in text_encoding: __lowerCamelCase : Dict = text_encoding.pop('input_ids') else: __lowerCamelCase : Optional[int] = None if text_encoding is not None: encoding_image_processor.update(SCREAMING_SNAKE_CASE__) return encoding_image_processor def lowerCAmelCase ( self : Dict ,*SCREAMING_SNAKE_CASE__ : str ,**SCREAMING_SNAKE_CASE__ : int): return self.tokenizer.batch_decode(*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : List[str] ,*SCREAMING_SNAKE_CASE__ : int ,**SCREAMING_SNAKE_CASE__ : Dict): return self.tokenizer.decode(*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) @property def lowerCAmelCase ( self : int): __lowerCamelCase : Dict = self.tokenizer.model_input_names __lowerCamelCase : int = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
73
1
import argparse from collections import OrderedDict from pathlib import Path import torch from transformers import ( VisualBertConfig, VisualBertForMultipleChoice, VisualBertForPreTraining, VisualBertForQuestionAnswering, VisualBertForVisualReasoning, ) from transformers.utils import logging logging.set_verbosity_info() a =logging.get_logger(__name__) a =[ ("""bert.bert""", """visual_bert"""), ("""bert.cls""", """cls"""), ("""bert.classifier""", """cls"""), ("""token_type_embeddings_visual""", """visual_token_type_embeddings"""), ("""position_embeddings_visual""", """visual_position_embeddings"""), ("""projection""", """visual_projection"""), ] a =[ """nlvr2_coco_pre_trained.th""", """nlvr2_fine_tuned.th""", """nlvr2_pre_trained.th""", """vcr_coco_pre_train.th""", """vcr_fine_tune.th""", """vcr_pre_train.th""", """vqa_coco_pre_trained.th""", """vqa_fine_tuned.th""", """vqa_pre_trained.th""", ] def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> List[str]: __lowerCamelCase : int = torch.load(lowerCamelCase__ , map_location='cpu' ) return sd def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__=rename_keys_prefix ) -> List[Any]: __lowerCamelCase : Tuple = OrderedDict() __lowerCamelCase : int = torch.arange(config.max_position_embeddings ).expand((1, -1) ) # detector_d = OrderedDict() for key in d: if "detector" in key: # detector_d[key.replace('detector.','')] = d[key] continue __lowerCamelCase : List[Any] = key for name_pair in rename_keys_prefix: __lowerCamelCase : Optional[Any] = new_key.replace(name_pair[0] , name_pair[1] ) __lowerCamelCase : Dict = d[key] if key == "bert.cls.predictions.decoder.weight": # Old bert code didn't have `decoder.bias`, but was added separately __lowerCamelCase : str = new_d['cls.predictions.bias'] return new_d @torch.no_grad() def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> Tuple: assert ( checkpoint_path.split('/' )[-1] in ACCEPTABLE_CHECKPOINTS ), F"The checkpoint provided must be in {ACCEPTABLE_CHECKPOINTS}." # Get Config if "pre" in checkpoint_path: __lowerCamelCase : Optional[Any] = 'pretraining' if "vcr" in checkpoint_path: __lowerCamelCase : Any = {'visual_embedding_dim': 5_1_2} elif "vqa_advanced" in checkpoint_path: __lowerCamelCase : List[str] = {'visual_embedding_dim': 2_0_4_8} elif "vqa" in checkpoint_path: __lowerCamelCase : Tuple = {'visual_embedding_dim': 2_0_4_8} elif "nlvr" in checkpoint_path: __lowerCamelCase : List[Any] = {'visual_embedding_dim': 1_0_2_4} else: raise NotImplementedError(F"No implementation found for `{checkpoint_path}`." ) else: if "vcr" in checkpoint_path: __lowerCamelCase : Tuple = {'visual_embedding_dim': 5_1_2} __lowerCamelCase : Any = 'multichoice' elif "vqa_advanced" in checkpoint_path: __lowerCamelCase : Tuple = {'visual_embedding_dim': 2_0_4_8} __lowerCamelCase : List[Any] = 'vqa_advanced' elif "vqa" in checkpoint_path: __lowerCamelCase : List[Any] = {'visual_embedding_dim': 2_0_4_8, 'num_labels': 3_1_2_9} __lowerCamelCase : Optional[int] = 'vqa' elif "nlvr" in checkpoint_path: __lowerCamelCase : Optional[Any] = { 'visual_embedding_dim': 1_0_2_4, 'num_labels': 2, } __lowerCamelCase : Any = 'nlvr' __lowerCamelCase : Any = VisualBertConfig(**lowerCamelCase__ ) # Load State Dict __lowerCamelCase : Dict = load_state_dict(lowerCamelCase__ ) __lowerCamelCase : Optional[Any] = get_new_dict(lowerCamelCase__ , lowerCamelCase__ ) if model_type == "pretraining": __lowerCamelCase : Union[str, Any] = VisualBertForPreTraining(lowerCamelCase__ ) elif model_type == "vqa": __lowerCamelCase : str = VisualBertForQuestionAnswering(lowerCamelCase__ ) elif model_type == "nlvr": __lowerCamelCase : Dict = VisualBertForVisualReasoning(lowerCamelCase__ ) elif model_type == "multichoice": __lowerCamelCase : Union[str, Any] = VisualBertForMultipleChoice(lowerCamelCase__ ) model.load_state_dict(lowerCamelCase__ ) # Save Checkpoints Path(lowerCamelCase__ ).mkdir(exist_ok=lowerCamelCase__ ) model.save_pretrained(lowerCamelCase__ ) if __name__ == "__main__": a =argparse.ArgumentParser() # Required parameters parser.add_argument("""orig_checkpoint_path""", type=str, help="""A path to .th on local filesystem.""") parser.add_argument("""pytorch_dump_folder_path""", type=str, help="""Path to the output PyTorch model.""") a =parser.parse_args() convert_visual_bert_checkpoint(args.orig_checkpoint_path, args.pytorch_dump_folder_path)
73
from bisect import bisect from itertools import accumulate def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> Union[str, Any]: __lowerCamelCase : Optional[Any] = sorted(zip(lowerCamelCase__ , lowerCamelCase__ ) , key=lambda lowerCamelCase__ : x[0] / x[1] , reverse=lowerCamelCase__ ) __lowerCamelCase , __lowerCamelCase : Any = [i[0] for i in r], [i[1] for i in r] __lowerCamelCase : List[str] = list(accumulate(lowerCamelCase__ ) ) __lowerCamelCase : Union[str, Any] = bisect(lowerCamelCase__ , lowerCamelCase__ ) return ( 0 if k == 0 else sum(vl[:k] ) + (w - acc[k - 1]) * (vl[k]) / (wt[k]) if k != n else sum(vl[:k] ) ) if __name__ == "__main__": import doctest doctest.testmod()
73
1
import tempfile import torch from diffusers import ( DEISMultistepScheduler, DPMSolverMultistepScheduler, DPMSolverSinglestepScheduler, UniPCMultistepScheduler, ) from .test_schedulers import SchedulerCommonTest class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : Any = (UniPCMultistepScheduler,) _UpperCAmelCase : List[Any] = (('''num_inference_steps''', 25),) def lowerCAmelCase ( self : Optional[Any] ,**SCREAMING_SNAKE_CASE__ : int): __lowerCamelCase : str = { 'num_train_timesteps': 1_0_0_0, 'beta_start': 0.0001, 'beta_end': 0.02, 'beta_schedule': 'linear', 'solver_order': 2, 'solver_type': 'bh2', } config.update(**SCREAMING_SNAKE_CASE__) return config def lowerCAmelCase ( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : Union[str, Any]=0 ,**SCREAMING_SNAKE_CASE__ : List[Any]): __lowerCamelCase : Union[str, Any] = dict(self.forward_default_kwargs) __lowerCamelCase : List[Any] = kwargs.pop('num_inference_steps' ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Any = self.dummy_sample __lowerCamelCase : List[Any] = 0.1 * sample __lowerCamelCase : Optional[Any] = [residual + 0.2, residual + 0.15, residual + 0.10] for scheduler_class in self.scheduler_classes: __lowerCamelCase : Any = self.get_scheduler_config(**SCREAMING_SNAKE_CASE__) __lowerCamelCase : Tuple = scheduler_class(**SCREAMING_SNAKE_CASE__) scheduler.set_timesteps(SCREAMING_SNAKE_CASE__) # copy over dummy past residuals __lowerCamelCase : Optional[Any] = dummy_past_residuals[: scheduler.config.solver_order] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[int] = scheduler_class.from_pretrained(SCREAMING_SNAKE_CASE__) new_scheduler.set_timesteps(SCREAMING_SNAKE_CASE__) # copy over dummy past residuals __lowerCamelCase : Union[str, Any] = dummy_past_residuals[: new_scheduler.config.solver_order] __lowerCamelCase , __lowerCamelCase : Union[str, Any] = sample, sample for t in range(SCREAMING_SNAKE_CASE__ ,time_step + scheduler.config.solver_order + 1): __lowerCamelCase : Any = scheduler.step(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__).prev_sample __lowerCamelCase : Tuple = new_scheduler.step(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__).prev_sample assert torch.sum(torch.abs(output - new_output)) < 1E-5, "Scheduler outputs are not identical" def lowerCAmelCase ( self : Tuple ,SCREAMING_SNAKE_CASE__ : Optional[Any]=0 ,**SCREAMING_SNAKE_CASE__ : Dict): __lowerCamelCase : List[Any] = dict(self.forward_default_kwargs) __lowerCamelCase : Any = kwargs.pop('num_inference_steps' ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[int] = self.dummy_sample __lowerCamelCase : Dict = 0.1 * sample __lowerCamelCase : Union[str, Any] = [residual + 0.2, residual + 0.15, residual + 0.10] for scheduler_class in self.scheduler_classes: __lowerCamelCase : Optional[int] = self.get_scheduler_config() __lowerCamelCase : List[str] = scheduler_class(**SCREAMING_SNAKE_CASE__) scheduler.set_timesteps(SCREAMING_SNAKE_CASE__) # copy over dummy past residuals (must be after setting timesteps) __lowerCamelCase : Union[str, Any] = dummy_past_residuals[: scheduler.config.solver_order] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = scheduler_class.from_pretrained(SCREAMING_SNAKE_CASE__) # copy over dummy past residuals new_scheduler.set_timesteps(SCREAMING_SNAKE_CASE__) # copy over dummy past residual (must be after setting timesteps) __lowerCamelCase : Optional[Any] = dummy_past_residuals[: new_scheduler.config.solver_order] __lowerCamelCase : Optional[int] = scheduler.step(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__).prev_sample __lowerCamelCase : Tuple = new_scheduler.step(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__).prev_sample assert torch.sum(torch.abs(output - new_output)) < 1E-5, "Scheduler outputs are not identical" def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : List[str]=None ,**SCREAMING_SNAKE_CASE__ : List[Any]): if scheduler is None: __lowerCamelCase : Any = self.scheduler_classes[0] __lowerCamelCase : Optional[int] = self.get_scheduler_config(**SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[str] = scheduler_class(**SCREAMING_SNAKE_CASE__) __lowerCamelCase : int = self.scheduler_classes[0] __lowerCamelCase : Optional[Any] = self.get_scheduler_config(**SCREAMING_SNAKE_CASE__) __lowerCamelCase : Union[str, Any] = scheduler_class(**SCREAMING_SNAKE_CASE__) __lowerCamelCase : int = 1_0 __lowerCamelCase : Any = self.dummy_model() __lowerCamelCase : List[Any] = self.dummy_sample_deter scheduler.set_timesteps(SCREAMING_SNAKE_CASE__) for i, t in enumerate(scheduler.timesteps): __lowerCamelCase : Any = model(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[str] = scheduler.step(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__).prev_sample return sample def lowerCAmelCase ( self : Union[str, Any]): __lowerCamelCase : List[Any] = dict(self.forward_default_kwargs) __lowerCamelCase : Union[str, Any] = kwargs.pop('num_inference_steps' ,SCREAMING_SNAKE_CASE__) for scheduler_class in self.scheduler_classes: __lowerCamelCase : Any = self.get_scheduler_config() __lowerCamelCase : int = scheduler_class(**SCREAMING_SNAKE_CASE__) __lowerCamelCase : int = self.dummy_sample __lowerCamelCase : Any = 0.1 * sample if num_inference_steps is not None and hasattr(SCREAMING_SNAKE_CASE__ ,'set_timesteps'): scheduler.set_timesteps(SCREAMING_SNAKE_CASE__) elif num_inference_steps is not None and not hasattr(SCREAMING_SNAKE_CASE__ ,'set_timesteps'): __lowerCamelCase : Optional[Any] = num_inference_steps # copy over dummy past residuals (must be done after set_timesteps) __lowerCamelCase : int = [residual + 0.2, residual + 0.15, residual + 0.10] __lowerCamelCase : List[Any] = dummy_past_residuals[: scheduler.config.solver_order] __lowerCamelCase : Optional[Any] = scheduler.timesteps[5] __lowerCamelCase : Optional[int] = scheduler.timesteps[6] __lowerCamelCase : Any = scheduler.step(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__).prev_sample __lowerCamelCase : Optional[int] = scheduler.step(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__).prev_sample self.assertEqual(output_a.shape ,sample.shape) self.assertEqual(output_a.shape ,output_a.shape) def lowerCAmelCase ( self : Tuple): # make sure that iterating over schedulers with same config names gives same results # for defaults __lowerCamelCase : Dict = UniPCMultistepScheduler(**self.get_scheduler_config()) __lowerCamelCase : Dict = self.full_loop(scheduler=SCREAMING_SNAKE_CASE__) __lowerCamelCase : Any = torch.mean(torch.abs(SCREAMING_SNAKE_CASE__)) assert abs(result_mean.item() - 0.2464) < 1E-3 __lowerCamelCase : Optional[int] = DPMSolverSinglestepScheduler.from_config(scheduler.config) __lowerCamelCase : Optional[Any] = DEISMultistepScheduler.from_config(scheduler.config) __lowerCamelCase : List[str] = DPMSolverMultistepScheduler.from_config(scheduler.config) __lowerCamelCase : Tuple = UniPCMultistepScheduler.from_config(scheduler.config) __lowerCamelCase : Optional[int] = self.full_loop(scheduler=SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[str] = torch.mean(torch.abs(SCREAMING_SNAKE_CASE__)) assert abs(result_mean.item() - 0.2464) < 1E-3 def lowerCAmelCase ( self : int): for timesteps in [2_5, 5_0, 1_0_0, 9_9_9, 1_0_0_0]: self.check_over_configs(num_train_timesteps=SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Tuple): self.check_over_configs(thresholding=SCREAMING_SNAKE_CASE__) for order in [1, 2, 3]: for solver_type in ["bh1", "bh2"]: for threshold in [0.5, 1.0, 2.0]: for prediction_type in ["epsilon", "sample"]: self.check_over_configs( thresholding=SCREAMING_SNAKE_CASE__ ,prediction_type=SCREAMING_SNAKE_CASE__ ,sample_max_value=SCREAMING_SNAKE_CASE__ ,solver_order=SCREAMING_SNAKE_CASE__ ,solver_type=SCREAMING_SNAKE_CASE__ ,) def lowerCAmelCase ( self : List[Any]): for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : List[str]): for solver_type in ["bh1", "bh2"]: for order in [1, 2, 3]: for prediction_type in ["epsilon", "sample"]: self.check_over_configs( solver_order=SCREAMING_SNAKE_CASE__ ,solver_type=SCREAMING_SNAKE_CASE__ ,prediction_type=SCREAMING_SNAKE_CASE__ ,) __lowerCamelCase : Union[str, Any] = self.full_loop( solver_order=SCREAMING_SNAKE_CASE__ ,solver_type=SCREAMING_SNAKE_CASE__ ,prediction_type=SCREAMING_SNAKE_CASE__ ,) assert not torch.isnan(SCREAMING_SNAKE_CASE__).any(), "Samples have nan numbers" def lowerCAmelCase ( self : Optional[Any]): self.check_over_configs(lower_order_final=SCREAMING_SNAKE_CASE__) self.check_over_configs(lower_order_final=SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : str): for num_inference_steps in [1, 2, 3, 5, 1_0, 5_0, 1_0_0, 9_9_9, 1_0_0_0]: self.check_over_forward(num_inference_steps=SCREAMING_SNAKE_CASE__ ,time_step=0) def lowerCAmelCase ( self : Optional[int]): __lowerCamelCase : List[Any] = self.full_loop() __lowerCamelCase : Union[str, Any] = torch.mean(torch.abs(SCREAMING_SNAKE_CASE__)) assert abs(result_mean.item() - 0.2464) < 1E-3 def lowerCAmelCase ( self : Optional[Any]): __lowerCamelCase : Optional[int] = self.full_loop(prediction_type='v_prediction') __lowerCamelCase : Optional[Any] = torch.mean(torch.abs(SCREAMING_SNAKE_CASE__)) assert abs(result_mean.item() - 0.1014) < 1E-3 def lowerCAmelCase ( self : int): __lowerCamelCase : Tuple = self.scheduler_classes[0] __lowerCamelCase : Optional[Any] = self.get_scheduler_config(thresholding=SCREAMING_SNAKE_CASE__ ,dynamic_thresholding_ratio=0) __lowerCamelCase : Union[str, Any] = scheduler_class(**SCREAMING_SNAKE_CASE__) __lowerCamelCase : int = 1_0 __lowerCamelCase : List[Any] = self.dummy_model() __lowerCamelCase : Any = self.dummy_sample_deter.half() scheduler.set_timesteps(SCREAMING_SNAKE_CASE__) for i, t in enumerate(scheduler.timesteps): __lowerCamelCase : Optional[Any] = model(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Tuple = scheduler.step(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__).prev_sample assert sample.dtype == torch.floataa def lowerCAmelCase ( self : List[str] ,**SCREAMING_SNAKE_CASE__ : Union[str, Any]): for scheduler_class in self.scheduler_classes: __lowerCamelCase : Any = self.get_scheduler_config(**SCREAMING_SNAKE_CASE__) __lowerCamelCase : str = scheduler_class(**SCREAMING_SNAKE_CASE__) scheduler.set_timesteps(scheduler.config.num_train_timesteps) assert len(scheduler.timesteps.unique()) == scheduler.num_inference_steps
73
from __future__ import annotations import math def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> list: if len(lowerCamelCase__ ) != 2 or len(a[0] ) != 2 or len(lowerCamelCase__ ) != 2 or len(b[0] ) != 2: raise Exception('Matrices are not 2x2' ) __lowerCamelCase : Optional[int] = [ [a[0][0] * b[0][0] + a[0][1] * b[1][0], a[0][0] * b[0][1] + a[0][1] * b[1][1]], [a[1][0] * b[0][0] + a[1][1] * b[1][0], a[1][0] * b[0][1] + a[1][1] * b[1][1]], ] return new_matrix def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> Optional[int]: return [ [matrix_a[row][col] + matrix_b[row][col] for col in range(len(matrix_a[row] ) )] for row in range(len(lowerCamelCase__ ) ) ] def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> List[str]: return [ [matrix_a[row][col] - matrix_b[row][col] for col in range(len(matrix_a[row] ) )] for row in range(len(lowerCamelCase__ ) ) ] def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> tuple[list, list, list, list]: if len(lowerCamelCase__ ) % 2 != 0 or len(a[0] ) % 2 != 0: raise Exception('Odd matrices are not supported!' ) __lowerCamelCase : Tuple = len(lowerCamelCase__ ) __lowerCamelCase : List[Any] = matrix_length // 2 __lowerCamelCase : Dict = [[a[i][j] for j in range(lowerCamelCase__ , lowerCamelCase__ )] for i in range(lowerCamelCase__ )] __lowerCamelCase : str = [ [a[i][j] for j in range(lowerCamelCase__ , lowerCamelCase__ )] for i in range(lowerCamelCase__ , lowerCamelCase__ ) ] __lowerCamelCase : Dict = [[a[i][j] for j in range(lowerCamelCase__ )] for i in range(lowerCamelCase__ )] __lowerCamelCase : Optional[Any] = [[a[i][j] for j in range(lowerCamelCase__ )] for i in range(lowerCamelCase__ , lowerCamelCase__ )] return top_left, top_right, bot_left, bot_right def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> tuple[int, int]: return len(lowerCamelCase__ ), len(matrix[0] ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> None: print('\n'.join(str(lowerCamelCase__ ) for line in matrix ) ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> list: if matrix_dimensions(lowerCamelCase__ ) == (2, 2): return default_matrix_multiplication(lowerCamelCase__ , lowerCamelCase__ ) __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : Optional[Any] = split_matrix(lowerCamelCase__ ) __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : Optional[Any] = split_matrix(lowerCamelCase__ ) __lowerCamelCase : str = actual_strassen(lowerCamelCase__ , matrix_subtraction(lowerCamelCase__ , lowerCamelCase__ ) ) __lowerCamelCase : List[str] = actual_strassen(matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) , lowerCamelCase__ ) __lowerCamelCase : List[Any] = actual_strassen(matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) , lowerCamelCase__ ) __lowerCamelCase : Tuple = actual_strassen(lowerCamelCase__ , matrix_subtraction(lowerCamelCase__ , lowerCamelCase__ ) ) __lowerCamelCase : Optional[int] = actual_strassen(matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) , matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) ) __lowerCamelCase : Dict = actual_strassen(matrix_subtraction(lowerCamelCase__ , lowerCamelCase__ ) , matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) ) __lowerCamelCase : Tuple = actual_strassen(matrix_subtraction(lowerCamelCase__ , lowerCamelCase__ ) , matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) ) __lowerCamelCase : Dict = matrix_addition(matrix_subtraction(matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) , lowerCamelCase__ ) , lowerCamelCase__ ) __lowerCamelCase : Tuple = matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) __lowerCamelCase : List[str] = matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) __lowerCamelCase : Any = matrix_subtraction(matrix_subtraction(matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) , lowerCamelCase__ ) , lowerCamelCase__ ) # construct the new matrix from our 4 quadrants __lowerCamelCase : List[Any] = [] for i in range(len(lowerCamelCase__ ) ): new_matrix.append(top_left[i] + top_right[i] ) for i in range(len(lowerCamelCase__ ) ): new_matrix.append(bot_left[i] + bot_right[i] ) return new_matrix def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> list: if matrix_dimensions(lowerCamelCase__ )[1] != matrix_dimensions(lowerCamelCase__ )[0]: __lowerCamelCase : Any = ( 'Unable to multiply these matrices, please check the dimensions.\n' F"Matrix A: {matrixa}\n" F"Matrix B: {matrixa}" ) raise Exception(lowerCamelCase__ ) __lowerCamelCase : str = matrix_dimensions(lowerCamelCase__ ) __lowerCamelCase : List[str] = matrix_dimensions(lowerCamelCase__ ) if dimensiona[0] == dimensiona[1] and dimensiona[0] == dimensiona[1]: return [matrixa, matrixa] __lowerCamelCase : str = max(*lowerCamelCase__ , *lowerCamelCase__ ) __lowerCamelCase : List[str] = int(math.pow(2 , math.ceil(math.loga(lowerCamelCase__ ) ) ) ) __lowerCamelCase : Any = matrixa __lowerCamelCase : int = matrixa # Adding zeros to the matrices so that the arrays dimensions are the same and also # power of 2 for i in range(0 , lowerCamelCase__ ): if i < dimensiona[0]: for _ in range(dimensiona[1] , lowerCamelCase__ ): new_matrixa[i].append(0 ) else: new_matrixa.append([0] * maxim ) if i < dimensiona[0]: for _ in range(dimensiona[1] , lowerCamelCase__ ): new_matrixa[i].append(0 ) else: new_matrixa.append([0] * maxim ) __lowerCamelCase : List[str] = actual_strassen(lowerCamelCase__ , lowerCamelCase__ ) # Removing the additional zeros for i in range(0 , lowerCamelCase__ ): if i < dimensiona[0]: for _ in range(dimensiona[1] , lowerCamelCase__ ): final_matrix[i].pop() else: final_matrix.pop() return final_matrix if __name__ == "__main__": a =[ [2, 3, 4, 5], [6, 4, 3, 1], [2, 3, 6, 7], [3, 1, 2, 4], [2, 3, 4, 5], [6, 4, 3, 1], [2, 3, 6, 7], [3, 1, 2, 4], [2, 3, 4, 5], [6, 2, 3, 1], ] a =[[0, 2, 1, 1], [16, 2, 3, 3], [2, 2, 7, 7], [13, 11, 22, 4]] print(strassen(matrixa, matrixa))
73
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) a ={ """configuration_mega""": ["""MEGA_PRETRAINED_CONFIG_ARCHIVE_MAP""", """MegaConfig""", """MegaOnnxConfig"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a =[ """MEGA_PRETRAINED_MODEL_ARCHIVE_LIST""", """MegaForCausalLM""", """MegaForMaskedLM""", """MegaForMultipleChoice""", """MegaForQuestionAnswering""", """MegaForSequenceClassification""", """MegaForTokenClassification""", """MegaModel""", """MegaPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_mega import MEGA_PRETRAINED_CONFIG_ARCHIVE_MAP, MegaConfig, MegaOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mega import ( MEGA_PRETRAINED_MODEL_ARCHIVE_LIST, MegaForCausalLM, MegaForMaskedLM, MegaForMultipleChoice, MegaForQuestionAnswering, MegaForSequenceClassification, MegaForTokenClassification, MegaModel, MegaPreTrainedModel, ) else: import sys a =_LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
73
from math import isclose, sqrt def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> tuple[float, float, float]: __lowerCamelCase : Tuple = point_y / 4 / point_x __lowerCamelCase : Tuple = 2 * normal_gradient / (1 + normal_gradient * normal_gradient) __lowerCamelCase : List[Any] = (1 - normal_gradient * normal_gradient) / ( 1 + normal_gradient * normal_gradient ) __lowerCamelCase : int = (sa - ca * incoming_gradient) / (ca + sa * incoming_gradient) # to find the next point, solve the simultaeneous equations: # y^2 + 4x^2 = 100 # y - b = m * (x - a) # ==> A x^2 + B x + C = 0 __lowerCamelCase : Any = outgoing_gradient**2 + 4 __lowerCamelCase : Optional[int] = 2 * outgoing_gradient * (point_y - outgoing_gradient * point_x) __lowerCamelCase : str = (point_y - outgoing_gradient * point_x) ** 2 - 1_0_0 __lowerCamelCase : str = ( -linear_term - sqrt(linear_term**2 - 4 * quadratic_term * constant_term ) ) / (2 * quadratic_term) __lowerCamelCase : Optional[Any] = ( -linear_term + sqrt(linear_term**2 - 4 * quadratic_term * constant_term ) ) / (2 * quadratic_term) # two solutions, one of which is our input point __lowerCamelCase : Optional[Any] = x_minus if isclose(lowerCamelCase__ , lowerCamelCase__ ) else x_plus __lowerCamelCase : Tuple = point_y + outgoing_gradient * (next_x - point_x) return next_x, next_y, outgoing_gradient def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ = 1.4 , lowerCamelCase__ = -9.6 ) -> int: __lowerCamelCase : int = 0 __lowerCamelCase : float = first_x_coord __lowerCamelCase : float = first_y_coord __lowerCamelCase : float = (10.1 - point_y) / (0.0 - point_x) while not (-0.01 <= point_x <= 0.01 and point_y > 0): __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : Any = next_point(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) num_reflections += 1 return num_reflections if __name__ == "__main__": print(F"""{solution() = }""")
73
1
import torch from transformers import CamembertForMaskedLM, CamembertTokenizer def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__=5 ) -> int: # Adapted from https://github.com/pytorch/fairseq/blob/master/fairseq/models/roberta/hub_interface.py assert masked_input.count('<mask>' ) == 1 __lowerCamelCase : Dict = torch.tensor(tokenizer.encode(lowerCamelCase__ , add_special_tokens=lowerCamelCase__ ) ).unsqueeze(0 ) # Batch size 1 __lowerCamelCase : Union[str, Any] = model(lowerCamelCase__ )[0] # The last hidden-state is the first element of the output tuple __lowerCamelCase : Tuple = (input_ids.squeeze() == tokenizer.mask_token_id).nonzero().item() __lowerCamelCase : List[str] = logits[0, masked_index, :] __lowerCamelCase : Dict = logits.softmax(dim=0 ) __lowerCamelCase , __lowerCamelCase : Optional[int] = prob.topk(k=lowerCamelCase__ , dim=0 ) __lowerCamelCase : Dict = ' '.join( [tokenizer.convert_ids_to_tokens(indices[i].item() ) for i in range(len(lowerCamelCase__ ) )] ) __lowerCamelCase : Optional[Any] = tokenizer.mask_token __lowerCamelCase : Optional[int] = [] for index, predicted_token_bpe in enumerate(topk_predicted_token_bpe.split(' ' ) ): __lowerCamelCase : List[str] = predicted_token_bpe.replace('\u2581' , ' ' ) if " {0}".format(lowerCamelCase__ ) in masked_input: topk_filled_outputs.append( ( masked_input.replace(' {0}'.format(lowerCamelCase__ ) , lowerCamelCase__ ), values[index].item(), predicted_token, ) ) else: topk_filled_outputs.append( ( masked_input.replace(lowerCamelCase__ , lowerCamelCase__ ), values[index].item(), predicted_token, ) ) return topk_filled_outputs a =CamembertTokenizer.from_pretrained("""camembert-base""") a =CamembertForMaskedLM.from_pretrained("""camembert-base""") model.eval() a ="""Le camembert est <mask> :)""" print(fill_mask(masked_input, model, tokenizer, topk=3))
73
import os import unicodedata from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging a =logging.get_logger(__name__) a ={"""vocab_file""": """spiece.model"""} a ={ """vocab_file""": { """albert-base-v1""": """https://huggingface.co/albert-base-v1/resolve/main/spiece.model""", """albert-large-v1""": """https://huggingface.co/albert-large-v1/resolve/main/spiece.model""", """albert-xlarge-v1""": """https://huggingface.co/albert-xlarge-v1/resolve/main/spiece.model""", """albert-xxlarge-v1""": """https://huggingface.co/albert-xxlarge-v1/resolve/main/spiece.model""", """albert-base-v2""": """https://huggingface.co/albert-base-v2/resolve/main/spiece.model""", """albert-large-v2""": """https://huggingface.co/albert-large-v2/resolve/main/spiece.model""", """albert-xlarge-v2""": """https://huggingface.co/albert-xlarge-v2/resolve/main/spiece.model""", """albert-xxlarge-v2""": """https://huggingface.co/albert-xxlarge-v2/resolve/main/spiece.model""", } } a ={ """albert-base-v1""": 512, """albert-large-v1""": 512, """albert-xlarge-v1""": 512, """albert-xxlarge-v1""": 512, """albert-base-v2""": 512, """albert-large-v2""": 512, """albert-xlarge-v2""": 512, """albert-xxlarge-v2""": 512, } a ="""▁""" class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : List[Any] = VOCAB_FILES_NAMES _UpperCAmelCase : List[str] = PRETRAINED_VOCAB_FILES_MAP _UpperCAmelCase : Optional[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self : str ,SCREAMING_SNAKE_CASE__ : Optional[int] ,SCREAMING_SNAKE_CASE__ : Tuple=True ,SCREAMING_SNAKE_CASE__ : str=True ,SCREAMING_SNAKE_CASE__ : List[str]=False ,SCREAMING_SNAKE_CASE__ : Any="[CLS]" ,SCREAMING_SNAKE_CASE__ : Optional[int]="[SEP]" ,SCREAMING_SNAKE_CASE__ : Optional[Any]="<unk>" ,SCREAMING_SNAKE_CASE__ : Any="[SEP]" ,SCREAMING_SNAKE_CASE__ : Optional[int]="<pad>" ,SCREAMING_SNAKE_CASE__ : Any="[CLS]" ,SCREAMING_SNAKE_CASE__ : Union[str, Any]="[MASK]" ,SCREAMING_SNAKE_CASE__ : Optional[Dict[str, Any]] = None ,**SCREAMING_SNAKE_CASE__ : Dict ,): # Mask token behave like a normal word, i.e. include the space before it and # is included in the raw text, there should be a match in a non-normalized sentence. __lowerCamelCase : Dict = ( AddedToken(SCREAMING_SNAKE_CASE__ ,lstrip=SCREAMING_SNAKE_CASE__ ,rstrip=SCREAMING_SNAKE_CASE__ ,normalized=SCREAMING_SNAKE_CASE__) if isinstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) else mask_token ) __lowerCamelCase : str = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( do_lower_case=SCREAMING_SNAKE_CASE__ ,remove_space=SCREAMING_SNAKE_CASE__ ,keep_accents=SCREAMING_SNAKE_CASE__ ,bos_token=SCREAMING_SNAKE_CASE__ ,eos_token=SCREAMING_SNAKE_CASE__ ,unk_token=SCREAMING_SNAKE_CASE__ ,sep_token=SCREAMING_SNAKE_CASE__ ,pad_token=SCREAMING_SNAKE_CASE__ ,cls_token=SCREAMING_SNAKE_CASE__ ,mask_token=SCREAMING_SNAKE_CASE__ ,sp_model_kwargs=self.sp_model_kwargs ,**SCREAMING_SNAKE_CASE__ ,) __lowerCamelCase : Any = do_lower_case __lowerCamelCase : Union[str, Any] = remove_space __lowerCamelCase : Tuple = keep_accents __lowerCamelCase : Dict = vocab_file __lowerCamelCase : str = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.Load(SCREAMING_SNAKE_CASE__) @property def lowerCAmelCase ( self : Optional[Any]): return len(self.sp_model) def lowerCAmelCase ( self : Optional[Any]): __lowerCamelCase : Optional[int] = {self.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__): i for i in range(self.vocab_size)} vocab.update(self.added_tokens_encoder) return vocab def __getstate__( self : Union[str, Any]): __lowerCamelCase : str = self.__dict__.copy() __lowerCamelCase : Tuple = None return state def __setstate__( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : str): __lowerCamelCase : List[str] = d # for backward compatibility if not hasattr(self ,'sp_model_kwargs'): __lowerCamelCase : List[str] = {} __lowerCamelCase : int = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.Load(self.vocab_file) def lowerCAmelCase ( self : Dict ,SCREAMING_SNAKE_CASE__ : List[Any]): if self.remove_space: __lowerCamelCase : Dict = ' '.join(inputs.strip().split()) else: __lowerCamelCase : Optional[Any] = inputs __lowerCamelCase : Tuple = outputs.replace('``' ,'"').replace('\'\'' ,'"') if not self.keep_accents: __lowerCamelCase : List[str] = unicodedata.normalize('NFKD' ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : str = ''.join([c for c in outputs if not unicodedata.combining(SCREAMING_SNAKE_CASE__)]) if self.do_lower_case: __lowerCamelCase : Optional[Any] = outputs.lower() return outputs def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : str): __lowerCamelCase : Tuple = self.preprocess_text(SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = self.sp_model.encode(SCREAMING_SNAKE_CASE__ ,out_type=SCREAMING_SNAKE_CASE__) __lowerCamelCase : Tuple = [] for piece in pieces: if len(SCREAMING_SNAKE_CASE__) > 1 and piece[-1] == str(',') and piece[-2].isdigit(): __lowerCamelCase : int = self.sp_model.EncodeAsPieces(piece[:-1].replace(SCREAMING_SNAKE_CASE__ ,'')) if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE: if len(cur_pieces[0]) == 1: __lowerCamelCase : Union[str, Any] = cur_pieces[1:] else: __lowerCamelCase : Dict = cur_pieces[0][1:] cur_pieces.append(piece[-1]) new_pieces.extend(SCREAMING_SNAKE_CASE__) else: new_pieces.append(SCREAMING_SNAKE_CASE__) return new_pieces def lowerCAmelCase ( self : Any ,SCREAMING_SNAKE_CASE__ : List[str]): return self.sp_model.PieceToId(SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : str ,SCREAMING_SNAKE_CASE__ : Any): return self.sp_model.IdToPiece(SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Tuple ,SCREAMING_SNAKE_CASE__ : int): __lowerCamelCase : Optional[Any] = [] __lowerCamelCase : int = '' __lowerCamelCase : Optional[int] = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(SCREAMING_SNAKE_CASE__) + token __lowerCamelCase : List[Any] = True __lowerCamelCase : Any = [] else: current_sub_tokens.append(SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = False out_string += self.sp_model.decode(SCREAMING_SNAKE_CASE__) return out_string.strip() def lowerCAmelCase ( self : Dict ,SCREAMING_SNAKE_CASE__ : List[int] ,SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None): __lowerCamelCase : Union[str, Any] = [self.sep_token_id] __lowerCamelCase : int = [self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def lowerCAmelCase ( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : List[int] ,SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ,SCREAMING_SNAKE_CASE__ : bool = False): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=SCREAMING_SNAKE_CASE__ ,token_ids_a=SCREAMING_SNAKE_CASE__ ,already_has_special_tokens=SCREAMING_SNAKE_CASE__) if token_ids_a is not None: return [1] + ([0] * len(SCREAMING_SNAKE_CASE__)) + [1] + ([0] * len(SCREAMING_SNAKE_CASE__)) + [1] return [1] + ([0] * len(SCREAMING_SNAKE_CASE__)) + [1] def lowerCAmelCase ( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : List[int] ,SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None): __lowerCamelCase : Tuple = [self.sep_token_id] __lowerCamelCase : List[Any] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep) * [0] return len(cls + token_ids_a + sep) * [0] + len(token_ids_a + sep) * [1] def lowerCAmelCase ( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : str ,SCREAMING_SNAKE_CASE__ : Optional[str] = None): if not os.path.isdir(SCREAMING_SNAKE_CASE__): logger.error(F"Vocabulary path ({save_directory}) should be a directory") return __lowerCamelCase : List[str] = os.path.join( SCREAMING_SNAKE_CASE__ ,(filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file']) if os.path.abspath(self.vocab_file) != os.path.abspath(SCREAMING_SNAKE_CASE__) and os.path.isfile(self.vocab_file): copyfile(self.vocab_file ,SCREAMING_SNAKE_CASE__) elif not os.path.isfile(self.vocab_file): with open(SCREAMING_SNAKE_CASE__ ,'wb') as fi: __lowerCamelCase : str = self.sp_model.serialized_model_proto() fi.write(SCREAMING_SNAKE_CASE__) return (out_vocab_file,)
73
1
from typing import Dict, List, Optional from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging a =logging.get_logger(__name__) a ={ """nielsr/canine-s""": 2048, } # Unicode defines 1,114,112 total “codepoints” a =1114112 # Below: Constants defining canonical codepoints for special, pseudo-characters. # Copied from https://github.com/google-research/language/blob/master/language/canine/special_codepoints.py a =0 a =0xe_0_0_0 a =0xe_0_0_1 a =0xe_0_0_2 a =0xe_0_0_3 a =0xe_0_0_4 # Maps special codepoints to human-readable names. a ={ # Special symbols are represented using codepoints values that are valid, # but designated as "Private Use", meaning that they will never be assigned # characters by the Unicode Consortium, and are thus safe for use here. # # NOTE: Do *NOT* add any sort of [UNK_CHAR] here. They are explicitly # excluded and should fail with a hard error. CLS: "[CLS]", SEP: "[SEP]", BOS: "[BOS]", MASK: "[MASK]", PAD: "[PAD]", RESERVED: "[RESERVED]", } # Maps special codepoint human-readable names to their codepoint values. a ={name: codepoint for codepoint, name in SPECIAL_CODEPOINTS.items()} class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : int = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : int=chr(SCREAMING_SNAKE_CASE__) ,SCREAMING_SNAKE_CASE__ : Tuple=chr(SCREAMING_SNAKE_CASE__) ,SCREAMING_SNAKE_CASE__ : str=chr(SCREAMING_SNAKE_CASE__) ,SCREAMING_SNAKE_CASE__ : Union[str, Any]=chr(SCREAMING_SNAKE_CASE__) ,SCREAMING_SNAKE_CASE__ : Any=chr(SCREAMING_SNAKE_CASE__) ,SCREAMING_SNAKE_CASE__ : List[Any]=chr(SCREAMING_SNAKE_CASE__) ,SCREAMING_SNAKE_CASE__ : Optional[int]=False ,SCREAMING_SNAKE_CASE__ : Optional[int]=2_0_4_8 ,**SCREAMING_SNAKE_CASE__ : int ,): __lowerCamelCase : List[Any] = AddedToken(SCREAMING_SNAKE_CASE__ ,lstrip=SCREAMING_SNAKE_CASE__ ,rstrip=SCREAMING_SNAKE_CASE__) if isinstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) else bos_token __lowerCamelCase : int = AddedToken(SCREAMING_SNAKE_CASE__ ,lstrip=SCREAMING_SNAKE_CASE__ ,rstrip=SCREAMING_SNAKE_CASE__) if isinstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) else eos_token __lowerCamelCase : List[str] = AddedToken(SCREAMING_SNAKE_CASE__ ,lstrip=SCREAMING_SNAKE_CASE__ ,rstrip=SCREAMING_SNAKE_CASE__) if isinstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) else sep_token __lowerCamelCase : Optional[Any] = AddedToken(SCREAMING_SNAKE_CASE__ ,lstrip=SCREAMING_SNAKE_CASE__ ,rstrip=SCREAMING_SNAKE_CASE__) if isinstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) else cls_token __lowerCamelCase : Tuple = AddedToken(SCREAMING_SNAKE_CASE__ ,lstrip=SCREAMING_SNAKE_CASE__ ,rstrip=SCREAMING_SNAKE_CASE__) if isinstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) else pad_token # Mask token behave like a normal word, i.e. include the space before it __lowerCamelCase : List[Any] = AddedToken(SCREAMING_SNAKE_CASE__ ,lstrip=SCREAMING_SNAKE_CASE__ ,rstrip=SCREAMING_SNAKE_CASE__) if isinstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) else mask_token super().__init__( bos_token=SCREAMING_SNAKE_CASE__ ,eos_token=SCREAMING_SNAKE_CASE__ ,sep_token=SCREAMING_SNAKE_CASE__ ,cls_token=SCREAMING_SNAKE_CASE__ ,pad_token=SCREAMING_SNAKE_CASE__ ,mask_token=SCREAMING_SNAKE_CASE__ ,add_prefix_space=SCREAMING_SNAKE_CASE__ ,model_max_length=SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__ ,) # Creates a mapping for looking up the IDs of special symbols. __lowerCamelCase : Dict[str, int] = {} for codepoint, name in SPECIAL_CODEPOINTS.items(): __lowerCamelCase : Union[str, Any] = codepoint # Creates a mapping for looking up the string forms of special symbol IDs. __lowerCamelCase : Dict[int, str] = { codepoint: name for name, codepoint in self._special_codepoints.items() } __lowerCamelCase : Any = UNICODE_VOCAB_SIZE __lowerCamelCase : Dict = len(self._special_codepoints) @property def lowerCAmelCase ( self : Any): return self._unicode_vocab_size def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : str): return list(SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Dict ,SCREAMING_SNAKE_CASE__ : str): try: return ord(SCREAMING_SNAKE_CASE__) except TypeError: raise ValueError(F"invalid token: '{token}'") def lowerCAmelCase ( self : Dict ,SCREAMING_SNAKE_CASE__ : int): try: if index in SPECIAL_CODEPOINTS: return SPECIAL_CODEPOINTS[index] return chr(SCREAMING_SNAKE_CASE__) except TypeError: raise ValueError(F"invalid id: {index}") def lowerCAmelCase ( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : Optional[int]): return "".join(SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : List[int] ,SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None): __lowerCamelCase : Tuple = [self.sep_token_id] __lowerCamelCase : Optional[Any] = [self.cls_token_id] __lowerCamelCase : str = cls + token_ids_a + sep if token_ids_a is not None: result += token_ids_a + sep return result def lowerCAmelCase ( self : List[str] ,SCREAMING_SNAKE_CASE__ : List[int] ,SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ,SCREAMING_SNAKE_CASE__ : bool = False): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=SCREAMING_SNAKE_CASE__ ,token_ids_a=SCREAMING_SNAKE_CASE__ ,already_has_special_tokens=SCREAMING_SNAKE_CASE__) __lowerCamelCase : Any = [1] + ([0] * len(SCREAMING_SNAKE_CASE__)) + [1] if token_ids_a is not None: result += ([0] * len(SCREAMING_SNAKE_CASE__)) + [1] return result def lowerCAmelCase ( self : Tuple ,SCREAMING_SNAKE_CASE__ : List[int] ,SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None): __lowerCamelCase : Tuple = [self.sep_token_id] __lowerCamelCase : Dict = [self.cls_token_id] __lowerCamelCase : Dict = len(cls + token_ids_a + sep) * [0] if token_ids_a is not None: result += len(token_ids_a + sep) * [1] return result def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : str ,SCREAMING_SNAKE_CASE__ : Optional[str] = None): return ()
73
def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> float: if discount_rate < 0: raise ValueError('Discount rate cannot be negative' ) if not cash_flows: raise ValueError('Cash flows list cannot be empty' ) __lowerCamelCase : int = sum( cash_flow / ((1 + discount_rate) ** i) for i, cash_flow in enumerate(lowerCamelCase__ ) ) return round(lowerCamelCase__ , ndigits=2 ) if __name__ == "__main__": import doctest doctest.testmod()
73
1
import mpmath # for roots of unity import numpy as np class A_ : def __init__( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : Union[str, Any]=None ,SCREAMING_SNAKE_CASE__ : str=None): # Input as list __lowerCamelCase : Optional[int] = list(poly_a or [0])[:] __lowerCamelCase : Dict = list(poly_b or [0])[:] # Remove leading zero coefficients while self.polyA[-1] == 0: self.polyA.pop() __lowerCamelCase : Optional[int] = len(self.polyA) while self.polyB[-1] == 0: self.polyB.pop() __lowerCamelCase : Any = len(self.polyB) # Add 0 to make lengths equal a power of 2 __lowerCamelCase : int = int( 2 ** np.ceil(np.loga(len(self.polyA) + len(self.polyB) - 1))) while len(self.polyA) < self.c_max_length: self.polyA.append(0) while len(self.polyB) < self.c_max_length: self.polyB.append(0) # A complex root used for the fourier transform __lowerCamelCase : Tuple = complex(mpmath.root(x=1 ,n=self.c_max_length ,k=1)) # The product __lowerCamelCase : Optional[Any] = self.__multiply() def lowerCAmelCase ( self : Any ,SCREAMING_SNAKE_CASE__ : int): __lowerCamelCase : Optional[Any] = [[x] for x in self.polyA] if which == 'A' else [[x] for x in self.polyB] # Corner case if len(SCREAMING_SNAKE_CASE__) <= 1: return dft[0] # __lowerCamelCase : str = self.c_max_length // 2 while next_ncol > 0: __lowerCamelCase : Optional[Any] = [[] for i in range(SCREAMING_SNAKE_CASE__)] __lowerCamelCase : Optional[int] = self.root**next_ncol # First half of next step __lowerCamelCase : Union[str, Any] = 1 for j in range(self.c_max_length // (next_ncol * 2)): for i in range(SCREAMING_SNAKE_CASE__): new_dft[i].append(dft[i][j] + current_root * dft[i + next_ncol][j]) current_root *= root # Second half of next step __lowerCamelCase : Optional[Any] = 1 for j in range(self.c_max_length // (next_ncol * 2)): for i in range(SCREAMING_SNAKE_CASE__): new_dft[i].append(dft[i][j] - current_root * dft[i + next_ncol][j]) current_root *= root # Update __lowerCamelCase : Union[str, Any] = new_dft __lowerCamelCase : Optional[Any] = next_ncol // 2 return dft[0] def lowerCAmelCase ( self : List[str]): __lowerCamelCase : Optional[int] = self.__dft('A') __lowerCamelCase : Dict = self.__dft('B') __lowerCamelCase : Optional[Any] = [[dft_a[i] * dft_b[i] for i in range(self.c_max_length)]] del dft_a del dft_b # Corner Case if len(inverce_c[0]) <= 1: return inverce_c[0] # Inverse DFT __lowerCamelCase : int = 2 while next_ncol <= self.c_max_length: __lowerCamelCase : Dict = [[] for i in range(SCREAMING_SNAKE_CASE__)] __lowerCamelCase : Dict = self.root ** (next_ncol // 2) __lowerCamelCase : Union[str, Any] = 1 # First half of next step for j in range(self.c_max_length // next_ncol): for i in range(next_ncol // 2): # Even positions new_inverse_c[i].append( ( inverce_c[i][j] + inverce_c[i][j + self.c_max_length // next_ncol] ) / 2) # Odd positions new_inverse_c[i + next_ncol // 2].append( ( inverce_c[i][j] - inverce_c[i][j + self.c_max_length // next_ncol] ) / (2 * current_root)) current_root *= root # Update __lowerCamelCase : List[Any] = new_inverse_c next_ncol *= 2 # Unpack __lowerCamelCase : Optional[Any] = [round(x[0].real ,8) + round(x[0].imag ,8) * 1j for x in inverce_c] # Remove leading 0's while inverce_c[-1] == 0: inverce_c.pop() return inverce_c def __str__( self : int): __lowerCamelCase : Union[str, Any] = 'A = ' + ' + '.join( F"{coef}*x^{i}" for coef, i in enumerate(self.polyA[: self.len_A])) __lowerCamelCase : Tuple = 'B = ' + ' + '.join( F"{coef}*x^{i}" for coef, i in enumerate(self.polyB[: self.len_B])) __lowerCamelCase : List[Any] = 'A*B = ' + ' + '.join( F"{coef}*x^{i}" for coef, i in enumerate(self.product)) return F"{a}\n{b}\n{c}" # Unit tests if __name__ == "__main__": import doctest doctest.testmod()
73
import copy from typing import Dict, List, Optional from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING a ={ """facebook/mask2former-swin-small-coco-instance""": ( """https://huggingface.co/facebook/mask2former-swin-small-coco-instance/blob/main/config.json""" ) # See all Mask2Former models at https://huggingface.co/models?filter=mask2former } a =logging.get_logger(__name__) class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : Dict = '''mask2former''' _UpperCAmelCase : Dict = ['''swin'''] _UpperCAmelCase : Optional[int] = {'''hidden_size''': '''hidden_dim'''} def __init__( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : Optional[Dict] = None ,SCREAMING_SNAKE_CASE__ : int = 2_5_6 ,SCREAMING_SNAKE_CASE__ : int = 2_5_6 ,SCREAMING_SNAKE_CASE__ : int = 2_5_6 ,SCREAMING_SNAKE_CASE__ : int = 1_0_2_4 ,SCREAMING_SNAKE_CASE__ : str = "relu" ,SCREAMING_SNAKE_CASE__ : int = 6 ,SCREAMING_SNAKE_CASE__ : int = 1_0 ,SCREAMING_SNAKE_CASE__ : int = 8 ,SCREAMING_SNAKE_CASE__ : float = 0.0 ,SCREAMING_SNAKE_CASE__ : int = 2_0_4_8 ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : int = 4 ,SCREAMING_SNAKE_CASE__ : int = 2_5_5 ,SCREAMING_SNAKE_CASE__ : int = 1_0_0 ,SCREAMING_SNAKE_CASE__ : float = 0.1 ,SCREAMING_SNAKE_CASE__ : float = 2.0 ,SCREAMING_SNAKE_CASE__ : float = 5.0 ,SCREAMING_SNAKE_CASE__ : float = 5.0 ,SCREAMING_SNAKE_CASE__ : int = 1_2_5_4_4 ,SCREAMING_SNAKE_CASE__ : float = 3.0 ,SCREAMING_SNAKE_CASE__ : float = 0.75 ,SCREAMING_SNAKE_CASE__ : float = 0.02 ,SCREAMING_SNAKE_CASE__ : float = 1.0 ,SCREAMING_SNAKE_CASE__ : bool = True ,SCREAMING_SNAKE_CASE__ : List[int] = [4, 8, 1_6, 3_2] ,SCREAMING_SNAKE_CASE__ : bool = None ,**SCREAMING_SNAKE_CASE__ : Optional[Any] ,): if backbone_config is None: logger.info('`backbone_config` is `None`. Initializing the config with the default `Swin` backbone.') __lowerCamelCase : Optional[Any] = CONFIG_MAPPING['swin']( image_size=2_2_4 ,in_channels=3 ,patch_size=4 ,embed_dim=9_6 ,depths=[2, 2, 1_8, 2] ,num_heads=[3, 6, 1_2, 2_4] ,window_size=7 ,drop_path_rate=0.3 ,use_absolute_embeddings=SCREAMING_SNAKE_CASE__ ,out_features=['stage1', 'stage2', 'stage3', 'stage4'] ,) if isinstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__): __lowerCamelCase : Union[str, Any] = backbone_config.pop('model_type') __lowerCamelCase : Dict = CONFIG_MAPPING[backbone_model_type] __lowerCamelCase : int = config_class.from_dict(SCREAMING_SNAKE_CASE__) # verify that the backbone is supported if backbone_config.model_type not in self.backbones_supported: logger.warning_once( F"Backbone {backbone_config.model_type} is not a supported model and may not be compatible with Mask2Former. " F"Supported model types: {','.join(self.backbones_supported)}") __lowerCamelCase : Dict = backbone_config __lowerCamelCase : int = feature_size __lowerCamelCase : List[str] = mask_feature_size __lowerCamelCase : int = hidden_dim __lowerCamelCase : str = encoder_feedforward_dim __lowerCamelCase : Optional[int] = activation_function __lowerCamelCase : int = encoder_layers __lowerCamelCase : List[Any] = decoder_layers __lowerCamelCase : Union[str, Any] = num_attention_heads __lowerCamelCase : Tuple = dropout __lowerCamelCase : Dict = dim_feedforward __lowerCamelCase : Union[str, Any] = pre_norm __lowerCamelCase : List[str] = enforce_input_projection __lowerCamelCase : Optional[int] = common_stride __lowerCamelCase : Dict = ignore_value __lowerCamelCase : Optional[Any] = num_queries __lowerCamelCase : int = no_object_weight __lowerCamelCase : Optional[Any] = class_weight __lowerCamelCase : str = mask_weight __lowerCamelCase : List[str] = dice_weight __lowerCamelCase : Dict = train_num_points __lowerCamelCase : Optional[int] = oversample_ratio __lowerCamelCase : Optional[Any] = importance_sample_ratio __lowerCamelCase : List[Any] = init_std __lowerCamelCase : Tuple = init_xavier_std __lowerCamelCase : Union[str, Any] = use_auxiliary_loss __lowerCamelCase : List[Any] = feature_strides __lowerCamelCase : Any = output_auxiliary_logits __lowerCamelCase : List[Any] = decoder_layers super().__init__(**SCREAMING_SNAKE_CASE__) @classmethod def lowerCAmelCase ( cls : str ,SCREAMING_SNAKE_CASE__ : PretrainedConfig ,**SCREAMING_SNAKE_CASE__ : Tuple): return cls( backbone_config=SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__ ,) def lowerCAmelCase ( self : str): __lowerCamelCase : List[Any] = copy.deepcopy(self.__dict__) __lowerCamelCase : List[Any] = self.backbone_config.to_dict() __lowerCamelCase : Union[str, Any] = self.__class__.model_type return output
73
1
# Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available a ={"""configuration_mra""": ["""MRA_PRETRAINED_CONFIG_ARCHIVE_MAP""", """MraConfig"""]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a =[ """MRA_PRETRAINED_MODEL_ARCHIVE_LIST""", """MraForMaskedLM""", """MraForMultipleChoice""", """MraForQuestionAnswering""", """MraForSequenceClassification""", """MraForTokenClassification""", """MraLayer""", """MraModel""", """MraPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_mra import MRA_PRETRAINED_CONFIG_ARCHIVE_MAP, MraConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mra import ( MRA_PRETRAINED_MODEL_ARCHIVE_LIST, MraForMaskedLM, MraForMultipleChoice, MraForQuestionAnswering, MraForSequenceClassification, MraForTokenClassification, MraLayer, MraModel, MraPreTrainedModel, ) else: import sys a =_LazyModule(__name__, globals()["""__file__"""], _import_structure)
73
import string # frequency taken from https://en.wikipedia.org/wiki/Letter_frequency a ={ """E""": 12.70, """T""": 9.06, """A""": 8.17, """O""": 7.51, """I""": 6.97, """N""": 6.75, """S""": 6.33, """H""": 6.09, """R""": 5.99, """D""": 4.25, """L""": 4.03, """C""": 2.78, """U""": 2.76, """M""": 2.41, """W""": 2.36, """F""": 2.23, """G""": 2.02, """Y""": 1.97, """P""": 1.93, """B""": 1.29, """V""": 0.98, """K""": 0.77, """J""": 0.15, """X""": 0.15, """Q""": 0.10, """Z""": 0.07, } a ="""ETAOINSHRDLCUMWFGYPBVKJXQZ""" a ="""ABCDEFGHIJKLMNOPQRSTUVWXYZ""" def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> dict[str, int]: __lowerCamelCase : Tuple = {letter: 0 for letter in string.ascii_uppercase} for letter in message.upper(): if letter in LETTERS: letter_count[letter] += 1 return letter_count def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> str: return x[0] def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> str: __lowerCamelCase : List[str] = get_letter_count(lowerCamelCase__ ) __lowerCamelCase : dict[int, list[str]] = { freq: [] for letter, freq in letter_to_freq.items() } for letter in LETTERS: freq_to_letter[letter_to_freq[letter]].append(lowerCamelCase__ ) __lowerCamelCase : dict[int, str] = {} for freq in freq_to_letter: freq_to_letter[freq].sort(key=ETAOIN.find , reverse=lowerCamelCase__ ) __lowerCamelCase : Optional[Any] = ''.join(freq_to_letter[freq] ) __lowerCamelCase : int = list(freq_to_letter_str.items() ) freq_pairs.sort(key=lowerCamelCase__ , reverse=lowerCamelCase__ ) __lowerCamelCase : list[str] = [freq_pair[1] for freq_pair in freq_pairs] return "".join(lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> int: __lowerCamelCase : str = get_frequency_order(lowerCamelCase__ ) __lowerCamelCase : Optional[Any] = 0 for common_letter in ETAOIN[:6]: if common_letter in freq_order[:6]: match_score += 1 for uncommon_letter in ETAOIN[-6:]: if uncommon_letter in freq_order[-6:]: match_score += 1 return match_score if __name__ == "__main__": import doctest doctest.testmod()
73
1
import copy import tempfile import unittest from huggingface_hub import HfFolder, delete_repo from parameterized import parameterized from requests.exceptions import HTTPError from transformers import AutoConfig, GenerationConfig from transformers.testing_utils import TOKEN, USER, is_staging_test class A_ ( unittest.TestCase ): @parameterized.expand([(None,), ('foo.json',)]) def lowerCAmelCase ( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : List[str]): __lowerCamelCase : Dict = GenerationConfig( do_sample=SCREAMING_SNAKE_CASE__ ,temperature=0.7 ,length_penalty=1.0 ,bad_words_ids=[[1, 2, 3], [4, 5]] ,) with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained(SCREAMING_SNAKE_CASE__ ,config_name=SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = GenerationConfig.from_pretrained(SCREAMING_SNAKE_CASE__ ,config_name=SCREAMING_SNAKE_CASE__) # Checks parameters that were specified self.assertEqual(loaded_config.do_sample ,SCREAMING_SNAKE_CASE__) self.assertEqual(loaded_config.temperature ,0.7) self.assertEqual(loaded_config.length_penalty ,1.0) self.assertEqual(loaded_config.bad_words_ids ,[[1, 2, 3], [4, 5]]) # Checks parameters that were not specified (defaults) self.assertEqual(loaded_config.top_k ,5_0) self.assertEqual(loaded_config.max_length ,2_0) self.assertEqual(loaded_config.max_time ,SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Tuple): __lowerCamelCase : Any = AutoConfig.from_pretrained('gpt2') __lowerCamelCase : Union[str, Any] = GenerationConfig.from_model_config(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Union[str, Any] = GenerationConfig() # The generation config has loaded a few non-default parameters from the model config self.assertNotEqual(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) # One of those parameters is eos_token_id -- check if it matches self.assertNotEqual(generation_config_from_model.eos_token_id ,default_generation_config.eos_token_id) self.assertEqual(generation_config_from_model.eos_token_id ,model_config.eos_token_id) def lowerCAmelCase ( self : Union[str, Any]): __lowerCamelCase : Tuple = GenerationConfig() __lowerCamelCase : List[str] = { 'max_new_tokens': 1_0_2_4, 'foo': 'bar', } __lowerCamelCase : List[Any] = copy.deepcopy(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Tuple = generation_config.update(**SCREAMING_SNAKE_CASE__) # update_kwargs was not modified (no side effects) self.assertEqual(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) # update_kwargs was used to update the config on valid attributes self.assertEqual(generation_config.max_new_tokens ,1_0_2_4) # `.update()` returns a dictionary of unused kwargs self.assertEqual(SCREAMING_SNAKE_CASE__ ,{'foo': 'bar'}) def lowerCAmelCase ( self : int): __lowerCamelCase : int = GenerationConfig() __lowerCamelCase : Union[str, Any] = 'bar' with tempfile.TemporaryDirectory('test-generation-config') as tmp_dir: generation_config.save_pretrained(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[int] = GenerationConfig.from_pretrained(SCREAMING_SNAKE_CASE__) # update_kwargs was used to update the config on valid attributes self.assertEqual(new_config.foo ,'bar') __lowerCamelCase : Dict = GenerationConfig.from_model_config(SCREAMING_SNAKE_CASE__) assert not hasattr(SCREAMING_SNAKE_CASE__ ,'foo') # no new kwargs should be initialized if from config def lowerCAmelCase ( self : List[str]): __lowerCamelCase : List[str] = GenerationConfig() self.assertEqual(default_config.temperature ,1.0) self.assertEqual(default_config.do_sample ,SCREAMING_SNAKE_CASE__) self.assertEqual(default_config.num_beams ,1) __lowerCamelCase : Any = GenerationConfig( do_sample=SCREAMING_SNAKE_CASE__ ,temperature=0.7 ,length_penalty=1.0 ,bad_words_ids=[[1, 2, 3], [4, 5]] ,) self.assertEqual(config.temperature ,0.7) self.assertEqual(config.do_sample ,SCREAMING_SNAKE_CASE__) self.assertEqual(config.num_beams ,1) with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Tuple = GenerationConfig.from_pretrained(SCREAMING_SNAKE_CASE__ ,temperature=1.0) self.assertEqual(loaded_config.temperature ,1.0) self.assertEqual(loaded_config.do_sample ,SCREAMING_SNAKE_CASE__) self.assertEqual(loaded_config.num_beams ,1) # default value @is_staging_test class A_ ( unittest.TestCase ): @classmethod def lowerCAmelCase ( cls : Optional[Any]): __lowerCamelCase : Union[str, Any] = TOKEN HfFolder.save_token(SCREAMING_SNAKE_CASE__) @classmethod def lowerCAmelCase ( cls : Tuple): try: delete_repo(token=cls._token ,repo_id='test-generation-config') except HTTPError: pass try: delete_repo(token=cls._token ,repo_id='valid_org/test-generation-config-org') except HTTPError: pass def lowerCAmelCase ( self : Any): __lowerCamelCase : Tuple = GenerationConfig( do_sample=SCREAMING_SNAKE_CASE__ ,temperature=0.7 ,length_penalty=1.0 ,) config.push_to_hub('test-generation-config' ,use_auth_token=self._token) __lowerCamelCase : str = GenerationConfig.from_pretrained(F"{USER}/test-generation-config") for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(SCREAMING_SNAKE_CASE__ ,getattr(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__)) # Reset repo delete_repo(token=self._token ,repo_id='test-generation-config') # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained( SCREAMING_SNAKE_CASE__ ,repo_id='test-generation-config' ,push_to_hub=SCREAMING_SNAKE_CASE__ ,use_auth_token=self._token) __lowerCamelCase : List[str] = GenerationConfig.from_pretrained(F"{USER}/test-generation-config") for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(SCREAMING_SNAKE_CASE__ ,getattr(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__)) def lowerCAmelCase ( self : Any): __lowerCamelCase : Tuple = GenerationConfig( do_sample=SCREAMING_SNAKE_CASE__ ,temperature=0.7 ,length_penalty=1.0 ,) config.push_to_hub('valid_org/test-generation-config-org' ,use_auth_token=self._token) __lowerCamelCase : str = GenerationConfig.from_pretrained('valid_org/test-generation-config-org') for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(SCREAMING_SNAKE_CASE__ ,getattr(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__)) # Reset repo delete_repo(token=self._token ,repo_id='valid_org/test-generation-config-org') # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained( SCREAMING_SNAKE_CASE__ ,repo_id='valid_org/test-generation-config-org' ,push_to_hub=SCREAMING_SNAKE_CASE__ ,use_auth_token=self._token) __lowerCamelCase : List[Any] = GenerationConfig.from_pretrained('valid_org/test-generation-config-org') for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(SCREAMING_SNAKE_CASE__ ,getattr(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__))
73
# This is the module that test_patching.py uses to test patch_submodule() import os # noqa: this is just for tests import os as renamed_os # noqa: this is just for tests from os import path # noqa: this is just for tests from os import path as renamed_path # noqa: this is just for tests from os.path import join # noqa: this is just for tests from os.path import join as renamed_join # noqa: this is just for tests a =open # noqa: we just need to have a builtin inside this module to test it properly
73
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, is_vision_available, ) a ={"""processing_layoutxlm""": ["""LayoutXLMProcessor"""]} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a =["""LayoutXLMTokenizer"""] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a =["""LayoutXLMTokenizerFast"""] if TYPE_CHECKING: from .processing_layoutxlm import LayoutXLMProcessor try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_layoutxlm import LayoutXLMTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_layoutxlm_fast import LayoutXLMTokenizerFast else: import sys a =_LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
73
# Function to print upper half of diamond (pyramid) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> str: for i in range(0 , lowerCamelCase__ ): for _ in range(0 , n - i - 1 ): # printing spaces print(' ' , end='' ) for _ in range(0 , i + 1 ): # printing stars print('* ' , end='' ) print() def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Tuple: for i in range(lowerCamelCase__ , 0 , -1 ): for _ in range(lowerCamelCase__ , 0 , -1 ): # printing stars print('* ' , end='' ) print() for _ in range(n - i + 1 , 0 , -1 ): # printing spaces print(' ' , end='' ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Any: if n <= 0: print(' ... .... nothing printing :(' ) return floyd(lowerCamelCase__ ) # upper half reverse_floyd(lowerCamelCase__ ) # lower half if __name__ == "__main__": print(r"""| /\ | |- | |- |--| |\ /| |-""") print(r"""|/ \| |- |_ |_ |__| | \/ | |_""") a =1 while K: a =int(input("""enter the number and , and see the magic : """)) print() pretty_print(user_number) a =int(input("""press 0 to exit... and 1 to continue...""")) print("""Good Bye...""")
73
1
from __future__ import annotations def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> List[str]: # Checks if the entire collection has been sorted if len(lowerCamelCase__ ) <= 1 or n <= 1: return insert_next(lowerCamelCase__ , n - 1 ) rec_insertion_sort(lowerCamelCase__ , n - 1 ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> str: # Checks order between adjacent elements if index >= len(lowerCamelCase__ ) or collection[index - 1] <= collection[index]: return # Swaps adjacent elements since they are not in ascending order __lowerCamelCase , __lowerCamelCase : Union[str, Any] = ( collection[index], collection[index - 1], ) insert_next(lowerCamelCase__ , index + 1 ) if __name__ == "__main__": a =input("""Enter integers separated by spaces: """) a =[int(num) for num in numbers.split()] rec_insertion_sort(number_list, len(number_list)) print(number_list)
73
import re import warnings from contextlib import contextmanager from ...processing_utils import ProcessorMixin class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : Any = ['''image_processor''', '''tokenizer'''] _UpperCAmelCase : List[Any] = '''AutoImageProcessor''' _UpperCAmelCase : Dict = '''AutoTokenizer''' def __init__( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : Optional[int]=None ,SCREAMING_SNAKE_CASE__ : List[Any]=None ,**SCREAMING_SNAKE_CASE__ : Union[str, Any]): __lowerCamelCase : List[str] = None if "feature_extractor" in kwargs: warnings.warn( 'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`' ' instead.' ,SCREAMING_SNAKE_CASE__ ,) __lowerCamelCase : Union[str, Any] = kwargs.pop('feature_extractor') __lowerCamelCase : Dict = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('You need to specify an `image_processor`.') if tokenizer is None: raise ValueError('You need to specify a `tokenizer`.') super().__init__(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Dict = self.image_processor __lowerCamelCase : Optional[int] = False def __call__( self : int ,*SCREAMING_SNAKE_CASE__ : Union[str, Any] ,**SCREAMING_SNAKE_CASE__ : Union[str, Any]): # For backward compatibility if self._in_target_context_manager: return self.current_processor(*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[int] = kwargs.pop('images' ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Union[str, Any] = kwargs.pop('text' ,SCREAMING_SNAKE_CASE__) if len(SCREAMING_SNAKE_CASE__) > 0: __lowerCamelCase : int = args[0] __lowerCamelCase : List[str] = args[1:] if images is None and text is None: raise ValueError('You need to specify either an `images` or `text` input to process.') if images is not None: __lowerCamelCase : Optional[int] = self.image_processor(SCREAMING_SNAKE_CASE__ ,*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) if text is not None: __lowerCamelCase : List[Any] = self.tokenizer(SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) if text is None: return inputs elif images is None: return encodings else: __lowerCamelCase : Optional[Any] = encodings['input_ids'] return inputs def lowerCAmelCase ( self : int ,*SCREAMING_SNAKE_CASE__ : Union[str, Any] ,**SCREAMING_SNAKE_CASE__ : Dict): return self.tokenizer.batch_decode(*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Optional[Any] ,*SCREAMING_SNAKE_CASE__ : List[Any] ,**SCREAMING_SNAKE_CASE__ : Any): return self.tokenizer.decode(*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) @contextmanager def lowerCAmelCase ( self : Tuple): warnings.warn( '`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your ' 'labels by using the argument `text` of the regular `__call__` method (either in the same call as ' 'your images inputs, or in a separate call.') __lowerCamelCase : List[Any] = True __lowerCamelCase : str = self.tokenizer yield __lowerCamelCase : Tuple = self.image_processor __lowerCamelCase : Tuple = False def lowerCAmelCase ( self : Any ,SCREAMING_SNAKE_CASE__ : str ,SCREAMING_SNAKE_CASE__ : int=False ,SCREAMING_SNAKE_CASE__ : List[Any]=None): if added_vocab is None: __lowerCamelCase : str = self.tokenizer.get_added_vocab() __lowerCamelCase : Union[str, Any] = {} while tokens: __lowerCamelCase : Tuple = re.search(R'<s_(.*?)>' ,SCREAMING_SNAKE_CASE__ ,re.IGNORECASE) if start_token is None: break __lowerCamelCase : Dict = start_token.group(1) __lowerCamelCase : List[str] = re.search(RF"</s_{key}>" ,SCREAMING_SNAKE_CASE__ ,re.IGNORECASE) __lowerCamelCase : Optional[int] = start_token.group() if end_token is None: __lowerCamelCase : List[Any] = tokens.replace(SCREAMING_SNAKE_CASE__ ,'') else: __lowerCamelCase : Tuple = end_token.group() __lowerCamelCase : int = re.escape(SCREAMING_SNAKE_CASE__) __lowerCamelCase : str = re.escape(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Union[str, Any] = re.search(F"{start_token_escaped}(.*?){end_token_escaped}" ,SCREAMING_SNAKE_CASE__ ,re.IGNORECASE) if content is not None: __lowerCamelCase : List[Any] = content.group(1).strip() if r"<s_" in content and r"</s_" in content: # non-leaf node __lowerCamelCase : str = self.tokenajson(SCREAMING_SNAKE_CASE__ ,is_inner_value=SCREAMING_SNAKE_CASE__ ,added_vocab=SCREAMING_SNAKE_CASE__) if value: if len(SCREAMING_SNAKE_CASE__) == 1: __lowerCamelCase : Tuple = value[0] __lowerCamelCase : int = value else: # leaf nodes __lowerCamelCase : Tuple = [] for leaf in content.split(R'<sep/>'): __lowerCamelCase : List[Any] = leaf.strip() if leaf in added_vocab and leaf[0] == "<" and leaf[-2:] == "/>": __lowerCamelCase : str = leaf[1:-2] # for categorical special tokens output[key].append(SCREAMING_SNAKE_CASE__) if len(output[key]) == 1: __lowerCamelCase : Dict = output[key][0] __lowerCamelCase : Dict = tokens[tokens.find(SCREAMING_SNAKE_CASE__) + len(SCREAMING_SNAKE_CASE__) :].strip() if tokens[:6] == r"<sep/>": # non-leaf nodes return [output] + self.tokenajson(tokens[6:] ,is_inner_value=SCREAMING_SNAKE_CASE__ ,added_vocab=SCREAMING_SNAKE_CASE__) if len(SCREAMING_SNAKE_CASE__): return [output] if is_inner_value else output else: return [] if is_inner_value else {"text_sequence": tokens} @property def lowerCAmelCase ( self : List[str]): warnings.warn( '`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.' ,SCREAMING_SNAKE_CASE__ ,) return self.image_processor_class @property def lowerCAmelCase ( self : List[Any]): warnings.warn( '`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.' ,SCREAMING_SNAKE_CASE__ ,) return self.image_processor
73
1
from scipy.stats import spearmanr import datasets a =""" The Spearman rank-order correlation coefficient is a measure of the relationship between two datasets. Like other correlation coefficients, this one varies between -1 and +1 with 0 implying no correlation. Positive correlations imply that as data in dataset x increases, so does data in dataset y. Negative correlations imply that as x increases, y decreases. Correlations of -1 or +1 imply an exact monotonic relationship. Unlike the Pearson correlation, the Spearman correlation does not assume that both datasets are normally distributed. The p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Spearman correlation at least as extreme as the one computed from these datasets. The p-values are not entirely reliable but are probably reasonable for datasets larger than 500 or so. """ a =""" Args: predictions (`List[float]`): Predicted labels, as returned by a model. references (`List[float]`): Ground truth labels. return_pvalue (`bool`): If `True`, returns the p-value. If `False`, returns only the spearmanr score. Defaults to `False`. Returns: spearmanr (`float`): Spearman correlation coefficient. p-value (`float`): p-value. **Note**: is only returned if `return_pvalue=True` is input. Examples: Example 1: >>> spearmanr_metric = datasets.load_metric(\"spearmanr\") >>> results = spearmanr_metric.compute(references=[1, 2, 3, 4, 5], predictions=[10, 9, 2.5, 6, 4]) >>> print(results) {'spearmanr': -0.7} Example 2: >>> spearmanr_metric = datasets.load_metric(\"spearmanr\") >>> results = spearmanr_metric.compute(references=[1, 2, 3, 4, 5], ... predictions=[10, 9, 2.5, 6, 4], ... return_pvalue=True) >>> print(results['spearmanr']) -0.7 >>> print(round(results['spearmanr_pvalue'], 2)) 0.19 """ a =r"""\ @book{kokoska2000crc, title={CRC standard probability and statistics tables and formulae}, author={Kokoska, Stephen and Zwillinger, Daniel}, year={2000}, publisher={Crc Press} } @article{2020SciPy-NMeth, author = {Virtanen, Pauli and Gommers, Ralf and Oliphant, Travis E. and Haberland, Matt and Reddy, Tyler and Cournapeau, David and Burovski, Evgeni and Peterson, Pearu and Weckesser, Warren and Bright, Jonathan and {van der Walt}, St{\'e}fan J. and Brett, Matthew and Wilson, Joshua and Millman, K. Jarrod and Mayorov, Nikolay and Nelson, Andrew R. J. and Jones, Eric and Kern, Robert and Larson, Eric and Carey, C J and Polat, {\.I}lhan and Feng, Yu and Moore, Eric W. and {VanderPlas}, Jake and Laxalde, Denis and Perktold, Josef and Cimrman, Robert and Henriksen, Ian and Quintero, E. A. and Harris, Charles R. and Archibald, Anne M. and Ribeiro, Ant{\^o}nio H. and Pedregosa, Fabian and {van Mulbregt}, Paul and {SciPy 1.0 Contributors}}, title = {{{SciPy} 1.0: Fundamental Algorithms for Scientific Computing in Python}}, journal = {Nature Methods}, year = {2020}, volume = {17}, pages = {261--272}, adsurl = {https://rdcu.be/b08Wh}, doi = {10.1038/s41592-019-0686-2}, } """ @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class A_ ( datasets.Metric ): def lowerCAmelCase ( self : Tuple): return datasets.MetricInfo( description=_DESCRIPTION ,citation=_CITATION ,inputs_description=_KWARGS_DESCRIPTION ,features=datasets.Features( { 'predictions': datasets.Value('float'), 'references': datasets.Value('float'), }) ,reference_urls=['https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.spearmanr.html'] ,) def lowerCAmelCase ( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : Dict ,SCREAMING_SNAKE_CASE__ : str ,SCREAMING_SNAKE_CASE__ : int=False): __lowerCamelCase : Any = spearmanr(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) if return_pvalue: return {"spearmanr": results[0], "spearmanr_pvalue": results[1]} else: return {"spearmanr": results[0]}
73
def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> int: __lowerCamelCase : Optional[int] = 0 __lowerCamelCase : Dict = len(lowerCamelCase__ ) - 1 while left <= right: # avoid divided by 0 during interpolation if sorted_collection[left] == sorted_collection[right]: if sorted_collection[left] == item: return left else: return None __lowerCamelCase : str = left + ((item - sorted_collection[left]) * (right - left)) // ( sorted_collection[right] - sorted_collection[left] ) # out of range check if point < 0 or point >= len(lowerCamelCase__ ): return None __lowerCamelCase : Tuple = sorted_collection[point] if current_item == item: return point else: if point < left: __lowerCamelCase : List[Any] = left __lowerCamelCase : Tuple = point elif point > right: __lowerCamelCase : Dict = right __lowerCamelCase : str = point else: if item < current_item: __lowerCamelCase : Dict = point - 1 else: __lowerCamelCase : Dict = point + 1 return None def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> Any: # avoid divided by 0 during interpolation if sorted_collection[left] == sorted_collection[right]: if sorted_collection[left] == item: return left else: return None __lowerCamelCase : Optional[int] = left + ((item - sorted_collection[left]) * (right - left)) // ( sorted_collection[right] - sorted_collection[left] ) # out of range check if point < 0 or point >= len(lowerCamelCase__ ): return None if sorted_collection[point] == item: return point elif point < left: return interpolation_search_by_recursion(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) elif point > right: return interpolation_search_by_recursion(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) else: if sorted_collection[point] > item: return interpolation_search_by_recursion( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , point - 1 ) else: return interpolation_search_by_recursion( lowerCamelCase__ , lowerCamelCase__ , point + 1 , lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Optional[Any]: if collection != sorted(lowerCamelCase__ ): raise ValueError('Collection must be ascending sorted' ) return True if __name__ == "__main__": import sys a =0 if debug == 1: a =[10, 30, 40, 45, 50, 66, 77, 93] try: __assert_sorted(collection) except ValueError: sys.exit("""Sequence must be ascending sorted to apply interpolation search""") a =67 a =interpolation_search(collection, target) if result is not None: print(F"""{target} found at positions: {result}""") else: print("""Not found""")
73
1
import argparse import json import os import fairseq import torch from fairseq.data import Dictionary from transformers import ( UniSpeechConfig, UniSpeechForCTC, UniSpeechForPreTraining, WavaVecaFeatureExtractor, WavaVecaPhonemeCTCTokenizer, WavaVecaProcessor, logging, ) logging.set_verbosity_info() a =logging.get_logger(__name__) a ={ """post_extract_proj""": """feature_projection.projection""", """encoder.pos_conv.0""": """encoder.pos_conv_embed.conv""", """self_attn.k_proj""": """encoder.layers.*.attention.k_proj""", """self_attn.v_proj""": """encoder.layers.*.attention.v_proj""", """self_attn.q_proj""": """encoder.layers.*.attention.q_proj""", """self_attn.out_proj""": """encoder.layers.*.attention.out_proj""", """self_attn_layer_norm""": """encoder.layers.*.layer_norm""", """fc1""": """encoder.layers.*.feed_forward.intermediate_dense""", """fc2""": """encoder.layers.*.feed_forward.output_dense""", """final_layer_norm""": """encoder.layers.*.final_layer_norm""", """encoder.layer_norm""": """encoder.layer_norm""", """w2v_model.layer_norm""": """feature_projection.layer_norm""", """quantizer.weight_proj""": """quantizer.weight_proj""", """quantizer.vars""": """quantizer.codevectors""", """project_q""": """project_q""", """final_proj""": """project_hid""", """w2v_encoder.proj""": """ctc_proj""", """mask_emb""": """masked_spec_embed""", } a =[ """ctc_proj""", """quantizer.weight_proj""", """quantizer.codevectors""", """project_q""", """project_hid""", ] def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> Dict: for attribute in key.split('.' ): if is_finetuned: if attribute in ["quantizer", "project_q", "project_hid"]: # those layers are only relevant for pretraining and should be dropped return if attribute == "ctc_proj": # we should rename `ctc_proj` to `lm_head` for fine-tuned phoneme models __lowerCamelCase : List[Any] = 'lm_head' __lowerCamelCase : Optional[int] = getattr(lowerCamelCase__ , lowerCamelCase__ ) if weight_type is not None: __lowerCamelCase : List[str] = getattr(lowerCamelCase__ , lowerCamelCase__ ).shape else: __lowerCamelCase : Dict = hf_pointer.shape assert hf_shape == value.shape, ( F"Shape of hf {key + '.' + weight_type if weight_type is not None else ''} is {hf_shape}, but should be" F" {value.shape} for {full_name}" ) if weight_type == "weight": __lowerCamelCase : Tuple = value elif weight_type == "weight_g": __lowerCamelCase : Tuple = value elif weight_type == "weight_v": __lowerCamelCase : Optional[Any] = value elif weight_type == "bias": __lowerCamelCase : List[str] = value else: __lowerCamelCase : Optional[int] = value logger.info(F"{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}." ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> Optional[int]: __lowerCamelCase : Tuple = [] __lowerCamelCase : Optional[Any] = fairseq_model.state_dict() __lowerCamelCase : Tuple = hf_model.unispeech.feature_extractor for name, value in fairseq_dict.items(): __lowerCamelCase : int = False if "conv_layers" in name: load_conv_layer( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , hf_model.config.feat_extract_norm == 'group' , ) __lowerCamelCase : Optional[Any] = True else: for key, mapped_key in MAPPING.items(): __lowerCamelCase : Union[str, Any] = 'unispeech.' + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key if key in name or key.split('w2v_model.' )[-1] == name.split('.' )[0]: __lowerCamelCase : List[str] = True if "*" in mapped_key: __lowerCamelCase : Any = name.split(lowerCamelCase__ )[0].split('.' )[-2] __lowerCamelCase : Union[str, Any] = mapped_key.replace('*' , lowerCamelCase__ ) if "weight_g" in name: __lowerCamelCase : Optional[int] = 'weight_g' elif "weight_v" in name: __lowerCamelCase : str = 'weight_v' elif "bias" in name: __lowerCamelCase : Dict = 'bias' elif "weight" in name: # TODO: don't match quantizer.weight_proj __lowerCamelCase : List[Any] = 'weight' else: __lowerCamelCase : Any = None set_recursively(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) continue if not is_used: unused_weights.append(lowerCamelCase__ ) logger.warning(F"Unused weights: {unused_weights}" ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> Optional[int]: __lowerCamelCase : str = full_name.split('conv_layers.' )[-1] __lowerCamelCase : Dict = name.split('.' ) __lowerCamelCase : Dict = int(items[0] ) __lowerCamelCase : int = int(items[1] ) if type_id == 0: if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, ( F"{full_name} has size {value.shape}, but" F" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found." ) __lowerCamelCase : Tuple = value logger.info(F"Feat extract conv layer {layer_id} was initialized from {full_name}." ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, ( F"{full_name} has size {value.shape}, but" F" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found." ) __lowerCamelCase : int = value logger.info(F"Feat extract conv layer {layer_id} was initialized from {full_name}." ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, ( F"{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was" " found." ) __lowerCamelCase : Optional[Any] = value logger.info(F"Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}." ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, ( F"{full_name} has size {value.shape}, but" F" {feature_extractor[layer_id].layer_norm.weight.data.shape} was found." ) __lowerCamelCase : List[str] = value logger.info(F"Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}." ) else: unused_weights.append(lowerCamelCase__ ) @torch.no_grad() def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__=None , lowerCamelCase__=None , lowerCamelCase__=True ) -> int: if config_path is not None: __lowerCamelCase : Tuple = UniSpeechConfig.from_pretrained(lowerCamelCase__ ) else: __lowerCamelCase : int = UniSpeechConfig() if is_finetuned: if dict_path: __lowerCamelCase : Tuple = Dictionary.load_from_json(lowerCamelCase__ ) # important change bos & pad token id since CTC symbol is <pad> and # not <s> as in fairseq __lowerCamelCase : Tuple = target_dict.pad_index __lowerCamelCase : Optional[Any] = target_dict.bos_index __lowerCamelCase : int = target_dict.eos_index __lowerCamelCase : List[str] = len(target_dict.symbols ) __lowerCamelCase : List[str] = os.path.join(lowerCamelCase__ , 'vocab.json' ) if not os.path.isdir(lowerCamelCase__ ): logger.error('--pytorch_dump_folder_path ({}) should be a directory'.format(lowerCamelCase__ ) ) return os.makedirs(lowerCamelCase__ , exist_ok=lowerCamelCase__ ) __lowerCamelCase : List[Any] = target_dict.indices # fairseq has the <pad> and <s> switched __lowerCamelCase : int = 4_2 __lowerCamelCase : Tuple = 4_3 with open(lowerCamelCase__ , 'w' , encoding='utf-8' ) as vocab_handle: json.dump(lowerCamelCase__ , lowerCamelCase__ ) __lowerCamelCase : Dict = WavaVecaPhonemeCTCTokenizer( lowerCamelCase__ , unk_token=target_dict.unk_word , pad_token=target_dict.pad_word , bos_token=target_dict.bos_word , eos_token=target_dict.eos_word , word_delimiter_token='|' , do_lower_case=lowerCamelCase__ , ) __lowerCamelCase : Optional[Any] = True if config.feat_extract_norm == 'layer' else False __lowerCamelCase : List[Any] = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=1_6_0_0_0 , padding_value=0 , do_normalize=lowerCamelCase__ , return_attention_mask=lowerCamelCase__ , ) __lowerCamelCase : int = WavaVecaProcessor(feature_extractor=lowerCamelCase__ , tokenizer=lowerCamelCase__ ) processor.save_pretrained(lowerCamelCase__ ) __lowerCamelCase : List[Any] = UniSpeechForCTC(lowerCamelCase__ ) else: __lowerCamelCase : str = UniSpeechForPreTraining(lowerCamelCase__ ) if is_finetuned: __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : Dict = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={'data': '/'.join(dict_path.split('/' )[:-1] ), 'w2v_path': checkpoint_path} ) else: __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : Tuple = fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path] ) __lowerCamelCase : Optional[Any] = model[0].eval() recursively_load_weights(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) hf_unispeech.save_pretrained(lowerCamelCase__ ) if __name__ == "__main__": a =argparse.ArgumentParser() parser.add_argument("""--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model.""") parser.add_argument("""--checkpoint_path""", default=None, type=str, help="""Path to fairseq checkpoint""") parser.add_argument("""--dict_path""", default=None, type=str, help="""Path to dict of fine-tuned model""") parser.add_argument("""--config_path""", default=None, type=str, help="""Path to hf config.json of model to convert""") parser.add_argument( """--not_finetuned""", action="""store_true""", help="""Whether the model to convert is a fine-tuned model or not""" ) a =parser.parse_args() convert_unispeech_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned )
73
import json import os import subprocess import unittest from ast import literal_eval import pytest from parameterized import parameterized, parameterized_class from . import is_sagemaker_available if is_sagemaker_available(): from sagemaker import Session, TrainingJobAnalytics from sagemaker.huggingface import HuggingFace @pytest.mark.skipif( literal_eval(os.getenv('''TEST_SAGEMAKER''' , '''False''' ) ) is not True , reason='''Skipping test because should only be run when releasing minor transformers version''' , ) @pytest.mark.usefixtures('''sm_env''' ) @parameterized_class( [ { '''framework''': '''pytorch''', '''script''': '''run_glue_model_parallelism.py''', '''model_name_or_path''': '''roberta-large''', '''instance_type''': '''ml.p3dn.24xlarge''', '''results''': {'''train_runtime''': 1_600, '''eval_accuracy''': 0.3, '''eval_loss''': 1.2}, }, { '''framework''': '''pytorch''', '''script''': '''run_glue.py''', '''model_name_or_path''': '''roberta-large''', '''instance_type''': '''ml.p3dn.24xlarge''', '''results''': {'''train_runtime''': 1_600, '''eval_accuracy''': 0.3, '''eval_loss''': 1.2}, }, ] ) class A_ ( unittest.TestCase ): def lowerCAmelCase ( self : Union[str, Any]): if self.framework == "pytorch": subprocess.run( F"cp ./examples/pytorch/text-classification/run_glue.py {self.env.test_path}/run_glue.py".split() ,encoding='utf-8' ,check=SCREAMING_SNAKE_CASE__ ,) assert hasattr(self ,'env') def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : int): # configuration for running training on smdistributed Model Parallel __lowerCamelCase : Any = { 'enabled': True, 'processes_per_host': 8, } __lowerCamelCase : List[Any] = { 'enabled': True, 'parameters': { 'microbatches': 4, 'placement_strategy': 'spread', 'pipeline': 'interleaved', 'optimize': 'speed', 'partitions': 4, 'ddp': True, }, } __lowerCamelCase : str = {'smdistributed': {'modelparallel': smp_options}, 'mpi': mpi_options} __lowerCamelCase : List[str] = 'trainer' if self.script == 'run_glue.py' else 'smtrainer' # creates estimator return HuggingFace( entry_point=self.script ,source_dir=self.env.test_path ,role=self.env.role ,image_uri=self.env.image_uri ,base_job_name=F"{self.env.base_job_name}-{instance_count}-smp-{name_extension}" ,instance_count=SCREAMING_SNAKE_CASE__ ,instance_type=self.instance_type ,debugger_hook_config=SCREAMING_SNAKE_CASE__ ,hyperparameters={ **self.env.hyperparameters, 'model_name_or_path': self.model_name_or_path, 'max_steps': 5_0_0, } ,metric_definitions=self.env.metric_definitions ,distribution=SCREAMING_SNAKE_CASE__ ,py_version='py36' ,) def lowerCAmelCase ( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : Any): TrainingJobAnalytics(SCREAMING_SNAKE_CASE__).export_csv(F"{self.env.test_path}/{job_name}_metrics.csv") @parameterized.expand([(1,)]) def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : Optional[Any]): # create estimator __lowerCamelCase : str = self.create_estimator(SCREAMING_SNAKE_CASE__) # run training estimator.fit() # result dataframe __lowerCamelCase : List[str] = TrainingJobAnalytics(estimator.latest_training_job.name).dataframe() # extract kpis __lowerCamelCase : Optional[int] = list(result_metrics_df[result_metrics_df.metric_name == 'eval_accuracy']['value']) __lowerCamelCase : Any = list(result_metrics_df[result_metrics_df.metric_name == 'eval_loss']['value']) # get train time from SageMaker job, this includes starting, preprocessing, stopping __lowerCamelCase : str = ( Session().describe_training_job(estimator.latest_training_job.name).get('TrainingTimeInSeconds' ,9_9_9_9_9_9) ) # assert kpis assert train_runtime <= self.results["train_runtime"] assert all(t >= self.results['eval_accuracy'] for t in eval_accuracy) assert all(t <= self.results['eval_loss'] for t in eval_loss) # dump tests result into json file to share in PR with open(F"{estimator.latest_training_job.name}.json" ,'w') as outfile: json.dump({'train_time': train_runtime, 'eval_accuracy': eval_accuracy, 'eval_loss': eval_loss} ,SCREAMING_SNAKE_CASE__)
73
1
import numpy as np from scipy.spatial.distance import cdist from sklearn.metrics import fa_score import datasets a ="""\ @inproceedings{kakwani2020indicnlpsuite, title={{IndicNLPSuite: Monolingual Corpora, Evaluation Benchmarks and Pre-trained Multilingual Language Models for Indian Languages}}, author={Divyanshu Kakwani and Anoop Kunchukuttan and Satish Golla and Gokul N.C. and Avik Bhattacharyya and Mitesh M. Khapra and Pratyush Kumar}, year={2020}, booktitle={Findings of EMNLP}, } """ a ="""\ IndicGLUE is a natural language understanding benchmark for Indian languages. It contains a wide variety of tasks and covers 11 major Indian languages - as, bn, gu, hi, kn, ml, mr, or, pa, ta, te. """ a =""" Compute IndicGLUE evaluation metric associated to each IndicGLUE dataset. Args: predictions: list of predictions to score (as int64), except for 'cvit-mkb-clsr' where each prediction is a vector (of float32). references: list of ground truth labels corresponding to the predictions (as int64), except for 'cvit-mkb-clsr' where each reference is a vector (of float32). Returns: depending on the IndicGLUE subset, one or several of: \"accuracy\": Accuracy \"f1\": F1 score \"precision\": Precision@10 Examples: >>> indic_glue_metric = datasets.load_metric('indic_glue', 'wnli') # 'wnli' or any of [\"copa\", \"sna\", \"csqa\", \"wstp\", \"inltkh\", \"bbca\", \"iitp-mr\", \"iitp-pr\", \"actsa-sc\", \"md\"] >>> references = [0, 1] >>> predictions = [0, 1] >>> results = indic_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {'accuracy': 1.0} >>> indic_glue_metric = datasets.load_metric('indic_glue', 'wiki-ner') >>> references = [0, 1] >>> predictions = [0, 1] >>> results = indic_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {'accuracy': 1.0, 'f1': 1.0} >>> indic_glue_metric = datasets.load_metric('indic_glue', 'cvit-mkb-clsr') >>> references = [[0.5, 0.5, 0.5], [0.1, 0.2, 0.3]] >>> predictions = [[0.5, 0.5, 0.5], [0.1, 0.2, 0.3]] >>> results = indic_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {'precision@10': 1.0} """ def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> List[str]: return float((preds == labels).mean() ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> List[str]: __lowerCamelCase : Optional[Any] = simple_accuracy(lowerCamelCase__ , lowerCamelCase__ ) __lowerCamelCase : Tuple = float(fa_score(y_true=lowerCamelCase__ , y_pred=lowerCamelCase__ ) ) return { "accuracy": acc, "f1": fa, } def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> Optional[Any]: __lowerCamelCase : Any = np.array(lowerCamelCase__ ) __lowerCamelCase : List[Any] = np.array(lowerCamelCase__ ) __lowerCamelCase : Any = en_sentvecs.shape[0] # mean centering __lowerCamelCase : Union[str, Any] = en_sentvecs - np.mean(lowerCamelCase__ , axis=0 ) __lowerCamelCase : Dict = in_sentvecs - np.mean(lowerCamelCase__ , axis=0 ) __lowerCamelCase : Optional[int] = cdist(lowerCamelCase__ , lowerCamelCase__ , 'cosine' ) __lowerCamelCase : Optional[Any] = np.array(range(lowerCamelCase__ ) ) __lowerCamelCase : Dict = sim.argsort(axis=1 )[:, :1_0] __lowerCamelCase : Optional[int] = np.any(preds == actual[:, None] , axis=1 ) return float(matches.mean() ) @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class A_ ( datasets.Metric ): def lowerCAmelCase ( self : Optional[Any]): if self.config_name not in [ "wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", "cvit-mkb-clsr", "iitp-mr", "iitp-pr", "actsa-sc", "md", "wiki-ner", ]: raise KeyError( 'You should supply a configuration name selected in ' '["wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", ' '"cvit-mkb-clsr", "iitp-mr", "iitp-pr", "actsa-sc", "md", ' '"wiki-ner"]') return datasets.MetricInfo( description=_DESCRIPTION ,citation=_CITATION ,inputs_description=_KWARGS_DESCRIPTION ,features=datasets.Features( { 'predictions': datasets.Value('int64') if self.config_name != 'cvit-mkb-clsr' else datasets.Sequence(datasets.Value('float32')), 'references': datasets.Value('int64') if self.config_name != 'cvit-mkb-clsr' else datasets.Sequence(datasets.Value('float32')), }) ,codebase_urls=[] ,reference_urls=[] ,format='numpy' if self.config_name != 'cvit-mkb-clsr' else None ,) def lowerCAmelCase ( self : Any ,SCREAMING_SNAKE_CASE__ : Tuple ,SCREAMING_SNAKE_CASE__ : Optional[Any]): if self.config_name == "cvit-mkb-clsr": return {"precision@10": precision_at_aa(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__)} elif self.config_name in ["wiki-ner"]: return acc_and_fa(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) elif self.config_name in [ "wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", "iitp-mr", "iitp-pr", "actsa-sc", "md", ]: return {"accuracy": simple_accuracy(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__)} else: raise KeyError( 'You should supply a configuration name selected in ' '["wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", ' '"cvit-mkb-clsr", "iitp-mr", "iitp-pr", "actsa-sc", "md", ' '"wiki-ner"]')
73
import unittest import numpy as np from transformers import DistilBertConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask if is_flax_available(): import jax.numpy as jnp from transformers.models.distilbert.modeling_flax_distilbert import ( FlaxDistilBertForMaskedLM, FlaxDistilBertForMultipleChoice, FlaxDistilBertForQuestionAnswering, FlaxDistilBertForSequenceClassification, FlaxDistilBertForTokenClassification, FlaxDistilBertModel, ) class A_ ( unittest.TestCase ): def __init__( self : Tuple ,SCREAMING_SNAKE_CASE__ : List[str] ,SCREAMING_SNAKE_CASE__ : Any=1_3 ,SCREAMING_SNAKE_CASE__ : int=7 ,SCREAMING_SNAKE_CASE__ : str=True ,SCREAMING_SNAKE_CASE__ : Dict=True ,SCREAMING_SNAKE_CASE__ : str=True ,SCREAMING_SNAKE_CASE__ : Dict=True ,SCREAMING_SNAKE_CASE__ : List[Any]=9_9 ,SCREAMING_SNAKE_CASE__ : List[Any]=3_2 ,SCREAMING_SNAKE_CASE__ : int=5 ,SCREAMING_SNAKE_CASE__ : List[Any]=4 ,SCREAMING_SNAKE_CASE__ : Optional[Any]=3_7 ,SCREAMING_SNAKE_CASE__ : Union[str, Any]="gelu" ,SCREAMING_SNAKE_CASE__ : int=0.1 ,SCREAMING_SNAKE_CASE__ : Optional[int]=0.1 ,SCREAMING_SNAKE_CASE__ : Optional[int]=5_1_2 ,SCREAMING_SNAKE_CASE__ : Dict=1_6 ,SCREAMING_SNAKE_CASE__ : Dict=2 ,SCREAMING_SNAKE_CASE__ : Optional[int]=0.02 ,SCREAMING_SNAKE_CASE__ : Dict=4 ,): __lowerCamelCase : int = parent __lowerCamelCase : Dict = batch_size __lowerCamelCase : Union[str, Any] = seq_length __lowerCamelCase : List[Any] = is_training __lowerCamelCase : Tuple = use_attention_mask __lowerCamelCase : List[str] = use_token_type_ids __lowerCamelCase : Any = use_labels __lowerCamelCase : List[str] = vocab_size __lowerCamelCase : Any = hidden_size __lowerCamelCase : Tuple = num_hidden_layers __lowerCamelCase : Union[str, Any] = num_attention_heads __lowerCamelCase : Union[str, Any] = intermediate_size __lowerCamelCase : List[Any] = hidden_act __lowerCamelCase : int = hidden_dropout_prob __lowerCamelCase : int = attention_probs_dropout_prob __lowerCamelCase : Union[str, Any] = max_position_embeddings __lowerCamelCase : Union[str, Any] = type_vocab_size __lowerCamelCase : List[str] = type_sequence_label_size __lowerCamelCase : Tuple = initializer_range __lowerCamelCase : Optional[int] = num_choices def lowerCAmelCase ( self : Union[str, Any]): __lowerCamelCase : Dict = ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size) __lowerCamelCase : Union[str, Any] = None if self.use_attention_mask: __lowerCamelCase : Any = random_attention_mask([self.batch_size, self.seq_length]) __lowerCamelCase : str = DistilBertConfig( vocab_size=self.vocab_size ,dim=self.hidden_size ,n_layers=self.num_hidden_layers ,n_heads=self.num_attention_heads ,hidden_dim=self.intermediate_size ,hidden_act=self.hidden_act ,dropout=self.hidden_dropout_prob ,attention_dropout=self.attention_probs_dropout_prob ,max_position_embeddings=self.max_position_embeddings ,initializer_range=self.initializer_range ,tie_weights_=SCREAMING_SNAKE_CASE__ ,) return config, input_ids, attention_mask def lowerCAmelCase ( self : List[Any]): __lowerCamelCase : List[str] = self.prepare_config_and_inputs() __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : Dict = config_and_inputs __lowerCamelCase : Any = {'input_ids': input_ids, 'attention_mask': attention_mask} return config, inputs_dict @require_flax class A_ ( SCREAMING_SNAKE_CASE , unittest.TestCase ): _UpperCAmelCase : Dict = ( ( FlaxDistilBertModel, FlaxDistilBertForMaskedLM, FlaxDistilBertForMultipleChoice, FlaxDistilBertForQuestionAnswering, FlaxDistilBertForSequenceClassification, FlaxDistilBertForTokenClassification, FlaxDistilBertForQuestionAnswering, ) if is_flax_available() else () ) def lowerCAmelCase ( self : Optional[Any]): __lowerCamelCase : Tuple = FlaxDistilBertModelTester(self) @slow def lowerCAmelCase ( self : int): for model_class_name in self.all_model_classes: __lowerCamelCase : List[Any] = model_class_name.from_pretrained('distilbert-base-uncased') __lowerCamelCase : List[str] = model(np.ones((1, 1))) self.assertIsNotNone(SCREAMING_SNAKE_CASE__) @require_flax class A_ ( unittest.TestCase ): @slow def lowerCAmelCase ( self : str): __lowerCamelCase : Union[str, Any] = FlaxDistilBertModel.from_pretrained('distilbert-base-uncased') __lowerCamelCase : str = np.array([[0, 3_4_5, 2_3_2, 3_2_8, 7_4_0, 1_4_0, 1_6_9_5, 6_9, 6_0_7_8, 1_5_8_8, 2]]) __lowerCamelCase : List[Any] = np.array([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]) __lowerCamelCase : Union[str, Any] = model(SCREAMING_SNAKE_CASE__ ,attention_mask=SCREAMING_SNAKE_CASE__)[0] __lowerCamelCase : Optional[int] = (1, 1_1, 7_6_8) self.assertEqual(output.shape ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Union[str, Any] = np.array([[[-0.1639, 0.3299, 0.1648], [-0.1746, 0.3289, 0.1710], [-0.1884, 0.3357, 0.1810]]]) self.assertTrue(jnp.allclose(output[:, 1:4, 1:4] ,SCREAMING_SNAKE_CASE__ ,atol=1E-4))
73
1
import argparse import struct import unittest class A_ : def __init__( self : List[str] ,SCREAMING_SNAKE_CASE__ : bytes): __lowerCamelCase : Dict = data # Initialize hash values __lowerCamelCase : List[str] = [ 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19, ] # Initialize round constants __lowerCamelCase : Tuple = [ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2, ] __lowerCamelCase : int = self.preprocessing(self.data) self.final_hash() @staticmethod def lowerCAmelCase ( SCREAMING_SNAKE_CASE__ : bytes): __lowerCamelCase : List[Any] = b'\x80' + (b'\x00' * (6_3 - (len(SCREAMING_SNAKE_CASE__) + 8) % 6_4)) __lowerCamelCase : List[Any] = struct.pack('>Q' ,(len(SCREAMING_SNAKE_CASE__) * 8)) return data + padding + big_endian_integer def lowerCAmelCase ( self : List[Any]): # Convert into blocks of 64 bytes __lowerCamelCase : Dict = [ self.preprocessed_data[x : x + 6_4] for x in range(0 ,len(self.preprocessed_data) ,6_4) ] for block in self.blocks: # Convert the given block into a list of 4 byte integers __lowerCamelCase : Optional[Any] = list(struct.unpack('>16L' ,SCREAMING_SNAKE_CASE__)) # add 48 0-ed integers words += [0] * 4_8 __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : List[str] = self.hashes for index in range(0 ,6_4): if index > 1_5: # modify the zero-ed indexes at the end of the array __lowerCamelCase : Any = ( self.ror(words[index - 1_5] ,7) ^ self.ror(words[index - 1_5] ,1_8) ^ (words[index - 1_5] >> 3) ) __lowerCamelCase : Tuple = ( self.ror(words[index - 2] ,1_7) ^ self.ror(words[index - 2] ,1_9) ^ (words[index - 2] >> 1_0) ) __lowerCamelCase : List[Any] = ( words[index - 1_6] + sa + words[index - 7] + sa ) % 0x100000000 # Compression __lowerCamelCase : Any = self.ror(SCREAMING_SNAKE_CASE__ ,6) ^ self.ror(SCREAMING_SNAKE_CASE__ ,1_1) ^ self.ror(SCREAMING_SNAKE_CASE__ ,2_5) __lowerCamelCase : Tuple = (e & f) ^ ((~e & 0xffffffff) & g) __lowerCamelCase : str = ( h + sa + ch + self.round_constants[index] + words[index] ) % 0x100000000 __lowerCamelCase : Dict = self.ror(SCREAMING_SNAKE_CASE__ ,2) ^ self.ror(SCREAMING_SNAKE_CASE__ ,1_3) ^ self.ror(SCREAMING_SNAKE_CASE__ ,2_2) __lowerCamelCase : Any = (a & b) ^ (a & c) ^ (b & c) __lowerCamelCase : int = (sa + maj) % 0x100000000 __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : Dict = ( g, f, e, ((d + tempa) % 0x100000000), c, b, a, ((tempa + tempa) % 0x100000000), ) __lowerCamelCase : Tuple = [a, b, c, d, e, f, g, h] # Modify final values __lowerCamelCase : Dict = [ ((element + mutated_hash_values[index]) % 0x100000000) for index, element in enumerate(self.hashes) ] __lowerCamelCase : Any = ''.join([hex(SCREAMING_SNAKE_CASE__)[2:].zfill(8) for value in self.hashes]) def lowerCAmelCase ( self : Any ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int): return 0xffffffff & (value << (3_2 - rotations)) | (value >> rotations) class A_ ( unittest.TestCase ): def lowerCAmelCase ( self : List[str]): import hashlib __lowerCamelCase : List[str] = bytes('Test String' ,'utf-8') self.assertEqual(SHAaaa(SCREAMING_SNAKE_CASE__).hash ,hashlib.shaaaa(SCREAMING_SNAKE_CASE__).hexdigest()) def SCREAMING_SNAKE_CASE__ ( ) -> None: import doctest doctest.testmod() __lowerCamelCase : List[str] = argparse.ArgumentParser() parser.add_argument( '-s' , '--string' , dest='input_string' , default='Hello World!! Welcome to Cryptography' , help='Hash the string' , ) parser.add_argument( '-f' , '--file' , dest='input_file' , help='Hash contents of a file' ) __lowerCamelCase : Optional[Any] = parser.parse_args() __lowerCamelCase : str = args.input_string # hash input should be a bytestring if args.input_file: with open(args.input_file , 'rb' ) as f: __lowerCamelCase : str = f.read() else: __lowerCamelCase : Optional[int] = bytes(lowerCamelCase__ , 'utf-8' ) print(SHAaaa(lowerCamelCase__ ).hash ) if __name__ == "__main__": main()
73
import csv import tweepy # Twitter API credentials a ="""""" a ="""""" a ="""""" a ="""""" def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> None: # authorize twitter, initialize tweepy __lowerCamelCase : Tuple = tweepy.OAuthHandler(lowerCamelCase__ , lowerCamelCase__ ) auth.set_access_token(lowerCamelCase__ , lowerCamelCase__ ) __lowerCamelCase : Optional[int] = tweepy.API(lowerCamelCase__ ) # initialize a list to hold all the tweepy Tweets __lowerCamelCase : str = [] # make initial request for most recent tweets (200 is the maximum allowed count) __lowerCamelCase : Union[str, Any] = api.user_timeline(screen_name=lowerCamelCase__ , count=2_0_0 ) # save most recent tweets alltweets.extend(lowerCamelCase__ ) # save the id of the oldest tweet less one __lowerCamelCase : Any = alltweets[-1].id - 1 # keep grabbing tweets until there are no tweets left to grab while len(lowerCamelCase__ ) > 0: print(F"getting tweets before {oldest}" ) # all subsequent requests use the max_id param to prevent duplicates __lowerCamelCase : str = api.user_timeline( screen_name=lowerCamelCase__ , count=2_0_0 , max_id=lowerCamelCase__ ) # save most recent tweets alltweets.extend(lowerCamelCase__ ) # update the id of the oldest tweet less one __lowerCamelCase : Optional[int] = alltweets[-1].id - 1 print(F"...{len(lowerCamelCase__ )} tweets downloaded so far" ) # transform the tweepy tweets into a 2D array that will populate the csv __lowerCamelCase : str = [[tweet.id_str, tweet.created_at, tweet.text] for tweet in alltweets] # write the csv with open(F"new_{screen_name}_tweets.csv" , 'w' ) as f: __lowerCamelCase : Any = csv.writer(lowerCamelCase__ ) writer.writerow(['id', 'created_at', 'text'] ) writer.writerows(lowerCamelCase__ ) if __name__ == "__main__": # pass in the username of the account you want to download get_all_tweets("""FirePing32""")
73
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) a ={ """configuration_vision_encoder_decoder""": ["""VisionEncoderDecoderConfig""", """VisionEncoderDecoderOnnxConfig"""] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a =["""VisionEncoderDecoderModel"""] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a =["""TFVisionEncoderDecoderModel"""] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a =["""FlaxVisionEncoderDecoderModel"""] if TYPE_CHECKING: from .configuration_vision_encoder_decoder import VisionEncoderDecoderConfig, VisionEncoderDecoderOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_vision_encoder_decoder import VisionEncoderDecoderModel try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_vision_encoder_decoder import TFVisionEncoderDecoderModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_vision_encoder_decoder import FlaxVisionEncoderDecoderModel else: import sys a =_LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
73
import numpy as np from scipy.spatial.distance import cdist from sklearn.metrics import fa_score import datasets a ="""\ @inproceedings{kakwani2020indicnlpsuite, title={{IndicNLPSuite: Monolingual Corpora, Evaluation Benchmarks and Pre-trained Multilingual Language Models for Indian Languages}}, author={Divyanshu Kakwani and Anoop Kunchukuttan and Satish Golla and Gokul N.C. and Avik Bhattacharyya and Mitesh M. Khapra and Pratyush Kumar}, year={2020}, booktitle={Findings of EMNLP}, } """ a ="""\ IndicGLUE is a natural language understanding benchmark for Indian languages. It contains a wide variety of tasks and covers 11 major Indian languages - as, bn, gu, hi, kn, ml, mr, or, pa, ta, te. """ a =""" Compute IndicGLUE evaluation metric associated to each IndicGLUE dataset. Args: predictions: list of predictions to score (as int64), except for 'cvit-mkb-clsr' where each prediction is a vector (of float32). references: list of ground truth labels corresponding to the predictions (as int64), except for 'cvit-mkb-clsr' where each reference is a vector (of float32). Returns: depending on the IndicGLUE subset, one or several of: \"accuracy\": Accuracy \"f1\": F1 score \"precision\": Precision@10 Examples: >>> indic_glue_metric = datasets.load_metric('indic_glue', 'wnli') # 'wnli' or any of [\"copa\", \"sna\", \"csqa\", \"wstp\", \"inltkh\", \"bbca\", \"iitp-mr\", \"iitp-pr\", \"actsa-sc\", \"md\"] >>> references = [0, 1] >>> predictions = [0, 1] >>> results = indic_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {'accuracy': 1.0} >>> indic_glue_metric = datasets.load_metric('indic_glue', 'wiki-ner') >>> references = [0, 1] >>> predictions = [0, 1] >>> results = indic_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {'accuracy': 1.0, 'f1': 1.0} >>> indic_glue_metric = datasets.load_metric('indic_glue', 'cvit-mkb-clsr') >>> references = [[0.5, 0.5, 0.5], [0.1, 0.2, 0.3]] >>> predictions = [[0.5, 0.5, 0.5], [0.1, 0.2, 0.3]] >>> results = indic_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {'precision@10': 1.0} """ def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> List[str]: return float((preds == labels).mean() ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> List[str]: __lowerCamelCase : Optional[Any] = simple_accuracy(lowerCamelCase__ , lowerCamelCase__ ) __lowerCamelCase : Tuple = float(fa_score(y_true=lowerCamelCase__ , y_pred=lowerCamelCase__ ) ) return { "accuracy": acc, "f1": fa, } def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> Optional[Any]: __lowerCamelCase : Any = np.array(lowerCamelCase__ ) __lowerCamelCase : List[Any] = np.array(lowerCamelCase__ ) __lowerCamelCase : Any = en_sentvecs.shape[0] # mean centering __lowerCamelCase : Union[str, Any] = en_sentvecs - np.mean(lowerCamelCase__ , axis=0 ) __lowerCamelCase : Dict = in_sentvecs - np.mean(lowerCamelCase__ , axis=0 ) __lowerCamelCase : Optional[int] = cdist(lowerCamelCase__ , lowerCamelCase__ , 'cosine' ) __lowerCamelCase : Optional[Any] = np.array(range(lowerCamelCase__ ) ) __lowerCamelCase : Dict = sim.argsort(axis=1 )[:, :1_0] __lowerCamelCase : Optional[int] = np.any(preds == actual[:, None] , axis=1 ) return float(matches.mean() ) @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class A_ ( datasets.Metric ): def lowerCAmelCase ( self : Optional[Any]): if self.config_name not in [ "wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", "cvit-mkb-clsr", "iitp-mr", "iitp-pr", "actsa-sc", "md", "wiki-ner", ]: raise KeyError( 'You should supply a configuration name selected in ' '["wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", ' '"cvit-mkb-clsr", "iitp-mr", "iitp-pr", "actsa-sc", "md", ' '"wiki-ner"]') return datasets.MetricInfo( description=_DESCRIPTION ,citation=_CITATION ,inputs_description=_KWARGS_DESCRIPTION ,features=datasets.Features( { 'predictions': datasets.Value('int64') if self.config_name != 'cvit-mkb-clsr' else datasets.Sequence(datasets.Value('float32')), 'references': datasets.Value('int64') if self.config_name != 'cvit-mkb-clsr' else datasets.Sequence(datasets.Value('float32')), }) ,codebase_urls=[] ,reference_urls=[] ,format='numpy' if self.config_name != 'cvit-mkb-clsr' else None ,) def lowerCAmelCase ( self : Any ,SCREAMING_SNAKE_CASE__ : Tuple ,SCREAMING_SNAKE_CASE__ : Optional[Any]): if self.config_name == "cvit-mkb-clsr": return {"precision@10": precision_at_aa(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__)} elif self.config_name in ["wiki-ner"]: return acc_and_fa(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) elif self.config_name in [ "wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", "iitp-mr", "iitp-pr", "actsa-sc", "md", ]: return {"accuracy": simple_accuracy(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__)} else: raise KeyError( 'You should supply a configuration name selected in ' '["wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", ' '"cvit-mkb-clsr", "iitp-mr", "iitp-pr", "actsa-sc", "md", ' '"wiki-ner"]')
73
1
import argparse from tax import checkpoints from transformers import AutoConfig, FlaxAutoModelForSeqaSeqLM def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> Any: __lowerCamelCase : Optional[Any] = AutoConfig.from_pretrained(lowerCamelCase__ ) __lowerCamelCase : Any = FlaxAutoModelForSeqaSeqLM.from_config(config=lowerCamelCase__ ) __lowerCamelCase : Union[str, Any] = checkpoints.load_tax_checkpoint(lowerCamelCase__ ) __lowerCamelCase : int = 'wi_0' in tax_model['target']['encoder']['layers_0']['mlp'] if config.model_type == "t5": __lowerCamelCase : Optional[int] = 'SelfAttention' if config.model_type == "longt5" and config.encoder_attention_type == "local": __lowerCamelCase : str = 'LocalSelfAttention' elif config.model_type == "longt5" and config.encoder_attention_type == "transient-global": __lowerCamelCase : Optional[Any] = 'TransientGlobalSelfAttention' else: raise ValueError( 'Given config is expected to have `model_type=\'t5\'`, or `model_type=\'longt5` with `encoder_attention_type`' ' attribute with a value from [\'local\', \'transient-global].' ) # Encoder for layer_index in range(config.num_layers ): __lowerCamelCase : int = F"layers_{str(lowerCamelCase__ )}" # Self-Attention __lowerCamelCase : List[str] = tax_model['target']['encoder'][layer_name]['attention']['key']['kernel'] __lowerCamelCase : Optional[int] = tax_model['target']['encoder'][layer_name]['attention']['out']['kernel'] __lowerCamelCase : int = tax_model['target']['encoder'][layer_name]['attention']['query']['kernel'] __lowerCamelCase : List[Any] = tax_model['target']['encoder'][layer_name]['attention']['value']['kernel'] # Global input layer norm if config.model_type == "longt5" and config.encoder_attention_type == "transient-global": __lowerCamelCase : Optional[int] = tax_model['target']['encoder'][layer_name]['attention']['T5LayerNorm_0']['scale'] # Layer Normalization __lowerCamelCase : Any = tax_model['target']['encoder'][layer_name]['pre_attention_layer_norm']['scale'] if split_mlp_wi: __lowerCamelCase : List[Any] = tax_model['target']['encoder'][layer_name]['mlp']['wi_0']['kernel'] __lowerCamelCase : List[Any] = tax_model['target']['encoder'][layer_name]['mlp']['wi_1']['kernel'] else: __lowerCamelCase : str = tax_model['target']['encoder'][layer_name]['mlp']['wi']['kernel'] __lowerCamelCase : List[str] = tax_model['target']['encoder'][layer_name]['mlp']['wo']['kernel'] # Layer Normalization __lowerCamelCase : Union[str, Any] = tax_model['target']['encoder'][layer_name]['pre_mlp_layer_norm']['scale'] # Assigning __lowerCamelCase : Tuple = flax_model.params['encoder']['block'][str(lowerCamelCase__ )]['layer'] __lowerCamelCase : Union[str, Any] = tax_attention_key __lowerCamelCase : Union[str, Any] = tax_attention_out __lowerCamelCase : Tuple = tax_attention_query __lowerCamelCase : List[Any] = tax_attention_value __lowerCamelCase : List[str] = tax_attention_layer_norm # Global input layer norm if config.model_type == "longt5" and config.encoder_attention_type == "transient-global": __lowerCamelCase : Tuple = tax_global_layer_norm if split_mlp_wi: __lowerCamelCase : Any = tax_mlp_wi_a __lowerCamelCase : Optional[int] = tax_mlp_wi_a else: __lowerCamelCase : Union[str, Any] = tax_mlp_wi __lowerCamelCase : Dict = tax_mlp_wo __lowerCamelCase : Optional[int] = tax_mlp_layer_norm __lowerCamelCase : List[str] = flax_model_encoder_layer_block # Only for layer 0: __lowerCamelCase : Union[str, Any] = tax_model['target']['encoder']['relpos_bias']['rel_embedding'].T __lowerCamelCase : List[str] = tax_encoder_rel_embedding # Side/global relative position_bias + layer norm if config.model_type == "longt5" and config.encoder_attention_type == "transient-global": __lowerCamelCase : Tuple = tax_model['target']['encoder']['side_relpos_bias']['rel_embedding'].T __lowerCamelCase : Tuple = tax_encoder_global_rel_embedding # Assigning __lowerCamelCase : Optional[int] = tax_model['target']['encoder']['encoder_norm']['scale'] __lowerCamelCase : Any = tax_encoder_norm # Decoder for layer_index in range(config.num_layers ): __lowerCamelCase : Tuple = F"layers_{str(lowerCamelCase__ )}" # Self-Attention __lowerCamelCase : Any = tax_model['target']['decoder'][layer_name]['self_attention']['key']['kernel'] __lowerCamelCase : int = tax_model['target']['decoder'][layer_name]['self_attention']['out']['kernel'] __lowerCamelCase : Optional[int] = tax_model['target']['decoder'][layer_name]['self_attention']['query']['kernel'] __lowerCamelCase : int = tax_model['target']['decoder'][layer_name]['self_attention']['value']['kernel'] # Layer Normalization __lowerCamelCase : Any = tax_model['target']['decoder'][layer_name]['pre_self_attention_layer_norm'][ 'scale' ] # Encoder-Decoder-Attention __lowerCamelCase : Any = tax_model['target']['decoder'][layer_name]['encoder_decoder_attention'] __lowerCamelCase : Optional[int] = tax_enc_dec_attention_module['key']['kernel'] __lowerCamelCase : List[Any] = tax_enc_dec_attention_module['out']['kernel'] __lowerCamelCase : int = tax_enc_dec_attention_module['query']['kernel'] __lowerCamelCase : Dict = tax_enc_dec_attention_module['value']['kernel'] # Layer Normalization __lowerCamelCase : str = tax_model['target']['decoder'][layer_name]['pre_cross_attention_layer_norm']['scale'] # MLP if split_mlp_wi: __lowerCamelCase : Tuple = tax_model['target']['decoder'][layer_name]['mlp']['wi_0']['kernel'] __lowerCamelCase : Dict = tax_model['target']['decoder'][layer_name]['mlp']['wi_1']['kernel'] else: __lowerCamelCase : Any = tax_model['target']['decoder'][layer_name]['mlp']['wi']['kernel'] __lowerCamelCase : Dict = tax_model['target']['decoder'][layer_name]['mlp']['wo']['kernel'] # Layer Normalization __lowerCamelCase : Optional[Any] = tax_model['target']['decoder'][layer_name]['pre_mlp_layer_norm']['scale'] # Assigning __lowerCamelCase : Any = flax_model.params['decoder']['block'][str(lowerCamelCase__ )]['layer'] __lowerCamelCase : Dict = tax_attention_key __lowerCamelCase : int = tax_attention_out __lowerCamelCase : Optional[Any] = tax_attention_query __lowerCamelCase : Any = tax_attention_value __lowerCamelCase : List[Any] = tax_pre_attention_layer_norm __lowerCamelCase : List[Any] = tax_enc_dec_attention_key __lowerCamelCase : List[Any] = tax_enc_dec_attention_out __lowerCamelCase : List[str] = tax_enc_dec_attention_query __lowerCamelCase : Optional[int] = tax_enc_dec_attention_value __lowerCamelCase : List[str] = tax_cross_layer_norm if split_mlp_wi: __lowerCamelCase : str = tax_mlp_wi_a __lowerCamelCase : List[str] = tax_mlp_wi_a else: __lowerCamelCase : int = tax_mlp_wi __lowerCamelCase : int = tax_mlp_wo __lowerCamelCase : int = txa_mlp_layer_norm __lowerCamelCase : Tuple = flax_model_decoder_layer_block # Decoder Normalization __lowerCamelCase : Optional[int] = tax_model['target']['decoder']['decoder_norm']['scale'] __lowerCamelCase : str = txa_decoder_norm # Only for layer 0: __lowerCamelCase : Any = tax_model['target']['decoder']['relpos_bias']['rel_embedding'].T __lowerCamelCase : Any = tax_decoder_rel_embedding # Token Embeddings __lowerCamelCase : int = tax_model['target']['token_embedder']['embedding'] __lowerCamelCase : List[Any] = txa_token_embeddings # LM Head (only in v1.1 and LongT5 checkpoints) if "logits_dense" in tax_model["target"]["decoder"]: __lowerCamelCase : Optional[int] = tax_model['target']['decoder']['logits_dense']['kernel'] flax_model.save_pretrained(lowerCamelCase__ ) print('T5X Model was sucessfully converted!' ) if __name__ == "__main__": a =argparse.ArgumentParser() # Required parameters parser.add_argument( """--t5x_checkpoint_path""", default=None, type=str, required=True, help="""Path the T5X checkpoint.""" ) parser.add_argument("""--config_name""", default=None, type=str, required=True, help="""Config name of LongT5/T5 model.""") parser.add_argument( """--flax_dump_folder_path""", default=None, type=str, required=True, help="""Path to the output FLAX model.""" ) a =parser.parse_args() convert_tax_checkpoint_to_flax(args.tax_checkpoint_path, args.config_name, args.flax_dump_folder_path)
73
from __future__ import annotations from scipy.special import comb # type: ignore class A_ : def __init__( self : List[str] ,SCREAMING_SNAKE_CASE__ : list[tuple[float, float]]): __lowerCamelCase : Union[str, Any] = list_of_points # Degree determines the flexibility of the curve. # Degree = 1 will produce a straight line. __lowerCamelCase : int = len(SCREAMING_SNAKE_CASE__) - 1 def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : float): assert 0 <= t <= 1, "Time t must be between 0 and 1." __lowerCamelCase : list[float] = [] for i in range(len(self.list_of_points)): # basis function for each i output_values.append( comb(self.degree ,SCREAMING_SNAKE_CASE__) * ((1 - t) ** (self.degree - i)) * (t**i)) # the basis must sum up to 1 for it to produce a valid Bezier curve. assert round(sum(SCREAMING_SNAKE_CASE__) ,5) == 1 return output_values def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : float): assert 0 <= t <= 1, "Time t must be between 0 and 1." __lowerCamelCase : Tuple = self.basis_function(SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = 0.0 __lowerCamelCase : Optional[Any] = 0.0 for i in range(len(self.list_of_points)): # For all points, sum up the product of i-th basis function and i-th point. x += basis_function[i] * self.list_of_points[i][0] y += basis_function[i] * self.list_of_points[i][1] return (x, y) def lowerCAmelCase ( self : int ,SCREAMING_SNAKE_CASE__ : float = 0.01): from matplotlib import pyplot as plt # type: ignore __lowerCamelCase : list[float] = [] # x coordinates of points to plot __lowerCamelCase : list[float] = [] # y coordinates of points to plot __lowerCamelCase : Any = 0.0 while t <= 1: __lowerCamelCase : List[Any] = self.bezier_curve_function(SCREAMING_SNAKE_CASE__) to_plot_x.append(value[0]) to_plot_y.append(value[1]) t += step_size __lowerCamelCase : Optional[Any] = [i[0] for i in self.list_of_points] __lowerCamelCase : List[str] = [i[1] for i in self.list_of_points] plt.plot( SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,color='blue' ,label='Curve of Degree ' + str(self.degree) ,) plt.scatter(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,color='red' ,label='Control Points') plt.legend() plt.show() if __name__ == "__main__": import doctest doctest.testmod() BezierCurve([(1, 2), (3, 5)]).plot_curve() # degree 1 BezierCurve([(0, 0), (5, 5), (5, 0)]).plot_curve() # degree 2 BezierCurve([(0, 0), (5, 5), (5, 0), (2.5, -2.5)]).plot_curve() # degree 3
73
1
import collections import os from typing import List, Optional, Tuple from transformers.utils import is_jieba_available, requires_backends if is_jieba_available(): import jieba from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging a =logging.get_logger(__name__) a ={"""vocab_file""": """vocab.txt"""} a ={ """vocab_file""": { """openbmb/cpm-ant-10b""": """https://huggingface.co/openbmb/cpm-ant-10b/blob/main/vocab.txt""", }, } a ={ """openbmb/cpm-ant-10b""": 1024, } def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Union[str, Any]: __lowerCamelCase : Optional[int] = collections.OrderedDict() with open(lowerCamelCase__ , 'r' , encoding='utf-8' ) as reader: __lowerCamelCase : Optional[int] = reader.readlines() for index, token in enumerate(lowerCamelCase__ ): __lowerCamelCase : Optional[Any] = token.rstrip('\n' ) __lowerCamelCase : Optional[Any] = index return vocab class A_ ( SCREAMING_SNAKE_CASE ): def __init__( self : Any ,SCREAMING_SNAKE_CASE__ : Tuple ,SCREAMING_SNAKE_CASE__ : Dict="<unk>" ,SCREAMING_SNAKE_CASE__ : Tuple=2_0_0): __lowerCamelCase : Optional[Any] = vocab __lowerCamelCase : Optional[int] = unk_token __lowerCamelCase : str = max_input_chars_per_word def lowerCAmelCase ( self : Any ,SCREAMING_SNAKE_CASE__ : List[Any]): __lowerCamelCase : int = list(SCREAMING_SNAKE_CASE__) if len(SCREAMING_SNAKE_CASE__) > self.max_input_chars_per_word: return [self.unk_token] __lowerCamelCase : List[Any] = 0 __lowerCamelCase : List[Any] = [] while start < len(SCREAMING_SNAKE_CASE__): __lowerCamelCase : List[str] = len(SCREAMING_SNAKE_CASE__) __lowerCamelCase : int = None while start < end: __lowerCamelCase : Dict = ''.join(chars[start:end]) if substr in self.vocab: __lowerCamelCase : str = substr break end -= 1 if cur_substr is None: sub_tokens.append(self.unk_token) start += 1 else: sub_tokens.append(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Dict = end return sub_tokens class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : List[Any] = VOCAB_FILES_NAMES _UpperCAmelCase : int = PRETRAINED_VOCAB_FILES_MAP _UpperCAmelCase : str = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _UpperCAmelCase : str = ['''input_ids''', '''attention_mask'''] _UpperCAmelCase : Union[str, Any] = False def __init__( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : str ,SCREAMING_SNAKE_CASE__ : Optional[int]="<d>" ,SCREAMING_SNAKE_CASE__ : str="</d>" ,SCREAMING_SNAKE_CASE__ : Dict="<s>" ,SCREAMING_SNAKE_CASE__ : Dict="</s>" ,SCREAMING_SNAKE_CASE__ : str="<pad>" ,SCREAMING_SNAKE_CASE__ : Any="<unk>" ,SCREAMING_SNAKE_CASE__ : Dict="</n>" ,SCREAMING_SNAKE_CASE__ : Any="</_>" ,SCREAMING_SNAKE_CASE__ : Any="left" ,**SCREAMING_SNAKE_CASE__ : str ,): requires_backends(self ,['jieba']) super().__init__( bod_token=SCREAMING_SNAKE_CASE__ ,eod_token=SCREAMING_SNAKE_CASE__ ,bos_token=SCREAMING_SNAKE_CASE__ ,eos_token=SCREAMING_SNAKE_CASE__ ,pad_token=SCREAMING_SNAKE_CASE__ ,unk_token=SCREAMING_SNAKE_CASE__ ,line_token=SCREAMING_SNAKE_CASE__ ,space_token=SCREAMING_SNAKE_CASE__ ,padding_side=SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__ ,) __lowerCamelCase : List[Any] = bod_token __lowerCamelCase : int = eod_token __lowerCamelCase : Dict = load_vocab(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Tuple = self.encoder[space_token] __lowerCamelCase : Optional[Any] = self.encoder[line_token] del self.encoder[space_token] del self.encoder[line_token] __lowerCamelCase : Tuple = collections.OrderedDict(sorted(self.encoder.items() ,key=lambda SCREAMING_SNAKE_CASE__: x[1])) __lowerCamelCase : Union[str, Any] = {v: k for k, v in self.encoder.items()} __lowerCamelCase : int = WordpieceTokenizer(vocab=self.encoder ,unk_token=self.unk_token) @property def lowerCAmelCase ( self : Union[str, Any]): return self.encoder[self.bod_token] @property def lowerCAmelCase ( self : Dict): return self.encoder[self.eod_token] @property def lowerCAmelCase ( self : int): return self.encoder["\n"] @property def lowerCAmelCase ( self : List[str]): return len(self.encoder) def lowerCAmelCase ( self : Optional[int]): return dict(self.encoder ,**self.added_tokens_encoder) def lowerCAmelCase ( self : List[str] ,SCREAMING_SNAKE_CASE__ : str): __lowerCamelCase : Tuple = [] for x in jieba.cut(SCREAMING_SNAKE_CASE__ ,cut_all=SCREAMING_SNAKE_CASE__): output_tokens.extend(self.wordpiece_tokenizer.tokenize(SCREAMING_SNAKE_CASE__)) return output_tokens def lowerCAmelCase ( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : List[Any] ,**SCREAMING_SNAKE_CASE__ : Optional[int]): __lowerCamelCase : Dict = [i for i in token_ids if i >= 0] __lowerCamelCase : Optional[int] = [ x for x in token_ids if x != self.pad_token_id and x != self.eos_token_id and x != self.bos_token_id ] return super()._decode(SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : List[str]): return token in self.encoder def lowerCAmelCase ( self : Any ,SCREAMING_SNAKE_CASE__ : List[str]): return "".join(SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : int ,SCREAMING_SNAKE_CASE__ : List[str]): return self.encoder.get(SCREAMING_SNAKE_CASE__ ,self.encoder.get(self.unk_token)) def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : Tuple): return self.decoder.get(SCREAMING_SNAKE_CASE__ ,self.unk_token) def lowerCAmelCase ( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : str ,SCREAMING_SNAKE_CASE__ : Optional[str] = None): if os.path.isdir(SCREAMING_SNAKE_CASE__): __lowerCamelCase : str = os.path.join( SCREAMING_SNAKE_CASE__ ,(filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file']) else: __lowerCamelCase : Dict = (filename_prefix + '-' if filename_prefix else '') + save_directory __lowerCamelCase : Optional[Any] = 0 if " " in self.encoder: __lowerCamelCase : Dict = self.encoder[' '] del self.encoder[" "] if "\n" in self.encoder: __lowerCamelCase : List[str] = self.encoder['\n'] del self.encoder["\n"] __lowerCamelCase : Any = collections.OrderedDict(sorted(self.encoder.items() ,key=lambda SCREAMING_SNAKE_CASE__: x[1])) with open(SCREAMING_SNAKE_CASE__ ,'w' ,encoding='utf-8') as writer: for token, token_index in self.encoder.items(): if index != token_index: logger.warning( F"Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive." ' Please check that the vocabulary is not corrupted!') __lowerCamelCase : Optional[Any] = token_index writer.write(token + '\n') index += 1 return (vocab_file,) def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : List[int] ,SCREAMING_SNAKE_CASE__ : List[int] = None): if token_ids_a is None: return [self.bos_token_id] + token_ids_a return [self.bos_token_id] + token_ids_a + [self.bos_token_id] + token_ids_a def lowerCAmelCase ( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : List[int] ,SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ,SCREAMING_SNAKE_CASE__ : bool = False): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=SCREAMING_SNAKE_CASE__ ,token_ids_a=SCREAMING_SNAKE_CASE__ ,already_has_special_tokens=SCREAMING_SNAKE_CASE__) if token_ids_a is not None: return [1] + ([0] * len(SCREAMING_SNAKE_CASE__)) + [1] + ([0] * len(SCREAMING_SNAKE_CASE__)) return [1] + ([0] * len(SCREAMING_SNAKE_CASE__))
73
from __future__ import annotations import time a =list[tuple[int, int]] a =[ [0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles [0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0], [1, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0], ] a =[[-1, 0], [0, -1], [1, 0], [0, 1]] # up, left, down, right class A_ : def __init__( self : List[str] ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : Node | None): __lowerCamelCase : Tuple = pos_x __lowerCamelCase : List[str] = pos_y __lowerCamelCase : str = (pos_y, pos_x) __lowerCamelCase : str = goal_x __lowerCamelCase : int = goal_y __lowerCamelCase : List[Any] = parent class A_ : def __init__( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : tuple[int, int] ,SCREAMING_SNAKE_CASE__ : tuple[int, int]): __lowerCamelCase : Any = Node(start[1] ,start[0] ,goal[1] ,goal[0] ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = Node(goal[1] ,goal[0] ,goal[1] ,goal[0] ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Union[str, Any] = [self.start] __lowerCamelCase : List[str] = False def lowerCAmelCase ( self : List[Any]): while self.node_queue: __lowerCamelCase : Any = self.node_queue.pop(0) if current_node.pos == self.target.pos: __lowerCamelCase : Dict = True return self.retrace_path(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Tuple = self.get_successors(SCREAMING_SNAKE_CASE__) for node in successors: self.node_queue.append(SCREAMING_SNAKE_CASE__) if not self.reached: return [self.start.pos] return None def lowerCAmelCase ( self : str ,SCREAMING_SNAKE_CASE__ : Node): __lowerCamelCase : Union[str, Any] = [] for action in delta: __lowerCamelCase : Optional[Any] = parent.pos_x + action[1] __lowerCamelCase : Optional[int] = parent.pos_y + action[0] if not (0 <= pos_x <= len(grid[0]) - 1 and 0 <= pos_y <= len(SCREAMING_SNAKE_CASE__) - 1): continue if grid[pos_y][pos_x] != 0: continue successors.append( Node(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,self.target.pos_y ,self.target.pos_x ,SCREAMING_SNAKE_CASE__)) return successors def lowerCAmelCase ( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : Node | None): __lowerCamelCase : List[Any] = node __lowerCamelCase : int = [] while current_node is not None: path.append((current_node.pos_y, current_node.pos_x)) __lowerCamelCase : int = current_node.parent path.reverse() return path class A_ : def __init__( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : int): __lowerCamelCase : int = BreadthFirstSearch(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = BreadthFirstSearch(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = False def lowerCAmelCase ( self : str): while self.fwd_bfs.node_queue or self.bwd_bfs.node_queue: __lowerCamelCase : Any = self.fwd_bfs.node_queue.pop(0) __lowerCamelCase : Any = self.bwd_bfs.node_queue.pop(0) if current_bwd_node.pos == current_fwd_node.pos: __lowerCamelCase : List[str] = True return self.retrace_bidirectional_path( SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = current_bwd_node __lowerCamelCase : int = current_fwd_node __lowerCamelCase : str = { self.fwd_bfs: self.fwd_bfs.get_successors(SCREAMING_SNAKE_CASE__), self.bwd_bfs: self.bwd_bfs.get_successors(SCREAMING_SNAKE_CASE__), } for bfs in [self.fwd_bfs, self.bwd_bfs]: for node in successors[bfs]: bfs.node_queue.append(SCREAMING_SNAKE_CASE__) if not self.reached: return [self.fwd_bfs.start.pos] return None def lowerCAmelCase ( self : Dict ,SCREAMING_SNAKE_CASE__ : Node ,SCREAMING_SNAKE_CASE__ : Node): __lowerCamelCase : List[Any] = self.fwd_bfs.retrace_path(SCREAMING_SNAKE_CASE__) __lowerCamelCase : str = self.bwd_bfs.retrace_path(SCREAMING_SNAKE_CASE__) bwd_path.pop() bwd_path.reverse() __lowerCamelCase : List[Any] = fwd_path + bwd_path return path if __name__ == "__main__": # all coordinates are given in format [y,x] import doctest doctest.testmod() a =(0, 0) a =(len(grid) - 1, len(grid[0]) - 1) for elem in grid: print(elem) a =time.time() a =BreadthFirstSearch(init, goal) a =bfs.search() a =time.time() - start_bfs_time print("""Unidirectional BFS computation time : """, bfs_time) a =time.time() a =BidirectionalBreadthFirstSearch(init, goal) a =bd_bfs.search() a =time.time() - start_bd_bfs_time print("""Bidirectional BFS computation time : """, bd_bfs_time)
73
1
from typing import Dict, List, Optional, Union import numpy as np from .feature_extraction_utils import BatchFeature, FeatureExtractionMixin from .utils import PaddingStrategy, TensorType, is_tf_tensor, is_torch_tensor, logging, to_numpy a =logging.get_logger(__name__) class A_ ( SCREAMING_SNAKE_CASE ): def __init__( self : int ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : float ,**SCREAMING_SNAKE_CASE__ : Dict): __lowerCamelCase : List[str] = feature_size __lowerCamelCase : Optional[int] = sampling_rate __lowerCamelCase : Dict = padding_value __lowerCamelCase : Any = kwargs.pop('padding_side' ,'right') __lowerCamelCase : int = kwargs.pop('return_attention_mask' ,SCREAMING_SNAKE_CASE__) super().__init__(**SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : int ,SCREAMING_SNAKE_CASE__ : Union[ BatchFeature, List[BatchFeature], Dict[str, BatchFeature], Dict[str, List[BatchFeature]], List[Dict[str, BatchFeature]], ] ,SCREAMING_SNAKE_CASE__ : Union[bool, str, PaddingStrategy] = True ,SCREAMING_SNAKE_CASE__ : Optional[int] = None ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : Optional[int] = None ,SCREAMING_SNAKE_CASE__ : Optional[bool] = None ,SCREAMING_SNAKE_CASE__ : Optional[Union[str, TensorType]] = None ,): # If we have a list of dicts, let's convert it in a dict of lists # We do this to allow using this method as a collate_fn function in PyTorch Dataloader if isinstance(SCREAMING_SNAKE_CASE__ ,(list, tuple)) and isinstance(processed_features[0] ,(dict, BatchFeature)): __lowerCamelCase : Tuple = { key: [example[key] for example in processed_features] for key in processed_features[0].keys() } # The model's main input name, usually `input_values`, has be passed for padding if self.model_input_names[0] not in processed_features: raise ValueError( 'You should supply an instance of `transformers.BatchFeature` or list of `transformers.BatchFeature`' F" to this method that includes {self.model_input_names[0]}, but you provided" F" {list(processed_features.keys())}") __lowerCamelCase : str = processed_features[self.model_input_names[0]] __lowerCamelCase : Any = ( return_attention_mask if return_attention_mask is not None else self.return_attention_mask ) if len(SCREAMING_SNAKE_CASE__) == 0: if return_attention_mask: __lowerCamelCase : List[str] = [] return processed_features # If we have PyTorch/TF tensors or lists as inputs, we cast them as Numpy arrays # and rebuild them afterwards if no return_tensors is specified # Note that we lose the specific device the tensor may be on for PyTorch __lowerCamelCase : Optional[Any] = required_input[0] if isinstance(SCREAMING_SNAKE_CASE__ ,(list, tuple)): # first_element might be an empty list/tuple in some edge cases so we grab the first non empty element. __lowerCamelCase : List[str] = 0 while len(required_input[index]) == 0: index += 1 if index < len(SCREAMING_SNAKE_CASE__): __lowerCamelCase : Tuple = required_input[index][0] if return_tensors is None: if is_tf_tensor(SCREAMING_SNAKE_CASE__): __lowerCamelCase : Any = 'tf' elif is_torch_tensor(SCREAMING_SNAKE_CASE__): __lowerCamelCase : Union[str, Any] = 'pt' elif isinstance(SCREAMING_SNAKE_CASE__ ,(int, float, list, tuple, np.ndarray)): __lowerCamelCase : Union[str, Any] = 'np' else: raise ValueError( F"type of {first_element} unknown: {type(SCREAMING_SNAKE_CASE__)}. " 'Should be one of a python, numpy, pytorch or tensorflow object.') for key, value in processed_features.items(): if isinstance(value[0] ,(int, float)): __lowerCamelCase : Union[str, Any] = to_numpy(SCREAMING_SNAKE_CASE__) else: __lowerCamelCase : Dict = [to_numpy(SCREAMING_SNAKE_CASE__) for v in value] # Convert padding_strategy in PaddingStrategy __lowerCamelCase : Tuple = self._get_padding_strategies(padding=SCREAMING_SNAKE_CASE__ ,max_length=SCREAMING_SNAKE_CASE__) __lowerCamelCase : Union[str, Any] = processed_features[self.model_input_names[0]] __lowerCamelCase : Union[str, Any] = len(SCREAMING_SNAKE_CASE__) if not all(len(SCREAMING_SNAKE_CASE__) == batch_size for v in processed_features.values()): raise ValueError('Some items in the output dictionary have a different batch size than others.') __lowerCamelCase : Any = [] for i in range(SCREAMING_SNAKE_CASE__): __lowerCamelCase : int = {k: v[i] for k, v in processed_features.items()} # truncation __lowerCamelCase : Union[str, Any] = self._truncate( SCREAMING_SNAKE_CASE__ ,max_length=SCREAMING_SNAKE_CASE__ ,pad_to_multiple_of=SCREAMING_SNAKE_CASE__ ,truncation=SCREAMING_SNAKE_CASE__ ,) truncated_inputs.append(SCREAMING_SNAKE_CASE__) if padding_strategy == PaddingStrategy.LONGEST: # make sure that `max_length` cannot be longer than the longest truncated length __lowerCamelCase : Any = max(len(input_slice[self.model_input_names[0]]) for input_slice in truncated_inputs) __lowerCamelCase : Optional[Any] = PaddingStrategy.MAX_LENGTH __lowerCamelCase : Optional[Any] = {} for i in range(SCREAMING_SNAKE_CASE__): # padding __lowerCamelCase : List[str] = self._pad( truncated_inputs[i] ,max_length=SCREAMING_SNAKE_CASE__ ,padding_strategy=SCREAMING_SNAKE_CASE__ ,pad_to_multiple_of=SCREAMING_SNAKE_CASE__ ,return_attention_mask=SCREAMING_SNAKE_CASE__ ,) for key, value in outputs.items(): if key not in batch_outputs: __lowerCamelCase : Union[str, Any] = [] if value.dtype is np.dtype(np.floataa): __lowerCamelCase : Any = value.astype(np.floataa) batch_outputs[key].append(SCREAMING_SNAKE_CASE__) return BatchFeature(SCREAMING_SNAKE_CASE__ ,tensor_type=SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Dict ,SCREAMING_SNAKE_CASE__ : Union[Dict[str, np.ndarray], BatchFeature] ,SCREAMING_SNAKE_CASE__ : Optional[int] = None ,SCREAMING_SNAKE_CASE__ : PaddingStrategy = PaddingStrategy.DO_NOT_PAD ,SCREAMING_SNAKE_CASE__ : Optional[int] = None ,SCREAMING_SNAKE_CASE__ : Optional[bool] = None ,): __lowerCamelCase : Optional[int] = processed_features[self.model_input_names[0]] if padding_strategy == PaddingStrategy.LONGEST: __lowerCamelCase : int = len(SCREAMING_SNAKE_CASE__) if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0): __lowerCamelCase : List[Any] = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of __lowerCamelCase : Dict = padding_strategy != PaddingStrategy.DO_NOT_PAD and len(SCREAMING_SNAKE_CASE__) < max_length if return_attention_mask and "attention_mask" not in processed_features: __lowerCamelCase : int = np.ones(len(SCREAMING_SNAKE_CASE__) ,dtype=np.intaa) if needs_to_be_padded: __lowerCamelCase : List[Any] = max_length - len(SCREAMING_SNAKE_CASE__) if self.padding_side == "right": if return_attention_mask: __lowerCamelCase : Any = np.pad( processed_features['attention_mask'] ,(0, difference)) __lowerCamelCase : str = ((0, difference), (0, 0)) if self.feature_size > 1 else (0, difference) __lowerCamelCase : Tuple = np.pad( SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,'constant' ,constant_values=self.padding_value) elif self.padding_side == "left": if return_attention_mask: __lowerCamelCase : List[Any] = np.pad( processed_features['attention_mask'] ,(difference, 0)) __lowerCamelCase : Any = ((difference, 0), (0, 0)) if self.feature_size > 1 else (difference, 0) __lowerCamelCase : Union[str, Any] = np.pad( SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,'constant' ,constant_values=self.padding_value) else: raise ValueError('Invalid padding strategy:' + str(self.padding_side)) return processed_features def lowerCAmelCase ( self : Dict ,SCREAMING_SNAKE_CASE__ : Union[Dict[str, np.ndarray], BatchFeature] ,SCREAMING_SNAKE_CASE__ : Optional[int] = None ,SCREAMING_SNAKE_CASE__ : Optional[int] = None ,SCREAMING_SNAKE_CASE__ : Optional[bool] = None ,): if not truncation: return processed_features elif truncation and max_length is None: raise ValueError('When setting ``truncation=True``, make sure that ``max_length`` is defined.') __lowerCamelCase : Union[str, Any] = processed_features[self.model_input_names[0]] # find `max_length` that fits `pad_to_multiple_of` if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0): __lowerCamelCase : Tuple = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of __lowerCamelCase : Optional[int] = len(SCREAMING_SNAKE_CASE__) > max_length if needs_to_be_truncated: __lowerCamelCase : Dict = processed_features[self.model_input_names[0]][:max_length] if "attention_mask" in processed_features: __lowerCamelCase : Optional[Any] = processed_features['attention_mask'][:max_length] return processed_features def lowerCAmelCase ( self : int ,SCREAMING_SNAKE_CASE__ : Any=False ,SCREAMING_SNAKE_CASE__ : List[Any]=None): # Get padding strategy if padding is not False: if padding is True: __lowerCamelCase : Any = PaddingStrategy.LONGEST # Default to pad to the longest sequence in the batch elif not isinstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__): __lowerCamelCase : Optional[int] = PaddingStrategy(SCREAMING_SNAKE_CASE__) elif isinstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__): __lowerCamelCase : Optional[Any] = padding else: __lowerCamelCase : Union[str, Any] = PaddingStrategy.DO_NOT_PAD # Set max length if needed if max_length is None: if padding_strategy == PaddingStrategy.MAX_LENGTH: raise ValueError( F"When setting ``padding={PaddingStrategy.MAX_LENGTH}``, make sure that max_length is defined") # Test if we have a padding value if padding_strategy != PaddingStrategy.DO_NOT_PAD and (self.padding_value is None): raise ValueError( 'Asking to pad but the feature_extractor does not have a padding value. Please select a value to use' ' as `padding_value`. For example: `feature_extractor.padding_value = 0.0`.') return padding_strategy
73
import qiskit def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> qiskit.result.counts.Counts: __lowerCamelCase : Optional[int] = qiskit.Aer.get_backend('aer_simulator' ) # Create a Quantum Circuit acting on the q register __lowerCamelCase : List[str] = qiskit.QuantumCircuit(lowerCamelCase__ , lowerCamelCase__ ) # Map the quantum measurement to the classical bits circuit.measure([0] , [0] ) # Execute the circuit on the simulator __lowerCamelCase : List[Any] = qiskit.execute(lowerCamelCase__ , lowerCamelCase__ , shots=1_0_0_0 ) # Return the histogram data of the results of the experiment. return job.result().get_counts(lowerCamelCase__ ) if __name__ == "__main__": print(F"""Total count for various states are: {single_qubit_measure(1, 1)}""")
73
1
import io import os import unicodedata from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging a =logging.get_logger(__name__) a ="""▁""" a ={"""vocab_file""": """vocab.txt""", """sentencepiece_model_ckpt""": """sentencepiece.bpe.model"""} a ={ """sentencepiece_model_file""": """sentencepiece.bpe.model""", """vocab_file""": """vocab.txt""", } a ={ """vocab_file""": { """ernie-m-base""": """https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/vocab.txt""", """ernie-m-large""": """https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/vocab.txt""", }, """sentencepiece_model_file""": { """ernie-m-base""": """https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/sentencepiece.bpe.model""", """ernie-m-large""": """https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/sentencepiece.bpe.model""", }, } a ={ """ernie-m-base""": 514, """ernie-m-large""": 514, } a ={ """ernie-m-base""": {"""do_lower_case""": False}, """ernie-m-large""": {"""do_lower_case""": False}, } class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : List[str] = ["input_ids"] _UpperCAmelCase : Dict = VOCAB_FILES_NAMES _UpperCAmelCase : Any = PRETRAINED_INIT_CONFIGURATION _UpperCAmelCase : Optional[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _UpperCAmelCase : Optional[int] = PRETRAINED_VOCAB_FILES_MAP _UpperCAmelCase : List[Any] = RESOURCE_FILES_NAMES def __init__( self : Dict ,SCREAMING_SNAKE_CASE__ : List[str] ,SCREAMING_SNAKE_CASE__ : Union[str, Any]=None ,SCREAMING_SNAKE_CASE__ : int=False ,SCREAMING_SNAKE_CASE__ : Union[str, Any]="utf8" ,SCREAMING_SNAKE_CASE__ : List[Any]="[UNK]" ,SCREAMING_SNAKE_CASE__ : Any="[SEP]" ,SCREAMING_SNAKE_CASE__ : Optional[Any]="[PAD]" ,SCREAMING_SNAKE_CASE__ : List[Any]="[CLS]" ,SCREAMING_SNAKE_CASE__ : Optional[Any]="[MASK]" ,SCREAMING_SNAKE_CASE__ : Optional[Dict[str, Any]] = None ,**SCREAMING_SNAKE_CASE__ : List[Any] ,): # Mask token behave like a normal word, i.e. include the space before it and # is included in the raw text, there should be a match in a non-normalized sentence. __lowerCamelCase : Any = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( do_lower_case=SCREAMING_SNAKE_CASE__ ,unk_token=SCREAMING_SNAKE_CASE__ ,sep_token=SCREAMING_SNAKE_CASE__ ,pad_token=SCREAMING_SNAKE_CASE__ ,cls_token=SCREAMING_SNAKE_CASE__ ,mask_token=SCREAMING_SNAKE_CASE__ ,vocab_file=SCREAMING_SNAKE_CASE__ ,encoding=SCREAMING_SNAKE_CASE__ ,sp_model_kwargs=self.sp_model_kwargs ,**SCREAMING_SNAKE_CASE__ ,) __lowerCamelCase : Tuple = do_lower_case __lowerCamelCase : Any = sentencepiece_model_ckpt __lowerCamelCase : Any = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.Load(SCREAMING_SNAKE_CASE__) # to mimic paddlenlp.transformers.ernie_m.tokenizer.ErnieMTokenizer functioning if vocab_file is not None: __lowerCamelCase : Union[str, Any] = self.load_vocab(filepath=SCREAMING_SNAKE_CASE__) else: __lowerCamelCase : List[Any] = {self.sp_model.id_to_piece(SCREAMING_SNAKE_CASE__): id for id in range(self.sp_model.get_piece_size())} __lowerCamelCase : Any = {v: k for k, v in self.vocab.items()} def lowerCAmelCase ( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : List[str]): if text is None: return None __lowerCamelCase : Optional[int] = self.tokenize(SCREAMING_SNAKE_CASE__) __lowerCamelCase , __lowerCamelCase : Optional[Any] = '', [] for i, ch in enumerate(SCREAMING_SNAKE_CASE__): if ch in self.SP_CHAR_MAPPING: __lowerCamelCase : Union[str, Any] = self.SP_CHAR_MAPPING.get(SCREAMING_SNAKE_CASE__) else: __lowerCamelCase : Optional[int] = unicodedata.normalize('NFKC' ,SCREAMING_SNAKE_CASE__) if self.is_whitespace(SCREAMING_SNAKE_CASE__): continue normalized_text += ch char_mapping.extend([i] * len(SCREAMING_SNAKE_CASE__)) __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : int = normalized_text, [], 0 if self.do_lower_case: __lowerCamelCase : Optional[Any] = text.lower() for token in split_tokens: if token[:1] == "▁": __lowerCamelCase : Any = token[1:] __lowerCamelCase : Union[str, Any] = text[offset:].index(SCREAMING_SNAKE_CASE__) + offset __lowerCamelCase : Tuple = start + len(SCREAMING_SNAKE_CASE__) token_mapping.append((char_mapping[start], char_mapping[end - 1] + 1)) __lowerCamelCase : List[Any] = end return token_mapping @property def lowerCAmelCase ( self : Optional[Any]): return len(self.vocab) def lowerCAmelCase ( self : Any): return dict(self.vocab ,**self.added_tokens_encoder) def __getstate__( self : int): __lowerCamelCase : List[str] = self.__dict__.copy() __lowerCamelCase : List[str] = None return state def __setstate__( self : Any ,SCREAMING_SNAKE_CASE__ : List[Any]): __lowerCamelCase : int = d # for backward compatibility if not hasattr(self ,'sp_model_kwargs'): __lowerCamelCase : int = {} __lowerCamelCase : Optional[int] = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.Load(self.sentencepiece_model_ckpt) def lowerCAmelCase ( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : List[Any]): return "".join((self.SP_CHAR_MAPPING.get(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) for c in text)) def lowerCAmelCase ( self : List[str] ,SCREAMING_SNAKE_CASE__ : Optional[int] ,SCREAMING_SNAKE_CASE__ : Optional[Any]=False ,SCREAMING_SNAKE_CASE__ : Dict=6_4 ,SCREAMING_SNAKE_CASE__ : Optional[Any]=0.1): if self.sp_model_kwargs.get('enable_sampling') is True: __lowerCamelCase : Optional[int] = True if self.sp_model_kwargs.get('alpha') is not None: __lowerCamelCase : Any = self.sp_model_kwargs.get('alpha') if self.sp_model_kwargs.get('nbest_size') is not None: __lowerCamelCase : Tuple = self.sp_model_kwargs.get('nbest_size') if not enable_sampling: __lowerCamelCase : Dict = self.sp_model.EncodeAsPieces(SCREAMING_SNAKE_CASE__) else: __lowerCamelCase : Optional[int] = self.sp_model.SampleEncodeAsPieces(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = [] for pi, piece in enumerate(SCREAMING_SNAKE_CASE__): if piece == SPIECE_UNDERLINE: if not pieces[pi + 1].startswith(SCREAMING_SNAKE_CASE__) and pi != 0: new_pieces.append(SCREAMING_SNAKE_CASE__) continue else: continue __lowerCamelCase : List[Any] = 0 for i, chunk in enumerate(SCREAMING_SNAKE_CASE__): if chunk == SPIECE_UNDERLINE: continue if self.is_ch_char(SCREAMING_SNAKE_CASE__) or self.is_punct(SCREAMING_SNAKE_CASE__): if i > lst_i and piece[lst_i:i] != SPIECE_UNDERLINE: new_pieces.append(piece[lst_i:i]) new_pieces.append(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[int] = i + 1 elif chunk.isdigit() and i > 0 and not piece[i - 1].isdigit(): if i > lst_i and piece[lst_i:i] != SPIECE_UNDERLINE: new_pieces.append(piece[lst_i:i]) __lowerCamelCase : Any = i elif not chunk.isdigit() and i > 0 and piece[i - 1].isdigit(): if i > lst_i and piece[lst_i:i] != SPIECE_UNDERLINE: new_pieces.append(piece[lst_i:i]) __lowerCamelCase : Dict = i if len(SCREAMING_SNAKE_CASE__) > lst_i: new_pieces.append(piece[lst_i:]) return new_pieces def lowerCAmelCase ( self : Tuple ,SCREAMING_SNAKE_CASE__ : int): __lowerCamelCase : List[str] = ''.join(SCREAMING_SNAKE_CASE__).replace(SCREAMING_SNAKE_CASE__ ,' ').strip() return out_string def lowerCAmelCase ( self : int ,SCREAMING_SNAKE_CASE__ : int): __lowerCamelCase : str = self.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__) __lowerCamelCase : str = ''.join(SCREAMING_SNAKE_CASE__).replace(SCREAMING_SNAKE_CASE__ ,' ').strip() return out_string def lowerCAmelCase ( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : List[Any]): return self.vocab.get(SCREAMING_SNAKE_CASE__ ,self.vocab.get(self.unk_token)) def lowerCAmelCase ( self : str ,SCREAMING_SNAKE_CASE__ : List[str]): return self.reverse_vocab.get(SCREAMING_SNAKE_CASE__ ,self.unk_token) def lowerCAmelCase ( self : Dict ,SCREAMING_SNAKE_CASE__ : Optional[Any] ,SCREAMING_SNAKE_CASE__ : Optional[Any]=None): if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] __lowerCamelCase : Dict = [self.cls_token_id] __lowerCamelCase : Dict = [self.sep_token_id] return _cls + token_ids_a + _sep + _sep + token_ids_a + _sep def lowerCAmelCase ( self : List[str] ,SCREAMING_SNAKE_CASE__ : Optional[Any] ,SCREAMING_SNAKE_CASE__ : int=None): if offset_mapping_a is None: return [(0, 0)] + offset_mapping_a + [(0, 0)] return [(0, 0)] + offset_mapping_a + [(0, 0), (0, 0)] + offset_mapping_a + [(0, 0)] def lowerCAmelCase ( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : Dict ,SCREAMING_SNAKE_CASE__ : Union[str, Any]=None ,SCREAMING_SNAKE_CASE__ : List[Any]=False): if already_has_special_tokens: if token_ids_a is not None: raise ValueError( 'You should not supply a second sequence if the provided sequence of ' 'ids is already formatted with special tokens for the model.') return [1 if x in [self.sep_token_id, self.cls_token_id] else 0 for x in token_ids_a] if token_ids_a is not None: return [1] + ([0] * len(SCREAMING_SNAKE_CASE__)) + [1, 1] + ([0] * len(SCREAMING_SNAKE_CASE__)) + [1] return [1] + ([0] * len(SCREAMING_SNAKE_CASE__)) + [1] def lowerCAmelCase ( self : Any ,SCREAMING_SNAKE_CASE__ : List[int] ,SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None): # called when `add_special_tokens` is True, so align with `build_inputs_with_special_tokens` method if token_ids_a is None: # [CLS] X [SEP] return (len(SCREAMING_SNAKE_CASE__) + 2) * [0] # [CLS] A [SEP] [SEP] B [SEP] return [0] * (len(SCREAMING_SNAKE_CASE__) + 1) + [1] * (len(SCREAMING_SNAKE_CASE__) + 3) def lowerCAmelCase ( self : Tuple ,SCREAMING_SNAKE_CASE__ : Optional[Any]): if "\u4e00" <= char <= "\u9fff": return True return False def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : Optional[int]): if ("a" <= char <= "z") or ("A" <= char <= "Z"): return True return False def lowerCAmelCase ( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : Any): if char in ",;:.?!~,;:。?!《》【】": return True return False def lowerCAmelCase ( self : Any ,SCREAMING_SNAKE_CASE__ : str): if char == " " or char == "\t" or char == "\n" or char == "\r": return True if len(SCREAMING_SNAKE_CASE__) == 1: __lowerCamelCase : int = unicodedata.category(SCREAMING_SNAKE_CASE__) if cat == "Zs": return True return False def lowerCAmelCase ( self : str ,SCREAMING_SNAKE_CASE__ : Union[str, Any]): __lowerCamelCase : Any = {} with io.open(SCREAMING_SNAKE_CASE__ ,'r' ,encoding='utf-8') as f: for index, line in enumerate(SCREAMING_SNAKE_CASE__): __lowerCamelCase : int = line.rstrip('\n') __lowerCamelCase : str = int(SCREAMING_SNAKE_CASE__) return token_to_idx def lowerCAmelCase ( self : str ,SCREAMING_SNAKE_CASE__ : str ,SCREAMING_SNAKE_CASE__ : Optional[str] = None): __lowerCamelCase : List[Any] = 0 if os.path.isdir(SCREAMING_SNAKE_CASE__): __lowerCamelCase : Union[str, Any] = os.path.join( SCREAMING_SNAKE_CASE__ ,(filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file']) else: __lowerCamelCase : str = (filename_prefix + '-' if filename_prefix else '') + save_directory with open(SCREAMING_SNAKE_CASE__ ,'w' ,encoding='utf-8') as writer: for token, token_index in sorted(self.vocab.items() ,key=lambda SCREAMING_SNAKE_CASE__: kv[1]): if index != token_index: logger.warning( F"Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive." ' Please check that the vocabulary is not corrupted!') __lowerCamelCase : Dict = token_index writer.write(token + '\n') index += 1 __lowerCamelCase : Any = os.path.join(SCREAMING_SNAKE_CASE__ ,'sentencepiece.bpe.model') with open(SCREAMING_SNAKE_CASE__ ,'wb') as fi: __lowerCamelCase : Dict = self.sp_model.serialized_model_proto() fi.write(SCREAMING_SNAKE_CASE__) return (vocab_file,)
73
import os import sys a =os.path.join(os.path.dirname(__file__), """src""") sys.path.append(SRC_DIR) from transformers import ( AutoConfig, AutoModel, AutoModelForCausalLM, AutoModelForMaskedLM, AutoModelForQuestionAnswering, AutoModelForSequenceClassification, AutoTokenizer, add_start_docstrings, ) a =[ """torch""", """numpy""", """tokenizers""", """filelock""", """requests""", """tqdm""", """regex""", """sentencepiece""", """sacremoses""", """importlib_metadata""", """huggingface_hub""", ] @add_start_docstrings(AutoConfig.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> int: return AutoConfig.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ ) @add_start_docstrings(AutoTokenizer.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> Optional[Any]: return AutoTokenizer.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ ) @add_start_docstrings(AutoModel.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> List[str]: return AutoModel.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ ) @add_start_docstrings(AutoModelForCausalLM.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> Any: return AutoModelForCausalLM.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ ) @add_start_docstrings(AutoModelForMaskedLM.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> List[str]: return AutoModelForMaskedLM.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ ) @add_start_docstrings(AutoModelForSequenceClassification.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> List[str]: return AutoModelForSequenceClassification.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ ) @add_start_docstrings(AutoModelForQuestionAnswering.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> Tuple: return AutoModelForQuestionAnswering.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ )
73
1
from typing import List, Optional, Union from ...image_utils import ImageInput from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : Union[str, Any] = ['''image_processor''', '''tokenizer'''] _UpperCAmelCase : Dict = '''BlipImageProcessor''' _UpperCAmelCase : List[str] = '''AutoTokenizer''' def __init__( self : str ,SCREAMING_SNAKE_CASE__ : List[str] ,SCREAMING_SNAKE_CASE__ : Union[str, Any]): __lowerCamelCase : Dict = False super().__init__(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = self.image_processor def __call__( self : Dict ,SCREAMING_SNAKE_CASE__ : ImageInput = None ,SCREAMING_SNAKE_CASE__ : Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None ,SCREAMING_SNAKE_CASE__ : bool = True ,SCREAMING_SNAKE_CASE__ : Union[bool, str, PaddingStrategy] = False ,SCREAMING_SNAKE_CASE__ : Union[bool, str, TruncationStrategy] = None ,SCREAMING_SNAKE_CASE__ : Optional[int] = None ,SCREAMING_SNAKE_CASE__ : int = 0 ,SCREAMING_SNAKE_CASE__ : Optional[int] = None ,SCREAMING_SNAKE_CASE__ : Optional[bool] = None ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = True ,SCREAMING_SNAKE_CASE__ : Optional[Union[str, TensorType]] = None ,**SCREAMING_SNAKE_CASE__ : List[str] ,): if images is None and text is None: raise ValueError('You have to specify either images or text.') # Get only text if images is None: __lowerCamelCase : Dict = self.tokenizer __lowerCamelCase : Tuple = self.tokenizer( text=SCREAMING_SNAKE_CASE__ ,add_special_tokens=SCREAMING_SNAKE_CASE__ ,padding=SCREAMING_SNAKE_CASE__ ,truncation=SCREAMING_SNAKE_CASE__ ,max_length=SCREAMING_SNAKE_CASE__ ,stride=SCREAMING_SNAKE_CASE__ ,pad_to_multiple_of=SCREAMING_SNAKE_CASE__ ,return_attention_mask=SCREAMING_SNAKE_CASE__ ,return_overflowing_tokens=SCREAMING_SNAKE_CASE__ ,return_special_tokens_mask=SCREAMING_SNAKE_CASE__ ,return_offsets_mapping=SCREAMING_SNAKE_CASE__ ,return_token_type_ids=SCREAMING_SNAKE_CASE__ ,return_length=SCREAMING_SNAKE_CASE__ ,verbose=SCREAMING_SNAKE_CASE__ ,return_tensors=SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__ ,) return text_encoding # add pixel_values __lowerCamelCase : Optional[int] = self.image_processor(SCREAMING_SNAKE_CASE__ ,return_tensors=SCREAMING_SNAKE_CASE__) if text is not None: __lowerCamelCase : Optional[Any] = self.tokenizer( text=SCREAMING_SNAKE_CASE__ ,add_special_tokens=SCREAMING_SNAKE_CASE__ ,padding=SCREAMING_SNAKE_CASE__ ,truncation=SCREAMING_SNAKE_CASE__ ,max_length=SCREAMING_SNAKE_CASE__ ,stride=SCREAMING_SNAKE_CASE__ ,pad_to_multiple_of=SCREAMING_SNAKE_CASE__ ,return_attention_mask=SCREAMING_SNAKE_CASE__ ,return_overflowing_tokens=SCREAMING_SNAKE_CASE__ ,return_special_tokens_mask=SCREAMING_SNAKE_CASE__ ,return_offsets_mapping=SCREAMING_SNAKE_CASE__ ,return_token_type_ids=SCREAMING_SNAKE_CASE__ ,return_length=SCREAMING_SNAKE_CASE__ ,verbose=SCREAMING_SNAKE_CASE__ ,return_tensors=SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__ ,) else: __lowerCamelCase : Any = None if text_encoding is not None: encoding_image_processor.update(SCREAMING_SNAKE_CASE__) return encoding_image_processor def lowerCAmelCase ( self : str ,*SCREAMING_SNAKE_CASE__ : Tuple ,**SCREAMING_SNAKE_CASE__ : Any): return self.tokenizer.batch_decode(*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : int ,*SCREAMING_SNAKE_CASE__ : List[str] ,**SCREAMING_SNAKE_CASE__ : Tuple): return self.tokenizer.decode(*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) @property # Copied from transformers.models.blip.processing_blip.BlipProcessor.model_input_names def lowerCAmelCase ( self : str): __lowerCamelCase : int = self.tokenizer.model_input_names __lowerCamelCase : Optional[Any] = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
73
from typing import Optional from urllib.parse import quote import huggingface_hub as hfh from packaging import version def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ = None ) -> str: if version.parse(hfh.__version__ ).release < version.parse('0.11.0' ).release: # old versions of hfh don't url-encode the file path __lowerCamelCase : int = quote(lowerCamelCase__ ) return hfh.hf_hub_url(lowerCamelCase__ , lowerCamelCase__ , repo_type='dataset' , revision=lowerCamelCase__ )
73
1
from manim import * class A_ ( SCREAMING_SNAKE_CASE ): def lowerCAmelCase ( self : Tuple): __lowerCamelCase : List[str] = Rectangle(height=0.5 ,width=0.5) __lowerCamelCase : Optional[int] = Rectangle(height=0.46 ,width=0.46).set_stroke(width=0) __lowerCamelCase : Dict = [mem.copy() for i in range(6)] __lowerCamelCase : List[Any] = [mem.copy() for i in range(6)] __lowerCamelCase : Dict = VGroup(*SCREAMING_SNAKE_CASE__).arrange(SCREAMING_SNAKE_CASE__ ,buff=0) __lowerCamelCase : Optional[Any] = VGroup(*SCREAMING_SNAKE_CASE__).arrange(SCREAMING_SNAKE_CASE__ ,buff=0) __lowerCamelCase : Any = VGroup(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__).arrange(SCREAMING_SNAKE_CASE__ ,buff=0) __lowerCamelCase : Union[str, Any] = Text('CPU' ,font_size=2_4) __lowerCamelCase : Union[str, Any] = Group(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__).arrange(SCREAMING_SNAKE_CASE__ ,buff=0.5 ,aligned_edge=SCREAMING_SNAKE_CASE__) cpu.move_to([-2.5, -0.5, 0]) self.add(SCREAMING_SNAKE_CASE__) __lowerCamelCase : str = [mem.copy() for i in range(1)] __lowerCamelCase : Optional[Any] = VGroup(*SCREAMING_SNAKE_CASE__).arrange(SCREAMING_SNAKE_CASE__ ,buff=0) __lowerCamelCase : int = Text('GPU' ,font_size=2_4) __lowerCamelCase : Union[str, Any] = Group(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__).arrange(SCREAMING_SNAKE_CASE__ ,buff=0.5 ,aligned_edge=SCREAMING_SNAKE_CASE__) gpu.align_to(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) gpu.set_x(gpu.get_x() - 1) self.add(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Tuple = [mem.copy() for i in range(6)] __lowerCamelCase : List[str] = VGroup(*SCREAMING_SNAKE_CASE__).arrange(SCREAMING_SNAKE_CASE__ ,buff=0) __lowerCamelCase : int = Text('Model' ,font_size=2_4) __lowerCamelCase : Dict = Group(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__).arrange(SCREAMING_SNAKE_CASE__ ,buff=0.5 ,aligned_edge=SCREAMING_SNAKE_CASE__) model.move_to([3, -1.0, 0]) self.play( Create(SCREAMING_SNAKE_CASE__ ,run_time=1) ,Create(SCREAMING_SNAKE_CASE__ ,run_time=1) ,Create(SCREAMING_SNAKE_CASE__ ,run_time=1) ,) __lowerCamelCase : List[Any] = MarkupText( F"First, an empty model skeleton is loaded\ninto <span fgcolor='{YELLOW}'>memory</span> without using much RAM." ,font_size=2_4 ,) __lowerCamelCase : Tuple = Square(side_length=2.2) key.move_to([-5, 2, 0]) __lowerCamelCase : Any = MarkupText( F"<b>Key:</b>\n\n<span fgcolor='{YELLOW}'>●</span> Empty Model" ,font_size=1_8 ,) key_text.move_to([-5, 2.4, 0]) step_a.move_to([2, 2, 0]) self.play(Write(SCREAMING_SNAKE_CASE__ ,run_time=2.5) ,Write(SCREAMING_SNAKE_CASE__) ,Write(SCREAMING_SNAKE_CASE__)) self.add(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = [] __lowerCamelCase : List[str] = [] __lowerCamelCase : Tuple = [] for i, rect in enumerate(SCREAMING_SNAKE_CASE__): __lowerCamelCase : Optional[int] = Rectangle(height=0.46 ,width=0.46).set_stroke(width=0.0).set_fill(SCREAMING_SNAKE_CASE__ ,opacity=0.7) cpu_target.move_to(SCREAMING_SNAKE_CASE__) cpu_target.generate_target() __lowerCamelCase : Optional[Any] = 0.46 / 4 __lowerCamelCase : Tuple = 0.46 / 3 if i == 0: cpu_target.target.next_to(cpu_left_col_base[0].get_corner(DOWN + LEFT) ,buff=0.02 ,direction=SCREAMING_SNAKE_CASE__) cpu_target.target.set_x(cpu_target.target.get_x() + 0.1) elif i == 3: cpu_target.target.next_to(cpu_targs[0].target ,direction=SCREAMING_SNAKE_CASE__ ,buff=0.0) else: cpu_target.target.next_to(cpu_targs[i - 1].target ,direction=SCREAMING_SNAKE_CASE__ ,buff=0.0) cpu_targs.append(SCREAMING_SNAKE_CASE__) first_animations.append(rect.animate(run_time=0.5).set_stroke(SCREAMING_SNAKE_CASE__)) second_animations.append(MoveToTarget(SCREAMING_SNAKE_CASE__ ,run_time=1.5)) self.play(*SCREAMING_SNAKE_CASE__) self.play(*SCREAMING_SNAKE_CASE__) self.wait()
73
def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , ) -> float: __lowerCamelCase : Dict = [redshift, radiation_density, matter_density, dark_energy] if any(p < 0 for p in parameters ): raise ValueError('All input parameters must be positive' ) if any(p > 1 for p in parameters[1:4] ): raise ValueError('Relative densities cannot be greater than one' ) else: __lowerCamelCase : Dict = 1 - (matter_density + radiation_density + dark_energy) __lowerCamelCase : Union[str, Any] = ( radiation_density * (redshift + 1) ** 4 + matter_density * (redshift + 1) ** 3 + curvature * (redshift + 1) ** 2 + dark_energy ) __lowerCamelCase : List[Any] = hubble_constant * e_a ** (1 / 2) return hubble if __name__ == "__main__": import doctest # run doctest doctest.testmod() # demo LCDM approximation a =0.3 print( hubble_parameter( hubble_constant=68.3, radiation_density=1E-4, matter_density=matter_density, dark_energy=1 - matter_density, redshift=0, ) )
73
1
import csv import tweepy # Twitter API credentials a ="""""" a ="""""" a ="""""" a ="""""" def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> None: # authorize twitter, initialize tweepy __lowerCamelCase : Tuple = tweepy.OAuthHandler(lowerCamelCase__ , lowerCamelCase__ ) auth.set_access_token(lowerCamelCase__ , lowerCamelCase__ ) __lowerCamelCase : Optional[int] = tweepy.API(lowerCamelCase__ ) # initialize a list to hold all the tweepy Tweets __lowerCamelCase : str = [] # make initial request for most recent tweets (200 is the maximum allowed count) __lowerCamelCase : Union[str, Any] = api.user_timeline(screen_name=lowerCamelCase__ , count=2_0_0 ) # save most recent tweets alltweets.extend(lowerCamelCase__ ) # save the id of the oldest tweet less one __lowerCamelCase : Any = alltweets[-1].id - 1 # keep grabbing tweets until there are no tweets left to grab while len(lowerCamelCase__ ) > 0: print(F"getting tweets before {oldest}" ) # all subsequent requests use the max_id param to prevent duplicates __lowerCamelCase : str = api.user_timeline( screen_name=lowerCamelCase__ , count=2_0_0 , max_id=lowerCamelCase__ ) # save most recent tweets alltweets.extend(lowerCamelCase__ ) # update the id of the oldest tweet less one __lowerCamelCase : Optional[int] = alltweets[-1].id - 1 print(F"...{len(lowerCamelCase__ )} tweets downloaded so far" ) # transform the tweepy tweets into a 2D array that will populate the csv __lowerCamelCase : str = [[tweet.id_str, tweet.created_at, tweet.text] for tweet in alltweets] # write the csv with open(F"new_{screen_name}_tweets.csv" , 'w' ) as f: __lowerCamelCase : Any = csv.writer(lowerCamelCase__ ) writer.writerow(['id', 'created_at', 'text'] ) writer.writerows(lowerCamelCase__ ) if __name__ == "__main__": # pass in the username of the account you want to download get_all_tweets("""FirePing32""")
73
from typing import List, Optional, Union from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : Optional[Any] = ['''image_processor''', '''tokenizer'''] _UpperCAmelCase : Union[str, Any] = '''Pix2StructImageProcessor''' _UpperCAmelCase : Any = ('''T5Tokenizer''', '''T5TokenizerFast''') def __init__( self : List[str] ,SCREAMING_SNAKE_CASE__ : str ,SCREAMING_SNAKE_CASE__ : int): __lowerCamelCase : List[Any] = False super().__init__(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) def __call__( self : str ,SCREAMING_SNAKE_CASE__ : Any=None ,SCREAMING_SNAKE_CASE__ : Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None ,SCREAMING_SNAKE_CASE__ : bool = True ,SCREAMING_SNAKE_CASE__ : Union[bool, str, PaddingStrategy] = False ,SCREAMING_SNAKE_CASE__ : Union[bool, str, TruncationStrategy] = None ,SCREAMING_SNAKE_CASE__ : Optional[int] = None ,SCREAMING_SNAKE_CASE__ : Optional[int] = 2_0_4_8 ,SCREAMING_SNAKE_CASE__ : int = 0 ,SCREAMING_SNAKE_CASE__ : Optional[int] = None ,SCREAMING_SNAKE_CASE__ : Optional[bool] = None ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = True ,SCREAMING_SNAKE_CASE__ : Optional[Union[str, TensorType]] = None ,**SCREAMING_SNAKE_CASE__ : Dict ,): if images is None and text is None: raise ValueError('You have to specify either images or text.') # Get only text if images is None and not self.image_processor.is_vqa: __lowerCamelCase : Tuple = self.tokenizer __lowerCamelCase : Dict = self.tokenizer( text=SCREAMING_SNAKE_CASE__ ,add_special_tokens=SCREAMING_SNAKE_CASE__ ,padding=SCREAMING_SNAKE_CASE__ ,truncation=SCREAMING_SNAKE_CASE__ ,max_length=SCREAMING_SNAKE_CASE__ ,stride=SCREAMING_SNAKE_CASE__ ,pad_to_multiple_of=SCREAMING_SNAKE_CASE__ ,return_attention_mask=SCREAMING_SNAKE_CASE__ ,return_overflowing_tokens=SCREAMING_SNAKE_CASE__ ,return_special_tokens_mask=SCREAMING_SNAKE_CASE__ ,return_offsets_mapping=SCREAMING_SNAKE_CASE__ ,return_token_type_ids=SCREAMING_SNAKE_CASE__ ,return_length=SCREAMING_SNAKE_CASE__ ,verbose=SCREAMING_SNAKE_CASE__ ,return_tensors=SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__ ,) return text_encoding if not self.image_processor.is_vqa: # add pixel_values __lowerCamelCase : List[Any] = self.image_processor( SCREAMING_SNAKE_CASE__ ,return_tensors=SCREAMING_SNAKE_CASE__ ,max_patches=SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) else: # add pixel_values and bbox __lowerCamelCase : List[Any] = self.image_processor( SCREAMING_SNAKE_CASE__ ,return_tensors=SCREAMING_SNAKE_CASE__ ,max_patches=SCREAMING_SNAKE_CASE__ ,header_text=SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) if text is not None and not self.image_processor.is_vqa: __lowerCamelCase : List[Any] = self.tokenizer( text=SCREAMING_SNAKE_CASE__ ,add_special_tokens=SCREAMING_SNAKE_CASE__ ,padding=SCREAMING_SNAKE_CASE__ ,truncation=SCREAMING_SNAKE_CASE__ ,max_length=SCREAMING_SNAKE_CASE__ ,stride=SCREAMING_SNAKE_CASE__ ,pad_to_multiple_of=SCREAMING_SNAKE_CASE__ ,return_attention_mask=SCREAMING_SNAKE_CASE__ ,return_overflowing_tokens=SCREAMING_SNAKE_CASE__ ,return_special_tokens_mask=SCREAMING_SNAKE_CASE__ ,return_offsets_mapping=SCREAMING_SNAKE_CASE__ ,return_token_type_ids=SCREAMING_SNAKE_CASE__ ,return_length=SCREAMING_SNAKE_CASE__ ,verbose=SCREAMING_SNAKE_CASE__ ,return_tensors=SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__ ,) if "attention_mask" in text_encoding: __lowerCamelCase : List[Any] = text_encoding.pop('attention_mask') if "input_ids" in text_encoding: __lowerCamelCase : Dict = text_encoding.pop('input_ids') else: __lowerCamelCase : Optional[int] = None if text_encoding is not None: encoding_image_processor.update(SCREAMING_SNAKE_CASE__) return encoding_image_processor def lowerCAmelCase ( self : Dict ,*SCREAMING_SNAKE_CASE__ : str ,**SCREAMING_SNAKE_CASE__ : int): return self.tokenizer.batch_decode(*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : List[str] ,*SCREAMING_SNAKE_CASE__ : int ,**SCREAMING_SNAKE_CASE__ : Dict): return self.tokenizer.decode(*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) @property def lowerCAmelCase ( self : int): __lowerCamelCase : Dict = self.tokenizer.model_input_names __lowerCamelCase : int = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
73
1
import math import flax.linen as nn import jax.numpy as jnp def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ = 1 , lowerCamelCase__ = 1 , lowerCamelCase__ = 1.0e4 , lowerCamelCase__ = False , lowerCamelCase__ = 1.0 , ) -> jnp.ndarray: assert timesteps.ndim == 1, "Timesteps should be a 1d-array" assert embedding_dim % 2 == 0, F"Embedding dimension {embedding_dim} should be even" __lowerCamelCase : Optional[int] = float(embedding_dim // 2 ) __lowerCamelCase : Optional[Any] = math.log(max_timescale / min_timescale ) / (num_timescales - freq_shift) __lowerCamelCase : Tuple = min_timescale * jnp.exp(jnp.arange(lowerCamelCase__ , dtype=jnp.floataa ) * -log_timescale_increment ) __lowerCamelCase : List[str] = jnp.expand_dims(lowerCamelCase__ , 1 ) * jnp.expand_dims(lowerCamelCase__ , 0 ) # scale embeddings __lowerCamelCase : Dict = scale * emb if flip_sin_to_cos: __lowerCamelCase : List[Any] = jnp.concatenate([jnp.cos(lowerCamelCase__ ), jnp.sin(lowerCamelCase__ )] , axis=1 ) else: __lowerCamelCase : Dict = jnp.concatenate([jnp.sin(lowerCamelCase__ ), jnp.cos(lowerCamelCase__ )] , axis=1 ) __lowerCamelCase : Union[str, Any] = jnp.reshape(lowerCamelCase__ , [jnp.shape(lowerCamelCase__ )[0], embedding_dim] ) return signal class A_ ( nn.Module ): _UpperCAmelCase : int = 32 _UpperCAmelCase : jnp.dtype = jnp.floataa @nn.compact def __call__( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : List[Any]): __lowerCamelCase : str = nn.Dense(self.time_embed_dim ,dtype=self.dtype ,name='linear_1')(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Any = nn.silu(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Union[str, Any] = nn.Dense(self.time_embed_dim ,dtype=self.dtype ,name='linear_2')(SCREAMING_SNAKE_CASE__) return temb class A_ ( nn.Module ): _UpperCAmelCase : int = 32 _UpperCAmelCase : bool = False _UpperCAmelCase : float = 1 @nn.compact def __call__( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : List[str]): return get_sinusoidal_embeddings( SCREAMING_SNAKE_CASE__ ,embedding_dim=self.dim ,flip_sin_to_cos=self.flip_sin_to_cos ,freq_shift=self.freq_shift)
73
from bisect import bisect from itertools import accumulate def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> Union[str, Any]: __lowerCamelCase : Optional[Any] = sorted(zip(lowerCamelCase__ , lowerCamelCase__ ) , key=lambda lowerCamelCase__ : x[0] / x[1] , reverse=lowerCamelCase__ ) __lowerCamelCase , __lowerCamelCase : Any = [i[0] for i in r], [i[1] for i in r] __lowerCamelCase : List[str] = list(accumulate(lowerCamelCase__ ) ) __lowerCamelCase : Union[str, Any] = bisect(lowerCamelCase__ , lowerCamelCase__ ) return ( 0 if k == 0 else sum(vl[:k] ) + (w - acc[k - 1]) * (vl[k]) / (wt[k]) if k != n else sum(vl[:k] ) ) if __name__ == "__main__": import doctest doctest.testmod()
73
1
from __future__ import annotations import copy import tempfile import unittest from transformers import CONFIG_MAPPING, AutoConfig, BertConfig, GPTaConfig, TaConfig, TapasConfig, is_tf_available from transformers.testing_utils import ( DUMMY_UNKNOWN_IDENTIFIER, SMALL_MODEL_IDENTIFIER, RequestCounter, require_tensorflow_probability, require_tf, slow, ) from ..bert.test_modeling_bert import BertModelTester if is_tf_available(): from transformers import ( TFAutoModel, TFAutoModelForCausalLM, TFAutoModelForMaskedLM, TFAutoModelForPreTraining, TFAutoModelForQuestionAnswering, TFAutoModelForSeqaSeqLM, TFAutoModelForSequenceClassification, TFAutoModelForTableQuestionAnswering, TFAutoModelForTokenClassification, TFAutoModelWithLMHead, TFBertForMaskedLM, TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification, TFBertModel, TFFunnelBaseModel, TFFunnelModel, TFGPTaLMHeadModel, TFRobertaForMaskedLM, TFTaForConditionalGeneration, TFTapasForQuestionAnswering, ) from transformers.models.auto.modeling_tf_auto import ( TF_MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_MASKED_LM_MAPPING, TF_MODEL_FOR_PRETRAINING_MAPPING, TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, TF_MODEL_MAPPING, ) from transformers.models.bert.modeling_tf_bert import TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST from transformers.models.gpta.modeling_tf_gpta import TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST from transformers.models.ta.modeling_tf_ta import TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST from transformers.models.tapas.modeling_tf_tapas import TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : str = '''new-model''' if is_tf_available(): class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : Tuple = NewModelConfig @require_tf class A_ ( unittest.TestCase ): @slow def lowerCAmelCase ( self : Tuple): __lowerCamelCase : str = 'bert-base-cased' __lowerCamelCase : str = AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE__) self.assertIsNotNone(SCREAMING_SNAKE_CASE__) self.assertIsInstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Tuple = TFAutoModel.from_pretrained(SCREAMING_SNAKE_CASE__) self.assertIsNotNone(SCREAMING_SNAKE_CASE__) self.assertIsInstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) @slow def lowerCAmelCase ( self : Optional[int]): __lowerCamelCase : Any = 'bert-base-cased' __lowerCamelCase : Tuple = AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE__) self.assertIsNotNone(SCREAMING_SNAKE_CASE__) self.assertIsInstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Union[str, Any] = TFAutoModelForPreTraining.from_pretrained(SCREAMING_SNAKE_CASE__) self.assertIsNotNone(SCREAMING_SNAKE_CASE__) self.assertIsInstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) @slow def lowerCAmelCase ( self : Optional[int]): for model_name in TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __lowerCamelCase : str = AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE__) self.assertIsNotNone(SCREAMING_SNAKE_CASE__) self.assertIsInstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Dict = TFAutoModelForCausalLM.from_pretrained(SCREAMING_SNAKE_CASE__) __lowerCamelCase , __lowerCamelCase : int = TFAutoModelForCausalLM.from_pretrained(SCREAMING_SNAKE_CASE__ ,output_loading_info=SCREAMING_SNAKE_CASE__) self.assertIsNotNone(SCREAMING_SNAKE_CASE__) self.assertIsInstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) @slow def lowerCAmelCase ( self : str): for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __lowerCamelCase : Optional[int] = AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE__) self.assertIsNotNone(SCREAMING_SNAKE_CASE__) self.assertIsInstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Dict = TFAutoModelWithLMHead.from_pretrained(SCREAMING_SNAKE_CASE__) self.assertIsNotNone(SCREAMING_SNAKE_CASE__) self.assertIsInstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) @slow def lowerCAmelCase ( self : List[str]): for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __lowerCamelCase : List[str] = AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE__) self.assertIsNotNone(SCREAMING_SNAKE_CASE__) self.assertIsInstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[str] = TFAutoModelForMaskedLM.from_pretrained(SCREAMING_SNAKE_CASE__) __lowerCamelCase , __lowerCamelCase : List[str] = TFAutoModelForMaskedLM.from_pretrained(SCREAMING_SNAKE_CASE__ ,output_loading_info=SCREAMING_SNAKE_CASE__) self.assertIsNotNone(SCREAMING_SNAKE_CASE__) self.assertIsInstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) @slow def lowerCAmelCase ( self : Any): for model_name in TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __lowerCamelCase : str = AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE__) self.assertIsNotNone(SCREAMING_SNAKE_CASE__) self.assertIsInstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Any = TFAutoModelForSeqaSeqLM.from_pretrained(SCREAMING_SNAKE_CASE__) __lowerCamelCase , __lowerCamelCase : Optional[Any] = TFAutoModelForSeqaSeqLM.from_pretrained(SCREAMING_SNAKE_CASE__ ,output_loading_info=SCREAMING_SNAKE_CASE__) self.assertIsNotNone(SCREAMING_SNAKE_CASE__) self.assertIsInstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) @slow def lowerCAmelCase ( self : Tuple): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: __lowerCamelCase : Dict = AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE__) self.assertIsNotNone(SCREAMING_SNAKE_CASE__) self.assertIsInstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[str] = TFAutoModelForSequenceClassification.from_pretrained(SCREAMING_SNAKE_CASE__) self.assertIsNotNone(SCREAMING_SNAKE_CASE__) self.assertIsInstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) @slow def lowerCAmelCase ( self : str): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: __lowerCamelCase : Tuple = AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE__) self.assertIsNotNone(SCREAMING_SNAKE_CASE__) self.assertIsInstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : int = TFAutoModelForQuestionAnswering.from_pretrained(SCREAMING_SNAKE_CASE__) self.assertIsNotNone(SCREAMING_SNAKE_CASE__) self.assertIsInstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) @slow @require_tensorflow_probability def lowerCAmelCase ( self : List[str]): for model_name in TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST[5:6]: __lowerCamelCase : List[str] = AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE__) self.assertIsNotNone(SCREAMING_SNAKE_CASE__) self.assertIsInstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = TFAutoModelForTableQuestionAnswering.from_pretrained(SCREAMING_SNAKE_CASE__) __lowerCamelCase , __lowerCamelCase : int = TFAutoModelForTableQuestionAnswering.from_pretrained( SCREAMING_SNAKE_CASE__ ,output_loading_info=SCREAMING_SNAKE_CASE__) self.assertIsNotNone(SCREAMING_SNAKE_CASE__) self.assertIsInstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Any): __lowerCamelCase : Tuple = TFAutoModelWithLMHead.from_pretrained(SCREAMING_SNAKE_CASE__) self.assertIsInstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) self.assertEqual(model.num_parameters() ,1_4_4_1_0) self.assertEqual(model.num_parameters(only_trainable=SCREAMING_SNAKE_CASE__) ,1_4_4_1_0) def lowerCAmelCase ( self : Union[str, Any]): __lowerCamelCase : Dict = TFAutoModelWithLMHead.from_pretrained(SCREAMING_SNAKE_CASE__) self.assertIsInstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) self.assertEqual(model.num_parameters() ,1_4_4_1_0) self.assertEqual(model.num_parameters(only_trainable=SCREAMING_SNAKE_CASE__) ,1_4_4_1_0) def lowerCAmelCase ( self : str): # For the auto model mapping, FunnelConfig has two models: FunnelModel and FunnelBaseModel __lowerCamelCase : Optional[Any] = TFAutoModel.from_pretrained('sgugger/funnel-random-tiny') self.assertIsInstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : str = copy.deepcopy(model.config) __lowerCamelCase : int = ['FunnelBaseModel'] __lowerCamelCase : List[str] = TFAutoModel.from_config(SCREAMING_SNAKE_CASE__) self.assertIsInstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) with tempfile.TemporaryDirectory() as tmp_dir: model.save_pretrained(SCREAMING_SNAKE_CASE__) __lowerCamelCase : str = TFAutoModel.from_pretrained(SCREAMING_SNAKE_CASE__) self.assertIsInstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Any): try: AutoConfig.register('new-model' ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Union[str, Any] = [ TFAutoModel, TFAutoModelForCausalLM, TFAutoModelForMaskedLM, TFAutoModelForPreTraining, TFAutoModelForQuestionAnswering, TFAutoModelForSequenceClassification, TFAutoModelForTokenClassification, ] for auto_class in auto_classes: with self.subTest(auto_class.__name__): # Wrong config class will raise an error with self.assertRaises(SCREAMING_SNAKE_CASE__): auto_class.register(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) auto_class.register(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(SCREAMING_SNAKE_CASE__): auto_class.register(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) # Now that the config is registered, it can be used as any other config with the auto-API __lowerCamelCase : List[Any] = BertModelTester(self).get_config() __lowerCamelCase : Optional[int] = NewModelConfig(**tiny_config.to_dict()) __lowerCamelCase : List[Any] = auto_class.from_config(SCREAMING_SNAKE_CASE__) self.assertIsInstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) with tempfile.TemporaryDirectory() as tmp_dir: model.save_pretrained(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Any = auto_class.from_pretrained(SCREAMING_SNAKE_CASE__) self.assertIsInstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) finally: if "new-model" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["new-model"] for mapping in ( TF_MODEL_MAPPING, TF_MODEL_FOR_PRETRAINING_MAPPING, TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, TF_MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_MASKED_LM_MAPPING, ): if NewModelConfig in mapping._extra_content: del mapping._extra_content[NewModelConfig] def lowerCAmelCase ( self : Optional[int]): with self.assertRaisesRegex( SCREAMING_SNAKE_CASE__ ,'bert-base is not a local folder and is not a valid model identifier'): __lowerCamelCase : str = TFAutoModel.from_pretrained('bert-base') def lowerCAmelCase ( self : str): with self.assertRaisesRegex( SCREAMING_SNAKE_CASE__ ,R'aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)'): __lowerCamelCase : Optional[Any] = TFAutoModel.from_pretrained(SCREAMING_SNAKE_CASE__ ,revision='aaaaaa') def lowerCAmelCase ( self : Union[str, Any]): with self.assertRaisesRegex( SCREAMING_SNAKE_CASE__ ,'hf-internal-testing/config-no-model does not appear to have a file named pytorch_model.bin' ,): __lowerCamelCase : str = TFAutoModel.from_pretrained('hf-internal-testing/config-no-model') def lowerCAmelCase ( self : Optional[int]): with self.assertRaisesRegex(SCREAMING_SNAKE_CASE__ ,'Use `from_pt=True` to load this model'): __lowerCamelCase : Any = TFAutoModel.from_pretrained('hf-internal-testing/tiny-bert-pt-only') def lowerCAmelCase ( self : Dict): # Make sure we have cached the model. __lowerCamelCase : Dict = TFAutoModel.from_pretrained('hf-internal-testing/tiny-random-bert') with RequestCounter() as counter: __lowerCamelCase : List[Any] = TFAutoModel.from_pretrained('hf-internal-testing/tiny-random-bert') self.assertEqual(counter.get_request_count ,0) self.assertEqual(counter.head_request_count ,1) self.assertEqual(counter.other_request_count ,0) # With a sharded checkpoint __lowerCamelCase : Dict = TFAutoModel.from_pretrained('ArthurZ/tiny-random-bert-sharded') with RequestCounter() as counter: __lowerCamelCase : List[str] = TFAutoModel.from_pretrained('ArthurZ/tiny-random-bert-sharded') self.assertEqual(counter.get_request_count ,0) self.assertEqual(counter.head_request_count ,1) self.assertEqual(counter.other_request_count ,0)
73
from __future__ import annotations import math def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> list: if len(lowerCamelCase__ ) != 2 or len(a[0] ) != 2 or len(lowerCamelCase__ ) != 2 or len(b[0] ) != 2: raise Exception('Matrices are not 2x2' ) __lowerCamelCase : Optional[int] = [ [a[0][0] * b[0][0] + a[0][1] * b[1][0], a[0][0] * b[0][1] + a[0][1] * b[1][1]], [a[1][0] * b[0][0] + a[1][1] * b[1][0], a[1][0] * b[0][1] + a[1][1] * b[1][1]], ] return new_matrix def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> Optional[int]: return [ [matrix_a[row][col] + matrix_b[row][col] for col in range(len(matrix_a[row] ) )] for row in range(len(lowerCamelCase__ ) ) ] def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> List[str]: return [ [matrix_a[row][col] - matrix_b[row][col] for col in range(len(matrix_a[row] ) )] for row in range(len(lowerCamelCase__ ) ) ] def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> tuple[list, list, list, list]: if len(lowerCamelCase__ ) % 2 != 0 or len(a[0] ) % 2 != 0: raise Exception('Odd matrices are not supported!' ) __lowerCamelCase : Tuple = len(lowerCamelCase__ ) __lowerCamelCase : List[Any] = matrix_length // 2 __lowerCamelCase : Dict = [[a[i][j] for j in range(lowerCamelCase__ , lowerCamelCase__ )] for i in range(lowerCamelCase__ )] __lowerCamelCase : str = [ [a[i][j] for j in range(lowerCamelCase__ , lowerCamelCase__ )] for i in range(lowerCamelCase__ , lowerCamelCase__ ) ] __lowerCamelCase : Dict = [[a[i][j] for j in range(lowerCamelCase__ )] for i in range(lowerCamelCase__ )] __lowerCamelCase : Optional[Any] = [[a[i][j] for j in range(lowerCamelCase__ )] for i in range(lowerCamelCase__ , lowerCamelCase__ )] return top_left, top_right, bot_left, bot_right def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> tuple[int, int]: return len(lowerCamelCase__ ), len(matrix[0] ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> None: print('\n'.join(str(lowerCamelCase__ ) for line in matrix ) ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> list: if matrix_dimensions(lowerCamelCase__ ) == (2, 2): return default_matrix_multiplication(lowerCamelCase__ , lowerCamelCase__ ) __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : Optional[Any] = split_matrix(lowerCamelCase__ ) __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : Optional[Any] = split_matrix(lowerCamelCase__ ) __lowerCamelCase : str = actual_strassen(lowerCamelCase__ , matrix_subtraction(lowerCamelCase__ , lowerCamelCase__ ) ) __lowerCamelCase : List[str] = actual_strassen(matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) , lowerCamelCase__ ) __lowerCamelCase : List[Any] = actual_strassen(matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) , lowerCamelCase__ ) __lowerCamelCase : Tuple = actual_strassen(lowerCamelCase__ , matrix_subtraction(lowerCamelCase__ , lowerCamelCase__ ) ) __lowerCamelCase : Optional[int] = actual_strassen(matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) , matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) ) __lowerCamelCase : Dict = actual_strassen(matrix_subtraction(lowerCamelCase__ , lowerCamelCase__ ) , matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) ) __lowerCamelCase : Tuple = actual_strassen(matrix_subtraction(lowerCamelCase__ , lowerCamelCase__ ) , matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) ) __lowerCamelCase : Dict = matrix_addition(matrix_subtraction(matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) , lowerCamelCase__ ) , lowerCamelCase__ ) __lowerCamelCase : Tuple = matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) __lowerCamelCase : List[str] = matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) __lowerCamelCase : Any = matrix_subtraction(matrix_subtraction(matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) , lowerCamelCase__ ) , lowerCamelCase__ ) # construct the new matrix from our 4 quadrants __lowerCamelCase : List[Any] = [] for i in range(len(lowerCamelCase__ ) ): new_matrix.append(top_left[i] + top_right[i] ) for i in range(len(lowerCamelCase__ ) ): new_matrix.append(bot_left[i] + bot_right[i] ) return new_matrix def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> list: if matrix_dimensions(lowerCamelCase__ )[1] != matrix_dimensions(lowerCamelCase__ )[0]: __lowerCamelCase : Any = ( 'Unable to multiply these matrices, please check the dimensions.\n' F"Matrix A: {matrixa}\n" F"Matrix B: {matrixa}" ) raise Exception(lowerCamelCase__ ) __lowerCamelCase : str = matrix_dimensions(lowerCamelCase__ ) __lowerCamelCase : List[str] = matrix_dimensions(lowerCamelCase__ ) if dimensiona[0] == dimensiona[1] and dimensiona[0] == dimensiona[1]: return [matrixa, matrixa] __lowerCamelCase : str = max(*lowerCamelCase__ , *lowerCamelCase__ ) __lowerCamelCase : List[str] = int(math.pow(2 , math.ceil(math.loga(lowerCamelCase__ ) ) ) ) __lowerCamelCase : Any = matrixa __lowerCamelCase : int = matrixa # Adding zeros to the matrices so that the arrays dimensions are the same and also # power of 2 for i in range(0 , lowerCamelCase__ ): if i < dimensiona[0]: for _ in range(dimensiona[1] , lowerCamelCase__ ): new_matrixa[i].append(0 ) else: new_matrixa.append([0] * maxim ) if i < dimensiona[0]: for _ in range(dimensiona[1] , lowerCamelCase__ ): new_matrixa[i].append(0 ) else: new_matrixa.append([0] * maxim ) __lowerCamelCase : List[str] = actual_strassen(lowerCamelCase__ , lowerCamelCase__ ) # Removing the additional zeros for i in range(0 , lowerCamelCase__ ): if i < dimensiona[0]: for _ in range(dimensiona[1] , lowerCamelCase__ ): final_matrix[i].pop() else: final_matrix.pop() return final_matrix if __name__ == "__main__": a =[ [2, 3, 4, 5], [6, 4, 3, 1], [2, 3, 6, 7], [3, 1, 2, 4], [2, 3, 4, 5], [6, 4, 3, 1], [2, 3, 6, 7], [3, 1, 2, 4], [2, 3, 4, 5], [6, 2, 3, 1], ] a =[[0, 2, 1, 1], [16, 2, 3, 3], [2, 2, 7, 7], [13, 11, 22, 4]] print(strassen(matrixa, matrixa))
73
1
import tempfile import unittest import numpy as np from diffusers import ( DDIMScheduler, DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, LMSDiscreteScheduler, OnnxStableDiffusionPipeline, PNDMScheduler, ) from diffusers.utils.testing_utils import is_onnx_available, nightly, require_onnxruntime, require_torch_gpu from ..test_pipelines_onnx_common import OnnxPipelineTesterMixin if is_onnx_available(): import onnxruntime as ort class A_ ( SCREAMING_SNAKE_CASE , unittest.TestCase ): _UpperCAmelCase : Tuple = '''hf-internal-testing/tiny-random-OnnxStableDiffusionPipeline''' def lowerCAmelCase ( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : str=0): __lowerCamelCase : Tuple = np.random.RandomState(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Any = { 'prompt': 'A painting of a squirrel eating a burger', 'generator': generator, 'num_inference_steps': 2, 'guidance_scale': 7.5, 'output_type': 'numpy', } return inputs def lowerCAmelCase ( self : List[str]): __lowerCamelCase : Tuple = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint ,provider='CPUExecutionProvider') pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__) __lowerCamelCase : Dict = self.get_dummy_inputs() __lowerCamelCase : Tuple = pipe(**SCREAMING_SNAKE_CASE__).images __lowerCamelCase : Optional[Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 1_2_8, 1_2_8, 3) __lowerCamelCase : Any = np.array([0.65072, 0.58492, 0.48219, 0.55521, 0.53180, 0.55939, 0.50697, 0.39800, 0.46455]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1E-2 def lowerCAmelCase ( self : Dict): __lowerCamelCase : List[str] = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint ,provider='CPUExecutionProvider') __lowerCamelCase : Optional[int] = PNDMScheduler.from_config(pipe.scheduler.config ,skip_prk_steps=SCREAMING_SNAKE_CASE__) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__) __lowerCamelCase : Tuple = self.get_dummy_inputs() __lowerCamelCase : List[Any] = pipe(**SCREAMING_SNAKE_CASE__).images __lowerCamelCase : List[Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 1_2_8, 1_2_8, 3) __lowerCamelCase : Union[str, Any] = np.array([0.65863, 0.59425, 0.49326, 0.56313, 0.53875, 0.56627, 0.51065, 0.39777, 0.46330]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1E-2 def lowerCAmelCase ( self : Tuple): __lowerCamelCase : int = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint ,provider='CPUExecutionProvider') __lowerCamelCase : Optional[Any] = LMSDiscreteScheduler.from_config(pipe.scheduler.config) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[str] = self.get_dummy_inputs() __lowerCamelCase : Dict = pipe(**SCREAMING_SNAKE_CASE__).images __lowerCamelCase : Any = image[0, -3:, -3:, -1] assert image.shape == (1, 1_2_8, 1_2_8, 3) __lowerCamelCase : List[str] = np.array([0.53755, 0.60786, 0.47402, 0.49488, 0.51869, 0.49819, 0.47985, 0.38957, 0.44279]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1E-2 def lowerCAmelCase ( self : List[str]): __lowerCamelCase : str = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint ,provider='CPUExecutionProvider') __lowerCamelCase : List[Any] = EulerDiscreteScheduler.from_config(pipe.scheduler.config) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__) __lowerCamelCase : Tuple = self.get_dummy_inputs() __lowerCamelCase : Optional[Any] = pipe(**SCREAMING_SNAKE_CASE__).images __lowerCamelCase : List[str] = image[0, -3:, -3:, -1] assert image.shape == (1, 1_2_8, 1_2_8, 3) __lowerCamelCase : List[Any] = np.array([0.53755, 0.60786, 0.47402, 0.49488, 0.51869, 0.49819, 0.47985, 0.38957, 0.44279]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1E-2 def lowerCAmelCase ( self : int): __lowerCamelCase : List[Any] = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint ,provider='CPUExecutionProvider') __lowerCamelCase : str = EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__) __lowerCamelCase : Any = self.get_dummy_inputs() __lowerCamelCase : Optional[int] = pipe(**SCREAMING_SNAKE_CASE__).images __lowerCamelCase : Optional[Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 1_2_8, 1_2_8, 3) __lowerCamelCase : List[Any] = np.array([0.53817, 0.60812, 0.47384, 0.49530, 0.51894, 0.49814, 0.47984, 0.38958, 0.44271]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1E-2 def lowerCAmelCase ( self : Dict): __lowerCamelCase : Tuple = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint ,provider='CPUExecutionProvider') __lowerCamelCase : List[Any] = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__) __lowerCamelCase : Union[str, Any] = self.get_dummy_inputs() __lowerCamelCase : Optional[Any] = pipe(**SCREAMING_SNAKE_CASE__).images __lowerCamelCase : str = image[0, -3:, -3:, -1] assert image.shape == (1, 1_2_8, 1_2_8, 3) __lowerCamelCase : List[str] = np.array([0.53895, 0.60808, 0.47933, 0.49608, 0.51886, 0.49950, 0.48053, 0.38957, 0.44200]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1E-2 def lowerCAmelCase ( self : Dict): __lowerCamelCase : Optional[Any] = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint ,provider='CPUExecutionProvider') pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__) __lowerCamelCase : Dict = self.get_dummy_inputs() __lowerCamelCase : Optional[int] = 3 * [inputs['prompt']] # forward __lowerCamelCase : List[Any] = pipe(**SCREAMING_SNAKE_CASE__) __lowerCamelCase : Union[str, Any] = output.images[0, -3:, -3:, -1] __lowerCamelCase : Union[str, Any] = self.get_dummy_inputs() __lowerCamelCase : Union[str, Any] = 3 * [inputs.pop('prompt')] __lowerCamelCase : Tuple = pipe.tokenizer( SCREAMING_SNAKE_CASE__ ,padding='max_length' ,max_length=pipe.tokenizer.model_max_length ,truncation=SCREAMING_SNAKE_CASE__ ,return_tensors='np' ,) __lowerCamelCase : List[Any] = text_inputs['input_ids'] __lowerCamelCase : Dict = pipe.text_encoder(input_ids=text_inputs.astype(np.intaa))[0] __lowerCamelCase : List[Any] = prompt_embeds # forward __lowerCamelCase : Optional[int] = pipe(**SCREAMING_SNAKE_CASE__) __lowerCamelCase : Dict = output.images[0, -3:, -3:, -1] assert np.abs(image_slice_a.flatten() - image_slice_a.flatten()).max() < 1E-4 def lowerCAmelCase ( self : Optional[Any]): __lowerCamelCase : Optional[int] = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint ,provider='CPUExecutionProvider') pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__) __lowerCamelCase : Any = self.get_dummy_inputs() __lowerCamelCase : Dict = 3 * ['this is a negative prompt'] __lowerCamelCase : Dict = negative_prompt __lowerCamelCase : Any = 3 * [inputs['prompt']] # forward __lowerCamelCase : Dict = pipe(**SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[str] = output.images[0, -3:, -3:, -1] __lowerCamelCase : Any = self.get_dummy_inputs() __lowerCamelCase : Dict = 3 * [inputs.pop('prompt')] __lowerCamelCase : Optional[int] = [] for p in [prompt, negative_prompt]: __lowerCamelCase : Any = pipe.tokenizer( SCREAMING_SNAKE_CASE__ ,padding='max_length' ,max_length=pipe.tokenizer.model_max_length ,truncation=SCREAMING_SNAKE_CASE__ ,return_tensors='np' ,) __lowerCamelCase : Optional[int] = text_inputs['input_ids'] embeds.append(pipe.text_encoder(input_ids=text_inputs.astype(np.intaa))[0]) __lowerCamelCase , __lowerCamelCase : Optional[int] = embeds # forward __lowerCamelCase : Optional[Any] = pipe(**SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[str] = output.images[0, -3:, -3:, -1] assert np.abs(image_slice_a.flatten() - image_slice_a.flatten()).max() < 1E-4 @nightly @require_onnxruntime @require_torch_gpu class A_ ( unittest.TestCase ): @property def lowerCAmelCase ( self : str): return ( "CUDAExecutionProvider", { "gpu_mem_limit": "15000000000", # 15GB "arena_extend_strategy": "kSameAsRequested", }, ) @property def lowerCAmelCase ( self : str): __lowerCamelCase : List[Any] = ort.SessionOptions() __lowerCamelCase : Any = False return options def lowerCAmelCase ( self : Union[str, Any]): # using the PNDM scheduler by default __lowerCamelCase : Optional[Any] = OnnxStableDiffusionPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' ,revision='onnx' ,safety_checker=SCREAMING_SNAKE_CASE__ ,feature_extractor=SCREAMING_SNAKE_CASE__ ,provider=self.gpu_provider ,sess_options=self.gpu_options ,) sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[int] = 'A painting of a squirrel eating a burger' np.random.seed(0) __lowerCamelCase : Dict = sd_pipe([prompt] ,guidance_scale=6.0 ,num_inference_steps=1_0 ,output_type='np') __lowerCamelCase : Union[str, Any] = output.images __lowerCamelCase : Union[str, Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 5_1_2, 5_1_2, 3) __lowerCamelCase : Optional[int] = np.array([0.0452, 0.0390, 0.0087, 0.0350, 0.0617, 0.0364, 0.0544, 0.0523, 0.0720]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1E-3 def lowerCAmelCase ( self : str): __lowerCamelCase : Any = DDIMScheduler.from_pretrained( 'runwayml/stable-diffusion-v1-5' ,subfolder='scheduler' ,revision='onnx') __lowerCamelCase : List[Any] = OnnxStableDiffusionPipeline.from_pretrained( 'runwayml/stable-diffusion-v1-5' ,revision='onnx' ,scheduler=SCREAMING_SNAKE_CASE__ ,safety_checker=SCREAMING_SNAKE_CASE__ ,feature_extractor=SCREAMING_SNAKE_CASE__ ,provider=self.gpu_provider ,sess_options=self.gpu_options ,) sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__) __lowerCamelCase : int = 'open neural network exchange' __lowerCamelCase : Union[str, Any] = np.random.RandomState(0) __lowerCamelCase : int = sd_pipe([prompt] ,guidance_scale=7.5 ,num_inference_steps=1_0 ,generator=SCREAMING_SNAKE_CASE__ ,output_type='np') __lowerCamelCase : Union[str, Any] = output.images __lowerCamelCase : Dict = image[0, -3:, -3:, -1] assert image.shape == (1, 5_1_2, 5_1_2, 3) __lowerCamelCase : Union[str, Any] = np.array([0.2867, 0.1974, 0.1481, 0.7294, 0.7251, 0.6667, 0.4194, 0.5642, 0.6486]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1E-3 def lowerCAmelCase ( self : List[Any]): __lowerCamelCase : List[str] = LMSDiscreteScheduler.from_pretrained( 'runwayml/stable-diffusion-v1-5' ,subfolder='scheduler' ,revision='onnx') __lowerCamelCase : Optional[Any] = OnnxStableDiffusionPipeline.from_pretrained( 'runwayml/stable-diffusion-v1-5' ,revision='onnx' ,scheduler=SCREAMING_SNAKE_CASE__ ,safety_checker=SCREAMING_SNAKE_CASE__ ,feature_extractor=SCREAMING_SNAKE_CASE__ ,provider=self.gpu_provider ,sess_options=self.gpu_options ,) sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[int] = 'open neural network exchange' __lowerCamelCase : Dict = np.random.RandomState(0) __lowerCamelCase : Optional[int] = sd_pipe([prompt] ,guidance_scale=7.5 ,num_inference_steps=1_0 ,generator=SCREAMING_SNAKE_CASE__ ,output_type='np') __lowerCamelCase : Union[str, Any] = output.images __lowerCamelCase : str = image[0, -3:, -3:, -1] assert image.shape == (1, 5_1_2, 5_1_2, 3) __lowerCamelCase : List[str] = np.array([0.2306, 0.1959, 0.1593, 0.6549, 0.6394, 0.5408, 0.5065, 0.6010, 0.6161]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1E-3 def lowerCAmelCase ( self : int): __lowerCamelCase : List[str] = 0 def test_callback_fn(SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : np.ndarray) -> None: __lowerCamelCase : Any = True nonlocal number_of_steps number_of_steps += 1 if step == 0: assert latents.shape == (1, 4, 6_4, 6_4) __lowerCamelCase : Dict = latents[0, -3:, -3:, -1] __lowerCamelCase : Dict = np.array( [-0.6772, -0.3835, -1.2456, 0.1905, -1.0974, 0.6967, -1.9353, 0.0178, 1.0167]) assert np.abs(latents_slice.flatten() - expected_slice).max() < 1E-3 elif step == 5: assert latents.shape == (1, 4, 6_4, 6_4) __lowerCamelCase : Tuple = latents[0, -3:, -3:, -1] __lowerCamelCase : Optional[int] = np.array( [-0.3351, 0.2241, -0.1837, -0.2325, -0.6577, 0.3393, -0.0241, 0.5899, 1.3875]) assert np.abs(latents_slice.flatten() - expected_slice).max() < 1E-3 __lowerCamelCase : int = False __lowerCamelCase : Optional[int] = OnnxStableDiffusionPipeline.from_pretrained( 'runwayml/stable-diffusion-v1-5' ,revision='onnx' ,safety_checker=SCREAMING_SNAKE_CASE__ ,feature_extractor=SCREAMING_SNAKE_CASE__ ,provider=self.gpu_provider ,sess_options=self.gpu_options ,) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[str] = 'Andromeda galaxy in a bottle' __lowerCamelCase : str = np.random.RandomState(0) pipe( prompt=SCREAMING_SNAKE_CASE__ ,num_inference_steps=5 ,guidance_scale=7.5 ,generator=SCREAMING_SNAKE_CASE__ ,callback=SCREAMING_SNAKE_CASE__ ,callback_steps=1 ,) assert test_callback_fn.has_been_called assert number_of_steps == 6 def lowerCAmelCase ( self : List[str]): __lowerCamelCase : Any = OnnxStableDiffusionPipeline.from_pretrained( 'runwayml/stable-diffusion-v1-5' ,revision='onnx' ,safety_checker=SCREAMING_SNAKE_CASE__ ,feature_extractor=SCREAMING_SNAKE_CASE__ ,provider=self.gpu_provider ,sess_options=self.gpu_options ,) assert isinstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) assert pipe.safety_checker is None __lowerCamelCase : Union[str, Any] = pipe('example prompt' ,num_inference_steps=2).images[0] assert image is not None # check that there's no error when saving a pipeline with one of the models being None with tempfile.TemporaryDirectory() as tmpdirname: pipe.save_pretrained(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Tuple = OnnxStableDiffusionPipeline.from_pretrained(SCREAMING_SNAKE_CASE__) # sanity check that the pipeline still works assert pipe.safety_checker is None __lowerCamelCase : Tuple = pipe('example prompt' ,num_inference_steps=2).images[0] assert image is not None
73
from math import isclose, sqrt def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> tuple[float, float, float]: __lowerCamelCase : Tuple = point_y / 4 / point_x __lowerCamelCase : Tuple = 2 * normal_gradient / (1 + normal_gradient * normal_gradient) __lowerCamelCase : List[Any] = (1 - normal_gradient * normal_gradient) / ( 1 + normal_gradient * normal_gradient ) __lowerCamelCase : int = (sa - ca * incoming_gradient) / (ca + sa * incoming_gradient) # to find the next point, solve the simultaeneous equations: # y^2 + 4x^2 = 100 # y - b = m * (x - a) # ==> A x^2 + B x + C = 0 __lowerCamelCase : Any = outgoing_gradient**2 + 4 __lowerCamelCase : Optional[int] = 2 * outgoing_gradient * (point_y - outgoing_gradient * point_x) __lowerCamelCase : str = (point_y - outgoing_gradient * point_x) ** 2 - 1_0_0 __lowerCamelCase : str = ( -linear_term - sqrt(linear_term**2 - 4 * quadratic_term * constant_term ) ) / (2 * quadratic_term) __lowerCamelCase : Optional[Any] = ( -linear_term + sqrt(linear_term**2 - 4 * quadratic_term * constant_term ) ) / (2 * quadratic_term) # two solutions, one of which is our input point __lowerCamelCase : Optional[Any] = x_minus if isclose(lowerCamelCase__ , lowerCamelCase__ ) else x_plus __lowerCamelCase : Tuple = point_y + outgoing_gradient * (next_x - point_x) return next_x, next_y, outgoing_gradient def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ = 1.4 , lowerCamelCase__ = -9.6 ) -> int: __lowerCamelCase : int = 0 __lowerCamelCase : float = first_x_coord __lowerCamelCase : float = first_y_coord __lowerCamelCase : float = (10.1 - point_y) / (0.0 - point_x) while not (-0.01 <= point_x <= 0.01 and point_y > 0): __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : Any = next_point(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) num_reflections += 1 return num_reflections if __name__ == "__main__": print(F"""{solution() = }""")
73
1
import argparse import io import requests import torch from omegaconf import OmegaConf from diffusers import AutoencoderKL from diffusers.pipelines.stable_diffusion.convert_from_ckpt import ( assign_to_checkpoint, conv_attn_to_linear, create_vae_diffusers_config, renew_vae_attention_paths, renew_vae_resnet_paths, ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> List[str]: __lowerCamelCase : str = checkpoint __lowerCamelCase : Optional[Any] = {} __lowerCamelCase : Any = vae_state_dict['encoder.conv_in.weight'] __lowerCamelCase : List[str] = vae_state_dict['encoder.conv_in.bias'] __lowerCamelCase : Optional[Any] = vae_state_dict['encoder.conv_out.weight'] __lowerCamelCase : int = vae_state_dict['encoder.conv_out.bias'] __lowerCamelCase : Union[str, Any] = vae_state_dict['encoder.norm_out.weight'] __lowerCamelCase : Optional[int] = vae_state_dict['encoder.norm_out.bias'] __lowerCamelCase : Optional[Any] = vae_state_dict['decoder.conv_in.weight'] __lowerCamelCase : Optional[int] = vae_state_dict['decoder.conv_in.bias'] __lowerCamelCase : Union[str, Any] = vae_state_dict['decoder.conv_out.weight'] __lowerCamelCase : Any = vae_state_dict['decoder.conv_out.bias'] __lowerCamelCase : int = vae_state_dict['decoder.norm_out.weight'] __lowerCamelCase : Optional[int] = vae_state_dict['decoder.norm_out.bias'] __lowerCamelCase : Dict = vae_state_dict['quant_conv.weight'] __lowerCamelCase : Optional[Any] = vae_state_dict['quant_conv.bias'] __lowerCamelCase : Optional[int] = vae_state_dict['post_quant_conv.weight'] __lowerCamelCase : str = vae_state_dict['post_quant_conv.bias'] # Retrieves the keys for the encoder down blocks only __lowerCamelCase : Optional[int] = len({'.'.join(layer.split('.' )[:3] ) for layer in vae_state_dict if 'encoder.down' in layer} ) __lowerCamelCase : str = { layer_id: [key for key in vae_state_dict if F"down.{layer_id}" in key] for layer_id in range(lowerCamelCase__ ) } # Retrieves the keys for the decoder up blocks only __lowerCamelCase : Any = len({'.'.join(layer.split('.' )[:3] ) for layer in vae_state_dict if 'decoder.up' in layer} ) __lowerCamelCase : Tuple = { layer_id: [key for key in vae_state_dict if F"up.{layer_id}" in key] for layer_id in range(lowerCamelCase__ ) } for i in range(lowerCamelCase__ ): __lowerCamelCase : Optional[int] = [key for key in down_blocks[i] if F"down.{i}" in key and F"down.{i}.downsample" not in key] if F"encoder.down.{i}.downsample.conv.weight" in vae_state_dict: __lowerCamelCase : Optional[Any] = vae_state_dict.pop( F"encoder.down.{i}.downsample.conv.weight" ) __lowerCamelCase : Union[str, Any] = vae_state_dict.pop( F"encoder.down.{i}.downsample.conv.bias" ) __lowerCamelCase : List[str] = renew_vae_resnet_paths(lowerCamelCase__ ) __lowerCamelCase : List[str] = {'old': F"down.{i}.block", 'new': F"down_blocks.{i}.resnets"} assign_to_checkpoint(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , additional_replacements=[meta_path] , config=lowerCamelCase__ ) __lowerCamelCase : int = [key for key in vae_state_dict if 'encoder.mid.block' in key] __lowerCamelCase : Optional[Any] = 2 for i in range(1 , num_mid_res_blocks + 1 ): __lowerCamelCase : str = [key for key in mid_resnets if F"encoder.mid.block_{i}" in key] __lowerCamelCase : Optional[int] = renew_vae_resnet_paths(lowerCamelCase__ ) __lowerCamelCase : Tuple = {'old': F"mid.block_{i}", 'new': F"mid_block.resnets.{i - 1}"} assign_to_checkpoint(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , additional_replacements=[meta_path] , config=lowerCamelCase__ ) __lowerCamelCase : Union[str, Any] = [key for key in vae_state_dict if 'encoder.mid.attn' in key] __lowerCamelCase : Optional[Any] = renew_vae_attention_paths(lowerCamelCase__ ) __lowerCamelCase : Any = {'old': 'mid.attn_1', 'new': 'mid_block.attentions.0'} assign_to_checkpoint(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , additional_replacements=[meta_path] , config=lowerCamelCase__ ) conv_attn_to_linear(lowerCamelCase__ ) for i in range(lowerCamelCase__ ): __lowerCamelCase : str = num_up_blocks - 1 - i __lowerCamelCase : Optional[int] = [ key for key in up_blocks[block_id] if F"up.{block_id}" in key and F"up.{block_id}.upsample" not in key ] if F"decoder.up.{block_id}.upsample.conv.weight" in vae_state_dict: __lowerCamelCase : Union[str, Any] = vae_state_dict[ F"decoder.up.{block_id}.upsample.conv.weight" ] __lowerCamelCase : int = vae_state_dict[ F"decoder.up.{block_id}.upsample.conv.bias" ] __lowerCamelCase : str = renew_vae_resnet_paths(lowerCamelCase__ ) __lowerCamelCase : Optional[int] = {'old': F"up.{block_id}.block", 'new': F"up_blocks.{i}.resnets"} assign_to_checkpoint(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , additional_replacements=[meta_path] , config=lowerCamelCase__ ) __lowerCamelCase : List[str] = [key for key in vae_state_dict if 'decoder.mid.block' in key] __lowerCamelCase : List[Any] = 2 for i in range(1 , num_mid_res_blocks + 1 ): __lowerCamelCase : Optional[Any] = [key for key in mid_resnets if F"decoder.mid.block_{i}" in key] __lowerCamelCase : Optional[Any] = renew_vae_resnet_paths(lowerCamelCase__ ) __lowerCamelCase : Optional[Any] = {'old': F"mid.block_{i}", 'new': F"mid_block.resnets.{i - 1}"} assign_to_checkpoint(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , additional_replacements=[meta_path] , config=lowerCamelCase__ ) __lowerCamelCase : Union[str, Any] = [key for key in vae_state_dict if 'decoder.mid.attn' in key] __lowerCamelCase : Optional[int] = renew_vae_attention_paths(lowerCamelCase__ ) __lowerCamelCase : List[Any] = {'old': 'mid.attn_1', 'new': 'mid_block.attentions.0'} assign_to_checkpoint(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , additional_replacements=[meta_path] , config=lowerCamelCase__ ) conv_attn_to_linear(lowerCamelCase__ ) return new_checkpoint def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , ) -> str: # Only support V1 __lowerCamelCase : Tuple = requests.get( ' https://raw.githubusercontent.com/CompVis/stable-diffusion/main/configs/stable-diffusion/v1-inference.yaml' ) __lowerCamelCase : List[Any] = io.BytesIO(r.content ) __lowerCamelCase : int = OmegaConf.load(lowerCamelCase__ ) __lowerCamelCase : int = 5_1_2 __lowerCamelCase : Optional[Any] = 'cuda' if torch.cuda.is_available() else 'cpu' if checkpoint_path.endswith('safetensors' ): from safetensors import safe_open __lowerCamelCase : Dict = {} with safe_open(lowerCamelCase__ , framework='pt' , device='cpu' ) as f: for key in f.keys(): __lowerCamelCase : Dict = f.get_tensor(lowerCamelCase__ ) else: __lowerCamelCase : Optional[int] = torch.load(lowerCamelCase__ , map_location=lowerCamelCase__ )['state_dict'] # Convert the VAE model. __lowerCamelCase : Dict = create_vae_diffusers_config(lowerCamelCase__ , image_size=lowerCamelCase__ ) __lowerCamelCase : Tuple = custom_convert_ldm_vae_checkpoint(lowerCamelCase__ , lowerCamelCase__ ) __lowerCamelCase : Union[str, Any] = AutoencoderKL(**lowerCamelCase__ ) vae.load_state_dict(lowerCamelCase__ ) vae.save_pretrained(lowerCamelCase__ ) if __name__ == "__main__": a =argparse.ArgumentParser() parser.add_argument("""--vae_pt_path""", default=None, type=str, required=True, help="""Path to the VAE.pt to convert.""") parser.add_argument("""--dump_path""", default=None, type=str, required=True, help="""Path to the VAE.pt to convert.""") a =parser.parse_args() vae_pt_to_vae_diffuser(args.vae_pt_path, args.dump_path)
73
import os import unicodedata from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging a =logging.get_logger(__name__) a ={"""vocab_file""": """spiece.model"""} a ={ """vocab_file""": { """albert-base-v1""": """https://huggingface.co/albert-base-v1/resolve/main/spiece.model""", """albert-large-v1""": """https://huggingface.co/albert-large-v1/resolve/main/spiece.model""", """albert-xlarge-v1""": """https://huggingface.co/albert-xlarge-v1/resolve/main/spiece.model""", """albert-xxlarge-v1""": """https://huggingface.co/albert-xxlarge-v1/resolve/main/spiece.model""", """albert-base-v2""": """https://huggingface.co/albert-base-v2/resolve/main/spiece.model""", """albert-large-v2""": """https://huggingface.co/albert-large-v2/resolve/main/spiece.model""", """albert-xlarge-v2""": """https://huggingface.co/albert-xlarge-v2/resolve/main/spiece.model""", """albert-xxlarge-v2""": """https://huggingface.co/albert-xxlarge-v2/resolve/main/spiece.model""", } } a ={ """albert-base-v1""": 512, """albert-large-v1""": 512, """albert-xlarge-v1""": 512, """albert-xxlarge-v1""": 512, """albert-base-v2""": 512, """albert-large-v2""": 512, """albert-xlarge-v2""": 512, """albert-xxlarge-v2""": 512, } a ="""▁""" class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : List[Any] = VOCAB_FILES_NAMES _UpperCAmelCase : List[str] = PRETRAINED_VOCAB_FILES_MAP _UpperCAmelCase : Optional[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self : str ,SCREAMING_SNAKE_CASE__ : Optional[int] ,SCREAMING_SNAKE_CASE__ : Tuple=True ,SCREAMING_SNAKE_CASE__ : str=True ,SCREAMING_SNAKE_CASE__ : List[str]=False ,SCREAMING_SNAKE_CASE__ : Any="[CLS]" ,SCREAMING_SNAKE_CASE__ : Optional[int]="[SEP]" ,SCREAMING_SNAKE_CASE__ : Optional[Any]="<unk>" ,SCREAMING_SNAKE_CASE__ : Any="[SEP]" ,SCREAMING_SNAKE_CASE__ : Optional[int]="<pad>" ,SCREAMING_SNAKE_CASE__ : Any="[CLS]" ,SCREAMING_SNAKE_CASE__ : Union[str, Any]="[MASK]" ,SCREAMING_SNAKE_CASE__ : Optional[Dict[str, Any]] = None ,**SCREAMING_SNAKE_CASE__ : Dict ,): # Mask token behave like a normal word, i.e. include the space before it and # is included in the raw text, there should be a match in a non-normalized sentence. __lowerCamelCase : Dict = ( AddedToken(SCREAMING_SNAKE_CASE__ ,lstrip=SCREAMING_SNAKE_CASE__ ,rstrip=SCREAMING_SNAKE_CASE__ ,normalized=SCREAMING_SNAKE_CASE__) if isinstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) else mask_token ) __lowerCamelCase : str = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( do_lower_case=SCREAMING_SNAKE_CASE__ ,remove_space=SCREAMING_SNAKE_CASE__ ,keep_accents=SCREAMING_SNAKE_CASE__ ,bos_token=SCREAMING_SNAKE_CASE__ ,eos_token=SCREAMING_SNAKE_CASE__ ,unk_token=SCREAMING_SNAKE_CASE__ ,sep_token=SCREAMING_SNAKE_CASE__ ,pad_token=SCREAMING_SNAKE_CASE__ ,cls_token=SCREAMING_SNAKE_CASE__ ,mask_token=SCREAMING_SNAKE_CASE__ ,sp_model_kwargs=self.sp_model_kwargs ,**SCREAMING_SNAKE_CASE__ ,) __lowerCamelCase : Any = do_lower_case __lowerCamelCase : Union[str, Any] = remove_space __lowerCamelCase : Tuple = keep_accents __lowerCamelCase : Dict = vocab_file __lowerCamelCase : str = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.Load(SCREAMING_SNAKE_CASE__) @property def lowerCAmelCase ( self : Optional[Any]): return len(self.sp_model) def lowerCAmelCase ( self : Optional[Any]): __lowerCamelCase : Optional[int] = {self.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__): i for i in range(self.vocab_size)} vocab.update(self.added_tokens_encoder) return vocab def __getstate__( self : Union[str, Any]): __lowerCamelCase : str = self.__dict__.copy() __lowerCamelCase : Tuple = None return state def __setstate__( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : str): __lowerCamelCase : List[str] = d # for backward compatibility if not hasattr(self ,'sp_model_kwargs'): __lowerCamelCase : List[str] = {} __lowerCamelCase : int = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.Load(self.vocab_file) def lowerCAmelCase ( self : Dict ,SCREAMING_SNAKE_CASE__ : List[Any]): if self.remove_space: __lowerCamelCase : Dict = ' '.join(inputs.strip().split()) else: __lowerCamelCase : Optional[Any] = inputs __lowerCamelCase : Tuple = outputs.replace('``' ,'"').replace('\'\'' ,'"') if not self.keep_accents: __lowerCamelCase : List[str] = unicodedata.normalize('NFKD' ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : str = ''.join([c for c in outputs if not unicodedata.combining(SCREAMING_SNAKE_CASE__)]) if self.do_lower_case: __lowerCamelCase : Optional[Any] = outputs.lower() return outputs def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : str): __lowerCamelCase : Tuple = self.preprocess_text(SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = self.sp_model.encode(SCREAMING_SNAKE_CASE__ ,out_type=SCREAMING_SNAKE_CASE__) __lowerCamelCase : Tuple = [] for piece in pieces: if len(SCREAMING_SNAKE_CASE__) > 1 and piece[-1] == str(',') and piece[-2].isdigit(): __lowerCamelCase : int = self.sp_model.EncodeAsPieces(piece[:-1].replace(SCREAMING_SNAKE_CASE__ ,'')) if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE: if len(cur_pieces[0]) == 1: __lowerCamelCase : Union[str, Any] = cur_pieces[1:] else: __lowerCamelCase : Dict = cur_pieces[0][1:] cur_pieces.append(piece[-1]) new_pieces.extend(SCREAMING_SNAKE_CASE__) else: new_pieces.append(SCREAMING_SNAKE_CASE__) return new_pieces def lowerCAmelCase ( self : Any ,SCREAMING_SNAKE_CASE__ : List[str]): return self.sp_model.PieceToId(SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : str ,SCREAMING_SNAKE_CASE__ : Any): return self.sp_model.IdToPiece(SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Tuple ,SCREAMING_SNAKE_CASE__ : int): __lowerCamelCase : Optional[Any] = [] __lowerCamelCase : int = '' __lowerCamelCase : Optional[int] = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(SCREAMING_SNAKE_CASE__) + token __lowerCamelCase : List[Any] = True __lowerCamelCase : Any = [] else: current_sub_tokens.append(SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = False out_string += self.sp_model.decode(SCREAMING_SNAKE_CASE__) return out_string.strip() def lowerCAmelCase ( self : Dict ,SCREAMING_SNAKE_CASE__ : List[int] ,SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None): __lowerCamelCase : Union[str, Any] = [self.sep_token_id] __lowerCamelCase : int = [self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def lowerCAmelCase ( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : List[int] ,SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ,SCREAMING_SNAKE_CASE__ : bool = False): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=SCREAMING_SNAKE_CASE__ ,token_ids_a=SCREAMING_SNAKE_CASE__ ,already_has_special_tokens=SCREAMING_SNAKE_CASE__) if token_ids_a is not None: return [1] + ([0] * len(SCREAMING_SNAKE_CASE__)) + [1] + ([0] * len(SCREAMING_SNAKE_CASE__)) + [1] return [1] + ([0] * len(SCREAMING_SNAKE_CASE__)) + [1] def lowerCAmelCase ( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : List[int] ,SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None): __lowerCamelCase : Tuple = [self.sep_token_id] __lowerCamelCase : List[Any] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep) * [0] return len(cls + token_ids_a + sep) * [0] + len(token_ids_a + sep) * [1] def lowerCAmelCase ( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : str ,SCREAMING_SNAKE_CASE__ : Optional[str] = None): if not os.path.isdir(SCREAMING_SNAKE_CASE__): logger.error(F"Vocabulary path ({save_directory}) should be a directory") return __lowerCamelCase : List[str] = os.path.join( SCREAMING_SNAKE_CASE__ ,(filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file']) if os.path.abspath(self.vocab_file) != os.path.abspath(SCREAMING_SNAKE_CASE__) and os.path.isfile(self.vocab_file): copyfile(self.vocab_file ,SCREAMING_SNAKE_CASE__) elif not os.path.isfile(self.vocab_file): with open(SCREAMING_SNAKE_CASE__ ,'wb') as fi: __lowerCamelCase : str = self.sp_model.serialized_model_proto() fi.write(SCREAMING_SNAKE_CASE__) return (out_vocab_file,)
73
1
from typing import TYPE_CHECKING from ...file_utils import _LazyModule, is_tokenizers_available, is_torch_available from ...utils import OptionalDependencyNotAvailable a ={"""configuration_gpt_neox""": ["""GPT_NEOX_PRETRAINED_CONFIG_ARCHIVE_MAP""", """GPTNeoXConfig"""]} try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a =["""GPTNeoXTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a =[ """GPT_NEOX_PRETRAINED_MODEL_ARCHIVE_LIST""", """GPTNeoXForCausalLM""", """GPTNeoXForQuestionAnswering""", """GPTNeoXForSequenceClassification""", """GPTNeoXForTokenClassification""", """GPTNeoXLayer""", """GPTNeoXModel""", """GPTNeoXPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_gpt_neox import GPT_NEOX_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTNeoXConfig try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_gpt_neox_fast import GPTNeoXTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_gpt_neox import ( GPT_NEOX_PRETRAINED_MODEL_ARCHIVE_LIST, GPTNeoXForCausalLM, GPTNeoXForQuestionAnswering, GPTNeoXForSequenceClassification, GPTNeoXForTokenClassification, GPTNeoXLayer, GPTNeoXModel, GPTNeoXPreTrainedModel, ) else: import sys a =_LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
73
def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> float: if discount_rate < 0: raise ValueError('Discount rate cannot be negative' ) if not cash_flows: raise ValueError('Cash flows list cannot be empty' ) __lowerCamelCase : int = sum( cash_flow / ((1 + discount_rate) ** i) for i, cash_flow in enumerate(lowerCamelCase__ ) ) return round(lowerCamelCase__ , ndigits=2 ) if __name__ == "__main__": import doctest doctest.testmod()
73
1
import random def _a ( a :int ) -> bool: a = num - 1 a = 0 while s % 2 == 0: a = s // 2 t += 1 for _ in range(5 ): a = random.randrange(2 , num - 1 ) a = pow(a , a , a ) if v != 1: a = 0 while v != (num - 1): if i == t - 1: return False else: a = i + 1 a = (v**2) % num return True def _a ( a :int ) -> bool: if num < 2: return False a = [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997, ] if num in low_primes: return True for prime in low_primes: if (num % prime) == 0: return False return rabin_miller(a ) def _a ( a :int = 1_024 ) -> int: while True: a = random.randrange(2 ** (keysize - 1) , 2 ** (keysize) ) if is_prime_low_num(a ): return num if __name__ == "__main__": UpperCAmelCase__ = generate_large_prime() print(("Prime number:", num)) print(("is_prime_low_num:", is_prime_low_num(num)))
0
import copy from typing import Dict, List, Optional from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING a ={ """facebook/mask2former-swin-small-coco-instance""": ( """https://huggingface.co/facebook/mask2former-swin-small-coco-instance/blob/main/config.json""" ) # See all Mask2Former models at https://huggingface.co/models?filter=mask2former } a =logging.get_logger(__name__) class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : Dict = '''mask2former''' _UpperCAmelCase : Dict = ['''swin'''] _UpperCAmelCase : Optional[int] = {'''hidden_size''': '''hidden_dim'''} def __init__( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : Optional[Dict] = None ,SCREAMING_SNAKE_CASE__ : int = 2_5_6 ,SCREAMING_SNAKE_CASE__ : int = 2_5_6 ,SCREAMING_SNAKE_CASE__ : int = 2_5_6 ,SCREAMING_SNAKE_CASE__ : int = 1_0_2_4 ,SCREAMING_SNAKE_CASE__ : str = "relu" ,SCREAMING_SNAKE_CASE__ : int = 6 ,SCREAMING_SNAKE_CASE__ : int = 1_0 ,SCREAMING_SNAKE_CASE__ : int = 8 ,SCREAMING_SNAKE_CASE__ : float = 0.0 ,SCREAMING_SNAKE_CASE__ : int = 2_0_4_8 ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : int = 4 ,SCREAMING_SNAKE_CASE__ : int = 2_5_5 ,SCREAMING_SNAKE_CASE__ : int = 1_0_0 ,SCREAMING_SNAKE_CASE__ : float = 0.1 ,SCREAMING_SNAKE_CASE__ : float = 2.0 ,SCREAMING_SNAKE_CASE__ : float = 5.0 ,SCREAMING_SNAKE_CASE__ : float = 5.0 ,SCREAMING_SNAKE_CASE__ : int = 1_2_5_4_4 ,SCREAMING_SNAKE_CASE__ : float = 3.0 ,SCREAMING_SNAKE_CASE__ : float = 0.75 ,SCREAMING_SNAKE_CASE__ : float = 0.02 ,SCREAMING_SNAKE_CASE__ : float = 1.0 ,SCREAMING_SNAKE_CASE__ : bool = True ,SCREAMING_SNAKE_CASE__ : List[int] = [4, 8, 1_6, 3_2] ,SCREAMING_SNAKE_CASE__ : bool = None ,**SCREAMING_SNAKE_CASE__ : Optional[Any] ,): if backbone_config is None: logger.info('`backbone_config` is `None`. Initializing the config with the default `Swin` backbone.') __lowerCamelCase : Optional[Any] = CONFIG_MAPPING['swin']( image_size=2_2_4 ,in_channels=3 ,patch_size=4 ,embed_dim=9_6 ,depths=[2, 2, 1_8, 2] ,num_heads=[3, 6, 1_2, 2_4] ,window_size=7 ,drop_path_rate=0.3 ,use_absolute_embeddings=SCREAMING_SNAKE_CASE__ ,out_features=['stage1', 'stage2', 'stage3', 'stage4'] ,) if isinstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__): __lowerCamelCase : Union[str, Any] = backbone_config.pop('model_type') __lowerCamelCase : Dict = CONFIG_MAPPING[backbone_model_type] __lowerCamelCase : int = config_class.from_dict(SCREAMING_SNAKE_CASE__) # verify that the backbone is supported if backbone_config.model_type not in self.backbones_supported: logger.warning_once( F"Backbone {backbone_config.model_type} is not a supported model and may not be compatible with Mask2Former. " F"Supported model types: {','.join(self.backbones_supported)}") __lowerCamelCase : Dict = backbone_config __lowerCamelCase : int = feature_size __lowerCamelCase : List[str] = mask_feature_size __lowerCamelCase : int = hidden_dim __lowerCamelCase : str = encoder_feedforward_dim __lowerCamelCase : Optional[int] = activation_function __lowerCamelCase : int = encoder_layers __lowerCamelCase : List[Any] = decoder_layers __lowerCamelCase : Union[str, Any] = num_attention_heads __lowerCamelCase : Tuple = dropout __lowerCamelCase : Dict = dim_feedforward __lowerCamelCase : Union[str, Any] = pre_norm __lowerCamelCase : List[str] = enforce_input_projection __lowerCamelCase : Optional[int] = common_stride __lowerCamelCase : Dict = ignore_value __lowerCamelCase : Optional[Any] = num_queries __lowerCamelCase : int = no_object_weight __lowerCamelCase : Optional[Any] = class_weight __lowerCamelCase : str = mask_weight __lowerCamelCase : List[str] = dice_weight __lowerCamelCase : Dict = train_num_points __lowerCamelCase : Optional[int] = oversample_ratio __lowerCamelCase : Optional[Any] = importance_sample_ratio __lowerCamelCase : List[Any] = init_std __lowerCamelCase : Tuple = init_xavier_std __lowerCamelCase : Union[str, Any] = use_auxiliary_loss __lowerCamelCase : List[Any] = feature_strides __lowerCamelCase : Any = output_auxiliary_logits __lowerCamelCase : List[Any] = decoder_layers super().__init__(**SCREAMING_SNAKE_CASE__) @classmethod def lowerCAmelCase ( cls : str ,SCREAMING_SNAKE_CASE__ : PretrainedConfig ,**SCREAMING_SNAKE_CASE__ : Tuple): return cls( backbone_config=SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__ ,) def lowerCAmelCase ( self : str): __lowerCamelCase : List[Any] = copy.deepcopy(self.__dict__) __lowerCamelCase : List[Any] = self.backbone_config.to_dict() __lowerCamelCase : Union[str, Any] = self.__class__.model_type return output
73
0
'''simple docstring''' import argparse import io import requests import torch from omegaconf import OmegaConf from diffusers import AutoencoderKL from diffusers.pipelines.stable_diffusion.convert_from_ckpt import ( assign_to_checkpoint, conv_attn_to_linear, create_vae_diffusers_config, renew_vae_attention_paths, renew_vae_resnet_paths, ) def lowerCAmelCase_ ( snake_case_ : List[Any] , snake_case_ : int ) -> Optional[int]: '''simple docstring''' UpperCAmelCase_ = checkpoint UpperCAmelCase_ = {} UpperCAmelCase_ = vae_state_dict["encoder.conv_in.weight"] UpperCAmelCase_ = vae_state_dict["encoder.conv_in.bias"] UpperCAmelCase_ = vae_state_dict["encoder.conv_out.weight"] UpperCAmelCase_ = vae_state_dict["encoder.conv_out.bias"] UpperCAmelCase_ = vae_state_dict["encoder.norm_out.weight"] UpperCAmelCase_ = vae_state_dict["encoder.norm_out.bias"] UpperCAmelCase_ = vae_state_dict["decoder.conv_in.weight"] UpperCAmelCase_ = vae_state_dict["decoder.conv_in.bias"] UpperCAmelCase_ = vae_state_dict["decoder.conv_out.weight"] UpperCAmelCase_ = vae_state_dict["decoder.conv_out.bias"] UpperCAmelCase_ = vae_state_dict["decoder.norm_out.weight"] UpperCAmelCase_ = vae_state_dict["decoder.norm_out.bias"] UpperCAmelCase_ = vae_state_dict["quant_conv.weight"] UpperCAmelCase_ = vae_state_dict["quant_conv.bias"] UpperCAmelCase_ = vae_state_dict["post_quant_conv.weight"] UpperCAmelCase_ = vae_state_dict["post_quant_conv.bias"] # Retrieves the keys for the encoder down blocks only UpperCAmelCase_ = len({".".join(layer.split("." )[:3] ) for layer in vae_state_dict if "encoder.down" in layer} ) UpperCAmelCase_ = { layer_id: [key for key in vae_state_dict if f"""down.{layer_id}""" in key] for layer_id in range(snake_case_ ) } # Retrieves the keys for the decoder up blocks only UpperCAmelCase_ = len({".".join(layer.split("." )[:3] ) for layer in vae_state_dict if "decoder.up" in layer} ) UpperCAmelCase_ = { layer_id: [key for key in vae_state_dict if f"""up.{layer_id}""" in key] for layer_id in range(snake_case_ ) } for i in range(snake_case_ ): UpperCAmelCase_ = [key for key in down_blocks[i] if f"""down.{i}""" in key and f"""down.{i}.downsample""" not in key] if f"""encoder.down.{i}.downsample.conv.weight""" in vae_state_dict: UpperCAmelCase_ = vae_state_dict.pop( f"""encoder.down.{i}.downsample.conv.weight""" ) UpperCAmelCase_ = vae_state_dict.pop( f"""encoder.down.{i}.downsample.conv.bias""" ) UpperCAmelCase_ = renew_vae_resnet_paths(snake_case_ ) UpperCAmelCase_ = {"old": f"""down.{i}.block""", "new": f"""down_blocks.{i}.resnets"""} assign_to_checkpoint(snake_case_ , snake_case_ , snake_case_ , additional_replacements=[meta_path] , config=snake_case_ ) UpperCAmelCase_ = [key for key in vae_state_dict if "encoder.mid.block" in key] UpperCAmelCase_ = 2 for i in range(1 , num_mid_res_blocks + 1 ): UpperCAmelCase_ = [key for key in mid_resnets if f"""encoder.mid.block_{i}""" in key] UpperCAmelCase_ = renew_vae_resnet_paths(snake_case_ ) UpperCAmelCase_ = {"old": f"""mid.block_{i}""", "new": f"""mid_block.resnets.{i - 1}"""} assign_to_checkpoint(snake_case_ , snake_case_ , snake_case_ , additional_replacements=[meta_path] , config=snake_case_ ) UpperCAmelCase_ = [key for key in vae_state_dict if "encoder.mid.attn" in key] UpperCAmelCase_ = renew_vae_attention_paths(snake_case_ ) UpperCAmelCase_ = {"old": "mid.attn_1", "new": "mid_block.attentions.0"} assign_to_checkpoint(snake_case_ , snake_case_ , snake_case_ , additional_replacements=[meta_path] , config=snake_case_ ) conv_attn_to_linear(snake_case_ ) for i in range(snake_case_ ): UpperCAmelCase_ = num_up_blocks - 1 - i UpperCAmelCase_ = [ key for key in up_blocks[block_id] if f"""up.{block_id}""" in key and f"""up.{block_id}.upsample""" not in key ] if f"""decoder.up.{block_id}.upsample.conv.weight""" in vae_state_dict: UpperCAmelCase_ = vae_state_dict[ f"""decoder.up.{block_id}.upsample.conv.weight""" ] UpperCAmelCase_ = vae_state_dict[ f"""decoder.up.{block_id}.upsample.conv.bias""" ] UpperCAmelCase_ = renew_vae_resnet_paths(snake_case_ ) UpperCAmelCase_ = {"old": f"""up.{block_id}.block""", "new": f"""up_blocks.{i}.resnets"""} assign_to_checkpoint(snake_case_ , snake_case_ , snake_case_ , additional_replacements=[meta_path] , config=snake_case_ ) UpperCAmelCase_ = [key for key in vae_state_dict if "decoder.mid.block" in key] UpperCAmelCase_ = 2 for i in range(1 , num_mid_res_blocks + 1 ): UpperCAmelCase_ = [key for key in mid_resnets if f"""decoder.mid.block_{i}""" in key] UpperCAmelCase_ = renew_vae_resnet_paths(snake_case_ ) UpperCAmelCase_ = {"old": f"""mid.block_{i}""", "new": f"""mid_block.resnets.{i - 1}"""} assign_to_checkpoint(snake_case_ , snake_case_ , snake_case_ , additional_replacements=[meta_path] , config=snake_case_ ) UpperCAmelCase_ = [key for key in vae_state_dict if "decoder.mid.attn" in key] UpperCAmelCase_ = renew_vae_attention_paths(snake_case_ ) UpperCAmelCase_ = {"old": "mid.attn_1", "new": "mid_block.attentions.0"} assign_to_checkpoint(snake_case_ , snake_case_ , snake_case_ , additional_replacements=[meta_path] , config=snake_case_ ) conv_attn_to_linear(snake_case_ ) return new_checkpoint def lowerCAmelCase_ ( snake_case_ : str , snake_case_ : str , ) -> Dict: '''simple docstring''' UpperCAmelCase_ = requests.get( " https://raw.githubusercontent.com/CompVis/stable-diffusion/main/configs/stable-diffusion/v1-inference.yaml" ) UpperCAmelCase_ = io.BytesIO(r.content ) UpperCAmelCase_ = OmegaConf.load(snake_case_ ) UpperCAmelCase_ = 5_12 UpperCAmelCase_ = "cuda" if torch.cuda.is_available() else "cpu" if checkpoint_path.endswith("safetensors" ): from safetensors import safe_open UpperCAmelCase_ = {} with safe_open(snake_case_ , framework="pt" , device="cpu" ) as f: for key in f.keys(): UpperCAmelCase_ = f.get_tensor(snake_case_ ) else: UpperCAmelCase_ = torch.load(snake_case_ , map_location=snake_case_ )["state_dict"] # Convert the VAE model. UpperCAmelCase_ = create_vae_diffusers_config(snake_case_ , image_size=snake_case_ ) UpperCAmelCase_ = custom_convert_ldm_vae_checkpoint(snake_case_ , snake_case_ ) UpperCAmelCase_ = AutoencoderKL(**snake_case_ ) vae.load_state_dict(snake_case_ ) vae.save_pretrained(snake_case_ ) if __name__ == "__main__": SCREAMING_SNAKE_CASE_: Optional[int] =argparse.ArgumentParser() parser.add_argument('--vae_pt_path', default=None, type=str, required=True, help='Path to the VAE.pt to convert.') parser.add_argument('--dump_path', default=None, type=str, required=True, help='Path to the VAE.pt to convert.') SCREAMING_SNAKE_CASE_: str =parser.parse_args() vae_pt_to_vae_diffuser(args.vae_pt_path, args.dump_path)
1
import string # frequency taken from https://en.wikipedia.org/wiki/Letter_frequency a ={ """E""": 12.70, """T""": 9.06, """A""": 8.17, """O""": 7.51, """I""": 6.97, """N""": 6.75, """S""": 6.33, """H""": 6.09, """R""": 5.99, """D""": 4.25, """L""": 4.03, """C""": 2.78, """U""": 2.76, """M""": 2.41, """W""": 2.36, """F""": 2.23, """G""": 2.02, """Y""": 1.97, """P""": 1.93, """B""": 1.29, """V""": 0.98, """K""": 0.77, """J""": 0.15, """X""": 0.15, """Q""": 0.10, """Z""": 0.07, } a ="""ETAOINSHRDLCUMWFGYPBVKJXQZ""" a ="""ABCDEFGHIJKLMNOPQRSTUVWXYZ""" def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> dict[str, int]: __lowerCamelCase : Tuple = {letter: 0 for letter in string.ascii_uppercase} for letter in message.upper(): if letter in LETTERS: letter_count[letter] += 1 return letter_count def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> str: return x[0] def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> str: __lowerCamelCase : List[str] = get_letter_count(lowerCamelCase__ ) __lowerCamelCase : dict[int, list[str]] = { freq: [] for letter, freq in letter_to_freq.items() } for letter in LETTERS: freq_to_letter[letter_to_freq[letter]].append(lowerCamelCase__ ) __lowerCamelCase : dict[int, str] = {} for freq in freq_to_letter: freq_to_letter[freq].sort(key=ETAOIN.find , reverse=lowerCamelCase__ ) __lowerCamelCase : Optional[Any] = ''.join(freq_to_letter[freq] ) __lowerCamelCase : int = list(freq_to_letter_str.items() ) freq_pairs.sort(key=lowerCamelCase__ , reverse=lowerCamelCase__ ) __lowerCamelCase : list[str] = [freq_pair[1] for freq_pair in freq_pairs] return "".join(lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> int: __lowerCamelCase : str = get_frequency_order(lowerCamelCase__ ) __lowerCamelCase : Optional[Any] = 0 for common_letter in ETAOIN[:6]: if common_letter in freq_order[:6]: match_score += 1 for uncommon_letter in ETAOIN[-6:]: if uncommon_letter in freq_order[-6:]: match_score += 1 return match_score if __name__ == "__main__": import doctest doctest.testmod()
73
0
'''simple docstring''' from __future__ import annotations class __lowerCAmelCase : '''simple docstring''' def __init__(self : Any , UpperCamelCase : int = 0 ): '''simple docstring''' lowercase__ = key def UpperCamelCase__ (self : str , UpperCamelCase : str , UpperCamelCase : int ): '''simple docstring''' assert isinstance(UpperCamelCase , UpperCamelCase ) and isinstance(UpperCamelCase , UpperCamelCase ) lowercase__ = key or self.__key or 1 # make sure key is an appropriate size key %= 255 return [chr(ord(UpperCamelCase ) ^ key ) for ch in content] def UpperCamelCase__ (self : List[Any] , UpperCamelCase : str , UpperCamelCase : int ): '''simple docstring''' assert isinstance(UpperCamelCase , UpperCamelCase ) and isinstance(UpperCamelCase , UpperCamelCase ) lowercase__ = key or self.__key or 1 # make sure key is an appropriate size key %= 255 return [chr(ord(UpperCamelCase ) ^ key ) for ch in content] def UpperCamelCase__ (self : Optional[Any] , UpperCamelCase : str , UpperCamelCase : int = 0 ): '''simple docstring''' assert isinstance(UpperCamelCase , UpperCamelCase ) and isinstance(UpperCamelCase , UpperCamelCase ) lowercase__ = key or self.__key or 1 # make sure key can be any size while key > 255: key -= 255 # This will be returned lowercase__ = '''''' for ch in content: ans += chr(ord(UpperCamelCase ) ^ key ) return ans def UpperCamelCase__ (self : Any , UpperCamelCase : str , UpperCamelCase : int = 0 ): '''simple docstring''' assert isinstance(UpperCamelCase , UpperCamelCase ) and isinstance(UpperCamelCase , UpperCamelCase ) lowercase__ = key or self.__key or 1 # make sure key can be any size while key > 255: key -= 255 # This will be returned lowercase__ = '''''' for ch in content: ans += chr(ord(UpperCamelCase ) ^ key ) return ans def UpperCamelCase__ (self : str , UpperCamelCase : str , UpperCamelCase : int = 0 ): '''simple docstring''' assert isinstance(UpperCamelCase , UpperCamelCase ) and isinstance(UpperCamelCase , UpperCamelCase ) try: with open(UpperCamelCase ) as fin, open('''encrypt.out''' , '''w+''' ) as fout: # actual encrypt-process for line in fin: fout.write(self.encrypt_string(UpperCamelCase , UpperCamelCase ) ) except OSError: return False return True def UpperCamelCase__ (self : Dict , UpperCamelCase : str , UpperCamelCase : int ): '''simple docstring''' assert isinstance(UpperCamelCase , UpperCamelCase ) and isinstance(UpperCamelCase , UpperCamelCase ) try: with open(UpperCamelCase ) as fin, open('''decrypt.out''' , '''w+''' ) as fout: # actual encrypt-process for line in fin: fout.write(self.decrypt_string(UpperCamelCase , UpperCamelCase ) ) except OSError: return False return True # Tests # crypt = XORCipher() # key = 67 # # test encrypt # print(crypt.encrypt("hallo welt",key)) # # test decrypt # print(crypt.decrypt(crypt.encrypt("hallo welt",key), key)) # # test encrypt_string # print(crypt.encrypt_string("hallo welt",key)) # # test decrypt_string # print(crypt.decrypt_string(crypt.encrypt_string("hallo welt",key),key)) # if (crypt.encrypt_file("test.txt",key)): # print("encrypt successful") # else: # print("encrypt unsuccessful") # if (crypt.decrypt_file("encrypt.out",key)): # print("decrypt successful") # else: # print("decrypt unsuccessful")
2
# This is the module that test_patching.py uses to test patch_submodule() import os # noqa: this is just for tests import os as renamed_os # noqa: this is just for tests from os import path # noqa: this is just for tests from os import path as renamed_path # noqa: this is just for tests from os.path import join # noqa: this is just for tests from os.path import join as renamed_join # noqa: this is just for tests a =open # noqa: we just need to have a builtin inside this module to test it properly
73
0
'''simple docstring''' from __future__ import annotations lowercase : Optional[Any] = list[tuple[int, int]] lowercase : Optional[Any] = [ [0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles [0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0], [1, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0], ] lowercase : List[str] = ([-1, 0], [0, -1], [1, 0], [0, 1]) # up, left, down, right class A : def __init__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , ) -> Optional[Any]: """simple docstring""" A : str = pos_x A : List[Any] = pos_y A : Union[str, Any] = (pos_y, pos_x) A : Tuple = goal_x A : Dict = goal_y A : Optional[int] = g_cost A : Union[str, Any] = parent A : Union[str, Any] = self.calculate_heuristic() def __lowerCAmelCase ( self ) -> float: """simple docstring""" A : List[Any] = abs(self.pos_x - self.goal_x ) A : str = abs(self.pos_y - self.goal_y ) return dx + dy def __lt__( self , SCREAMING_SNAKE_CASE ) -> bool: """simple docstring""" return self.f_cost < other.f_cost class A : def __init__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> str: """simple docstring""" A : int = Node(start[1] , start[0] , goal[1] , goal[0] , 0 , SCREAMING_SNAKE_CASE ) A : str = Node(goal[1] , goal[0] , goal[1] , goal[0] , 99999 , SCREAMING_SNAKE_CASE ) A : List[Any] = [self.start] A : list[Node] = [] A : List[Any] = False def __lowerCAmelCase ( self ) -> Path | None: """simple docstring""" while self.open_nodes: # Open Nodes are sorted using __lt__ self.open_nodes.sort() A : Tuple = self.open_nodes.pop(0 ) if current_node.pos == self.target.pos: A : List[Any] = True return self.retrace_path(SCREAMING_SNAKE_CASE ) self.closed_nodes.append(SCREAMING_SNAKE_CASE ) A : Tuple = self.get_successors(SCREAMING_SNAKE_CASE ) for child_node in successors: if child_node in self.closed_nodes: continue if child_node not in self.open_nodes: self.open_nodes.append(SCREAMING_SNAKE_CASE ) else: # retrieve the best current path A : Optional[int] = self.open_nodes.pop(self.open_nodes.index(SCREAMING_SNAKE_CASE ) ) if child_node.g_cost < better_node.g_cost: self.open_nodes.append(SCREAMING_SNAKE_CASE ) else: self.open_nodes.append(SCREAMING_SNAKE_CASE ) if not self.reached: return [self.start.pos] return None def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE ) -> list[Node]: """simple docstring""" A : Union[str, Any] = [] for action in delta: A : Union[str, Any] = parent.pos_x + action[1] A : str = parent.pos_y + action[0] if not (0 <= pos_x <= len(grid[0] ) - 1 and 0 <= pos_y <= len(SCREAMING_SNAKE_CASE ) - 1): continue if grid[pos_y][pos_x] != 0: continue successors.append( Node( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , self.target.pos_y , self.target.pos_x , parent.g_cost + 1 , SCREAMING_SNAKE_CASE , ) ) return successors def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE ) -> Path: """simple docstring""" A : Optional[Any] = node A : Any = [] while current_node is not None: path.append((current_node.pos_y, current_node.pos_x) ) A : str = current_node.parent path.reverse() return path if __name__ == "__main__": lowercase : Tuple = (0, 0) lowercase : Union[str, Any] = (len(grid) - 1, len(grid[0]) - 1) for elem in grid: print(elem) print('------') lowercase : List[str] = GreedyBestFirst(init, goal) lowercase : Any = greedy_bf.search() if path: for pos_x, pos_y in path: lowercase : Optional[Any] = 2 for elem in grid: print(elem)
3
# Function to print upper half of diamond (pyramid) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> str: for i in range(0 , lowerCamelCase__ ): for _ in range(0 , n - i - 1 ): # printing spaces print(' ' , end='' ) for _ in range(0 , i + 1 ): # printing stars print('* ' , end='' ) print() def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Tuple: for i in range(lowerCamelCase__ , 0 , -1 ): for _ in range(lowerCamelCase__ , 0 , -1 ): # printing stars print('* ' , end='' ) print() for _ in range(n - i + 1 , 0 , -1 ): # printing spaces print(' ' , end='' ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Any: if n <= 0: print(' ... .... nothing printing :(' ) return floyd(lowerCamelCase__ ) # upper half reverse_floyd(lowerCamelCase__ ) # lower half if __name__ == "__main__": print(r"""| /\ | |- | |- |--| |\ /| |-""") print(r"""|/ \| |- |_ |_ |__| | \/ | |_""") a =1 while K: a =int(input("""enter the number and , and see the magic : """)) print() pretty_print(user_number) a =int(input("""press 0 to exit... and 1 to continue...""")) print("""Good Bye...""")
73
0
'''simple docstring''' from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ..auto import CONFIG_MAPPING __snake_case =logging.get_logger(__name__) __snake_case ={ """microsoft/table-transformer-detection""": ( """https://huggingface.co/microsoft/table-transformer-detection/resolve/main/config.json""" ), } class UpperCAmelCase_ ( __lowercase ): lowerCamelCase : Optional[int] = '''table-transformer''' lowerCamelCase : List[str] = ['''past_key_values'''] lowerCamelCase : List[Any] = { '''hidden_size''': '''d_model''', '''num_attention_heads''': '''encoder_attention_heads''', } def __init__( self : List[str] , UpperCAmelCase__ : str=True , UpperCAmelCase__ : List[Any]=None , UpperCAmelCase__ : Union[str, Any]=3 , UpperCAmelCase__ : Tuple=1_0_0 , UpperCAmelCase__ : Any=6 , UpperCAmelCase__ : int=2_0_4_8 , UpperCAmelCase__ : List[str]=8 , UpperCAmelCase__ : Union[str, Any]=6 , UpperCAmelCase__ : Tuple=2_0_4_8 , UpperCAmelCase__ : int=8 , UpperCAmelCase__ : str=0.0 , UpperCAmelCase__ : str=0.0 , UpperCAmelCase__ : Optional[int]=True , UpperCAmelCase__ : List[Any]="relu" , UpperCAmelCase__ : Dict=2_5_6 , UpperCAmelCase__ : Any=0.1 , UpperCAmelCase__ : Union[str, Any]=0.0 , UpperCAmelCase__ : str=0.0 , UpperCAmelCase__ : Optional[Any]=0.02 , UpperCAmelCase__ : Union[str, Any]=1.0 , UpperCAmelCase__ : Any=False , UpperCAmelCase__ : List[Any]="sine" , UpperCAmelCase__ : Optional[int]="resnet50" , UpperCAmelCase__ : Union[str, Any]=True , UpperCAmelCase__ : Any=False , UpperCAmelCase__ : int=1 , UpperCAmelCase__ : Dict=5 , UpperCAmelCase__ : Tuple=2 , UpperCAmelCase__ : List[Any]=1 , UpperCAmelCase__ : Optional[int]=1 , UpperCAmelCase__ : Dict=5 , UpperCAmelCase__ : List[Any]=2 , UpperCAmelCase__ : List[Any]=0.1 , **UpperCAmelCase__ : Union[str, Any] , ) -> Optional[int]: if backbone_config is not None and use_timm_backbone: raise ValueError('You can\'t specify both `backbone_config` and `use_timm_backbone`.' ) if not use_timm_backbone: if backbone_config is None: logger.info('`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.' ) lowerCAmelCase = CONFIG_MAPPING['resnet'](out_features=['stage4'] ) elif isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): lowerCAmelCase = backbone_config.get('model_type' ) lowerCAmelCase = CONFIG_MAPPING[backbone_model_type] lowerCAmelCase = config_class.from_dict(UpperCAmelCase__ ) # set timm attributes to None lowerCAmelCase , lowerCAmelCase , lowerCAmelCase = None, None, None lowerCAmelCase = use_timm_backbone lowerCAmelCase = backbone_config lowerCAmelCase = num_channels lowerCAmelCase = num_queries lowerCAmelCase = d_model lowerCAmelCase = encoder_ffn_dim lowerCAmelCase = encoder_layers lowerCAmelCase = encoder_attention_heads lowerCAmelCase = decoder_ffn_dim lowerCAmelCase = decoder_layers lowerCAmelCase = decoder_attention_heads lowerCAmelCase = dropout lowerCAmelCase = attention_dropout lowerCAmelCase = activation_dropout lowerCAmelCase = activation_function lowerCAmelCase = init_std lowerCAmelCase = init_xavier_std lowerCAmelCase = encoder_layerdrop lowerCAmelCase = decoder_layerdrop lowerCAmelCase = encoder_layers lowerCAmelCase = auxiliary_loss lowerCAmelCase = position_embedding_type lowerCAmelCase = backbone lowerCAmelCase = use_pretrained_backbone lowerCAmelCase = dilation # Hungarian matcher lowerCAmelCase = class_cost lowerCAmelCase = bbox_cost lowerCAmelCase = giou_cost # Loss coefficients lowerCAmelCase = mask_loss_coefficient lowerCAmelCase = dice_loss_coefficient lowerCAmelCase = bbox_loss_coefficient lowerCAmelCase = giou_loss_coefficient lowerCAmelCase = eos_coefficient super().__init__(is_encoder_decoder=UpperCAmelCase__ , **UpperCAmelCase__ ) @property def __UpperCAmelCase ( self : int ) -> int: return self.encoder_attention_heads @property def __UpperCAmelCase ( self : Optional[Any] ) -> int: return self.d_model class UpperCAmelCase_ ( __lowercase ): lowerCamelCase : Dict = version.parse('''1.11''' ) @property def __UpperCAmelCase ( self : Any ) -> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ('pixel_mask', {0: 'batch'}), ] ) @property def __UpperCAmelCase ( self : Optional[int] ) -> float: return 1E-5 @property def __UpperCAmelCase ( self : Optional[int] ) -> int: return 1_2
4
import re import warnings from contextlib import contextmanager from ...processing_utils import ProcessorMixin class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : Any = ['''image_processor''', '''tokenizer'''] _UpperCAmelCase : List[Any] = '''AutoImageProcessor''' _UpperCAmelCase : Dict = '''AutoTokenizer''' def __init__( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : Optional[int]=None ,SCREAMING_SNAKE_CASE__ : List[Any]=None ,**SCREAMING_SNAKE_CASE__ : Union[str, Any]): __lowerCamelCase : List[str] = None if "feature_extractor" in kwargs: warnings.warn( 'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`' ' instead.' ,SCREAMING_SNAKE_CASE__ ,) __lowerCamelCase : Union[str, Any] = kwargs.pop('feature_extractor') __lowerCamelCase : Dict = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('You need to specify an `image_processor`.') if tokenizer is None: raise ValueError('You need to specify a `tokenizer`.') super().__init__(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Dict = self.image_processor __lowerCamelCase : Optional[int] = False def __call__( self : int ,*SCREAMING_SNAKE_CASE__ : Union[str, Any] ,**SCREAMING_SNAKE_CASE__ : Union[str, Any]): # For backward compatibility if self._in_target_context_manager: return self.current_processor(*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[int] = kwargs.pop('images' ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Union[str, Any] = kwargs.pop('text' ,SCREAMING_SNAKE_CASE__) if len(SCREAMING_SNAKE_CASE__) > 0: __lowerCamelCase : int = args[0] __lowerCamelCase : List[str] = args[1:] if images is None and text is None: raise ValueError('You need to specify either an `images` or `text` input to process.') if images is not None: __lowerCamelCase : Optional[int] = self.image_processor(SCREAMING_SNAKE_CASE__ ,*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) if text is not None: __lowerCamelCase : List[Any] = self.tokenizer(SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) if text is None: return inputs elif images is None: return encodings else: __lowerCamelCase : Optional[Any] = encodings['input_ids'] return inputs def lowerCAmelCase ( self : int ,*SCREAMING_SNAKE_CASE__ : Union[str, Any] ,**SCREAMING_SNAKE_CASE__ : Dict): return self.tokenizer.batch_decode(*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Optional[Any] ,*SCREAMING_SNAKE_CASE__ : List[Any] ,**SCREAMING_SNAKE_CASE__ : Any): return self.tokenizer.decode(*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) @contextmanager def lowerCAmelCase ( self : Tuple): warnings.warn( '`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your ' 'labels by using the argument `text` of the regular `__call__` method (either in the same call as ' 'your images inputs, or in a separate call.') __lowerCamelCase : List[Any] = True __lowerCamelCase : str = self.tokenizer yield __lowerCamelCase : Tuple = self.image_processor __lowerCamelCase : Tuple = False def lowerCAmelCase ( self : Any ,SCREAMING_SNAKE_CASE__ : str ,SCREAMING_SNAKE_CASE__ : int=False ,SCREAMING_SNAKE_CASE__ : List[Any]=None): if added_vocab is None: __lowerCamelCase : str = self.tokenizer.get_added_vocab() __lowerCamelCase : Union[str, Any] = {} while tokens: __lowerCamelCase : Tuple = re.search(R'<s_(.*?)>' ,SCREAMING_SNAKE_CASE__ ,re.IGNORECASE) if start_token is None: break __lowerCamelCase : Dict = start_token.group(1) __lowerCamelCase : List[str] = re.search(RF"</s_{key}>" ,SCREAMING_SNAKE_CASE__ ,re.IGNORECASE) __lowerCamelCase : Optional[int] = start_token.group() if end_token is None: __lowerCamelCase : List[Any] = tokens.replace(SCREAMING_SNAKE_CASE__ ,'') else: __lowerCamelCase : Tuple = end_token.group() __lowerCamelCase : int = re.escape(SCREAMING_SNAKE_CASE__) __lowerCamelCase : str = re.escape(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Union[str, Any] = re.search(F"{start_token_escaped}(.*?){end_token_escaped}" ,SCREAMING_SNAKE_CASE__ ,re.IGNORECASE) if content is not None: __lowerCamelCase : List[Any] = content.group(1).strip() if r"<s_" in content and r"</s_" in content: # non-leaf node __lowerCamelCase : str = self.tokenajson(SCREAMING_SNAKE_CASE__ ,is_inner_value=SCREAMING_SNAKE_CASE__ ,added_vocab=SCREAMING_SNAKE_CASE__) if value: if len(SCREAMING_SNAKE_CASE__) == 1: __lowerCamelCase : Tuple = value[0] __lowerCamelCase : int = value else: # leaf nodes __lowerCamelCase : Tuple = [] for leaf in content.split(R'<sep/>'): __lowerCamelCase : List[Any] = leaf.strip() if leaf in added_vocab and leaf[0] == "<" and leaf[-2:] == "/>": __lowerCamelCase : str = leaf[1:-2] # for categorical special tokens output[key].append(SCREAMING_SNAKE_CASE__) if len(output[key]) == 1: __lowerCamelCase : Dict = output[key][0] __lowerCamelCase : Dict = tokens[tokens.find(SCREAMING_SNAKE_CASE__) + len(SCREAMING_SNAKE_CASE__) :].strip() if tokens[:6] == r"<sep/>": # non-leaf nodes return [output] + self.tokenajson(tokens[6:] ,is_inner_value=SCREAMING_SNAKE_CASE__ ,added_vocab=SCREAMING_SNAKE_CASE__) if len(SCREAMING_SNAKE_CASE__): return [output] if is_inner_value else output else: return [] if is_inner_value else {"text_sequence": tokens} @property def lowerCAmelCase ( self : List[str]): warnings.warn( '`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.' ,SCREAMING_SNAKE_CASE__ ,) return self.image_processor_class @property def lowerCAmelCase ( self : List[Any]): warnings.warn( '`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.' ,SCREAMING_SNAKE_CASE__ ,) return self.image_processor
73
0
from dataclasses import dataclass from typing import Optional, Tuple, Union import torch import torch.nn as nn from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, apply_forward_hook from .modeling_utils import ModelMixin from .vae import Decoder, DecoderOutput, Encoder, VectorQuantizer @dataclass class lowerCamelCase__ ( lowerCAmelCase): SCREAMING_SNAKE_CASE__ = 42 class lowerCamelCase__ ( lowerCAmelCase , lowerCAmelCase): @register_to_config def __init__(self , UpperCAmelCase = 3 , UpperCAmelCase = 3 , UpperCAmelCase = ("DownEncoderBlock2D",) , UpperCAmelCase = ("UpDecoderBlock2D",) , UpperCAmelCase = (6_4,) , UpperCAmelCase = 1 , UpperCAmelCase = "silu" , UpperCAmelCase = 3 , UpperCAmelCase = 3_2 , UpperCAmelCase = 2_5_6 , UpperCAmelCase = 3_2 , UpperCAmelCase = None , UpperCAmelCase = 0.1_8215 , UpperCAmelCase = "group" , ) -> Any: super().__init__() # pass init params to Encoder _lowercase =Encoder( in_channels=UpperCAmelCase , out_channels=UpperCAmelCase , down_block_types=UpperCAmelCase , block_out_channels=UpperCAmelCase , layers_per_block=UpperCAmelCase , act_fn=UpperCAmelCase , norm_num_groups=UpperCAmelCase , double_z=UpperCAmelCase , ) _lowercase =vq_embed_dim if vq_embed_dim is not None else latent_channels _lowercase =nn.Convad(UpperCAmelCase , UpperCAmelCase , 1 ) _lowercase =VectorQuantizer(UpperCAmelCase , UpperCAmelCase , beta=0.25 , remap=UpperCAmelCase , sane_index_shape=UpperCAmelCase ) _lowercase =nn.Convad(UpperCAmelCase , UpperCAmelCase , 1 ) # pass init params to Decoder _lowercase =Decoder( in_channels=UpperCAmelCase , out_channels=UpperCAmelCase , up_block_types=UpperCAmelCase , block_out_channels=UpperCAmelCase , layers_per_block=UpperCAmelCase , act_fn=UpperCAmelCase , norm_num_groups=UpperCAmelCase , norm_type=UpperCAmelCase , ) @apply_forward_hook def __A (self , UpperCAmelCase , UpperCAmelCase = True ) -> VQEncoderOutput: _lowercase =self.encoder(UpperCAmelCase ) _lowercase =self.quant_conv(UpperCAmelCase ) if not return_dict: return (h,) return VQEncoderOutput(latents=UpperCAmelCase ) @apply_forward_hook def __A (self , UpperCAmelCase , UpperCAmelCase = False , UpperCAmelCase = True ) -> Union[DecoderOutput, torch.FloatTensor]: # also go through quantization layer if not force_not_quantize: _lowercase , _lowercase , _lowercase =self.quantize(UpperCAmelCase ) else: _lowercase =h _lowercase =self.post_quant_conv(UpperCAmelCase ) _lowercase =self.decoder(UpperCAmelCase , quant if self.config.norm_type == '''spatial''' else None ) if not return_dict: return (dec,) return DecoderOutput(sample=UpperCAmelCase ) def __A (self , UpperCAmelCase , UpperCAmelCase = True ) -> Union[DecoderOutput, torch.FloatTensor]: _lowercase =sample _lowercase =self.encode(UpperCAmelCase ).latents _lowercase =self.decode(UpperCAmelCase ).sample if not return_dict: return (dec,) return DecoderOutput(sample=UpperCAmelCase )
5
def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> int: __lowerCamelCase : Optional[int] = 0 __lowerCamelCase : Dict = len(lowerCamelCase__ ) - 1 while left <= right: # avoid divided by 0 during interpolation if sorted_collection[left] == sorted_collection[right]: if sorted_collection[left] == item: return left else: return None __lowerCamelCase : str = left + ((item - sorted_collection[left]) * (right - left)) // ( sorted_collection[right] - sorted_collection[left] ) # out of range check if point < 0 or point >= len(lowerCamelCase__ ): return None __lowerCamelCase : Tuple = sorted_collection[point] if current_item == item: return point else: if point < left: __lowerCamelCase : List[Any] = left __lowerCamelCase : Tuple = point elif point > right: __lowerCamelCase : Dict = right __lowerCamelCase : str = point else: if item < current_item: __lowerCamelCase : Dict = point - 1 else: __lowerCamelCase : Dict = point + 1 return None def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> Any: # avoid divided by 0 during interpolation if sorted_collection[left] == sorted_collection[right]: if sorted_collection[left] == item: return left else: return None __lowerCamelCase : Optional[int] = left + ((item - sorted_collection[left]) * (right - left)) // ( sorted_collection[right] - sorted_collection[left] ) # out of range check if point < 0 or point >= len(lowerCamelCase__ ): return None if sorted_collection[point] == item: return point elif point < left: return interpolation_search_by_recursion(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) elif point > right: return interpolation_search_by_recursion(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) else: if sorted_collection[point] > item: return interpolation_search_by_recursion( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , point - 1 ) else: return interpolation_search_by_recursion( lowerCamelCase__ , lowerCamelCase__ , point + 1 , lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Optional[Any]: if collection != sorted(lowerCamelCase__ ): raise ValueError('Collection must be ascending sorted' ) return True if __name__ == "__main__": import sys a =0 if debug == 1: a =[10, 30, 40, 45, 50, 66, 77, 93] try: __assert_sorted(collection) except ValueError: sys.exit("""Sequence must be ascending sorted to apply interpolation search""") a =67 a =interpolation_search(collection, target) if result is not None: print(F"""{target} found at positions: {result}""") else: print("""Not found""")
73
0
import math import os import sys def __lowerCAmelCase ( a__ ) -> str: __a = '''''' try: with open(a__ , '''rb''' ) as binary_file: __a = binary_file.read() for dat in data: __a = F"""{dat:08b}""" result += curr_byte return result except OSError: print('''File not accessible''' ) sys.exit() def __lowerCAmelCase ( a__ , a__ , a__ , a__ ) -> None: lexicon.pop(a__ ) __a = last_match_id if math.loga(a__ ).is_integer(): for curr_key in lexicon: __a = '''0''' + lexicon[curr_key] __a = bin(a__ )[2:] def __lowerCAmelCase ( a__ ) -> str: __a = {'''0''': '''0''', '''1''': '''1'''} __a , __a = '''''', '''''' __a = len(a__ ) for i in range(len(a__ ) ): curr_string += data_bits[i] if curr_string not in lexicon: continue __a = lexicon[curr_string] result += last_match_id add_key_to_lexicon(a__ , a__ , a__ , a__ ) index += 1 __a = '''''' while curr_string != "" and curr_string not in lexicon: curr_string += "0" if curr_string != "": __a = lexicon[curr_string] result += last_match_id return result def __lowerCAmelCase ( a__ , a__ ) -> str: __a = os.path.getsize(a__ ) __a = bin(a__ )[2:] __a = len(a__ ) return "0" * (length_length - 1) + file_length_binary + compressed def __lowerCAmelCase ( a__ , a__ ) -> None: __a = 8 try: with open(a__ , '''wb''' ) as opened_file: __a = [ to_write[i : i + byte_length] for i in range(0 , len(a__ ) , a__ ) ] if len(result_byte_array[-1] ) % byte_length == 0: result_byte_array.append('''10000000''' ) else: result_byte_array[-1] += "1" + "0" * ( byte_length - len(result_byte_array[-1] ) - 1 ) for elem in result_byte_array: opened_file.write(int(a__ , 2 ).to_bytes(1 , byteorder='''big''' ) ) except OSError: print('''File not accessible''' ) sys.exit() def __lowerCAmelCase ( a__ , a__ ) -> None: __a = read_file_binary(a__ ) __a = compress_data(a__ ) __a = add_file_length(a__ , a__ ) write_file_binary(a__ , a__ ) if __name__ == "__main__": compress(sys.argv[1], sys.argv[2])
6
import json import os import subprocess import unittest from ast import literal_eval import pytest from parameterized import parameterized, parameterized_class from . import is_sagemaker_available if is_sagemaker_available(): from sagemaker import Session, TrainingJobAnalytics from sagemaker.huggingface import HuggingFace @pytest.mark.skipif( literal_eval(os.getenv('''TEST_SAGEMAKER''' , '''False''' ) ) is not True , reason='''Skipping test because should only be run when releasing minor transformers version''' , ) @pytest.mark.usefixtures('''sm_env''' ) @parameterized_class( [ { '''framework''': '''pytorch''', '''script''': '''run_glue_model_parallelism.py''', '''model_name_or_path''': '''roberta-large''', '''instance_type''': '''ml.p3dn.24xlarge''', '''results''': {'''train_runtime''': 1_600, '''eval_accuracy''': 0.3, '''eval_loss''': 1.2}, }, { '''framework''': '''pytorch''', '''script''': '''run_glue.py''', '''model_name_or_path''': '''roberta-large''', '''instance_type''': '''ml.p3dn.24xlarge''', '''results''': {'''train_runtime''': 1_600, '''eval_accuracy''': 0.3, '''eval_loss''': 1.2}, }, ] ) class A_ ( unittest.TestCase ): def lowerCAmelCase ( self : Union[str, Any]): if self.framework == "pytorch": subprocess.run( F"cp ./examples/pytorch/text-classification/run_glue.py {self.env.test_path}/run_glue.py".split() ,encoding='utf-8' ,check=SCREAMING_SNAKE_CASE__ ,) assert hasattr(self ,'env') def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : int): # configuration for running training on smdistributed Model Parallel __lowerCamelCase : Any = { 'enabled': True, 'processes_per_host': 8, } __lowerCamelCase : List[Any] = { 'enabled': True, 'parameters': { 'microbatches': 4, 'placement_strategy': 'spread', 'pipeline': 'interleaved', 'optimize': 'speed', 'partitions': 4, 'ddp': True, }, } __lowerCamelCase : str = {'smdistributed': {'modelparallel': smp_options}, 'mpi': mpi_options} __lowerCamelCase : List[str] = 'trainer' if self.script == 'run_glue.py' else 'smtrainer' # creates estimator return HuggingFace( entry_point=self.script ,source_dir=self.env.test_path ,role=self.env.role ,image_uri=self.env.image_uri ,base_job_name=F"{self.env.base_job_name}-{instance_count}-smp-{name_extension}" ,instance_count=SCREAMING_SNAKE_CASE__ ,instance_type=self.instance_type ,debugger_hook_config=SCREAMING_SNAKE_CASE__ ,hyperparameters={ **self.env.hyperparameters, 'model_name_or_path': self.model_name_or_path, 'max_steps': 5_0_0, } ,metric_definitions=self.env.metric_definitions ,distribution=SCREAMING_SNAKE_CASE__ ,py_version='py36' ,) def lowerCAmelCase ( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : Any): TrainingJobAnalytics(SCREAMING_SNAKE_CASE__).export_csv(F"{self.env.test_path}/{job_name}_metrics.csv") @parameterized.expand([(1,)]) def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : Optional[Any]): # create estimator __lowerCamelCase : str = self.create_estimator(SCREAMING_SNAKE_CASE__) # run training estimator.fit() # result dataframe __lowerCamelCase : List[str] = TrainingJobAnalytics(estimator.latest_training_job.name).dataframe() # extract kpis __lowerCamelCase : Optional[int] = list(result_metrics_df[result_metrics_df.metric_name == 'eval_accuracy']['value']) __lowerCamelCase : Any = list(result_metrics_df[result_metrics_df.metric_name == 'eval_loss']['value']) # get train time from SageMaker job, this includes starting, preprocessing, stopping __lowerCamelCase : str = ( Session().describe_training_job(estimator.latest_training_job.name).get('TrainingTimeInSeconds' ,9_9_9_9_9_9) ) # assert kpis assert train_runtime <= self.results["train_runtime"] assert all(t >= self.results['eval_accuracy'] for t in eval_accuracy) assert all(t <= self.results['eval_loss'] for t in eval_loss) # dump tests result into json file to share in PR with open(F"{estimator.latest_training_job.name}.json" ,'w') as outfile: json.dump({'train_time': train_runtime, 'eval_accuracy': eval_accuracy, 'eval_loss': eval_loss} ,SCREAMING_SNAKE_CASE__)
73
0
import inspect import warnings from typing import Any, Dict, Optional, Union from packaging import version def _snake_case( *SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Optional[Union[Dict, Any]] = None , SCREAMING_SNAKE_CASE__ : Union[str, Any]=True , SCREAMING_SNAKE_CASE__ : int=2 ) -> Optional[int]: '''simple docstring''' from .. import __version__ A__ = take_from A__ = () if not isinstance(args[0] , SCREAMING_SNAKE_CASE__ ): A__ = (args,) for attribute, version_name, message in args: if version.parse(version.parse(SCREAMING_SNAKE_CASE__ ).base_version ) >= version.parse(SCREAMING_SNAKE_CASE__ ): raise ValueError( f'The deprecation tuple {(attribute, version_name, message)} should be removed since diffusers\'' f' version {__version__} is >= {version_name}' ) A__ = None if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) and attribute in deprecated_kwargs: values += (deprecated_kwargs.pop(SCREAMING_SNAKE_CASE__ ),) A__ = f'The `{attribute}` argument is deprecated and will be removed in version {version_name}.' elif hasattr(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): values += (getattr(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ),) A__ = f'The `{attribute}` attribute is deprecated and will be removed in version {version_name}.' elif deprecated_kwargs is None: A__ = f'`{attribute}` is deprecated and will be removed in version {version_name}.' if warning is not None: A__ = warning + ' ' if standard_warn else '' warnings.warn(warning + message , SCREAMING_SNAKE_CASE__ , stacklevel=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) and len(SCREAMING_SNAKE_CASE__ ) > 0: A__ = inspect.getouterframes(inspect.currentframe() )[1] A__ = call_frame.filename A__ = call_frame.lineno A__ = call_frame.function A__ , A__ = next(iter(deprecated_kwargs.items() ) ) raise TypeError(f'{function} in {filename} line {line_number-1} got an unexpected keyword argument `{key}`' ) if len(SCREAMING_SNAKE_CASE__ ) == 0: return elif len(SCREAMING_SNAKE_CASE__ ) == 1: return values[0] return values
7
import unittest import numpy as np from transformers import DistilBertConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask if is_flax_available(): import jax.numpy as jnp from transformers.models.distilbert.modeling_flax_distilbert import ( FlaxDistilBertForMaskedLM, FlaxDistilBertForMultipleChoice, FlaxDistilBertForQuestionAnswering, FlaxDistilBertForSequenceClassification, FlaxDistilBertForTokenClassification, FlaxDistilBertModel, ) class A_ ( unittest.TestCase ): def __init__( self : Tuple ,SCREAMING_SNAKE_CASE__ : List[str] ,SCREAMING_SNAKE_CASE__ : Any=1_3 ,SCREAMING_SNAKE_CASE__ : int=7 ,SCREAMING_SNAKE_CASE__ : str=True ,SCREAMING_SNAKE_CASE__ : Dict=True ,SCREAMING_SNAKE_CASE__ : str=True ,SCREAMING_SNAKE_CASE__ : Dict=True ,SCREAMING_SNAKE_CASE__ : List[Any]=9_9 ,SCREAMING_SNAKE_CASE__ : List[Any]=3_2 ,SCREAMING_SNAKE_CASE__ : int=5 ,SCREAMING_SNAKE_CASE__ : List[Any]=4 ,SCREAMING_SNAKE_CASE__ : Optional[Any]=3_7 ,SCREAMING_SNAKE_CASE__ : Union[str, Any]="gelu" ,SCREAMING_SNAKE_CASE__ : int=0.1 ,SCREAMING_SNAKE_CASE__ : Optional[int]=0.1 ,SCREAMING_SNAKE_CASE__ : Optional[int]=5_1_2 ,SCREAMING_SNAKE_CASE__ : Dict=1_6 ,SCREAMING_SNAKE_CASE__ : Dict=2 ,SCREAMING_SNAKE_CASE__ : Optional[int]=0.02 ,SCREAMING_SNAKE_CASE__ : Dict=4 ,): __lowerCamelCase : int = parent __lowerCamelCase : Dict = batch_size __lowerCamelCase : Union[str, Any] = seq_length __lowerCamelCase : List[Any] = is_training __lowerCamelCase : Tuple = use_attention_mask __lowerCamelCase : List[str] = use_token_type_ids __lowerCamelCase : Any = use_labels __lowerCamelCase : List[str] = vocab_size __lowerCamelCase : Any = hidden_size __lowerCamelCase : Tuple = num_hidden_layers __lowerCamelCase : Union[str, Any] = num_attention_heads __lowerCamelCase : Union[str, Any] = intermediate_size __lowerCamelCase : List[Any] = hidden_act __lowerCamelCase : int = hidden_dropout_prob __lowerCamelCase : int = attention_probs_dropout_prob __lowerCamelCase : Union[str, Any] = max_position_embeddings __lowerCamelCase : Union[str, Any] = type_vocab_size __lowerCamelCase : List[str] = type_sequence_label_size __lowerCamelCase : Tuple = initializer_range __lowerCamelCase : Optional[int] = num_choices def lowerCAmelCase ( self : Union[str, Any]): __lowerCamelCase : Dict = ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size) __lowerCamelCase : Union[str, Any] = None if self.use_attention_mask: __lowerCamelCase : Any = random_attention_mask([self.batch_size, self.seq_length]) __lowerCamelCase : str = DistilBertConfig( vocab_size=self.vocab_size ,dim=self.hidden_size ,n_layers=self.num_hidden_layers ,n_heads=self.num_attention_heads ,hidden_dim=self.intermediate_size ,hidden_act=self.hidden_act ,dropout=self.hidden_dropout_prob ,attention_dropout=self.attention_probs_dropout_prob ,max_position_embeddings=self.max_position_embeddings ,initializer_range=self.initializer_range ,tie_weights_=SCREAMING_SNAKE_CASE__ ,) return config, input_ids, attention_mask def lowerCAmelCase ( self : List[Any]): __lowerCamelCase : List[str] = self.prepare_config_and_inputs() __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : Dict = config_and_inputs __lowerCamelCase : Any = {'input_ids': input_ids, 'attention_mask': attention_mask} return config, inputs_dict @require_flax class A_ ( SCREAMING_SNAKE_CASE , unittest.TestCase ): _UpperCAmelCase : Dict = ( ( FlaxDistilBertModel, FlaxDistilBertForMaskedLM, FlaxDistilBertForMultipleChoice, FlaxDistilBertForQuestionAnswering, FlaxDistilBertForSequenceClassification, FlaxDistilBertForTokenClassification, FlaxDistilBertForQuestionAnswering, ) if is_flax_available() else () ) def lowerCAmelCase ( self : Optional[Any]): __lowerCamelCase : Tuple = FlaxDistilBertModelTester(self) @slow def lowerCAmelCase ( self : int): for model_class_name in self.all_model_classes: __lowerCamelCase : List[Any] = model_class_name.from_pretrained('distilbert-base-uncased') __lowerCamelCase : List[str] = model(np.ones((1, 1))) self.assertIsNotNone(SCREAMING_SNAKE_CASE__) @require_flax class A_ ( unittest.TestCase ): @slow def lowerCAmelCase ( self : str): __lowerCamelCase : Union[str, Any] = FlaxDistilBertModel.from_pretrained('distilbert-base-uncased') __lowerCamelCase : str = np.array([[0, 3_4_5, 2_3_2, 3_2_8, 7_4_0, 1_4_0, 1_6_9_5, 6_9, 6_0_7_8, 1_5_8_8, 2]]) __lowerCamelCase : List[Any] = np.array([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]) __lowerCamelCase : Union[str, Any] = model(SCREAMING_SNAKE_CASE__ ,attention_mask=SCREAMING_SNAKE_CASE__)[0] __lowerCamelCase : Optional[int] = (1, 1_1, 7_6_8) self.assertEqual(output.shape ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Union[str, Any] = np.array([[[-0.1639, 0.3299, 0.1648], [-0.1746, 0.3289, 0.1710], [-0.1884, 0.3357, 0.1810]]]) self.assertTrue(jnp.allclose(output[:, 1:4, 1:4] ,SCREAMING_SNAKE_CASE__ ,atol=1E-4))
73
0
import argparse import json from pathlib import Path import requests import torch from huggingface_hub import cached_download, hf_hub_url from PIL import Image from transformers import DPTConfig, DPTForDepthEstimation, DPTForSemanticSegmentation, DPTImageProcessor from transformers.utils import logging logging.set_verbosity_info() lowerCAmelCase_ = logging.get_logger(__name__) def __SCREAMING_SNAKE_CASE (SCREAMING_SNAKE_CASE__ ): snake_case_ = DPTConfig() if "large" in checkpoint_url: snake_case_ = 1024 snake_case_ = 4096 snake_case_ = 24 snake_case_ = 16 snake_case_ = [5, 11, 17, 23] snake_case_ = [256, 512, 1024, 1024] snake_case_ = (1, 384, 384) if "ade" in checkpoint_url: snake_case_ = True snake_case_ = 150 snake_case_ = '''huggingface/label-files''' snake_case_ = '''ade20k-id2label.json''' snake_case_ = json.load(open(cached_download(hf_hub_url(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , repo_type='''dataset''' ) ) , '''r''' ) ) snake_case_ = {int(SCREAMING_SNAKE_CASE__ ): v for k, v in idalabel.items()} snake_case_ = idalabel snake_case_ = {v: k for k, v in idalabel.items()} snake_case_ = [1, 150, 480, 480] return config, expected_shape def __SCREAMING_SNAKE_CASE (SCREAMING_SNAKE_CASE__ ): snake_case_ = ['''pretrained.model.head.weight''', '''pretrained.model.head.bias'''] for k in ignore_keys: state_dict.pop(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def __SCREAMING_SNAKE_CASE (SCREAMING_SNAKE_CASE__ ): if ( "pretrained.model" in name and "cls_token" not in name and "pos_embed" not in name and "patch_embed" not in name ): snake_case_ = name.replace('''pretrained.model''' , '''dpt.encoder''' ) if "pretrained.model" in name: snake_case_ = name.replace('''pretrained.model''' , '''dpt.embeddings''' ) if "patch_embed" in name: snake_case_ = name.replace('''patch_embed''' , '''patch_embeddings''' ) if "pos_embed" in name: snake_case_ = name.replace('''pos_embed''' , '''position_embeddings''' ) if "attn.proj" in name: snake_case_ = name.replace('''attn.proj''' , '''attention.output.dense''' ) if "proj" in name and "project" not in name: snake_case_ = name.replace('''proj''' , '''projection''' ) if "blocks" in name: snake_case_ = name.replace('''blocks''' , '''layer''' ) if "mlp.fc1" in name: snake_case_ = name.replace('''mlp.fc1''' , '''intermediate.dense''' ) if "mlp.fc2" in name: snake_case_ = name.replace('''mlp.fc2''' , '''output.dense''' ) if "norm1" in name: snake_case_ = name.replace('''norm1''' , '''layernorm_before''' ) if "norm2" in name: snake_case_ = name.replace('''norm2''' , '''layernorm_after''' ) if "scratch.output_conv" in name: snake_case_ = name.replace('''scratch.output_conv''' , '''head''' ) if "scratch" in name: snake_case_ = name.replace('''scratch''' , '''neck''' ) if "layer1_rn" in name: snake_case_ = name.replace('''layer1_rn''' , '''convs.0''' ) if "layer2_rn" in name: snake_case_ = name.replace('''layer2_rn''' , '''convs.1''' ) if "layer3_rn" in name: snake_case_ = name.replace('''layer3_rn''' , '''convs.2''' ) if "layer4_rn" in name: snake_case_ = name.replace('''layer4_rn''' , '''convs.3''' ) if "refinenet" in name: snake_case_ = int(name[len('''neck.refinenet''' ) : len('''neck.refinenet''' ) + 1] ) # tricky here: we need to map 4 to 0, 3 to 1, 2 to 2 and 1 to 3 snake_case_ = name.replace(F'''refinenet{layer_idx}''' , F'''fusion_stage.layers.{abs(layer_idx-4 )}''' ) if "out_conv" in name: snake_case_ = name.replace('''out_conv''' , '''projection''' ) if "resConfUnit1" in name: snake_case_ = name.replace('''resConfUnit1''' , '''residual_layer1''' ) if "resConfUnit2" in name: snake_case_ = name.replace('''resConfUnit2''' , '''residual_layer2''' ) if "conv1" in name: snake_case_ = name.replace('''conv1''' , '''convolution1''' ) if "conv2" in name: snake_case_ = name.replace('''conv2''' , '''convolution2''' ) # readout blocks if "pretrained.act_postprocess1.0.project.0" in name: snake_case_ = name.replace('''pretrained.act_postprocess1.0.project.0''' , '''neck.reassemble_stage.readout_projects.0.0''' ) if "pretrained.act_postprocess2.0.project.0" in name: snake_case_ = name.replace('''pretrained.act_postprocess2.0.project.0''' , '''neck.reassemble_stage.readout_projects.1.0''' ) if "pretrained.act_postprocess3.0.project.0" in name: snake_case_ = name.replace('''pretrained.act_postprocess3.0.project.0''' , '''neck.reassemble_stage.readout_projects.2.0''' ) if "pretrained.act_postprocess4.0.project.0" in name: snake_case_ = name.replace('''pretrained.act_postprocess4.0.project.0''' , '''neck.reassemble_stage.readout_projects.3.0''' ) # resize blocks if "pretrained.act_postprocess1.3" in name: snake_case_ = name.replace('''pretrained.act_postprocess1.3''' , '''neck.reassemble_stage.layers.0.projection''' ) if "pretrained.act_postprocess1.4" in name: snake_case_ = name.replace('''pretrained.act_postprocess1.4''' , '''neck.reassemble_stage.layers.0.resize''' ) if "pretrained.act_postprocess2.3" in name: snake_case_ = name.replace('''pretrained.act_postprocess2.3''' , '''neck.reassemble_stage.layers.1.projection''' ) if "pretrained.act_postprocess2.4" in name: snake_case_ = name.replace('''pretrained.act_postprocess2.4''' , '''neck.reassemble_stage.layers.1.resize''' ) if "pretrained.act_postprocess3.3" in name: snake_case_ = name.replace('''pretrained.act_postprocess3.3''' , '''neck.reassemble_stage.layers.2.projection''' ) if "pretrained.act_postprocess4.3" in name: snake_case_ = name.replace('''pretrained.act_postprocess4.3''' , '''neck.reassemble_stage.layers.3.projection''' ) if "pretrained.act_postprocess4.4" in name: snake_case_ = name.replace('''pretrained.act_postprocess4.4''' , '''neck.reassemble_stage.layers.3.resize''' ) if "pretrained" in name: snake_case_ = name.replace('''pretrained''' , '''dpt''' ) if "bn" in name: snake_case_ = name.replace('''bn''' , '''batch_norm''' ) if "head" in name: snake_case_ = name.replace('''head''' , '''head.head''' ) if "encoder.norm" in name: snake_case_ = name.replace('''encoder.norm''' , '''layernorm''' ) if "auxlayer" in name: snake_case_ = name.replace('''auxlayer''' , '''auxiliary_head.head''' ) return name def __SCREAMING_SNAKE_CASE (SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): for i in range(config.num_hidden_layers ): # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) snake_case_ = state_dict.pop(F'''dpt.encoder.layer.{i}.attn.qkv.weight''' ) snake_case_ = state_dict.pop(F'''dpt.encoder.layer.{i}.attn.qkv.bias''' ) # next, add query, keys and values (in that order) to the state dict snake_case_ = in_proj_weight[: config.hidden_size, :] snake_case_ = in_proj_bias[: config.hidden_size] snake_case_ = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] snake_case_ = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] snake_case_ = in_proj_weight[ -config.hidden_size :, : ] snake_case_ = in_proj_bias[-config.hidden_size :] def __SCREAMING_SNAKE_CASE (): snake_case_ = '''http://images.cocodataset.org/val2017/000000039769.jpg''' snake_case_ = Image.open(requests.get(SCREAMING_SNAKE_CASE__ , stream=SCREAMING_SNAKE_CASE__ ).raw ) return im @torch.no_grad() def __SCREAMING_SNAKE_CASE (SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): snake_case_, snake_case_ = get_dpt_config(SCREAMING_SNAKE_CASE__ ) # load original state_dict from URL snake_case_ = torch.hub.load_state_dict_from_url(SCREAMING_SNAKE_CASE__ , map_location='''cpu''' ) # remove certain keys remove_ignore_keys_(SCREAMING_SNAKE_CASE__ ) # rename keys for key in state_dict.copy().keys(): snake_case_ = state_dict.pop(SCREAMING_SNAKE_CASE__ ) snake_case_ = val # read in qkv matrices read_in_q_k_v(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # load HuggingFace model snake_case_ = DPTForSemanticSegmentation(SCREAMING_SNAKE_CASE__ ) if '''ade''' in checkpoint_url else DPTForDepthEstimation(SCREAMING_SNAKE_CASE__ ) model.load_state_dict(SCREAMING_SNAKE_CASE__ ) model.eval() # Check outputs on an image snake_case_ = 480 if '''ade''' in checkpoint_url else 384 snake_case_ = DPTImageProcessor(size=SCREAMING_SNAKE_CASE__ ) snake_case_ = prepare_img() snake_case_ = image_processor(SCREAMING_SNAKE_CASE__ , return_tensors='''pt''' ) # forward pass snake_case_ = model(**SCREAMING_SNAKE_CASE__ ).logits if '''ade''' in checkpoint_url else model(**SCREAMING_SNAKE_CASE__ ).predicted_depth # Assert logits snake_case_ = torch.tensor([[6.3199, 6.3629, 6.4148], [6.3850, 6.3615, 6.4166], [6.3519, 6.3176, 6.3575]] ) if "ade" in checkpoint_url: snake_case_ = torch.tensor([[4.0480, 4.2420, 4.4360], [4.3124, 4.5693, 4.8261], [4.5768, 4.8965, 5.2163]] ) assert outputs.shape == torch.Size(SCREAMING_SNAKE_CASE__ ) assert ( torch.allclose(outputs[0, 0, :3, :3] , SCREAMING_SNAKE_CASE__ , atol=1E-4 ) if "ade" in checkpoint_url else torch.allclose(outputs[0, :3, :3] , SCREAMING_SNAKE_CASE__ ) ) Path(SCREAMING_SNAKE_CASE__ ).mkdir(exist_ok=SCREAMING_SNAKE_CASE__ ) print(F'''Saving model to {pytorch_dump_folder_path}''' ) model.save_pretrained(SCREAMING_SNAKE_CASE__ ) print(F'''Saving image processor to {pytorch_dump_folder_path}''' ) image_processor.save_pretrained(SCREAMING_SNAKE_CASE__ ) if push_to_hub: print('''Pushing model to hub...''' ) model.push_to_hub( repo_path_or_name=Path(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) , organization='''nielsr''' , commit_message='''Add model''' , use_temp_dir=SCREAMING_SNAKE_CASE__ , ) image_processor.push_to_hub( repo_path_or_name=Path(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) , organization='''nielsr''' , commit_message='''Add image processor''' , use_temp_dir=SCREAMING_SNAKE_CASE__ , ) if __name__ == "__main__": lowerCAmelCase_ = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--checkpoint_url''', default='''https://github.com/intel-isl/DPT/releases/download/1_0/dpt_large-midas-2f21e586.pt''', type=str, help='''URL of the original DPT checkpoint you\'d like to convert.''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model directory.''', ) parser.add_argument( '''--push_to_hub''', action='''store_true''', ) parser.add_argument( '''--model_name''', default='''dpt-large''', type=str, help='''Name of the model, in case you\'re pushing to the hub.''', ) lowerCAmelCase_ = parser.parse_args() convert_dpt_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path, args.push_to_hub, args.model_name)
8
import csv import tweepy # Twitter API credentials a ="""""" a ="""""" a ="""""" a ="""""" def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> None: # authorize twitter, initialize tweepy __lowerCamelCase : Tuple = tweepy.OAuthHandler(lowerCamelCase__ , lowerCamelCase__ ) auth.set_access_token(lowerCamelCase__ , lowerCamelCase__ ) __lowerCamelCase : Optional[int] = tweepy.API(lowerCamelCase__ ) # initialize a list to hold all the tweepy Tweets __lowerCamelCase : str = [] # make initial request for most recent tweets (200 is the maximum allowed count) __lowerCamelCase : Union[str, Any] = api.user_timeline(screen_name=lowerCamelCase__ , count=2_0_0 ) # save most recent tweets alltweets.extend(lowerCamelCase__ ) # save the id of the oldest tweet less one __lowerCamelCase : Any = alltweets[-1].id - 1 # keep grabbing tweets until there are no tweets left to grab while len(lowerCamelCase__ ) > 0: print(F"getting tweets before {oldest}" ) # all subsequent requests use the max_id param to prevent duplicates __lowerCamelCase : str = api.user_timeline( screen_name=lowerCamelCase__ , count=2_0_0 , max_id=lowerCamelCase__ ) # save most recent tweets alltweets.extend(lowerCamelCase__ ) # update the id of the oldest tweet less one __lowerCamelCase : Optional[int] = alltweets[-1].id - 1 print(F"...{len(lowerCamelCase__ )} tweets downloaded so far" ) # transform the tweepy tweets into a 2D array that will populate the csv __lowerCamelCase : str = [[tweet.id_str, tweet.created_at, tweet.text] for tweet in alltweets] # write the csv with open(F"new_{screen_name}_tweets.csv" , 'w' ) as f: __lowerCamelCase : Any = csv.writer(lowerCamelCase__ ) writer.writerow(['id', 'created_at', 'text'] ) writer.writerows(lowerCamelCase__ ) if __name__ == "__main__": # pass in the username of the account you want to download get_all_tweets("""FirePing32""")
73
0
from math import ceil from typing import List, Optional, Union import numpy as np from ...audio_utils import mel_filter_bank, spectrogram, window_function from ...feature_extraction_sequence_utils import BatchFeature, SequenceFeatureExtractor from ...utils import TensorType, logging __lowerCAmelCase : Dict =logging.get_logger(__name__) class _lowercase ( A__ ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Union[str, Any] = ['''audio_values''', '''audio_mask'''] def __init__( self :Optional[Any] , lowerCAmelCase__ :str=2_048 , lowerCAmelCase__ :str=1 , lowerCAmelCase__ :List[Any]=[16, 16] , lowerCAmelCase__ :List[str]=128 , lowerCAmelCase__ :Dict=44_100 , lowerCAmelCase__ :Tuple=86 , lowerCAmelCase__ :List[str]=2_048 , lowerCAmelCase__ :Union[str, Any]=0.0 , **lowerCAmelCase__ :int , ) -> str: super().__init__( feature_size=lowerCAmelCase__ , sampling_rate=lowerCAmelCase__ , padding_value=lowerCAmelCase__ , **lowerCAmelCase__ , ) __SCREAMING_SNAKE_CASE : Union[str, Any] = spectrogram_length __SCREAMING_SNAKE_CASE : Dict = num_channels __SCREAMING_SNAKE_CASE : List[Any] = patch_size __SCREAMING_SNAKE_CASE : Optional[int] = feature_size // self.patch_size[1] __SCREAMING_SNAKE_CASE : Optional[Any] = n_fft __SCREAMING_SNAKE_CASE : int = sampling_rate // hop_length_to_sampling_rate __SCREAMING_SNAKE_CASE : Optional[int] = sampling_rate __SCREAMING_SNAKE_CASE : Tuple = padding_value __SCREAMING_SNAKE_CASE : Dict = mel_filter_bank( num_frequency_bins=1 + n_fft // 2 , num_mel_filters=lowerCAmelCase__ , min_frequency=0.0 , max_frequency=2_2050.0 , sampling_rate=lowerCAmelCase__ , norm='''slaney''' , mel_scale='''slaney''' , ).T def __magic_name__( self :Union[str, Any] , lowerCAmelCase__ :np.array ) -> np.ndarray: __SCREAMING_SNAKE_CASE : Union[str, Any] = spectrogram( lowerCAmelCase__ , window_function(self.n_fft , '''hann''' ) , frame_length=self.n_fft , hop_length=self.hop_length , power=2.0 , mel_filters=self.mel_filters.T , log_mel='''dB''' , db_range=80.0 , ) __SCREAMING_SNAKE_CASE : Tuple = log_spec[:, :-1] __SCREAMING_SNAKE_CASE : Tuple = log_spec - 20.0 __SCREAMING_SNAKE_CASE : List[str] = np.clip(log_spec / 40.0 , -2.0 , 0.0 ) + 1.0 return log_spec def __call__( self :Dict , lowerCAmelCase__ :Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]] , lowerCAmelCase__ :Optional[Union[str, TensorType]] = None , lowerCAmelCase__ :Optional[bool] = True , lowerCAmelCase__ :Optional[int] = None , lowerCAmelCase__ :bool = False , lowerCAmelCase__ :bool = False , **lowerCAmelCase__ :Union[str, Any] , ) -> BatchFeature: if sampling_rate is not None: if sampling_rate != self.sampling_rate: raise ValueError( '''This feature extractor is set to support sampling rate''' f''' of {self.sampling_rate}. Please make sure that the provided `raw_speech` input was sampled''' f''' with {self.sampling_rate} and not {sampling_rate}.''' ) else: logger.warning( '''It is strongly recommended to pass the `sampling_rate` argument to this function. ''' '''Failing to do so can result in silent errors that might be hard to debug.''' ) __SCREAMING_SNAKE_CASE : Any = isinstance(lowerCAmelCase__ , np.ndarray ) and len(raw_speech.shape ) > 1 if is_batched_numpy and len(raw_speech.shape ) > 2: raise ValueError(f'''Only mono-channel audio is supported for input to {self}''' ) __SCREAMING_SNAKE_CASE : str = is_batched_numpy or ( isinstance(lowerCAmelCase__ , (list, tuple) ) and (isinstance(raw_speech[0] , (np.ndarray, tuple, list) )) ) if is_batched: __SCREAMING_SNAKE_CASE : Union[str, Any] = [np.asarray([speech] , dtype=np.floataa ).T for speech in raw_speech] elif not is_batched and not isinstance(lowerCAmelCase__ , np.ndarray ): __SCREAMING_SNAKE_CASE : Union[str, Any] = np.asarray(lowerCAmelCase__ , dtype=np.floataa ) elif isinstance(lowerCAmelCase__ , np.ndarray ) and raw_speech.dtype is np.dtype(np.floataa ): __SCREAMING_SNAKE_CASE : Optional[Any] = raw_speech.astype(np.floataa ) # always return batch if not is_batched: __SCREAMING_SNAKE_CASE : str = [np.asarray([raw_speech] ).T] # Convert audio signals to log mel spectrograms, truncate by time axis __SCREAMING_SNAKE_CASE : Optional[Any] = [ self._np_extract_fbank_features(waveform.squeeze() ).T[: self.spectrogram_length] for waveform in raw_speech ] if isinstance(audio_features[0] , lowerCAmelCase__ ): __SCREAMING_SNAKE_CASE : Optional[Any] = [np.asarray(lowerCAmelCase__ , dtype=np.floataa ) for feature in audio_features] # Create audio attention mask __SCREAMING_SNAKE_CASE : Tuple = max( [ceil(feature.shape[0] / self.patch_size[0] ) * self.freq_len for feature in audio_features] ) # The maximum number of audio patches in a batch if return_attention_mask: __SCREAMING_SNAKE_CASE : Dict = [ (ceil(feature.shape[0] / self.patch_size[0] ) * self.freq_len) * [1] + (max_patch_len - ceil(feature.shape[0] / self.patch_size[0] ) * self.freq_len) * [0] for feature in audio_features ] __SCREAMING_SNAKE_CASE : Optional[int] = np.array(lowerCAmelCase__ ).astype(np.floataa ) # convert into correct format for padding __SCREAMING_SNAKE_CASE : Optional[int] = max_patch_len // self.freq_len * self.patch_size[0] # The maximum audio size in a batch __SCREAMING_SNAKE_CASE : List[str] = np.ones([len(lowerCAmelCase__ ), 1, max_time_len, self.feature_size] ).astype(np.floataa ) __SCREAMING_SNAKE_CASE : Union[str, Any] = padded_audio_features * self.padding_value for i in range(len(lowerCAmelCase__ ) ): __SCREAMING_SNAKE_CASE : Dict = audio_features[i] __SCREAMING_SNAKE_CASE : str = feature # return as BatchFeature if return_attention_mask: __SCREAMING_SNAKE_CASE : Dict = {'''audio_values''': padded_audio_features, '''audio_mask''': audio_mask} else: __SCREAMING_SNAKE_CASE : List[str] = {'''audio_values''': padded_audio_features} __SCREAMING_SNAKE_CASE : Any = BatchFeature(data=lowerCAmelCase__ , tensor_type=lowerCAmelCase__ ) return encoded_inputs
9
import numpy as np from scipy.spatial.distance import cdist from sklearn.metrics import fa_score import datasets a ="""\ @inproceedings{kakwani2020indicnlpsuite, title={{IndicNLPSuite: Monolingual Corpora, Evaluation Benchmarks and Pre-trained Multilingual Language Models for Indian Languages}}, author={Divyanshu Kakwani and Anoop Kunchukuttan and Satish Golla and Gokul N.C. and Avik Bhattacharyya and Mitesh M. Khapra and Pratyush Kumar}, year={2020}, booktitle={Findings of EMNLP}, } """ a ="""\ IndicGLUE is a natural language understanding benchmark for Indian languages. It contains a wide variety of tasks and covers 11 major Indian languages - as, bn, gu, hi, kn, ml, mr, or, pa, ta, te. """ a =""" Compute IndicGLUE evaluation metric associated to each IndicGLUE dataset. Args: predictions: list of predictions to score (as int64), except for 'cvit-mkb-clsr' where each prediction is a vector (of float32). references: list of ground truth labels corresponding to the predictions (as int64), except for 'cvit-mkb-clsr' where each reference is a vector (of float32). Returns: depending on the IndicGLUE subset, one or several of: \"accuracy\": Accuracy \"f1\": F1 score \"precision\": Precision@10 Examples: >>> indic_glue_metric = datasets.load_metric('indic_glue', 'wnli') # 'wnli' or any of [\"copa\", \"sna\", \"csqa\", \"wstp\", \"inltkh\", \"bbca\", \"iitp-mr\", \"iitp-pr\", \"actsa-sc\", \"md\"] >>> references = [0, 1] >>> predictions = [0, 1] >>> results = indic_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {'accuracy': 1.0} >>> indic_glue_metric = datasets.load_metric('indic_glue', 'wiki-ner') >>> references = [0, 1] >>> predictions = [0, 1] >>> results = indic_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {'accuracy': 1.0, 'f1': 1.0} >>> indic_glue_metric = datasets.load_metric('indic_glue', 'cvit-mkb-clsr') >>> references = [[0.5, 0.5, 0.5], [0.1, 0.2, 0.3]] >>> predictions = [[0.5, 0.5, 0.5], [0.1, 0.2, 0.3]] >>> results = indic_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {'precision@10': 1.0} """ def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> List[str]: return float((preds == labels).mean() ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> List[str]: __lowerCamelCase : Optional[Any] = simple_accuracy(lowerCamelCase__ , lowerCamelCase__ ) __lowerCamelCase : Tuple = float(fa_score(y_true=lowerCamelCase__ , y_pred=lowerCamelCase__ ) ) return { "accuracy": acc, "f1": fa, } def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> Optional[Any]: __lowerCamelCase : Any = np.array(lowerCamelCase__ ) __lowerCamelCase : List[Any] = np.array(lowerCamelCase__ ) __lowerCamelCase : Any = en_sentvecs.shape[0] # mean centering __lowerCamelCase : Union[str, Any] = en_sentvecs - np.mean(lowerCamelCase__ , axis=0 ) __lowerCamelCase : Dict = in_sentvecs - np.mean(lowerCamelCase__ , axis=0 ) __lowerCamelCase : Optional[int] = cdist(lowerCamelCase__ , lowerCamelCase__ , 'cosine' ) __lowerCamelCase : Optional[Any] = np.array(range(lowerCamelCase__ ) ) __lowerCamelCase : Dict = sim.argsort(axis=1 )[:, :1_0] __lowerCamelCase : Optional[int] = np.any(preds == actual[:, None] , axis=1 ) return float(matches.mean() ) @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class A_ ( datasets.Metric ): def lowerCAmelCase ( self : Optional[Any]): if self.config_name not in [ "wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", "cvit-mkb-clsr", "iitp-mr", "iitp-pr", "actsa-sc", "md", "wiki-ner", ]: raise KeyError( 'You should supply a configuration name selected in ' '["wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", ' '"cvit-mkb-clsr", "iitp-mr", "iitp-pr", "actsa-sc", "md", ' '"wiki-ner"]') return datasets.MetricInfo( description=_DESCRIPTION ,citation=_CITATION ,inputs_description=_KWARGS_DESCRIPTION ,features=datasets.Features( { 'predictions': datasets.Value('int64') if self.config_name != 'cvit-mkb-clsr' else datasets.Sequence(datasets.Value('float32')), 'references': datasets.Value('int64') if self.config_name != 'cvit-mkb-clsr' else datasets.Sequence(datasets.Value('float32')), }) ,codebase_urls=[] ,reference_urls=[] ,format='numpy' if self.config_name != 'cvit-mkb-clsr' else None ,) def lowerCAmelCase ( self : Any ,SCREAMING_SNAKE_CASE__ : Tuple ,SCREAMING_SNAKE_CASE__ : Optional[Any]): if self.config_name == "cvit-mkb-clsr": return {"precision@10": precision_at_aa(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__)} elif self.config_name in ["wiki-ner"]: return acc_and_fa(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) elif self.config_name in [ "wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", "iitp-mr", "iitp-pr", "actsa-sc", "md", ]: return {"accuracy": simple_accuracy(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__)} else: raise KeyError( 'You should supply a configuration name selected in ' '["wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", ' '"cvit-mkb-clsr", "iitp-mr", "iitp-pr", "actsa-sc", "md", ' '"wiki-ner"]')
73
0
from __future__ import annotations import inspect import unittest from typing import List, Tuple from transformers import RegNetConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST, TFRegNetForImageClassification, TFRegNetModel if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class _SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__(self : int , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : List[str]=3 , UpperCAmelCase_ : Optional[int]=32 , UpperCAmelCase_ : List[str]=3 , UpperCAmelCase_ : Optional[Any]=10 , UpperCAmelCase_ : str=[10, 20, 30, 40] , UpperCAmelCase_ : Union[str, Any]=[1, 1, 2, 1] , UpperCAmelCase_ : Tuple=True , UpperCAmelCase_ : int=True , UpperCAmelCase_ : List[str]="relu" , UpperCAmelCase_ : str=3 , UpperCAmelCase_ : Tuple=None , ) ->Tuple: '''simple docstring''' lowerCamelCase__: Any =parent lowerCamelCase__: List[Any] =batch_size lowerCamelCase__: int =image_size lowerCamelCase__: Optional[Any] =num_channels lowerCamelCase__: List[Any] =embeddings_size lowerCamelCase__: Any =hidden_sizes lowerCamelCase__: List[Any] =depths lowerCamelCase__: List[Any] =is_training lowerCamelCase__: Tuple =use_labels lowerCamelCase__: Any =hidden_act lowerCamelCase__: int =num_labels lowerCamelCase__: List[str] =scope lowerCamelCase__: str =len(UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : List[Any]) ->Optional[Any]: '''simple docstring''' lowerCamelCase__: Tuple =floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) lowerCamelCase__: Union[str, Any] =None if self.use_labels: lowerCamelCase__: Dict =ids_tensor([self.batch_size] , self.num_labels) lowerCamelCase__: Tuple =self.get_config() return config, pixel_values, labels def SCREAMING_SNAKE_CASE_ (self : Union[str, Any]) ->Union[str, Any]: '''simple docstring''' return RegNetConfig( num_channels=self.num_channels , embeddings_size=self.embeddings_size , hidden_sizes=self.hidden_sizes , depths=self.depths , hidden_act=self.hidden_act , num_labels=self.num_labels , ) def SCREAMING_SNAKE_CASE_ (self : Dict , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Dict) ->List[str]: '''simple docstring''' lowerCamelCase__: int =TFRegNetModel(config=UpperCAmelCase_) lowerCamelCase__: Optional[Any] =model(UpperCAmelCase_ , training=UpperCAmelCase_) # expected last hidden states: B, C, H // 32, W // 32 self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) , ) def SCREAMING_SNAKE_CASE_ (self : Optional[int] , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Any , UpperCAmelCase_ : Dict) ->Tuple: '''simple docstring''' lowerCamelCase__: Union[str, Any] =self.num_labels lowerCamelCase__: List[str] =TFRegNetForImageClassification(UpperCAmelCase_) lowerCamelCase__: List[str] =model(UpperCAmelCase_ , labels=UpperCAmelCase_ , training=UpperCAmelCase_) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels)) def SCREAMING_SNAKE_CASE_ (self : Any) ->Optional[int]: '''simple docstring''' lowerCamelCase__: List[Any] =self.prepare_config_and_inputs() lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: Union[str, Any] =config_and_inputs lowerCamelCase__: int ={"pixel_values": pixel_values} return config, inputs_dict @require_tf class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' lowercase_ = (TFRegNetModel, TFRegNetForImageClassification) if is_tf_available() else () lowercase_ = ( {"feature-extraction": TFRegNetModel, "image-classification": TFRegNetForImageClassification} if is_tf_available() else {} ) lowercase_ = False lowercase_ = False lowercase_ = False lowercase_ = False lowercase_ = False def SCREAMING_SNAKE_CASE_ (self : str) ->int: '''simple docstring''' lowerCamelCase__: List[Any] =TFRegNetModelTester(self) lowerCamelCase__: Union[str, Any] =ConfigTester(self , config_class=UpperCAmelCase_ , has_text_modality=UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : List[Any]) ->Optional[Any]: '''simple docstring''' return @unittest.skip(reason="RegNet does not use inputs_embeds") def SCREAMING_SNAKE_CASE_ (self : Tuple) ->int: '''simple docstring''' pass @unittest.skipIf( not is_tf_available() or len(tf.config.list_physical_devices("GPU")) == 0 , reason="TF does not support backprop for grouped convolutions on CPU." , ) @slow def SCREAMING_SNAKE_CASE_ (self : Dict) ->int: '''simple docstring''' super().test_keras_fit() @unittest.skip(reason="RegNet does not support input and output embeddings") def SCREAMING_SNAKE_CASE_ (self : Any) ->Tuple: '''simple docstring''' pass def SCREAMING_SNAKE_CASE_ (self : Any) ->Tuple: '''simple docstring''' lowerCamelCase__ , lowerCamelCase__: str =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCamelCase__: str =model_class(UpperCAmelCase_) lowerCamelCase__: Optional[Any] =inspect.signature(model.call) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowerCamelCase__: Dict =[*signature.parameters.keys()] lowerCamelCase__: Optional[int] =["pixel_values"] self.assertListEqual(arg_names[:1] , UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : int) ->str: '''simple docstring''' lowerCamelCase__: List[Any] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Optional[int]) ->Dict: '''simple docstring''' def check_hidden_states_output(UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : List[Any]): lowerCamelCase__: List[str] =model_class(UpperCAmelCase_) lowerCamelCase__: List[str] =model(**self._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_) , training=UpperCAmelCase_) lowerCamelCase__: List[Any] =outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states lowerCamelCase__: Optional[int] =self.model_tester.num_stages self.assertEqual(len(UpperCAmelCase_) , expected_num_stages + 1) # RegNet's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:]) , [self.model_tester.image_size // 2, self.model_tester.image_size // 2] , ) lowerCamelCase__ , lowerCamelCase__: Tuple =self.model_tester.prepare_config_and_inputs_for_common() lowerCamelCase__: int =["basic", "bottleneck"] for model_class in self.all_model_classes: for layer_type in layers_type: lowerCamelCase__: Any =layer_type lowerCamelCase__: str =True check_hidden_states_output(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] lowerCamelCase__: str =True check_hidden_states_output(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : int) ->Optional[Any]: '''simple docstring''' lowerCamelCase__ , lowerCamelCase__: int =self.model_tester.prepare_config_and_inputs_for_common() def check_equivalence(UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : Optional[int]={}): lowerCamelCase__: int =model(UpperCAmelCase_ , return_dict=UpperCAmelCase_ , **UpperCAmelCase_) lowerCamelCase__: Union[str, Any] =model(UpperCAmelCase_ , return_dict=UpperCAmelCase_ , **UpperCAmelCase_).to_tuple() def recursive_check(UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Union[str, Any]): if isinstance(UpperCAmelCase_ , (List, Tuple)): for tuple_iterable_value, dict_iterable_value in zip(UpperCAmelCase_ , UpperCAmelCase_): recursive_check(UpperCAmelCase_ , UpperCAmelCase_) elif tuple_object is None: return else: self.assertTrue( all(tf.equal(UpperCAmelCase_ , UpperCAmelCase_)) , msg=( "Tuple and dict output are not equal. Difference:" F""" {tf.math.reduce_max(tf.abs(tuple_object - dict_object))}""" ) , ) recursive_check(UpperCAmelCase_ , UpperCAmelCase_) for model_class in self.all_model_classes: lowerCamelCase__: Optional[int] =model_class(UpperCAmelCase_) lowerCamelCase__: List[Any] =self._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_) lowerCamelCase__: int =self._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_) check_equivalence(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_) lowerCamelCase__: List[Any] =self._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_ , return_labels=UpperCAmelCase_) lowerCamelCase__: int =self._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_ , return_labels=UpperCAmelCase_) check_equivalence(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_) lowerCamelCase__: Union[str, Any] =self._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_) lowerCamelCase__: Union[str, Any] =self._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_) check_equivalence(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , {"output_hidden_states": True}) lowerCamelCase__: Union[str, Any] =self._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_ , return_labels=UpperCAmelCase_) lowerCamelCase__: List[str] =self._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_ , return_labels=UpperCAmelCase_) check_equivalence(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , {"output_hidden_states": True}) def SCREAMING_SNAKE_CASE_ (self : Optional[Any]) ->Tuple: '''simple docstring''' lowerCamelCase__: str =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*UpperCAmelCase_) @slow def SCREAMING_SNAKE_CASE_ (self : List[Any]) ->str: '''simple docstring''' for model_name in TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowerCamelCase__: Optional[Any] =TFRegNetModel.from_pretrained(UpperCAmelCase_) self.assertIsNotNone(UpperCAmelCase_) def lowerCAmelCase_ ( ) -> List[Any]: """simple docstring""" lowerCamelCase__: Union[str, Any] =Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_tf @require_vision class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' @cached_property def SCREAMING_SNAKE_CASE_ (self : str) ->List[Any]: '''simple docstring''' return ( AutoImageProcessor.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]) if is_vision_available() else None ) @slow def SCREAMING_SNAKE_CASE_ (self : Any) ->Dict: '''simple docstring''' lowerCamelCase__: Optional[int] =TFRegNetForImageClassification.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]) lowerCamelCase__: Union[str, Any] =self.default_image_processor lowerCamelCase__: Union[str, Any] =prepare_img() lowerCamelCase__: Any =image_processor(images=UpperCAmelCase_ , return_tensors="tf") # forward pass lowerCamelCase__: Tuple =model(**UpperCAmelCase_ , training=UpperCAmelCase_) # verify the logits lowerCamelCase__: List[str] =tf.TensorShape((1, 1_000)) self.assertEqual(outputs.logits.shape , UpperCAmelCase_) lowerCamelCase__: int =tf.constant([-0.4180, -1.5051, -3.4836]) tf.debugging.assert_near(outputs.logits[0, :3] , UpperCAmelCase_ , atol=1E-4)
10
from __future__ import annotations from scipy.special import comb # type: ignore class A_ : def __init__( self : List[str] ,SCREAMING_SNAKE_CASE__ : list[tuple[float, float]]): __lowerCamelCase : Union[str, Any] = list_of_points # Degree determines the flexibility of the curve. # Degree = 1 will produce a straight line. __lowerCamelCase : int = len(SCREAMING_SNAKE_CASE__) - 1 def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : float): assert 0 <= t <= 1, "Time t must be between 0 and 1." __lowerCamelCase : list[float] = [] for i in range(len(self.list_of_points)): # basis function for each i output_values.append( comb(self.degree ,SCREAMING_SNAKE_CASE__) * ((1 - t) ** (self.degree - i)) * (t**i)) # the basis must sum up to 1 for it to produce a valid Bezier curve. assert round(sum(SCREAMING_SNAKE_CASE__) ,5) == 1 return output_values def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : float): assert 0 <= t <= 1, "Time t must be between 0 and 1." __lowerCamelCase : Tuple = self.basis_function(SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = 0.0 __lowerCamelCase : Optional[Any] = 0.0 for i in range(len(self.list_of_points)): # For all points, sum up the product of i-th basis function and i-th point. x += basis_function[i] * self.list_of_points[i][0] y += basis_function[i] * self.list_of_points[i][1] return (x, y) def lowerCAmelCase ( self : int ,SCREAMING_SNAKE_CASE__ : float = 0.01): from matplotlib import pyplot as plt # type: ignore __lowerCamelCase : list[float] = [] # x coordinates of points to plot __lowerCamelCase : list[float] = [] # y coordinates of points to plot __lowerCamelCase : Any = 0.0 while t <= 1: __lowerCamelCase : List[Any] = self.bezier_curve_function(SCREAMING_SNAKE_CASE__) to_plot_x.append(value[0]) to_plot_y.append(value[1]) t += step_size __lowerCamelCase : Optional[Any] = [i[0] for i in self.list_of_points] __lowerCamelCase : List[str] = [i[1] for i in self.list_of_points] plt.plot( SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,color='blue' ,label='Curve of Degree ' + str(self.degree) ,) plt.scatter(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,color='red' ,label='Control Points') plt.legend() plt.show() if __name__ == "__main__": import doctest doctest.testmod() BezierCurve([(1, 2), (3, 5)]).plot_curve() # degree 1 BezierCurve([(0, 0), (5, 5), (5, 0)]).plot_curve() # degree 2 BezierCurve([(0, 0), (5, 5), (5, 0), (2.5, -2.5)]).plot_curve() # degree 3
73
0
import argparse from transformers import CLIPImageProcessor, CLIPVisionModelWithProjection from diffusers import UnCLIPImageVariationPipeline, UnCLIPPipeline if __name__ == "__main__": lowerCAmelCase__ = argparse.ArgumentParser() parser.add_argument('--dump_path', default=None, type=str, required=True, help='Path to the output model.') parser.add_argument( '--txt2img_unclip', default='kakaobrain/karlo-v1-alpha', type=str, required=False, help='The pretrained txt2img unclip.', ) lowerCAmelCase__ = parser.parse_args() lowerCAmelCase__ = UnCLIPPipeline.from_pretrained(args.txtaimg_unclip) lowerCAmelCase__ = CLIPImageProcessor() lowerCAmelCase__ = CLIPVisionModelWithProjection.from_pretrained('openai/clip-vit-large-patch14') lowerCAmelCase__ = UnCLIPImageVariationPipeline( decoder=txtaimg.decoder, text_encoder=txtaimg.text_encoder, tokenizer=txtaimg.tokenizer, text_proj=txtaimg.text_proj, feature_extractor=feature_extractor, image_encoder=image_encoder, super_res_first=txtaimg.super_res_first, super_res_last=txtaimg.super_res_last, decoder_scheduler=txtaimg.decoder_scheduler, super_res_scheduler=txtaimg.super_res_scheduler, ) imgaimg.save_pretrained(args.dump_path)
11
from __future__ import annotations import time a =list[tuple[int, int]] a =[ [0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles [0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0], [1, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0], ] a =[[-1, 0], [0, -1], [1, 0], [0, 1]] # up, left, down, right class A_ : def __init__( self : List[str] ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : Node | None): __lowerCamelCase : Tuple = pos_x __lowerCamelCase : List[str] = pos_y __lowerCamelCase : str = (pos_y, pos_x) __lowerCamelCase : str = goal_x __lowerCamelCase : int = goal_y __lowerCamelCase : List[Any] = parent class A_ : def __init__( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : tuple[int, int] ,SCREAMING_SNAKE_CASE__ : tuple[int, int]): __lowerCamelCase : Any = Node(start[1] ,start[0] ,goal[1] ,goal[0] ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = Node(goal[1] ,goal[0] ,goal[1] ,goal[0] ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Union[str, Any] = [self.start] __lowerCamelCase : List[str] = False def lowerCAmelCase ( self : List[Any]): while self.node_queue: __lowerCamelCase : Any = self.node_queue.pop(0) if current_node.pos == self.target.pos: __lowerCamelCase : Dict = True return self.retrace_path(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Tuple = self.get_successors(SCREAMING_SNAKE_CASE__) for node in successors: self.node_queue.append(SCREAMING_SNAKE_CASE__) if not self.reached: return [self.start.pos] return None def lowerCAmelCase ( self : str ,SCREAMING_SNAKE_CASE__ : Node): __lowerCamelCase : Union[str, Any] = [] for action in delta: __lowerCamelCase : Optional[Any] = parent.pos_x + action[1] __lowerCamelCase : Optional[int] = parent.pos_y + action[0] if not (0 <= pos_x <= len(grid[0]) - 1 and 0 <= pos_y <= len(SCREAMING_SNAKE_CASE__) - 1): continue if grid[pos_y][pos_x] != 0: continue successors.append( Node(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,self.target.pos_y ,self.target.pos_x ,SCREAMING_SNAKE_CASE__)) return successors def lowerCAmelCase ( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : Node | None): __lowerCamelCase : List[Any] = node __lowerCamelCase : int = [] while current_node is not None: path.append((current_node.pos_y, current_node.pos_x)) __lowerCamelCase : int = current_node.parent path.reverse() return path class A_ : def __init__( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : int): __lowerCamelCase : int = BreadthFirstSearch(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = BreadthFirstSearch(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = False def lowerCAmelCase ( self : str): while self.fwd_bfs.node_queue or self.bwd_bfs.node_queue: __lowerCamelCase : Any = self.fwd_bfs.node_queue.pop(0) __lowerCamelCase : Any = self.bwd_bfs.node_queue.pop(0) if current_bwd_node.pos == current_fwd_node.pos: __lowerCamelCase : List[str] = True return self.retrace_bidirectional_path( SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = current_bwd_node __lowerCamelCase : int = current_fwd_node __lowerCamelCase : str = { self.fwd_bfs: self.fwd_bfs.get_successors(SCREAMING_SNAKE_CASE__), self.bwd_bfs: self.bwd_bfs.get_successors(SCREAMING_SNAKE_CASE__), } for bfs in [self.fwd_bfs, self.bwd_bfs]: for node in successors[bfs]: bfs.node_queue.append(SCREAMING_SNAKE_CASE__) if not self.reached: return [self.fwd_bfs.start.pos] return None def lowerCAmelCase ( self : Dict ,SCREAMING_SNAKE_CASE__ : Node ,SCREAMING_SNAKE_CASE__ : Node): __lowerCamelCase : List[Any] = self.fwd_bfs.retrace_path(SCREAMING_SNAKE_CASE__) __lowerCamelCase : str = self.bwd_bfs.retrace_path(SCREAMING_SNAKE_CASE__) bwd_path.pop() bwd_path.reverse() __lowerCamelCase : List[Any] = fwd_path + bwd_path return path if __name__ == "__main__": # all coordinates are given in format [y,x] import doctest doctest.testmod() a =(0, 0) a =(len(grid) - 1, len(grid[0]) - 1) for elem in grid: print(elem) a =time.time() a =BreadthFirstSearch(init, goal) a =bfs.search() a =time.time() - start_bfs_time print("""Unidirectional BFS computation time : """, bfs_time) a =time.time() a =BidirectionalBreadthFirstSearch(init, goal) a =bd_bfs.search() a =time.time() - start_bd_bfs_time print("""Bidirectional BFS computation time : """, bd_bfs_time)
73
0
from __future__ import annotations import random # Maximum size of the population. Bigger could be faster but is more memory expensive. UpperCAmelCase_ = 200 # Number of elements selected in every generation of evolution. The selection takes # place from best to worst of that generation and must be smaller than N_POPULATION. UpperCAmelCase_ = 50 # Probability that an element of a generation can mutate, changing one of its genes. # This will guarantee that all genes will be used during evolution. UpperCAmelCase_ = 0.4 # Just a seed to improve randomness required by the algorithm. random.seed(random.randint(0, 1_000)) def lowerCamelCase__ ( A__ : str , A__ : str ): '''simple docstring''' __lowerCamelCase = len([g for position, g in enumerate(A__ ) if g == main_target[position]] ) return (item, float(A__ )) def lowerCamelCase__ ( A__ : str , A__ : str ): '''simple docstring''' __lowerCamelCase = random.randint(0 , len(A__ ) - 1 ) __lowerCamelCase = parent_a[:random_slice] + parent_a[random_slice:] __lowerCamelCase = parent_a[:random_slice] + parent_a[random_slice:] return (child_a, child_a) def lowerCamelCase__ ( A__ : str , A__ : list[str] ): '''simple docstring''' __lowerCamelCase = list(A__ ) if random.uniform(0 , 1 ) < MUTATION_PROBABILITY: __lowerCamelCase = random.choice(A__ ) return "".join(A__ ) def lowerCamelCase__ ( A__ : tuple[str, float] , A__ : list[tuple[str, float]] , A__ : list[str] , ): '''simple docstring''' __lowerCamelCase = [] # Generate more children proportionally to the fitness score. __lowerCamelCase = int(parent_a[1] * 100 ) + 1 __lowerCamelCase = 10 if child_n >= 10 else child_n for _ in range(A__ ): __lowerCamelCase = population_score[random.randint(0 , A__ )][0] __lowerCamelCase, __lowerCamelCase = crossover(parent_a[0] , A__ ) # Append new string to the population list. pop.append(mutate(A__ , A__ ) ) pop.append(mutate(A__ , A__ ) ) return pop def lowerCamelCase__ ( A__ : str , A__ : list[str] , A__ : bool = True ): '''simple docstring''' if N_POPULATION < N_SELECTED: __lowerCamelCase = f'{N_POPULATION} must be bigger than {N_SELECTED}' raise ValueError(A__ ) # Verify that the target contains no genes besides the ones inside genes variable. __lowerCamelCase = sorted({c for c in target if c not in genes} ) if not_in_genes_list: __lowerCamelCase = f'{not_in_genes_list} is not in genes list, evolution cannot converge' raise ValueError(A__ ) # Generate random starting population. __lowerCamelCase = [] for _ in range(A__ ): population.append("""""".join([random.choice(A__ ) for i in range(len(A__ ) )] ) ) # Just some logs to know what the algorithms is doing. __lowerCamelCase, __lowerCamelCase = 0, 0 # This loop will end when we find a perfect match for our target. while True: generation += 1 total_population += len(A__ ) # Random population created. Now it's time to evaluate. # Adding a bit of concurrency can make everything faster, # # import concurrent.futures # population_score: list[tuple[str, float]] = [] # with concurrent.futures.ThreadPoolExecutor( # max_workers=NUM_WORKERS) as executor: # futures = {executor.submit(evaluate, item) for item in population} # concurrent.futures.wait(futures) # population_score = [item.result() for item in futures] # # but with a simple algorithm like this, it will probably be slower. # We just need to call evaluate for every item inside the population. __lowerCamelCase = [evaluate(A__ , A__ ) for item in population] # Check if there is a matching evolution. __lowerCamelCase = sorted(A__ , key=lambda A__ : x[1] , reverse=A__ ) if population_score[0][0] == target: return (generation, total_population, population_score[0][0]) # Print the best result every 10 generation. # Just to know that the algorithm is working. if debug and generation % 10 == 0: print( f'\nGeneration: {generation}' f'\nTotal Population:{total_population}' f'\nBest score: {population_score[0][1]}' f'\nBest string: {population_score[0][0]}' ) # Flush the old population, keeping some of the best evolutions. # Keeping this avoid regression of evolution. __lowerCamelCase = population[: int(N_POPULATION / 3 )] population.clear() population.extend(A__ ) # Normalize population score to be between 0 and 1. __lowerCamelCase = [ (item, score / len(A__ )) for item, score in population_score ] # This is selection for i in range(A__ ): population.extend(select(population_score[int(A__ )] , A__ , A__ ) ) # Check if the population has already reached the maximum value and if so, # break the cycle. If this check is disabled, the algorithm will take # forever to compute large strings, but will also calculate small strings in # a far fewer generations. if len(A__ ) > N_POPULATION: break if __name__ == "__main__": UpperCAmelCase_ = ( 'This is a genetic algorithm to evaluate, combine, evolve, and mutate a string!' ) UpperCAmelCase_ = list( ' ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklm' 'nopqrstuvwxyz.,;!?+-*#@^\'èéòà€ù=)(&%$£/\\' ) UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ = basic(target_str, genes_list) print( f"""\nGeneration: {generation}\nTotal Population: {population}\nTarget: {target}""" )
12
import qiskit def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> qiskit.result.counts.Counts: __lowerCamelCase : Optional[int] = qiskit.Aer.get_backend('aer_simulator' ) # Create a Quantum Circuit acting on the q register __lowerCamelCase : List[str] = qiskit.QuantumCircuit(lowerCamelCase__ , lowerCamelCase__ ) # Map the quantum measurement to the classical bits circuit.measure([0] , [0] ) # Execute the circuit on the simulator __lowerCamelCase : List[Any] = qiskit.execute(lowerCamelCase__ , lowerCamelCase__ , shots=1_0_0_0 ) # Return the histogram data of the results of the experiment. return job.result().get_counts(lowerCamelCase__ ) if __name__ == "__main__": print(F"""Total count for various states are: {single_qubit_measure(1, 1)}""")
73
0
import inspect from typing import List, Optional, Tuple, Union import numpy as np import PIL import torch import torch.utils.checkpoint from ...models import UNetaDModel, VQModel from ...schedulers import ( DDIMScheduler, DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, LMSDiscreteScheduler, PNDMScheduler, ) from ...utils import PIL_INTERPOLATION, randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput def A_ ( _UpperCAmelCase ): SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Optional[Any] = image.size SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: str = (x - x % 32 for x in (w, h)) # resize to integer multiple of 32 SCREAMING_SNAKE_CASE_: Tuple = image.resize((w, h) , resample=PIL_INTERPOLATION["lanczos"] ) SCREAMING_SNAKE_CASE_: str = np.array(_UpperCAmelCase ).astype(np.floataa ) / 2_5_5.0 SCREAMING_SNAKE_CASE_: Optional[Any] = image[None].transpose(0 , 3 , 1 , 2 ) SCREAMING_SNAKE_CASE_: str = torch.from_numpy(_UpperCAmelCase ) return 2.0 * image - 1.0 class __lowercase ( UpperCAmelCase_ ): """simple docstring""" def __init__( self : Tuple , lowerCAmelCase__ : VQModel , lowerCAmelCase__ : UNetaDModel , lowerCAmelCase__ : Union[ DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler, EulerDiscreteScheduler, EulerAncestralDiscreteScheduler, DPMSolverMultistepScheduler, ] , ): super().__init__() self.register_modules(vqvae=lowerCAmelCase__ , unet=lowerCAmelCase__ , scheduler=lowerCAmelCase__) @torch.no_grad() def __call__( self : str , lowerCAmelCase__ : Union[torch.Tensor, PIL.Image.Image] = None , lowerCAmelCase__ : Optional[int] = 1 , lowerCAmelCase__ : Optional[int] = 100 , lowerCAmelCase__ : Optional[float] = 0.0 , lowerCAmelCase__ : Optional[Union[torch.Generator, List[torch.Generator]]] = None , lowerCAmelCase__ : Optional[str] = "pil" , lowerCAmelCase__ : bool = True , ): if isinstance(lowerCAmelCase__ , PIL.Image.Image): SCREAMING_SNAKE_CASE_: List[str] = 1 elif isinstance(lowerCAmelCase__ , torch.Tensor): SCREAMING_SNAKE_CASE_: str = image.shape[0] else: raise ValueError(F"`image` has to be of type `PIL.Image.Image` or `torch.Tensor` but is {type(lowerCAmelCase__)}") if isinstance(lowerCAmelCase__ , PIL.Image.Image): SCREAMING_SNAKE_CASE_: Dict = preprocess(lowerCAmelCase__) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Optional[int] = image.shape[-2:] # in_channels should be 6: 3 for latents, 3 for low resolution image SCREAMING_SNAKE_CASE_: List[str] = (batch_size, self.unet.config.in_channels // 2, height, width) SCREAMING_SNAKE_CASE_: List[str] = next(self.unet.parameters()).dtype SCREAMING_SNAKE_CASE_: Dict = randn_tensor(lowerCAmelCase__ , generator=lowerCAmelCase__ , device=self.device , dtype=lowerCAmelCase__) SCREAMING_SNAKE_CASE_: str = image.to(device=self.device , dtype=lowerCAmelCase__) # set timesteps and move to the correct device self.scheduler.set_timesteps(lowerCAmelCase__ , device=self.device) SCREAMING_SNAKE_CASE_: List[str] = self.scheduler.timesteps # scale the initial noise by the standard deviation required by the scheduler SCREAMING_SNAKE_CASE_: List[str] = latents * self.scheduler.init_noise_sigma # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature. # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 # and should be between [0, 1] SCREAMING_SNAKE_CASE_: List[str] = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys()) SCREAMING_SNAKE_CASE_: Optional[Any] = {} if accepts_eta: SCREAMING_SNAKE_CASE_: int = eta for t in self.progress_bar(lowerCAmelCase__): # concat latents and low resolution image in the channel dimension. SCREAMING_SNAKE_CASE_: Optional[Any] = torch.cat([latents, image] , dim=1) SCREAMING_SNAKE_CASE_: List[Any] = self.scheduler.scale_model_input(lowerCAmelCase__ , lowerCAmelCase__) # predict the noise residual SCREAMING_SNAKE_CASE_: Union[str, Any] = self.unet(lowerCAmelCase__ , lowerCAmelCase__).sample # compute the previous noisy sample x_t -> x_t-1 SCREAMING_SNAKE_CASE_: int = self.scheduler.step(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , **lowerCAmelCase__).prev_sample # decode the image latents with the VQVAE SCREAMING_SNAKE_CASE_: int = self.vqvae.decode(lowerCAmelCase__).sample SCREAMING_SNAKE_CASE_: Optional[Any] = torch.clamp(lowerCAmelCase__ , -1.0 , 1.0) SCREAMING_SNAKE_CASE_: Optional[int] = image / 2 + 0.5 SCREAMING_SNAKE_CASE_: Optional[Any] = image.cpu().permute(0 , 2 , 3 , 1).numpy() if output_type == "pil": SCREAMING_SNAKE_CASE_: Dict = self.numpy_to_pil(lowerCAmelCase__) if not return_dict: return (image,) return ImagePipelineOutput(images=lowerCAmelCase__)
13
import os import sys a =os.path.join(os.path.dirname(__file__), """src""") sys.path.append(SRC_DIR) from transformers import ( AutoConfig, AutoModel, AutoModelForCausalLM, AutoModelForMaskedLM, AutoModelForQuestionAnswering, AutoModelForSequenceClassification, AutoTokenizer, add_start_docstrings, ) a =[ """torch""", """numpy""", """tokenizers""", """filelock""", """requests""", """tqdm""", """regex""", """sentencepiece""", """sacremoses""", """importlib_metadata""", """huggingface_hub""", ] @add_start_docstrings(AutoConfig.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> int: return AutoConfig.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ ) @add_start_docstrings(AutoTokenizer.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> Optional[Any]: return AutoTokenizer.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ ) @add_start_docstrings(AutoModel.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> List[str]: return AutoModel.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ ) @add_start_docstrings(AutoModelForCausalLM.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> Any: return AutoModelForCausalLM.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ ) @add_start_docstrings(AutoModelForMaskedLM.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> List[str]: return AutoModelForMaskedLM.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ ) @add_start_docstrings(AutoModelForSequenceClassification.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> List[str]: return AutoModelForSequenceClassification.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ ) @add_start_docstrings(AutoModelForQuestionAnswering.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> Tuple: return AutoModelForQuestionAnswering.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ )
73
0
import argparse import json from collections import OrderedDict from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( ConditionalDetrConfig, ConditionalDetrForObjectDetection, ConditionalDetrForSegmentation, ConditionalDetrImageProcessor, ) from transformers.utils import logging logging.set_verbosity_info() _lowerCamelCase : str = logging.get_logger(__name__) # here we list all keys to be renamed (original name on the left, our name on the right) _lowerCamelCase : List[str] = [] for i in range(6): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append( (F'''transformer.encoder.layers.{i}.self_attn.out_proj.weight''', F'''encoder.layers.{i}.self_attn.out_proj.weight''') ) rename_keys.append( (F'''transformer.encoder.layers.{i}.self_attn.out_proj.bias''', F'''encoder.layers.{i}.self_attn.out_proj.bias''') ) rename_keys.append((F'''transformer.encoder.layers.{i}.linear1.weight''', F'''encoder.layers.{i}.fc1.weight''')) rename_keys.append((F'''transformer.encoder.layers.{i}.linear1.bias''', F'''encoder.layers.{i}.fc1.bias''')) rename_keys.append((F'''transformer.encoder.layers.{i}.linear2.weight''', F'''encoder.layers.{i}.fc2.weight''')) rename_keys.append((F'''transformer.encoder.layers.{i}.linear2.bias''', F'''encoder.layers.{i}.fc2.bias''')) rename_keys.append( (F'''transformer.encoder.layers.{i}.norm1.weight''', F'''encoder.layers.{i}.self_attn_layer_norm.weight''') ) rename_keys.append((F'''transformer.encoder.layers.{i}.norm1.bias''', F'''encoder.layers.{i}.self_attn_layer_norm.bias''')) rename_keys.append((F'''transformer.encoder.layers.{i}.norm2.weight''', F'''encoder.layers.{i}.final_layer_norm.weight''')) rename_keys.append((F'''transformer.encoder.layers.{i}.norm2.bias''', F'''encoder.layers.{i}.final_layer_norm.bias''')) # decoder layers: 2 times output projection, 2 feedforward neural networks and 3 layernorms rename_keys.append( (F'''transformer.decoder.layers.{i}.self_attn.out_proj.weight''', F'''decoder.layers.{i}.self_attn.out_proj.weight''') ) rename_keys.append( (F'''transformer.decoder.layers.{i}.self_attn.out_proj.bias''', F'''decoder.layers.{i}.self_attn.out_proj.bias''') ) rename_keys.append( ( F'''transformer.decoder.layers.{i}.cross_attn.out_proj.weight''', F'''decoder.layers.{i}.encoder_attn.out_proj.weight''', ) ) rename_keys.append( ( F'''transformer.decoder.layers.{i}.cross_attn.out_proj.bias''', F'''decoder.layers.{i}.encoder_attn.out_proj.bias''', ) ) rename_keys.append((F'''transformer.decoder.layers.{i}.linear1.weight''', F'''decoder.layers.{i}.fc1.weight''')) rename_keys.append((F'''transformer.decoder.layers.{i}.linear1.bias''', F'''decoder.layers.{i}.fc1.bias''')) rename_keys.append((F'''transformer.decoder.layers.{i}.linear2.weight''', F'''decoder.layers.{i}.fc2.weight''')) rename_keys.append((F'''transformer.decoder.layers.{i}.linear2.bias''', F'''decoder.layers.{i}.fc2.bias''')) rename_keys.append( (F'''transformer.decoder.layers.{i}.norm1.weight''', F'''decoder.layers.{i}.self_attn_layer_norm.weight''') ) rename_keys.append((F'''transformer.decoder.layers.{i}.norm1.bias''', F'''decoder.layers.{i}.self_attn_layer_norm.bias''')) rename_keys.append( (F'''transformer.decoder.layers.{i}.norm2.weight''', F'''decoder.layers.{i}.encoder_attn_layer_norm.weight''') ) rename_keys.append( (F'''transformer.decoder.layers.{i}.norm2.bias''', F'''decoder.layers.{i}.encoder_attn_layer_norm.bias''') ) rename_keys.append((F'''transformer.decoder.layers.{i}.norm3.weight''', F'''decoder.layers.{i}.final_layer_norm.weight''')) rename_keys.append((F'''transformer.decoder.layers.{i}.norm3.bias''', F'''decoder.layers.{i}.final_layer_norm.bias''')) # q, k, v projections in self/cross-attention in decoder for conditional DETR rename_keys.append( (F'''transformer.decoder.layers.{i}.sa_qcontent_proj.weight''', F'''decoder.layers.{i}.sa_qcontent_proj.weight''') ) rename_keys.append( (F'''transformer.decoder.layers.{i}.sa_kcontent_proj.weight''', F'''decoder.layers.{i}.sa_kcontent_proj.weight''') ) rename_keys.append( (F'''transformer.decoder.layers.{i}.sa_qpos_proj.weight''', F'''decoder.layers.{i}.sa_qpos_proj.weight''') ) rename_keys.append( (F'''transformer.decoder.layers.{i}.sa_kpos_proj.weight''', F'''decoder.layers.{i}.sa_kpos_proj.weight''') ) rename_keys.append((F'''transformer.decoder.layers.{i}.sa_v_proj.weight''', F'''decoder.layers.{i}.sa_v_proj.weight''')) rename_keys.append( (F'''transformer.decoder.layers.{i}.ca_qcontent_proj.weight''', F'''decoder.layers.{i}.ca_qcontent_proj.weight''') ) # rename_keys.append((f"transformer.decoder.layers.{i}.ca_qpos_proj.weight", f"decoder.layers.{i}.ca_qpos_proj.weight")) rename_keys.append( (F'''transformer.decoder.layers.{i}.ca_kcontent_proj.weight''', F'''decoder.layers.{i}.ca_kcontent_proj.weight''') ) rename_keys.append( (F'''transformer.decoder.layers.{i}.ca_kpos_proj.weight''', F'''decoder.layers.{i}.ca_kpos_proj.weight''') ) rename_keys.append((F'''transformer.decoder.layers.{i}.ca_v_proj.weight''', F'''decoder.layers.{i}.ca_v_proj.weight''')) rename_keys.append( (F'''transformer.decoder.layers.{i}.ca_qpos_sine_proj.weight''', F'''decoder.layers.{i}.ca_qpos_sine_proj.weight''') ) rename_keys.append( (F'''transformer.decoder.layers.{i}.sa_qcontent_proj.bias''', F'''decoder.layers.{i}.sa_qcontent_proj.bias''') ) rename_keys.append( (F'''transformer.decoder.layers.{i}.sa_kcontent_proj.bias''', F'''decoder.layers.{i}.sa_kcontent_proj.bias''') ) rename_keys.append((F'''transformer.decoder.layers.{i}.sa_qpos_proj.bias''', F'''decoder.layers.{i}.sa_qpos_proj.bias''')) rename_keys.append((F'''transformer.decoder.layers.{i}.sa_kpos_proj.bias''', F'''decoder.layers.{i}.sa_kpos_proj.bias''')) rename_keys.append((F'''transformer.decoder.layers.{i}.sa_v_proj.bias''', F'''decoder.layers.{i}.sa_v_proj.bias''')) rename_keys.append( (F'''transformer.decoder.layers.{i}.ca_qcontent_proj.bias''', F'''decoder.layers.{i}.ca_qcontent_proj.bias''') ) # rename_keys.append((f"transformer.decoder.layers.{i}.ca_qpos_proj.bias", f"decoder.layers.{i}.ca_qpos_proj.bias")) rename_keys.append( (F'''transformer.decoder.layers.{i}.ca_kcontent_proj.bias''', F'''decoder.layers.{i}.ca_kcontent_proj.bias''') ) rename_keys.append((F'''transformer.decoder.layers.{i}.ca_kpos_proj.bias''', F'''decoder.layers.{i}.ca_kpos_proj.bias''')) rename_keys.append((F'''transformer.decoder.layers.{i}.ca_v_proj.bias''', F'''decoder.layers.{i}.ca_v_proj.bias''')) rename_keys.append( (F'''transformer.decoder.layers.{i}.ca_qpos_sine_proj.bias''', F'''decoder.layers.{i}.ca_qpos_sine_proj.bias''') ) # convolutional projection + query embeddings + layernorm of decoder + class and bounding box heads # for conditional DETR, also convert reference point head and query scale MLP rename_keys.extend( [ ("""input_proj.weight""", """input_projection.weight"""), ("""input_proj.bias""", """input_projection.bias"""), ("""query_embed.weight""", """query_position_embeddings.weight"""), ("""transformer.decoder.norm.weight""", """decoder.layernorm.weight"""), ("""transformer.decoder.norm.bias""", """decoder.layernorm.bias"""), ("""class_embed.weight""", """class_labels_classifier.weight"""), ("""class_embed.bias""", """class_labels_classifier.bias"""), ("""bbox_embed.layers.0.weight""", """bbox_predictor.layers.0.weight"""), ("""bbox_embed.layers.0.bias""", """bbox_predictor.layers.0.bias"""), ("""bbox_embed.layers.1.weight""", """bbox_predictor.layers.1.weight"""), ("""bbox_embed.layers.1.bias""", """bbox_predictor.layers.1.bias"""), ("""bbox_embed.layers.2.weight""", """bbox_predictor.layers.2.weight"""), ("""bbox_embed.layers.2.bias""", """bbox_predictor.layers.2.bias"""), ("""transformer.decoder.ref_point_head.layers.0.weight""", """decoder.ref_point_head.layers.0.weight"""), ("""transformer.decoder.ref_point_head.layers.0.bias""", """decoder.ref_point_head.layers.0.bias"""), ("""transformer.decoder.ref_point_head.layers.1.weight""", """decoder.ref_point_head.layers.1.weight"""), ("""transformer.decoder.ref_point_head.layers.1.bias""", """decoder.ref_point_head.layers.1.bias"""), ("""transformer.decoder.query_scale.layers.0.weight""", """decoder.query_scale.layers.0.weight"""), ("""transformer.decoder.query_scale.layers.0.bias""", """decoder.query_scale.layers.0.bias"""), ("""transformer.decoder.query_scale.layers.1.weight""", """decoder.query_scale.layers.1.weight"""), ("""transformer.decoder.query_scale.layers.1.bias""", """decoder.query_scale.layers.1.bias"""), ("""transformer.decoder.layers.0.ca_qpos_proj.weight""", """decoder.layers.0.ca_qpos_proj.weight"""), ("""transformer.decoder.layers.0.ca_qpos_proj.bias""", """decoder.layers.0.ca_qpos_proj.bias"""), ] ) def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ , lowercase_ ) -> Optional[Any]: """simple docstring""" A__ = state_dict.pop(lowercase_ ) A__ = val def SCREAMING_SNAKE_CASE ( lowercase_ ) -> List[str]: """simple docstring""" A__ = OrderedDict() for key, value in state_dict.items(): if "backbone.0.body" in key: A__ = key.replace('''backbone.0.body''' , '''backbone.conv_encoder.model''' ) A__ = value else: A__ = value return new_state_dict def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_=False ) -> Dict: """simple docstring""" A__ = '''''' if is_panoptic: A__ = '''conditional_detr.''' # first: transformer encoder for i in range(6 ): # read in weights + bias of input projection layer (in PyTorch's MultiHeadAttention, this is a single matrix + bias) A__ = state_dict.pop(f"""{prefix}transformer.encoder.layers.{i}.self_attn.in_proj_weight""" ) A__ = state_dict.pop(f"""{prefix}transformer.encoder.layers.{i}.self_attn.in_proj_bias""" ) # next, add query, keys and values (in that order) to the state dict A__ = in_proj_weight[:256, :] A__ = in_proj_bias[:256] A__ = in_proj_weight[256:512, :] A__ = in_proj_bias[256:512] A__ = in_proj_weight[-256:, :] A__ = in_proj_bias[-256:] def SCREAMING_SNAKE_CASE ( ) -> List[Any]: """simple docstring""" A__ = '''http://images.cocodataset.org/val2017/000000039769.jpg''' A__ = Image.open(requests.get(lowercase_ , stream=lowercase_ ).raw ) return im @torch.no_grad() def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ ) -> Tuple: """simple docstring""" A__ = ConditionalDetrConfig() # set backbone and dilation attributes if "resnet101" in model_name: A__ = '''resnet101''' if "dc5" in model_name: A__ = True A__ = '''panoptic''' in model_name if is_panoptic: A__ = 250 else: A__ = 91 A__ = '''huggingface/label-files''' A__ = '''coco-detection-id2label.json''' A__ = json.load(open(hf_hub_download(lowercase_ , lowercase_ , repo_type='''dataset''' ) , '''r''' ) ) A__ = {int(lowercase_ ): v for k, v in idalabel.items()} A__ = idalabel A__ = {v: k for k, v in idalabel.items()} # load image processor A__ = '''coco_panoptic''' if is_panoptic else '''coco_detection''' A__ = ConditionalDetrImageProcessor(format=lowercase_ ) # prepare image A__ = prepare_img() A__ = image_processor(images=lowercase_ , return_tensors='''pt''' ) A__ = encoding['''pixel_values'''] logger.info(f"""Converting model {model_name}...""" ) # load original model from torch hub A__ = torch.hub.load('''DeppMeng/ConditionalDETR''' , lowercase_ , pretrained=lowercase_ ).eval() A__ = conditional_detr.state_dict() # rename keys for src, dest in rename_keys: if is_panoptic: A__ = '''conditional_detr.''' + src rename_key(lowercase_ , lowercase_ , lowercase_ ) A__ = rename_backbone_keys(lowercase_ ) # query, key and value matrices need special treatment read_in_q_k_v(lowercase_ , is_panoptic=lowercase_ ) # important: we need to prepend a prefix to each of the base model keys as the head models use different attributes for them A__ = '''conditional_detr.model.''' if is_panoptic else '''model.''' for key in state_dict.copy().keys(): if is_panoptic: if ( key.startswith('''conditional_detr''' ) and not key.startswith('''class_labels_classifier''' ) and not key.startswith('''bbox_predictor''' ) ): A__ = state_dict.pop(lowercase_ ) A__ = val elif "class_labels_classifier" in key or "bbox_predictor" in key: A__ = state_dict.pop(lowercase_ ) A__ = val elif key.startswith('''bbox_attention''' ) or key.startswith('''mask_head''' ): continue else: A__ = state_dict.pop(lowercase_ ) A__ = val else: if not key.startswith('''class_labels_classifier''' ) and not key.startswith('''bbox_predictor''' ): A__ = state_dict.pop(lowercase_ ) A__ = val # finally, create HuggingFace model and load state dict A__ = ConditionalDetrForSegmentation(lowercase_ ) if is_panoptic else ConditionalDetrForObjectDetection(lowercase_ ) model.load_state_dict(lowercase_ ) model.eval() model.push_to_hub(repo_id=lowercase_ , organization='''DepuMeng''' , commit_message='''Add model''' ) # verify our conversion A__ = conditional_detr(lowercase_ ) A__ = model(lowercase_ ) assert torch.allclose(outputs.logits , original_outputs['''pred_logits'''] , atol=1E-4 ) assert torch.allclose(outputs.pred_boxes , original_outputs['''pred_boxes'''] , atol=1E-4 ) if is_panoptic: assert torch.allclose(outputs.pred_masks , original_outputs['''pred_masks'''] , atol=1E-4 ) # Save model and image processor logger.info(f"""Saving PyTorch model and image processor to {pytorch_dump_folder_path}...""" ) Path(lowercase_ ).mkdir(exist_ok=lowercase_ ) model.save_pretrained(lowercase_ ) image_processor.save_pretrained(lowercase_ ) if __name__ == "__main__": _lowerCamelCase : Dict = argparse.ArgumentParser() parser.add_argument( """--model_name""", default="""conditional_detr_resnet50""", type=str, help="""Name of the CONDITIONAL_DETR model you'd like to convert.""", ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the folder to output PyTorch model.""" ) _lowerCamelCase : Optional[Any] = parser.parse_args() convert_conditional_detr_checkpoint(args.model_name, args.pytorch_dump_folder_path)
14
from typing import Optional from urllib.parse import quote import huggingface_hub as hfh from packaging import version def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ = None ) -> str: if version.parse(hfh.__version__ ).release < version.parse('0.11.0' ).release: # old versions of hfh don't url-encode the file path __lowerCamelCase : int = quote(lowerCamelCase__ ) return hfh.hf_hub_url(lowerCamelCase__ , lowerCamelCase__ , repo_type='dataset' , revision=lowerCamelCase__ )
73
0
from math import ceil def UpperCAmelCase ( a_ = 1_0_0_1 ) -> int: """simple docstring""" __A = 1 for i in range(1 , int(ceil(n / 2.0 ) ) ): __A = 2 * i + 1 __A = 2 * i __A = total + 4 * odd**2 - 6 * even return total if __name__ == "__main__": import sys if len(sys.argv) == 1: print(solution()) else: try: SCREAMING_SNAKE_CASE :Tuple = int(sys.argv[1]) print(solution(n)) except ValueError: print('Invalid entry - please enter a number')
15
def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , ) -> float: __lowerCamelCase : Dict = [redshift, radiation_density, matter_density, dark_energy] if any(p < 0 for p in parameters ): raise ValueError('All input parameters must be positive' ) if any(p > 1 for p in parameters[1:4] ): raise ValueError('Relative densities cannot be greater than one' ) else: __lowerCamelCase : Dict = 1 - (matter_density + radiation_density + dark_energy) __lowerCamelCase : Union[str, Any] = ( radiation_density * (redshift + 1) ** 4 + matter_density * (redshift + 1) ** 3 + curvature * (redshift + 1) ** 2 + dark_energy ) __lowerCamelCase : List[Any] = hubble_constant * e_a ** (1 / 2) return hubble if __name__ == "__main__": import doctest # run doctest doctest.testmod() # demo LCDM approximation a =0.3 print( hubble_parameter( hubble_constant=68.3, radiation_density=1E-4, matter_density=matter_density, dark_energy=1 - matter_density, redshift=0, ) )
73
0
"""simple docstring""" import logging import os import random import sys from dataclasses import dataclass, field from typing import Optional import datasets import numpy as np import pandas as pd from datasets import load_dataset import transformers from transformers import ( AutoConfig, BartForSequenceClassification, DataCollatorWithPadding, EvalPrediction, HfArgumentParser, TapexTokenizer, Trainer, TrainingArguments, default_data_collator, set_seed, ) from transformers.trainer_utils import get_last_checkpoint from transformers.utils import check_min_version from transformers.utils.versions import require_version # Will error if the minimal version of Transformers is not installed. Remove at your own risks. check_min_version('4.17.0.dev0') require_version('datasets>=1.8.0', 'To fix: pip install -r examples/pytorch/text-classification/requirements.txt') lowerCAmelCase_ = logging.getLogger(__name__) @dataclass class __A : '''simple docstring''' lowerCAmelCase : Optional[str] = field( default="tab_fact" ,metadata={"help": "The name of the dataset to use (via the datasets library)."} ) lowerCAmelCase : Optional[str] = field( default="tab_fact" ,metadata={"help": "The configuration name of the dataset to use (via the datasets library)."} ,) lowerCAmelCase : int = field( default=1_0_2_4 ,metadata={ "help": ( "The maximum total input sequence length after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." ) } ,) lowerCAmelCase : bool = field( default=A_ ,metadata={"help": "Overwrite the cached preprocessed datasets or not."} ) lowerCAmelCase : bool = field( default=A_ ,metadata={ "help": ( "Whether to pad all samples to `max_seq_length`. " "If False, will pad the samples dynamically when batching to the maximum length in the batch." ) } ,) lowerCAmelCase : Optional[int] = field( default=A_ ,metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of training examples to this " "value if set." ) } ,) lowerCAmelCase : Optional[int] = field( default=A_ ,metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of evaluation examples to this " "value if set." ) } ,) lowerCAmelCase : Optional[int] = field( default=A_ ,metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of prediction examples to this " "value if set." ) } ,) lowerCAmelCase : Optional[str] = field( default=A_ ,metadata={"help": "A csv or a json file containing the training data."} ) lowerCAmelCase : Optional[str] = field( default=A_ ,metadata={"help": "A csv or a json file containing the validation data."} ) lowerCAmelCase : Optional[str] = field(default=A_ ,metadata={"help": "A csv or a json file containing the test data."} ) def UpperCAmelCase ( self : str ) -> Any: """simple docstring""" if self.dataset_name is not None: pass elif self.train_file is None or self.validation_file is None: raise ValueError('''Need either a GLUE task, a training/validation file or a dataset name.''' ) else: lowercase__ : List[str] = self.train_file.split('''.''' )[-1] assert train_extension in ["csv", "json"], "`train_file` should be a csv or a json file." lowercase__ : Optional[int] = self.validation_file.split('''.''' )[-1] assert ( validation_extension == train_extension ), "`validation_file` should have the same extension (csv or json) as `train_file`." @dataclass class __A : '''simple docstring''' lowerCAmelCase : str = field( default=A_ ,metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"} ) lowerCAmelCase : Optional[str] = field( default=A_ ,metadata={"help": "Pretrained config name or path if not the same as model_name"} ) lowerCAmelCase : Optional[str] = field( default=A_ ,metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"} ) lowerCAmelCase : Optional[str] = field( default=A_ ,metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"} ,) lowerCAmelCase : bool = field( default=A_ ,metadata={"help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."} ,) lowerCAmelCase : str = field( default="main" ,metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."} ,) lowerCAmelCase : bool = field( default=A_ ,metadata={ "help": ( "Will use the token generated when running `huggingface-cli login` (necessary to use this script " "with private models)." ) } ,) def __UpperCAmelCase ( ) -> List[Any]: # See all possible arguments in src/transformers/training_args.py # or by passing the --help flag to this script. # We now keep distinct sets of args, for a cleaner separation of concerns. lowercase__ : Union[str, Any] = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith('''.json''' ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. lowercase__ , lowercase__ , lowercase__ : Optional[Any] = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: lowercase__ , lowercase__ , lowercase__ : Optional[Any] = parser.parse_args_into_dataclasses() # Setup logging logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''' , datefmt='''%m/%d/%Y %H:%M:%S''' , handlers=[logging.StreamHandler(sys.stdout )] , ) lowercase__ : Tuple = training_args.get_process_log_level() logger.setLevel(__lowerCamelCase ) datasets.utils.logging.set_verbosity(__lowerCamelCase ) transformers.utils.logging.set_verbosity(__lowerCamelCase ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Log on each process the small summary: logger.warning( f"""Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}""" + f"""distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}""" ) logger.info(f"""Training/evaluation parameters {training_args}""" ) # Detecting last checkpoint. lowercase__ : List[Any] = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: lowercase__ : List[Any] = get_last_checkpoint(training_args.output_dir ) if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0: raise ValueError( f"""Output directory ({training_args.output_dir}) already exists and is not empty. """ '''Use --overwrite_output_dir to overcome.''' ) elif last_checkpoint is not None and training_args.resume_from_checkpoint is None: logger.info( f"""Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change """ '''the `--output_dir` or add `--overwrite_output_dir` to train from scratch.''' ) # Set seed before initializing model. set_seed(training_args.seed ) # Get the datasets: you can either provide your own CSV/JSON training and evaluation files (see below) # or specify a GLUE benchmark task (the dataset will be downloaded automatically from the datasets Hub). # # For JSON files, this script will use the `question` column for the input question and `table` column for the corresponding table. # # If the CSVs/JSONs contain only one non-label column, the script does single sentence classification on this # single column. You can easily tweak this behavior (see below) # # In distributed training, the load_dataset function guarantee that only one local process can concurrently # download the dataset. if data_args.dataset_name is not None: # Downloading and loading a dataset from the hub. lowercase__ : Union[str, Any] = load_dataset( data_args.dataset_name , data_args.dataset_config_name , cache_dir=model_args.cache_dir ) else: # Loading a dataset from your local files. # CSV/JSON training and evaluation files are needed. lowercase__ : Any = {'''train''': data_args.train_file, '''validation''': data_args.validation_file} # Get the test dataset: you can provide your own CSV/JSON test file (see below) # when you use `do_predict` without specifying a GLUE benchmark task. if training_args.do_predict: if data_args.test_file is not None: lowercase__ : str = data_args.train_file.split('''.''' )[-1] lowercase__ : Tuple = data_args.test_file.split('''.''' )[-1] assert ( test_extension == train_extension ), "`test_file` should have the same extension (csv or json) as `train_file`." lowercase__ : Dict = data_args.test_file else: raise ValueError('''Need either a GLUE task or a test file for `do_predict`.''' ) for key in data_files.keys(): logger.info(f"""load a local file for {key}: {data_files[key]}""" ) if data_args.train_file.endswith('''.csv''' ): # Loading a dataset from local csv files lowercase__ : Union[str, Any] = load_dataset('''csv''' , data_files=__lowerCamelCase , cache_dir=model_args.cache_dir ) else: # Loading a dataset from local json files lowercase__ : Optional[Any] = load_dataset('''json''' , data_files=__lowerCamelCase , cache_dir=model_args.cache_dir ) # See more about loading any type of standard or custom dataset at # https://huggingface.co/docs/datasets/loading_datasets.html. # Labels lowercase__ : int = raw_datasets['''train'''].features['''label'''].names lowercase__ : List[Any] = len(__lowerCamelCase ) # Load pretrained model and tokenizer # # In distributed training, the .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. lowercase__ : int = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , num_labels=__lowerCamelCase , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) # load tapex tokenizer lowercase__ : List[Any] = TapexTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , use_fast=model_args.use_fast_tokenizer , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , add_prefix_space=__lowerCamelCase , ) lowercase__ : Any = BartForSequenceClassification.from_pretrained( model_args.model_name_or_path , from_tf=bool('''.ckpt''' in model_args.model_name_or_path ) , config=__lowerCamelCase , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) # Padding strategy if data_args.pad_to_max_length: lowercase__ : str = '''max_length''' else: # We will pad later, dynamically at batch creation, to the max sequence length in each batch lowercase__ : List[Any] = False # Some models have set the order of the labels to use, so let's make sure we do use it. lowercase__ : Any = {'''Refused''': 0, '''Entailed''': 1} lowercase__ : str = {0: '''Refused''', 1: '''Entailed'''} if data_args.max_seq_length > tokenizer.model_max_length: logger.warning( f"""The max_seq_length passed ({data_args.max_seq_length}) is larger than the maximum length for the""" f"""model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}.""" ) lowercase__ : str = min(data_args.max_seq_length , tokenizer.model_max_length ) def preprocess_tabfact_function(__lowerCamelCase ): # Tokenize the texts def _convert_table_text_to_pandas(__lowerCamelCase ): lowercase__ : Dict = [_table_row.split('''#''' ) for _table_row in _table_text.strip('''\n''' ).split('''\n''' )] lowercase__ : List[Any] = pd.DataFrame.from_records(_table_content[1:] , columns=_table_content[0] ) return _table_pd lowercase__ : Tuple = examples['''statement'''] lowercase__ : str = list(map(_convert_table_text_to_pandas , examples['''table_text'''] ) ) lowercase__ : Dict = tokenizer(__lowerCamelCase , __lowerCamelCase , padding=__lowerCamelCase , max_length=__lowerCamelCase , truncation=__lowerCamelCase ) lowercase__ : List[Any] = examples['''label'''] return result with training_args.main_process_first(desc='''dataset map pre-processing''' ): lowercase__ : List[Any] = raw_datasets.map( __lowerCamelCase , batched=__lowerCamelCase , load_from_cache_file=not data_args.overwrite_cache , desc='''Running tokenizer on dataset''' , ) if training_args.do_train: if "train" not in raw_datasets: raise ValueError('''--do_train requires a train dataset''' ) lowercase__ : str = raw_datasets['''train'''] if data_args.max_train_samples is not None: lowercase__ : Union[str, Any] = train_dataset.select(range(data_args.max_train_samples ) ) if training_args.do_eval: if "validation" not in raw_datasets and "validation_matched" not in raw_datasets: raise ValueError('''--do_eval requires a validation dataset''' ) lowercase__ : Any = raw_datasets['''validation'''] if data_args.max_eval_samples is not None: lowercase__ : Optional[int] = eval_dataset.select(range(data_args.max_eval_samples ) ) if training_args.do_predict or data_args.test_file is not None: if "test" not in raw_datasets and "test_matched" not in raw_datasets: raise ValueError('''--do_predict requires a test dataset''' ) lowercase__ : Optional[Any] = raw_datasets['''test'''] if data_args.max_predict_samples is not None: lowercase__ : str = predict_dataset.select(range(data_args.max_predict_samples ) ) # Log a few random samples from the training set: if training_args.do_train: for index in random.sample(range(len(__lowerCamelCase ) ) , 3 ): logger.info(f"""Sample {index} of the training set: {train_dataset[index]}.""" ) # You can define your custom compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with a # predictions and label_ids field) and has to return a dictionary string to float. def compute_metrics(__lowerCamelCase ): lowercase__ : Union[str, Any] = p.predictions[0] if isinstance(p.predictions , __lowerCamelCase ) else p.predictions lowercase__ : Dict = np.argmax(__lowerCamelCase , axis=1 ) return {"accuracy": (preds == p.label_ids).astype(np.floataa ).mean().item()} # Data collator will default to DataCollatorWithPadding, so we change it if we already did the padding. if data_args.pad_to_max_length: lowercase__ : List[str] = default_data_collator elif training_args.fpaa: lowercase__ : Any = DataCollatorWithPadding(__lowerCamelCase , pad_to_multiple_of=8 ) else: lowercase__ : List[Any] = None # Initialize our Trainer lowercase__ : Union[str, Any] = Trainer( model=__lowerCamelCase , args=__lowerCamelCase , train_dataset=train_dataset if training_args.do_train else None , eval_dataset=eval_dataset if training_args.do_eval else None , compute_metrics=__lowerCamelCase , tokenizer=__lowerCamelCase , data_collator=__lowerCamelCase , ) # Training if training_args.do_train: lowercase__ : Dict = None if training_args.resume_from_checkpoint is not None: lowercase__ : Dict = training_args.resume_from_checkpoint elif last_checkpoint is not None: lowercase__ : int = last_checkpoint lowercase__ : List[str] = trainer.train(resume_from_checkpoint=__lowerCamelCase ) lowercase__ : List[str] = train_result.metrics lowercase__ : List[str] = ( data_args.max_train_samples if data_args.max_train_samples is not None else len(__lowerCamelCase ) ) lowercase__ : Any = min(__lowerCamelCase , len(__lowerCamelCase ) ) trainer.save_model() # Saves the tokenizer too for easy upload trainer.log_metrics('''train''' , __lowerCamelCase ) trainer.save_metrics('''train''' , __lowerCamelCase ) trainer.save_state() # Evaluation if training_args.do_eval: logger.info('''*** Evaluate ***''' ) lowercase__ : Union[str, Any] = trainer.evaluate(eval_dataset=__lowerCamelCase ) lowercase__ : Union[str, Any] = data_args.max_eval_samples if data_args.max_eval_samples is not None else len(__lowerCamelCase ) lowercase__ : Tuple = min(__lowerCamelCase , len(__lowerCamelCase ) ) trainer.log_metrics('''eval''' , __lowerCamelCase ) trainer.save_metrics('''eval''' , __lowerCamelCase ) if training_args.do_predict: logger.info('''*** Predict ***''' ) # Removing the `label` columns because it contains -1 and Trainer won't like that. lowercase__ : Tuple = predict_dataset.remove_columns('''label''' ) lowercase__ : str = trainer.predict(__lowerCamelCase , metric_key_prefix='''predict''' ).predictions lowercase__ : Tuple = np.argmax(__lowerCamelCase , axis=1 ) lowercase__ : List[Any] = os.path.join(training_args.output_dir , '''predict_results_tabfact.txt''' ) if trainer.is_world_process_zero(): with open(__lowerCamelCase , '''w''' ) as writer: logger.info('''***** Predict Results *****''' ) writer.write('''index\tprediction\n''' ) for index, item in enumerate(__lowerCamelCase ): lowercase__ : Optional[Any] = label_list[item] writer.write(f"""{index}\t{item}\n""" ) lowercase__ : Dict = {'''finetuned_from''': model_args.model_name_or_path, '''tasks''': '''text-classification'''} if training_args.push_to_hub: trainer.push_to_hub(**__lowerCamelCase ) else: trainer.create_model_card(**__lowerCamelCase ) def __UpperCAmelCase ( __lowerCamelCase ) -> Optional[int]: # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
16
from typing import List, Optional, Union from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : Optional[Any] = ['''image_processor''', '''tokenizer'''] _UpperCAmelCase : Union[str, Any] = '''Pix2StructImageProcessor''' _UpperCAmelCase : Any = ('''T5Tokenizer''', '''T5TokenizerFast''') def __init__( self : List[str] ,SCREAMING_SNAKE_CASE__ : str ,SCREAMING_SNAKE_CASE__ : int): __lowerCamelCase : List[Any] = False super().__init__(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) def __call__( self : str ,SCREAMING_SNAKE_CASE__ : Any=None ,SCREAMING_SNAKE_CASE__ : Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None ,SCREAMING_SNAKE_CASE__ : bool = True ,SCREAMING_SNAKE_CASE__ : Union[bool, str, PaddingStrategy] = False ,SCREAMING_SNAKE_CASE__ : Union[bool, str, TruncationStrategy] = None ,SCREAMING_SNAKE_CASE__ : Optional[int] = None ,SCREAMING_SNAKE_CASE__ : Optional[int] = 2_0_4_8 ,SCREAMING_SNAKE_CASE__ : int = 0 ,SCREAMING_SNAKE_CASE__ : Optional[int] = None ,SCREAMING_SNAKE_CASE__ : Optional[bool] = None ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = True ,SCREAMING_SNAKE_CASE__ : Optional[Union[str, TensorType]] = None ,**SCREAMING_SNAKE_CASE__ : Dict ,): if images is None and text is None: raise ValueError('You have to specify either images or text.') # Get only text if images is None and not self.image_processor.is_vqa: __lowerCamelCase : Tuple = self.tokenizer __lowerCamelCase : Dict = self.tokenizer( text=SCREAMING_SNAKE_CASE__ ,add_special_tokens=SCREAMING_SNAKE_CASE__ ,padding=SCREAMING_SNAKE_CASE__ ,truncation=SCREAMING_SNAKE_CASE__ ,max_length=SCREAMING_SNAKE_CASE__ ,stride=SCREAMING_SNAKE_CASE__ ,pad_to_multiple_of=SCREAMING_SNAKE_CASE__ ,return_attention_mask=SCREAMING_SNAKE_CASE__ ,return_overflowing_tokens=SCREAMING_SNAKE_CASE__ ,return_special_tokens_mask=SCREAMING_SNAKE_CASE__ ,return_offsets_mapping=SCREAMING_SNAKE_CASE__ ,return_token_type_ids=SCREAMING_SNAKE_CASE__ ,return_length=SCREAMING_SNAKE_CASE__ ,verbose=SCREAMING_SNAKE_CASE__ ,return_tensors=SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__ ,) return text_encoding if not self.image_processor.is_vqa: # add pixel_values __lowerCamelCase : List[Any] = self.image_processor( SCREAMING_SNAKE_CASE__ ,return_tensors=SCREAMING_SNAKE_CASE__ ,max_patches=SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) else: # add pixel_values and bbox __lowerCamelCase : List[Any] = self.image_processor( SCREAMING_SNAKE_CASE__ ,return_tensors=SCREAMING_SNAKE_CASE__ ,max_patches=SCREAMING_SNAKE_CASE__ ,header_text=SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) if text is not None and not self.image_processor.is_vqa: __lowerCamelCase : List[Any] = self.tokenizer( text=SCREAMING_SNAKE_CASE__ ,add_special_tokens=SCREAMING_SNAKE_CASE__ ,padding=SCREAMING_SNAKE_CASE__ ,truncation=SCREAMING_SNAKE_CASE__ ,max_length=SCREAMING_SNAKE_CASE__ ,stride=SCREAMING_SNAKE_CASE__ ,pad_to_multiple_of=SCREAMING_SNAKE_CASE__ ,return_attention_mask=SCREAMING_SNAKE_CASE__ ,return_overflowing_tokens=SCREAMING_SNAKE_CASE__ ,return_special_tokens_mask=SCREAMING_SNAKE_CASE__ ,return_offsets_mapping=SCREAMING_SNAKE_CASE__ ,return_token_type_ids=SCREAMING_SNAKE_CASE__ ,return_length=SCREAMING_SNAKE_CASE__ ,verbose=SCREAMING_SNAKE_CASE__ ,return_tensors=SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__ ,) if "attention_mask" in text_encoding: __lowerCamelCase : List[Any] = text_encoding.pop('attention_mask') if "input_ids" in text_encoding: __lowerCamelCase : Dict = text_encoding.pop('input_ids') else: __lowerCamelCase : Optional[int] = None if text_encoding is not None: encoding_image_processor.update(SCREAMING_SNAKE_CASE__) return encoding_image_processor def lowerCAmelCase ( self : Dict ,*SCREAMING_SNAKE_CASE__ : str ,**SCREAMING_SNAKE_CASE__ : int): return self.tokenizer.batch_decode(*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : List[str] ,*SCREAMING_SNAKE_CASE__ : int ,**SCREAMING_SNAKE_CASE__ : Dict): return self.tokenizer.decode(*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) @property def lowerCAmelCase ( self : int): __lowerCamelCase : Dict = self.tokenizer.model_input_names __lowerCamelCase : int = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
73
0
"""simple docstring""" import json import os import tempfile import transformers import datasets from utils import generate_example_dataset, get_duration _a = 50_00_00 _a , _a = os.path.split(__file__) _a = os.path.join(RESULTS_BASEPATH, 'results', RESULTS_FILENAME.replace('.py', '.json')) @get_duration def _A ( UpperCamelCase_ : datasets.Dataset, **UpperCamelCase_ : Tuple) -> Optional[Any]: '''simple docstring''' __lowercase = dataset.map(**UpperCamelCase_) @get_duration def _A ( UpperCamelCase_ : datasets.Dataset, **UpperCamelCase_ : str) -> Tuple: '''simple docstring''' __lowercase = dataset.filter(**UpperCamelCase_) def _A ( ) -> Optional[int]: '''simple docstring''' __lowercase = {"num examples": SPEED_TEST_N_EXAMPLES} with tempfile.TemporaryDirectory() as tmp_dir: __lowercase = datasets.Features({"text": datasets.Value("string"), "numbers": datasets.Value("float32")}) __lowercase = generate_example_dataset( os.path.join(UpperCamelCase_, "dataset.arrow"), UpperCamelCase_, num_examples=UpperCamelCase_) __lowercase = transformers.AutoTokenizer.from_pretrained("bert-base-cased", use_fast=UpperCamelCase_) def tokenize(UpperCamelCase_ : int): return tokenizer(examples["text"]) __lowercase = map(UpperCamelCase_) __lowercase = map(UpperCamelCase_, batched=UpperCamelCase_) __lowercase = map(UpperCamelCase_, function=lambda UpperCamelCase_: None, batched=UpperCamelCase_) with dataset.formatted_as(type="numpy"): __lowercase = map(UpperCamelCase_, function=lambda UpperCamelCase_: None, batched=UpperCamelCase_) with dataset.formatted_as(type="pandas"): __lowercase = map(UpperCamelCase_, function=lambda UpperCamelCase_: None, batched=UpperCamelCase_) with dataset.formatted_as(type="torch", columns="numbers"): __lowercase = map(UpperCamelCase_, function=lambda UpperCamelCase_: None, batched=UpperCamelCase_) with dataset.formatted_as(type="tensorflow", columns="numbers"): __lowercase = map(UpperCamelCase_, function=lambda UpperCamelCase_: None, batched=UpperCamelCase_) __lowercase = map(UpperCamelCase_, function=UpperCamelCase_, batched=UpperCamelCase_) __lowercase = filter(UpperCamelCase_) # Activate later when tokenizer support batched inputs # with dataset.formatted_as(type='numpy'): # times[func.__name__ + " fast-tokenizer batched numpy"] = func(dataset, function=tokenize, batched=True) with open(UpperCamelCase_, "wb") as f: f.write(json.dumps(UpperCamelCase_).encode("utf-8")) if __name__ == "__main__": # useful to run the profiler benchmark_map_filter()
17
from bisect import bisect from itertools import accumulate def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> Union[str, Any]: __lowerCamelCase : Optional[Any] = sorted(zip(lowerCamelCase__ , lowerCamelCase__ ) , key=lambda lowerCamelCase__ : x[0] / x[1] , reverse=lowerCamelCase__ ) __lowerCamelCase , __lowerCamelCase : Any = [i[0] for i in r], [i[1] for i in r] __lowerCamelCase : List[str] = list(accumulate(lowerCamelCase__ ) ) __lowerCamelCase : Union[str, Any] = bisect(lowerCamelCase__ , lowerCamelCase__ ) return ( 0 if k == 0 else sum(vl[:k] ) + (w - acc[k - 1]) * (vl[k]) / (wt[k]) if k != n else sum(vl[:k] ) ) if __name__ == "__main__": import doctest doctest.testmod()
73
0
import argparse import json from typing import List from ltp import LTP from transformers import BertTokenizer def _snake_case ( lowerCAmelCase : Dict ): """simple docstring""" if ( (cp >= 0X4_E_0_0 and cp <= 0X9_F_F_F) or (cp >= 0X3_4_0_0 and cp <= 0X4_D_B_F) # or (cp >= 0X2_0_0_0_0 and cp <= 0X2_A_6_D_F) # or (cp >= 0X2_A_7_0_0 and cp <= 0X2_B_7_3_F) # or (cp >= 0X2_B_7_4_0 and cp <= 0X2_B_8_1_F) # or (cp >= 0X2_B_8_2_0 and cp <= 0X2_C_E_A_F) # or (cp >= 0XF_9_0_0 and cp <= 0XF_A_F_F) or (cp >= 0X2_F_8_0_0 and cp <= 0X2_F_A_1_F) # ): # return True return False def _snake_case ( lowerCAmelCase : str ): """simple docstring""" for char in word: SCREAMING_SNAKE_CASE_ : Any = ord(lowerCAmelCase ) if not _is_chinese_char(lowerCAmelCase ): return 0 return 1 def _snake_case ( lowerCAmelCase : List[str] ): """simple docstring""" SCREAMING_SNAKE_CASE_ : str = set() for token in tokens: SCREAMING_SNAKE_CASE_ : int = len(lowerCAmelCase ) > 1 and is_chinese(lowerCAmelCase ) if chinese_word: word_set.add(lowerCAmelCase ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = list(lowerCAmelCase ) return word_list def _snake_case ( lowerCAmelCase : List[str] , lowerCAmelCase : set() ): """simple docstring""" if not chinese_word_set: return bert_tokens SCREAMING_SNAKE_CASE_ : str = max([len(lowerCAmelCase ) for w in chinese_word_set] ) SCREAMING_SNAKE_CASE_ : int = bert_tokens SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Any = 0, len(lowerCAmelCase ) while start < end: SCREAMING_SNAKE_CASE_ : Optional[int] = True if is_chinese(bert_word[start] ): SCREAMING_SNAKE_CASE_ : List[str] = min(end - start , lowerCAmelCase ) for i in range(lowerCAmelCase , 1 , -1 ): SCREAMING_SNAKE_CASE_ : Tuple = "".join(bert_word[start : start + i] ) if whole_word in chinese_word_set: for j in range(start + 1 , start + i ): SCREAMING_SNAKE_CASE_ : Optional[int] = "##" + bert_word[j] SCREAMING_SNAKE_CASE_ : int = start + i SCREAMING_SNAKE_CASE_ : Optional[Any] = False break if single_word: start += 1 return bert_word def _snake_case ( lowerCAmelCase : List[str] , lowerCAmelCase : LTP , lowerCAmelCase : BertTokenizer ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = [] for i in range(0 , len(lowerCAmelCase ) , 1_0_0 ): SCREAMING_SNAKE_CASE_ : Optional[int] = ltp_tokenizer.seg(lines[i : i + 1_0_0] )[0] SCREAMING_SNAKE_CASE_ : List[Any] = [get_chinese_word(lowerCAmelCase ) for r in res] ltp_res.extend(lowerCAmelCase ) assert len(lowerCAmelCase ) == len(lowerCAmelCase ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = [] for i in range(0 , len(lowerCAmelCase ) , 1_0_0 ): SCREAMING_SNAKE_CASE_ : str = bert_tokenizer(lines[i : i + 1_0_0] , add_special_tokens=lowerCAmelCase , truncation=lowerCAmelCase , max_length=5_1_2 ) bert_res.extend(res["input_ids"] ) assert len(lowerCAmelCase ) == len(lowerCAmelCase ) SCREAMING_SNAKE_CASE_ : int = [] for input_ids, chinese_word in zip(lowerCAmelCase , lowerCAmelCase ): SCREAMING_SNAKE_CASE_ : str = [] for id in input_ids: SCREAMING_SNAKE_CASE_ : Tuple = bert_tokenizer._convert_id_to_token(lowerCAmelCase ) input_tokens.append(lowerCAmelCase ) SCREAMING_SNAKE_CASE_ : Any = add_sub_symbol(lowerCAmelCase , lowerCAmelCase ) SCREAMING_SNAKE_CASE_ : Tuple = [] # We only save pos of chinese subwords start with ##, which mean is part of a whole word. for i, token in enumerate(lowerCAmelCase ): if token[:2] == "##": SCREAMING_SNAKE_CASE_ : List[Any] = token[2:] # save chinese tokens' pos if len(lowerCAmelCase ) == 1 and _is_chinese_char(ord(lowerCAmelCase ) ): ref_id.append(lowerCAmelCase ) ref_ids.append(lowerCAmelCase ) assert len(lowerCAmelCase ) == len(lowerCAmelCase ) return ref_ids def _snake_case ( lowerCAmelCase : Optional[int] ): """simple docstring""" with open(args.file_name , "r" , encoding="utf-8" ) as f: SCREAMING_SNAKE_CASE_ : List[Any] = f.readlines() SCREAMING_SNAKE_CASE_ : int = [line.strip() for line in data if len(lowerCAmelCase ) > 0 and not line.isspace()] # avoid delimiter like '\u2029' SCREAMING_SNAKE_CASE_ : Union[str, Any] = LTP(args.ltp ) # faster in GPU device SCREAMING_SNAKE_CASE_ : Tuple = BertTokenizer.from_pretrained(args.bert ) SCREAMING_SNAKE_CASE_ : List[str] = prepare_ref(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) with open(args.save_path , "w" , encoding="utf-8" ) as f: SCREAMING_SNAKE_CASE_ : Optional[int] = [json.dumps(lowerCAmelCase ) + "\n" for ref in ref_ids] f.writelines(lowerCAmelCase ) if __name__ == "__main__": __lowerCamelCase : Any = argparse.ArgumentParser(description='''prepare_chinese_ref''') parser.add_argument( '''--file_name''', type=str, default='''./resources/chinese-demo.txt''', help='''file need process, same as training data in lm''', ) parser.add_argument( '''--ltp''', type=str, default='''./resources/ltp''', help='''resources for LTP tokenizer, usually a path''' ) parser.add_argument('''--bert''', type=str, default='''./resources/robert''', help='''resources for Bert tokenizer''') parser.add_argument('''--save_path''', type=str, default='''./resources/ref.txt''', help='''path to save res''') __lowerCamelCase : int = parser.parse_args() main(args)
18
from __future__ import annotations import math def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> list: if len(lowerCamelCase__ ) != 2 or len(a[0] ) != 2 or len(lowerCamelCase__ ) != 2 or len(b[0] ) != 2: raise Exception('Matrices are not 2x2' ) __lowerCamelCase : Optional[int] = [ [a[0][0] * b[0][0] + a[0][1] * b[1][0], a[0][0] * b[0][1] + a[0][1] * b[1][1]], [a[1][0] * b[0][0] + a[1][1] * b[1][0], a[1][0] * b[0][1] + a[1][1] * b[1][1]], ] return new_matrix def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> Optional[int]: return [ [matrix_a[row][col] + matrix_b[row][col] for col in range(len(matrix_a[row] ) )] for row in range(len(lowerCamelCase__ ) ) ] def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> List[str]: return [ [matrix_a[row][col] - matrix_b[row][col] for col in range(len(matrix_a[row] ) )] for row in range(len(lowerCamelCase__ ) ) ] def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> tuple[list, list, list, list]: if len(lowerCamelCase__ ) % 2 != 0 or len(a[0] ) % 2 != 0: raise Exception('Odd matrices are not supported!' ) __lowerCamelCase : Tuple = len(lowerCamelCase__ ) __lowerCamelCase : List[Any] = matrix_length // 2 __lowerCamelCase : Dict = [[a[i][j] for j in range(lowerCamelCase__ , lowerCamelCase__ )] for i in range(lowerCamelCase__ )] __lowerCamelCase : str = [ [a[i][j] for j in range(lowerCamelCase__ , lowerCamelCase__ )] for i in range(lowerCamelCase__ , lowerCamelCase__ ) ] __lowerCamelCase : Dict = [[a[i][j] for j in range(lowerCamelCase__ )] for i in range(lowerCamelCase__ )] __lowerCamelCase : Optional[Any] = [[a[i][j] for j in range(lowerCamelCase__ )] for i in range(lowerCamelCase__ , lowerCamelCase__ )] return top_left, top_right, bot_left, bot_right def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> tuple[int, int]: return len(lowerCamelCase__ ), len(matrix[0] ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> None: print('\n'.join(str(lowerCamelCase__ ) for line in matrix ) ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> list: if matrix_dimensions(lowerCamelCase__ ) == (2, 2): return default_matrix_multiplication(lowerCamelCase__ , lowerCamelCase__ ) __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : Optional[Any] = split_matrix(lowerCamelCase__ ) __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : Optional[Any] = split_matrix(lowerCamelCase__ ) __lowerCamelCase : str = actual_strassen(lowerCamelCase__ , matrix_subtraction(lowerCamelCase__ , lowerCamelCase__ ) ) __lowerCamelCase : List[str] = actual_strassen(matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) , lowerCamelCase__ ) __lowerCamelCase : List[Any] = actual_strassen(matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) , lowerCamelCase__ ) __lowerCamelCase : Tuple = actual_strassen(lowerCamelCase__ , matrix_subtraction(lowerCamelCase__ , lowerCamelCase__ ) ) __lowerCamelCase : Optional[int] = actual_strassen(matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) , matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) ) __lowerCamelCase : Dict = actual_strassen(matrix_subtraction(lowerCamelCase__ , lowerCamelCase__ ) , matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) ) __lowerCamelCase : Tuple = actual_strassen(matrix_subtraction(lowerCamelCase__ , lowerCamelCase__ ) , matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) ) __lowerCamelCase : Dict = matrix_addition(matrix_subtraction(matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) , lowerCamelCase__ ) , lowerCamelCase__ ) __lowerCamelCase : Tuple = matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) __lowerCamelCase : List[str] = matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) __lowerCamelCase : Any = matrix_subtraction(matrix_subtraction(matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) , lowerCamelCase__ ) , lowerCamelCase__ ) # construct the new matrix from our 4 quadrants __lowerCamelCase : List[Any] = [] for i in range(len(lowerCamelCase__ ) ): new_matrix.append(top_left[i] + top_right[i] ) for i in range(len(lowerCamelCase__ ) ): new_matrix.append(bot_left[i] + bot_right[i] ) return new_matrix def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> list: if matrix_dimensions(lowerCamelCase__ )[1] != matrix_dimensions(lowerCamelCase__ )[0]: __lowerCamelCase : Any = ( 'Unable to multiply these matrices, please check the dimensions.\n' F"Matrix A: {matrixa}\n" F"Matrix B: {matrixa}" ) raise Exception(lowerCamelCase__ ) __lowerCamelCase : str = matrix_dimensions(lowerCamelCase__ ) __lowerCamelCase : List[str] = matrix_dimensions(lowerCamelCase__ ) if dimensiona[0] == dimensiona[1] and dimensiona[0] == dimensiona[1]: return [matrixa, matrixa] __lowerCamelCase : str = max(*lowerCamelCase__ , *lowerCamelCase__ ) __lowerCamelCase : List[str] = int(math.pow(2 , math.ceil(math.loga(lowerCamelCase__ ) ) ) ) __lowerCamelCase : Any = matrixa __lowerCamelCase : int = matrixa # Adding zeros to the matrices so that the arrays dimensions are the same and also # power of 2 for i in range(0 , lowerCamelCase__ ): if i < dimensiona[0]: for _ in range(dimensiona[1] , lowerCamelCase__ ): new_matrixa[i].append(0 ) else: new_matrixa.append([0] * maxim ) if i < dimensiona[0]: for _ in range(dimensiona[1] , lowerCamelCase__ ): new_matrixa[i].append(0 ) else: new_matrixa.append([0] * maxim ) __lowerCamelCase : List[str] = actual_strassen(lowerCamelCase__ , lowerCamelCase__ ) # Removing the additional zeros for i in range(0 , lowerCamelCase__ ): if i < dimensiona[0]: for _ in range(dimensiona[1] , lowerCamelCase__ ): final_matrix[i].pop() else: final_matrix.pop() return final_matrix if __name__ == "__main__": a =[ [2, 3, 4, 5], [6, 4, 3, 1], [2, 3, 6, 7], [3, 1, 2, 4], [2, 3, 4, 5], [6, 4, 3, 1], [2, 3, 6, 7], [3, 1, 2, 4], [2, 3, 4, 5], [6, 2, 3, 1], ] a =[[0, 2, 1, 1], [16, 2, 3, 3], [2, 2, 7, 7], [13, 11, 22, 4]] print(strassen(matrixa, matrixa))
73
0
from typing import Any class _SCREAMING_SNAKE_CASE : def __init__( self , lowercase ) -> Optional[Any]: lowerCamelCase_ = data lowerCamelCase_ = None class _SCREAMING_SNAKE_CASE : def __init__( self ) -> List[Any]: lowerCamelCase_ = None def SCREAMING_SNAKE_CASE_( self ) -> Tuple: lowerCamelCase_ = self.head while temp is not None: print(temp.data , end=" " ) lowerCamelCase_ = temp.next print() def SCREAMING_SNAKE_CASE_( self , lowercase ) -> Dict: lowerCamelCase_ = Node(lowercase ) lowerCamelCase_ = self.head lowerCamelCase_ = new_node def SCREAMING_SNAKE_CASE_( self , lowercase , lowercase ) -> Dict: if node_data_a == node_data_a: return else: lowerCamelCase_ = self.head while node_a is not None and node_a.data != node_data_a: lowerCamelCase_ = node_a.next lowerCamelCase_ = self.head while node_a is not None and node_a.data != node_data_a: lowerCamelCase_ = node_a.next if node_a is None or node_a is None: return lowerCamelCase_ , lowerCamelCase_ = node_a.data, node_a.data if __name__ == "__main__": __A =LinkedList() for i in range(5, 0, -1): ll.push(i) ll.print_list() ll.swap_nodes(1, 4) print('''After swapping''') ll.print_list()
19
from math import isclose, sqrt def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> tuple[float, float, float]: __lowerCamelCase : Tuple = point_y / 4 / point_x __lowerCamelCase : Tuple = 2 * normal_gradient / (1 + normal_gradient * normal_gradient) __lowerCamelCase : List[Any] = (1 - normal_gradient * normal_gradient) / ( 1 + normal_gradient * normal_gradient ) __lowerCamelCase : int = (sa - ca * incoming_gradient) / (ca + sa * incoming_gradient) # to find the next point, solve the simultaeneous equations: # y^2 + 4x^2 = 100 # y - b = m * (x - a) # ==> A x^2 + B x + C = 0 __lowerCamelCase : Any = outgoing_gradient**2 + 4 __lowerCamelCase : Optional[int] = 2 * outgoing_gradient * (point_y - outgoing_gradient * point_x) __lowerCamelCase : str = (point_y - outgoing_gradient * point_x) ** 2 - 1_0_0 __lowerCamelCase : str = ( -linear_term - sqrt(linear_term**2 - 4 * quadratic_term * constant_term ) ) / (2 * quadratic_term) __lowerCamelCase : Optional[Any] = ( -linear_term + sqrt(linear_term**2 - 4 * quadratic_term * constant_term ) ) / (2 * quadratic_term) # two solutions, one of which is our input point __lowerCamelCase : Optional[Any] = x_minus if isclose(lowerCamelCase__ , lowerCamelCase__ ) else x_plus __lowerCamelCase : Tuple = point_y + outgoing_gradient * (next_x - point_x) return next_x, next_y, outgoing_gradient def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ = 1.4 , lowerCamelCase__ = -9.6 ) -> int: __lowerCamelCase : int = 0 __lowerCamelCase : float = first_x_coord __lowerCamelCase : float = first_y_coord __lowerCamelCase : float = (10.1 - point_y) / (0.0 - point_x) while not (-0.01 <= point_x <= 0.01 and point_y > 0): __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : Any = next_point(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) num_reflections += 1 return num_reflections if __name__ == "__main__": print(F"""{solution() = }""")
73
0
import json import os import shutil import tempfile import unittest from multiprocessing import get_context from pathlib import Path import datasets import numpy as np from datasets import load_dataset from parameterized import parameterized from transformers import AutoProcessor from transformers.models.wavaveca import WavaVecaCTCTokenizer, WavaVecaFeatureExtractor from transformers.models.wavaveca.tokenization_wavaveca import VOCAB_FILES_NAMES from transformers.testing_utils import require_pyctcdecode, require_torch, require_torchaudio, slow from transformers.utils import FEATURE_EXTRACTOR_NAME, is_pyctcdecode_available, is_torch_available from ..wavaveca.test_feature_extraction_wavaveca import floats_list if is_pyctcdecode_available(): from huggingface_hub import snapshot_download from pyctcdecode import BeamSearchDecoderCTC from transformers.models.wavaveca_with_lm import WavaVecaProcessorWithLM from transformers.models.wavaveca_with_lm.processing_wavaveca_with_lm import WavaVecaDecoderWithLMOutput if is_torch_available(): from transformers import WavaVecaForCTC @require_pyctcdecode class __snake_case ( unittest.TestCase ): def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' lowercase : int = """| <pad> <unk> <s> </s> a b c d e f g h i j k""".split() lowercase : Tuple = dict(zip(snake_case ,range(len(snake_case ) ) ) ) lowercase : int = { """unk_token""": """<unk>""", """bos_token""": """<s>""", """eos_token""": """</s>""", } lowercase : str = { """feature_size""": 1, """padding_value""": 0.0, """sampling_rate""": 16000, """return_attention_mask""": False, """do_normalize""": True, } lowercase : Optional[Any] = tempfile.mkdtemp() lowercase : Optional[Any] = os.path.join(self.tmpdirname ,VOCAB_FILES_NAMES["""vocab_file"""] ) lowercase : Optional[Any] = os.path.join(self.tmpdirname ,snake_case ) with open(self.vocab_file ,"""w""" ,encoding="""utf-8""" ) as fp: fp.write(json.dumps(snake_case ) + """\n""" ) with open(self.feature_extraction_file ,"""w""" ,encoding="""utf-8""" ) as fp: fp.write(json.dumps(snake_case ) + """\n""" ) # load decoder from hub lowercase : Tuple = """hf-internal-testing/ngram-beam-search-decoder""" def _SCREAMING_SNAKE_CASE ( self ,**snake_case ): '''simple docstring''' lowercase : List[str] = self.add_kwargs_tokens_map.copy() kwargs.update(snake_case ) return WavaVecaCTCTokenizer.from_pretrained(self.tmpdirname ,**snake_case ) def _SCREAMING_SNAKE_CASE ( self ,**snake_case ): '''simple docstring''' return WavaVecaFeatureExtractor.from_pretrained(self.tmpdirname ,**snake_case ) def _SCREAMING_SNAKE_CASE ( self ,**snake_case ): '''simple docstring''' return BeamSearchDecoderCTC.load_from_hf_hub(self.decoder_name ,**snake_case ) def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' shutil.rmtree(self.tmpdirname ) def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' lowercase : Dict = self.get_tokenizer() lowercase : Tuple = self.get_feature_extractor() lowercase : Optional[Any] = self.get_decoder() lowercase : Any = WavaVecaProcessorWithLM(tokenizer=snake_case ,feature_extractor=snake_case ,decoder=snake_case ) processor.save_pretrained(self.tmpdirname ) lowercase : List[str] = WavaVecaProcessorWithLM.from_pretrained(self.tmpdirname ) # tokenizer self.assertEqual(processor.tokenizer.get_vocab() ,tokenizer.get_vocab() ) self.assertIsInstance(processor.tokenizer ,snake_case ) # feature extractor self.assertEqual(processor.feature_extractor.to_json_string() ,feature_extractor.to_json_string() ) self.assertIsInstance(processor.feature_extractor ,snake_case ) # decoder self.assertEqual(processor.decoder._alphabet.labels ,decoder._alphabet.labels ) self.assertEqual( processor.decoder.model_container[decoder._model_key]._unigram_set ,decoder.model_container[decoder._model_key]._unigram_set ,) self.assertIsInstance(processor.decoder ,snake_case ) def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' lowercase : Optional[int] = WavaVecaProcessorWithLM( tokenizer=self.get_tokenizer() ,feature_extractor=self.get_feature_extractor() ,decoder=self.get_decoder() ) processor.save_pretrained(self.tmpdirname ) # make sure that error is thrown when decoder alphabet doesn't match lowercase : Any = WavaVecaProcessorWithLM.from_pretrained( self.tmpdirname ,alpha=5.0 ,beta=3.0 ,score_boundary=-7.0 ,unk_score_offset=3 ) # decoder self.assertEqual(processor.language_model.alpha ,5.0 ) self.assertEqual(processor.language_model.beta ,3.0 ) self.assertEqual(processor.language_model.score_boundary ,-7.0 ) self.assertEqual(processor.language_model.unk_score_offset ,3 ) def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' lowercase : Optional[Any] = self.get_tokenizer() # add token to trigger raise tokenizer.add_tokens(["""xx"""] ) with self.assertRaisesRegex(snake_case ,"""include""" ): WavaVecaProcessorWithLM( tokenizer=snake_case ,feature_extractor=self.get_feature_extractor() ,decoder=self.get_decoder() ) def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' lowercase : int = self.get_feature_extractor() lowercase : Union[str, Any] = self.get_tokenizer() lowercase : Optional[int] = self.get_decoder() lowercase : str = WavaVecaProcessorWithLM(tokenizer=snake_case ,feature_extractor=snake_case ,decoder=snake_case ) lowercase : Union[str, Any] = floats_list((3, 1000) ) lowercase : List[str] = feature_extractor(snake_case ,return_tensors="""np""" ) lowercase : Optional[int] = processor(snake_case ,return_tensors="""np""" ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() ,input_processor[key].sum() ,delta=1e-2 ) def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' lowercase : int = self.get_feature_extractor() lowercase : List[str] = self.get_tokenizer() lowercase : str = self.get_decoder() lowercase : Union[str, Any] = WavaVecaProcessorWithLM(tokenizer=snake_case ,feature_extractor=snake_case ,decoder=snake_case ) lowercase : str = """This is a test string""" lowercase : Tuple = processor(text=snake_case ) lowercase : Union[str, Any] = tokenizer(snake_case ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] ,encoded_processor[key] ) def _SCREAMING_SNAKE_CASE ( self ,snake_case=(2, 10, 16) ,snake_case=77 ): '''simple docstring''' np.random.seed(snake_case ) return np.random.rand(*snake_case ) def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' lowercase : int = self.get_feature_extractor() lowercase : Any = self.get_tokenizer() lowercase : Union[str, Any] = self.get_decoder() lowercase : Optional[int] = WavaVecaProcessorWithLM(tokenizer=snake_case ,feature_extractor=snake_case ,decoder=snake_case ) lowercase : int = self._get_dummy_logits(shape=(10, 16) ,seed=13 ) lowercase : Optional[int] = processor.decode(snake_case ) lowercase : Tuple = decoder.decode_beams(snake_case )[0] self.assertEqual(decoded_decoder[0] ,decoded_processor.text ) self.assertEqual("""</s> <s> </s>""" ,decoded_processor.text ) self.assertEqual(decoded_decoder[-2] ,decoded_processor.logit_score ) self.assertEqual(decoded_decoder[-1] ,decoded_processor.lm_score ) @parameterized.expand([[None], ["""fork"""], ["""spawn"""]] ) def _SCREAMING_SNAKE_CASE ( self ,snake_case ): '''simple docstring''' lowercase : str = self.get_feature_extractor() lowercase : Tuple = self.get_tokenizer() lowercase : Dict = self.get_decoder() lowercase : Tuple = WavaVecaProcessorWithLM(tokenizer=snake_case ,feature_extractor=snake_case ,decoder=snake_case ) lowercase : Optional[int] = self._get_dummy_logits() # note: pool should be instantiated *after* Wav2Vec2ProcessorWithLM. # otherwise, the LM won't be available to the pool's sub-processes. # manual logic used to allow parameterized test for both pool=None and pool=Pool(...) if pool_context is None: lowercase : Any = processor.batch_decode(snake_case ) else: with get_context(snake_case ).Pool() as pool: lowercase : Optional[Any] = processor.batch_decode(snake_case ,snake_case ) lowercase : Dict = list(snake_case ) with get_context("""fork""" ).Pool() as p: lowercase : List[str] = decoder.decode_beams_batch(snake_case ,snake_case ) lowercase , lowercase , lowercase : List[str] = [], [], [] for beams in decoded_beams: texts_decoder.append(beams[0][0] ) logit_scores_decoder.append(beams[0][-2] ) lm_scores_decoder.append(beams[0][-1] ) self.assertListEqual(snake_case ,decoded_processor.text ) self.assertListEqual(["""<s> <s> </s>""", """<s> <s> <s>"""] ,decoded_processor.text ) self.assertListEqual(snake_case ,decoded_processor.logit_score ) self.assertListEqual(snake_case ,decoded_processor.lm_score ) def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' lowercase : List[str] = self.get_feature_extractor() lowercase : int = self.get_tokenizer() lowercase : Dict = self.get_decoder() lowercase : int = WavaVecaProcessorWithLM(tokenizer=snake_case ,feature_extractor=snake_case ,decoder=snake_case ) lowercase : int = self._get_dummy_logits() lowercase : Any = 15 lowercase : Union[str, Any] = -20.0 lowercase : Any = -4.0 lowercase : Dict = processor.batch_decode( snake_case ,beam_width=snake_case ,beam_prune_logp=snake_case ,token_min_logp=snake_case ,) lowercase : Optional[int] = decoded_processor_out.text lowercase : Tuple = list(snake_case ) with get_context("""fork""" ).Pool() as pool: lowercase : int = decoder.decode_beams_batch( snake_case ,snake_case ,beam_width=snake_case ,beam_prune_logp=snake_case ,token_min_logp=snake_case ,) lowercase : Any = [d[0][0] for d in decoded_decoder_out] lowercase : Tuple = [d[0][2] for d in decoded_decoder_out] lowercase : List[Any] = [d[0][3] for d in decoded_decoder_out] self.assertListEqual(snake_case ,snake_case ) self.assertListEqual(["""</s> <s> <s>""", """<s> <s> <s>"""] ,snake_case ) self.assertTrue(np.array_equal(snake_case ,decoded_processor_out.logit_score ) ) self.assertTrue(np.allclose([-20.054, -18.447] ,snake_case ,atol=1e-3 ) ) self.assertTrue(np.array_equal(snake_case ,decoded_processor_out.lm_score ) ) self.assertTrue(np.allclose([-15.554, -13.9_474] ,snake_case ,atol=1e-3 ) ) def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' lowercase : Any = self.get_feature_extractor() lowercase : Union[str, Any] = self.get_tokenizer() lowercase : Union[str, Any] = self.get_decoder() lowercase : Optional[int] = WavaVecaProcessorWithLM(tokenizer=snake_case ,feature_extractor=snake_case ,decoder=snake_case ) lowercase : Optional[int] = self._get_dummy_logits() lowercase : List[str] = 2.0 lowercase : Any = 5.0 lowercase : Tuple = -20.0 lowercase : List[Any] = True lowercase : Union[str, Any] = processor.batch_decode( snake_case ,alpha=snake_case ,beta=snake_case ,unk_score_offset=snake_case ,lm_score_boundary=snake_case ,) lowercase : Union[str, Any] = decoded_processor_out.text lowercase : List[Any] = list(snake_case ) decoder.reset_params( alpha=snake_case ,beta=snake_case ,unk_score_offset=snake_case ,lm_score_boundary=snake_case ,) with get_context("""fork""" ).Pool() as pool: lowercase : str = decoder.decode_beams_batch( snake_case ,snake_case ,) lowercase : Any = [d[0][0] for d in decoded_decoder_out] self.assertListEqual(snake_case ,snake_case ) self.assertListEqual(["""<s> </s> <s> </s> </s>""", """</s> </s> <s> </s> </s>"""] ,snake_case ) lowercase : str = processor.decoder.model_container[processor.decoder._model_key] self.assertEqual(lm_model.alpha ,2.0 ) self.assertEqual(lm_model.beta ,5.0 ) self.assertEqual(lm_model.unk_score_offset ,-20.0 ) self.assertEqual(lm_model.score_boundary ,snake_case ) def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' lowercase : List[str] = WavaVecaProcessorWithLM.from_pretrained("""hf-internal-testing/processor_with_lm""" ) lowercase : Optional[int] = processor.decoder.model_container[processor.decoder._model_key] lowercase : Dict = Path(language_model._kenlm_model.path.decode("""utf-8""" ) ).parent.parent.absolute() lowercase : List[str] = os.listdir(snake_case ) lowercase : Dict = ["""alphabet.json""", """language_model"""] downloaded_decoder_files.sort() expected_decoder_files.sort() # test that only decoder relevant files from # https://huggingface.co/hf-internal-testing/processor_with_lm/tree/main # are downloaded and none of the rest (e.g. README.md, ...) self.assertListEqual(snake_case ,snake_case ) def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' lowercase : Tuple = snapshot_download("""hf-internal-testing/processor_with_lm""" ) lowercase : Optional[int] = WavaVecaProcessorWithLM.from_pretrained(snake_case ) lowercase : List[str] = processor.decoder.model_container[processor.decoder._model_key] lowercase : Dict = Path(language_model._kenlm_model.path.decode("""utf-8""" ) ).parent.parent.absolute() lowercase : List[str] = os.listdir(snake_case ) lowercase : Dict = os.listdir(snake_case ) local_decoder_files.sort() expected_decoder_files.sort() # test that both decoder form hub and local files in cache are the same self.assertListEqual(snake_case ,snake_case ) def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' lowercase : str = WavaVecaProcessorWithLM.from_pretrained("""hf-internal-testing/processor_with_lm""" ) lowercase : int = AutoProcessor.from_pretrained("""hf-internal-testing/processor_with_lm""" ) lowercase : Union[str, Any] = floats_list((3, 1000) ) lowercase : Optional[int] = processor_wavaveca(snake_case ,return_tensors="""np""" ) lowercase : Dict = processor_auto(snake_case ,return_tensors="""np""" ) for key in input_wavaveca.keys(): self.assertAlmostEqual(input_wavaveca[key].sum() ,input_auto[key].sum() ,delta=1e-2 ) lowercase : str = self._get_dummy_logits() lowercase : Optional[int] = processor_wavaveca.batch_decode(snake_case ) lowercase : Any = processor_auto.batch_decode(snake_case ) self.assertListEqual(decoded_wavaveca.text ,decoded_auto.text ) def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' lowercase : Any = self.get_feature_extractor() lowercase : str = self.get_tokenizer() lowercase : int = self.get_decoder() lowercase : List[str] = WavaVecaProcessorWithLM(tokenizer=snake_case ,feature_extractor=snake_case ,decoder=snake_case ) self.assertListEqual( processor.model_input_names ,feature_extractor.model_input_names ,msg="""`processor` and `feature_extractor` model input names do not match""" ,) @staticmethod def _SCREAMING_SNAKE_CASE ( snake_case ,snake_case ): '''simple docstring''' lowercase : Optional[Any] = [d[key] for d in offsets] return retrieved_list def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' lowercase : Any = WavaVecaProcessorWithLM.from_pretrained("""hf-internal-testing/processor_with_lm""" ) lowercase : int = self._get_dummy_logits()[0] lowercase : Optional[int] = processor.decode(snake_case ,output_word_offsets=snake_case ) # check Wav2Vec2CTCTokenizerOutput keys for word self.assertEqual(len(outputs.keys() ) ,4 ) self.assertTrue("""text""" in outputs ) self.assertTrue("""word_offsets""" in outputs ) self.assertTrue(isinstance(snake_case ,snake_case ) ) self.assertEqual(""" """.join(self.get_from_offsets(outputs["""word_offsets"""] ,"""word""" ) ) ,outputs.text ) self.assertListEqual(self.get_from_offsets(outputs["""word_offsets"""] ,"""word""" ) ,["""<s>""", """<s>""", """</s>"""] ) self.assertListEqual(self.get_from_offsets(outputs["""word_offsets"""] ,"""start_offset""" ) ,[0, 2, 4] ) self.assertListEqual(self.get_from_offsets(outputs["""word_offsets"""] ,"""end_offset""" ) ,[1, 3, 5] ) def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' lowercase : List[Any] = WavaVecaProcessorWithLM.from_pretrained("""hf-internal-testing/processor_with_lm""" ) lowercase : int = self._get_dummy_logits() lowercase : Tuple = processor.batch_decode(snake_case ,output_word_offsets=snake_case ) # check Wav2Vec2CTCTokenizerOutput keys for word self.assertEqual(len(outputs.keys() ) ,4 ) self.assertTrue("""text""" in outputs ) self.assertTrue("""word_offsets""" in outputs ) self.assertTrue(isinstance(snake_case ,snake_case ) ) self.assertListEqual( [""" """.join(self.get_from_offsets(snake_case ,"""word""" ) ) for o in outputs["""word_offsets"""]] ,outputs.text ) self.assertListEqual(self.get_from_offsets(outputs["""word_offsets"""][0] ,"""word""" ) ,["""<s>""", """<s>""", """</s>"""] ) self.assertListEqual(self.get_from_offsets(outputs["""word_offsets"""][0] ,"""start_offset""" ) ,[0, 2, 4] ) self.assertListEqual(self.get_from_offsets(outputs["""word_offsets"""][0] ,"""end_offset""" ) ,[1, 3, 5] ) @slow @require_torch @require_torchaudio def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' import torch lowercase : Any = load_dataset("""common_voice""" ,"""en""" ,split="""train""" ,streaming=snake_case ) lowercase : List[Any] = ds.cast_column("""audio""" ,datasets.Audio(sampling_rate=16000 ) ) lowercase : List[Any] = iter(snake_case ) lowercase : Optional[int] = next(snake_case ) lowercase : List[str] = AutoProcessor.from_pretrained("""patrickvonplaten/wav2vec2-base-100h-with-lm""" ) lowercase : str = WavaVecaForCTC.from_pretrained("""patrickvonplaten/wav2vec2-base-100h-with-lm""" ) # compare to filename `common_voice_en_100038.mp3` of dataset viewer on https://huggingface.co/datasets/common_voice/viewer/en/train lowercase : int = processor(sample["""audio"""]["""array"""] ,return_tensors="""pt""" ).input_values with torch.no_grad(): lowercase : Dict = model(snake_case ).logits.cpu().numpy() lowercase : Dict = processor.decode(logits[0] ,output_word_offsets=snake_case ) lowercase : str = model.config.inputs_to_logits_ratio / processor.feature_extractor.sampling_rate lowercase : Dict = [ { """start_time""": d["""start_offset"""] * time_offset, """end_time""": d["""end_offset"""] * time_offset, """word""": d["""word"""], } for d in output["""word_offsets"""] ] lowercase : Tuple = """WHY DOES MILISANDRA LOOK LIKE SHE WANTS TO CONSUME JOHN SNOW ON THE RIVER AT THE WALL""" # output words self.assertEqual(""" """.join(self.get_from_offsets(snake_case ,"""word""" ) ) ,snake_case ) self.assertEqual(""" """.join(self.get_from_offsets(snake_case ,"""word""" ) ) ,output.text ) # output times lowercase : Tuple = torch.tensor(self.get_from_offsets(snake_case ,"""start_time""" ) ) lowercase : Union[str, Any] = torch.tensor(self.get_from_offsets(snake_case ,"""end_time""" ) ) # fmt: off lowercase : int = torch.tensor([1.4_199, 1.6_599, 2.2_599, 3.0, 3.24, 3.5_999, 3.7_999, 4.0_999, 4.26, 4.94, 5.28, 5.6_599, 5.78, 5.94, 6.32, 6.5_399, 6.6_599] ) lowercase : List[str] = torch.tensor([1.5_399, 1.8_999, 2.9, 3.16, 3.5_399, 3.72, 4.0_199, 4.1_799, 4.76, 5.1_599, 5.5_599, 5.6_999, 5.86, 6.1_999, 6.38, 6.6_199, 6.94] ) # fmt: on self.assertTrue(torch.allclose(snake_case ,snake_case ,atol=0.01 ) ) self.assertTrue(torch.allclose(snake_case ,snake_case ,atol=0.01 ) )
20
import os import unicodedata from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging a =logging.get_logger(__name__) a ={"""vocab_file""": """spiece.model"""} a ={ """vocab_file""": { """albert-base-v1""": """https://huggingface.co/albert-base-v1/resolve/main/spiece.model""", """albert-large-v1""": """https://huggingface.co/albert-large-v1/resolve/main/spiece.model""", """albert-xlarge-v1""": """https://huggingface.co/albert-xlarge-v1/resolve/main/spiece.model""", """albert-xxlarge-v1""": """https://huggingface.co/albert-xxlarge-v1/resolve/main/spiece.model""", """albert-base-v2""": """https://huggingface.co/albert-base-v2/resolve/main/spiece.model""", """albert-large-v2""": """https://huggingface.co/albert-large-v2/resolve/main/spiece.model""", """albert-xlarge-v2""": """https://huggingface.co/albert-xlarge-v2/resolve/main/spiece.model""", """albert-xxlarge-v2""": """https://huggingface.co/albert-xxlarge-v2/resolve/main/spiece.model""", } } a ={ """albert-base-v1""": 512, """albert-large-v1""": 512, """albert-xlarge-v1""": 512, """albert-xxlarge-v1""": 512, """albert-base-v2""": 512, """albert-large-v2""": 512, """albert-xlarge-v2""": 512, """albert-xxlarge-v2""": 512, } a ="""▁""" class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : List[Any] = VOCAB_FILES_NAMES _UpperCAmelCase : List[str] = PRETRAINED_VOCAB_FILES_MAP _UpperCAmelCase : Optional[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self : str ,SCREAMING_SNAKE_CASE__ : Optional[int] ,SCREAMING_SNAKE_CASE__ : Tuple=True ,SCREAMING_SNAKE_CASE__ : str=True ,SCREAMING_SNAKE_CASE__ : List[str]=False ,SCREAMING_SNAKE_CASE__ : Any="[CLS]" ,SCREAMING_SNAKE_CASE__ : Optional[int]="[SEP]" ,SCREAMING_SNAKE_CASE__ : Optional[Any]="<unk>" ,SCREAMING_SNAKE_CASE__ : Any="[SEP]" ,SCREAMING_SNAKE_CASE__ : Optional[int]="<pad>" ,SCREAMING_SNAKE_CASE__ : Any="[CLS]" ,SCREAMING_SNAKE_CASE__ : Union[str, Any]="[MASK]" ,SCREAMING_SNAKE_CASE__ : Optional[Dict[str, Any]] = None ,**SCREAMING_SNAKE_CASE__ : Dict ,): # Mask token behave like a normal word, i.e. include the space before it and # is included in the raw text, there should be a match in a non-normalized sentence. __lowerCamelCase : Dict = ( AddedToken(SCREAMING_SNAKE_CASE__ ,lstrip=SCREAMING_SNAKE_CASE__ ,rstrip=SCREAMING_SNAKE_CASE__ ,normalized=SCREAMING_SNAKE_CASE__) if isinstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) else mask_token ) __lowerCamelCase : str = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( do_lower_case=SCREAMING_SNAKE_CASE__ ,remove_space=SCREAMING_SNAKE_CASE__ ,keep_accents=SCREAMING_SNAKE_CASE__ ,bos_token=SCREAMING_SNAKE_CASE__ ,eos_token=SCREAMING_SNAKE_CASE__ ,unk_token=SCREAMING_SNAKE_CASE__ ,sep_token=SCREAMING_SNAKE_CASE__ ,pad_token=SCREAMING_SNAKE_CASE__ ,cls_token=SCREAMING_SNAKE_CASE__ ,mask_token=SCREAMING_SNAKE_CASE__ ,sp_model_kwargs=self.sp_model_kwargs ,**SCREAMING_SNAKE_CASE__ ,) __lowerCamelCase : Any = do_lower_case __lowerCamelCase : Union[str, Any] = remove_space __lowerCamelCase : Tuple = keep_accents __lowerCamelCase : Dict = vocab_file __lowerCamelCase : str = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.Load(SCREAMING_SNAKE_CASE__) @property def lowerCAmelCase ( self : Optional[Any]): return len(self.sp_model) def lowerCAmelCase ( self : Optional[Any]): __lowerCamelCase : Optional[int] = {self.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__): i for i in range(self.vocab_size)} vocab.update(self.added_tokens_encoder) return vocab def __getstate__( self : Union[str, Any]): __lowerCamelCase : str = self.__dict__.copy() __lowerCamelCase : Tuple = None return state def __setstate__( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : str): __lowerCamelCase : List[str] = d # for backward compatibility if not hasattr(self ,'sp_model_kwargs'): __lowerCamelCase : List[str] = {} __lowerCamelCase : int = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.Load(self.vocab_file) def lowerCAmelCase ( self : Dict ,SCREAMING_SNAKE_CASE__ : List[Any]): if self.remove_space: __lowerCamelCase : Dict = ' '.join(inputs.strip().split()) else: __lowerCamelCase : Optional[Any] = inputs __lowerCamelCase : Tuple = outputs.replace('``' ,'"').replace('\'\'' ,'"') if not self.keep_accents: __lowerCamelCase : List[str] = unicodedata.normalize('NFKD' ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : str = ''.join([c for c in outputs if not unicodedata.combining(SCREAMING_SNAKE_CASE__)]) if self.do_lower_case: __lowerCamelCase : Optional[Any] = outputs.lower() return outputs def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : str): __lowerCamelCase : Tuple = self.preprocess_text(SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = self.sp_model.encode(SCREAMING_SNAKE_CASE__ ,out_type=SCREAMING_SNAKE_CASE__) __lowerCamelCase : Tuple = [] for piece in pieces: if len(SCREAMING_SNAKE_CASE__) > 1 and piece[-1] == str(',') and piece[-2].isdigit(): __lowerCamelCase : int = self.sp_model.EncodeAsPieces(piece[:-1].replace(SCREAMING_SNAKE_CASE__ ,'')) if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE: if len(cur_pieces[0]) == 1: __lowerCamelCase : Union[str, Any] = cur_pieces[1:] else: __lowerCamelCase : Dict = cur_pieces[0][1:] cur_pieces.append(piece[-1]) new_pieces.extend(SCREAMING_SNAKE_CASE__) else: new_pieces.append(SCREAMING_SNAKE_CASE__) return new_pieces def lowerCAmelCase ( self : Any ,SCREAMING_SNAKE_CASE__ : List[str]): return self.sp_model.PieceToId(SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : str ,SCREAMING_SNAKE_CASE__ : Any): return self.sp_model.IdToPiece(SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Tuple ,SCREAMING_SNAKE_CASE__ : int): __lowerCamelCase : Optional[Any] = [] __lowerCamelCase : int = '' __lowerCamelCase : Optional[int] = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(SCREAMING_SNAKE_CASE__) + token __lowerCamelCase : List[Any] = True __lowerCamelCase : Any = [] else: current_sub_tokens.append(SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = False out_string += self.sp_model.decode(SCREAMING_SNAKE_CASE__) return out_string.strip() def lowerCAmelCase ( self : Dict ,SCREAMING_SNAKE_CASE__ : List[int] ,SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None): __lowerCamelCase : Union[str, Any] = [self.sep_token_id] __lowerCamelCase : int = [self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def lowerCAmelCase ( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : List[int] ,SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ,SCREAMING_SNAKE_CASE__ : bool = False): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=SCREAMING_SNAKE_CASE__ ,token_ids_a=SCREAMING_SNAKE_CASE__ ,already_has_special_tokens=SCREAMING_SNAKE_CASE__) if token_ids_a is not None: return [1] + ([0] * len(SCREAMING_SNAKE_CASE__)) + [1] + ([0] * len(SCREAMING_SNAKE_CASE__)) + [1] return [1] + ([0] * len(SCREAMING_SNAKE_CASE__)) + [1] def lowerCAmelCase ( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : List[int] ,SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None): __lowerCamelCase : Tuple = [self.sep_token_id] __lowerCamelCase : List[Any] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep) * [0] return len(cls + token_ids_a + sep) * [0] + len(token_ids_a + sep) * [1] def lowerCAmelCase ( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : str ,SCREAMING_SNAKE_CASE__ : Optional[str] = None): if not os.path.isdir(SCREAMING_SNAKE_CASE__): logger.error(F"Vocabulary path ({save_directory}) should be a directory") return __lowerCamelCase : List[str] = os.path.join( SCREAMING_SNAKE_CASE__ ,(filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file']) if os.path.abspath(self.vocab_file) != os.path.abspath(SCREAMING_SNAKE_CASE__) and os.path.isfile(self.vocab_file): copyfile(self.vocab_file ,SCREAMING_SNAKE_CASE__) elif not os.path.isfile(self.vocab_file): with open(SCREAMING_SNAKE_CASE__ ,'wb') as fi: __lowerCamelCase : str = self.sp_model.serialized_model_proto() fi.write(SCREAMING_SNAKE_CASE__) return (out_vocab_file,)
73
0
import os import tempfile import unittest import uuid from pathlib import Path from transformers.testing_utils import get_tests_dir, require_soundfile, require_torch, require_vision from transformers.tools.agent_types import AgentAudio, AgentImage, AgentText from transformers.utils import is_soundfile_availble, is_torch_available, is_vision_available if is_torch_available(): import torch if is_soundfile_availble(): import soundfile as sf if is_vision_available(): from PIL import Image def UpperCamelCase_( lowerCamelCase_="" ) -> str: _lowercase : Optional[Any] = tempfile.mkdtemp() return os.path.join(lowerCamelCase_ , str(uuid.uuida() ) + suffix ) @require_soundfile @require_torch class _lowerCamelCase( unittest.TestCase ): def UpperCamelCase ( self) -> str: """simple docstring""" _lowercase : List[Any] = torch.rand(12, dtype=torch.floataa) - 0.5 _lowercase : Dict = AgentAudio(lowerCamelCase) _lowercase : List[Any] = str(agent_type.to_string()) # Ensure that the tensor and the agent_type's tensor are the same self.assertTrue(torch.allclose(lowerCamelCase, agent_type.to_raw(), atol=1E-4)) del agent_type # Ensure the path remains even after the object deletion self.assertTrue(os.path.exists(lowerCamelCase)) # Ensure that the file contains the same value as the original tensor _lowercase , _lowercase : List[Any] = sf.read(lowerCamelCase) self.assertTrue(torch.allclose(lowerCamelCase, torch.tensor(lowerCamelCase), atol=1E-4)) def UpperCamelCase ( self) -> Dict: """simple docstring""" _lowercase : List[str] = torch.rand(12, dtype=torch.floataa) - 0.5 _lowercase : Optional[Any] = get_new_path(suffix='.wav') sf.write(lowerCamelCase, lowerCamelCase, 1_60_00) _lowercase : List[str] = AgentAudio(lowerCamelCase) self.assertTrue(torch.allclose(lowerCamelCase, agent_type.to_raw(), atol=1E-4)) self.assertEqual(agent_type.to_string(), lowerCamelCase) @require_vision @require_torch class _lowerCamelCase( unittest.TestCase ): def UpperCamelCase ( self) -> Union[str, Any]: """simple docstring""" _lowercase : str = torch.randint(0, 2_56, (64, 64, 3)) _lowercase : List[Any] = AgentImage(lowerCamelCase) _lowercase : Any = str(agent_type.to_string()) # Ensure that the tensor and the agent_type's tensor are the same self.assertTrue(torch.allclose(lowerCamelCase, agent_type._tensor, atol=1E-4)) self.assertIsInstance(agent_type.to_raw(), Image.Image) # Ensure the path remains even after the object deletion del agent_type self.assertTrue(os.path.exists(lowerCamelCase)) def UpperCamelCase ( self) -> List[Any]: """simple docstring""" _lowercase : Optional[Any] = Path(get_tests_dir('fixtures/tests_samples/COCO')) / '000000039769.png' _lowercase : Any = Image.open(lowerCamelCase) _lowercase : Optional[int] = AgentImage(lowerCamelCase) self.assertTrue(path.samefile(agent_type.to_string())) self.assertTrue(image == agent_type.to_raw()) # Ensure the path remains even after the object deletion del agent_type self.assertTrue(os.path.exists(lowerCamelCase)) def UpperCamelCase ( self) -> Any: """simple docstring""" _lowercase : Optional[int] = Path(get_tests_dir('fixtures/tests_samples/COCO')) / '000000039769.png' _lowercase : Optional[int] = Image.open(lowerCamelCase) _lowercase : List[str] = AgentImage(lowerCamelCase) self.assertFalse(path.samefile(agent_type.to_string())) self.assertTrue(image == agent_type.to_raw()) # Ensure the path remains even after the object deletion del agent_type self.assertTrue(os.path.exists(lowerCamelCase)) class _lowerCamelCase( unittest.TestCase ): def UpperCamelCase ( self) -> Tuple: """simple docstring""" _lowercase : Optional[int] = 'Hey!' _lowercase : List[str] = AgentText(lowerCamelCase) self.assertEqual(lowerCamelCase, agent_type.to_string()) self.assertEqual(lowerCamelCase, agent_type.to_raw()) self.assertEqual(lowerCamelCase, lowerCamelCase)
21
def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> float: if discount_rate < 0: raise ValueError('Discount rate cannot be negative' ) if not cash_flows: raise ValueError('Cash flows list cannot be empty' ) __lowerCamelCase : int = sum( cash_flow / ((1 + discount_rate) ** i) for i, cash_flow in enumerate(lowerCamelCase__ ) ) return round(lowerCamelCase__ , ndigits=2 ) if __name__ == "__main__": import doctest doctest.testmod()
73
0
'''simple docstring''' import os import re import shutil import sys import tempfile import unittest import black __SCREAMING_SNAKE_CASE :Optional[int] = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) sys.path.append(os.path.join(git_repo_path, '''utils''')) import check_copies # noqa: E402 # This is the reference code that will be used in the tests. # If BertLMPredictionHead is changed in modeling_bert.py, this code needs to be manually updated. __SCREAMING_SNAKE_CASE :Any = ''' def __init__(self, config): super().__init__() self.transform = BertPredictionHeadTransform(config) # The output weights are the same as the input embeddings, but there is # an output-only bias for each token. self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False) self.bias = nn.Parameter(torch.zeros(config.vocab_size)) # Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings` self.decoder.bias = self.bias def forward(self, hidden_states): hidden_states = self.transform(hidden_states) hidden_states = self.decoder(hidden_states) return hidden_states ''' class A_ ( unittest.TestCase ): def lowercase ( self : List[Any] ): _UpperCAmelCase = tempfile.mkdtemp() os.makedirs(os.path.join(self.transformer_dir , "models/bert/" ) ) _UpperCAmelCase = self.transformer_dir shutil.copy( os.path.join(snake_case_ , "src/transformers/models/bert/modeling_bert.py" ) , os.path.join(self.transformer_dir , "models/bert/modeling_bert.py" ) , ) def lowercase ( self : Optional[Any] ): _UpperCAmelCase = "src/transformers" shutil.rmtree(self.transformer_dir ) def lowercase ( self : Dict , snake_case_ : int , snake_case_ : Any , snake_case_ : Any , snake_case_ : Union[str, Any]=None ): _UpperCAmelCase = comment + f'\nclass {class_name}(nn.Module):\n' + class_code if overwrite_result is not None: _UpperCAmelCase = comment + f'\nclass {class_name}(nn.Module):\n' + overwrite_result _UpperCAmelCase = black.Mode(target_versions={black.TargetVersion.PYaa} , line_length=1_1_9 ) _UpperCAmelCase = black.format_str(snake_case_ , mode=snake_case_ ) _UpperCAmelCase = os.path.join(self.transformer_dir , "new_code.py" ) with open(snake_case_ , "w" , newline="\n" ) as f: f.write(snake_case_ ) if overwrite_result is None: self.assertTrue(len(check_copies.is_copy_consistent(snake_case_ ) ) == 0 ) else: check_copies.is_copy_consistent(f.name , overwrite=snake_case_ ) with open(snake_case_ , "r" ) as f: self.assertTrue(f.read() , snake_case_ ) def lowercase ( self : List[Any] ): _UpperCAmelCase = check_copies.find_code_in_transformers("models.bert.modeling_bert.BertLMPredictionHead" ) self.assertEqual(snake_case_ , snake_case_ ) def lowercase ( self : Any ): # Base copy consistency self.check_copy_consistency( "# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead" , "BertLMPredictionHead" , REFERENCE_CODE + "\n" , ) # With no empty line at the end self.check_copy_consistency( "# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead" , "BertLMPredictionHead" , snake_case_ , ) # Copy consistency with rename self.check_copy_consistency( "# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead with Bert->TestModel" , "TestModelLMPredictionHead" , re.sub("Bert" , "TestModel" , snake_case_ ) , ) # Copy consistency with a really long name _UpperCAmelCase = "TestModelWithAReallyLongNameBecauseSomePeopleLikeThatForSomeReason" self.check_copy_consistency( f'# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead with Bert->{long_class_name}' , f'{long_class_name}LMPredictionHead' , re.sub("Bert" , snake_case_ , snake_case_ ) , ) # Copy consistency with overwrite self.check_copy_consistency( "# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead with Bert->TestModel" , "TestModelLMPredictionHead" , snake_case_ , overwrite_result=re.sub("Bert" , "TestModel" , snake_case_ ) , ) def lowercase ( self : List[Any] ): _UpperCAmelCase = check_copies.LOCALIZED_READMES["README_zh-hans.md"] _UpperCAmelCase = ( "1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (from Google Research and the" " Toyota Technological Institute at Chicago) released with the paper [ALBERT: A Lite BERT for" " Self-supervised Learning of Language Representations](https://arxiv.org/abs/1909.11942), by Zhenzhong" " Lan, Mingda Chen, Sebastian Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut.\n1." " **[DistilBERT](https://huggingface.co/transformers/model_doc/distilbert.html)** (from HuggingFace)," " released together with the paper [DistilBERT, a distilled version of BERT: smaller, faster, cheaper and" " lighter](https://arxiv.org/abs/1910.01108) by Victor Sanh, Lysandre Debut and Thomas Wolf. The same" " method has been applied to compress GPT2 into" " [DistilGPT2](https://github.com/huggingface/transformers/tree/main/examples/distillation), RoBERTa into" " [DistilRoBERTa](https://github.com/huggingface/transformers/tree/main/examples/distillation)," " Multilingual BERT into" " [DistilmBERT](https://github.com/huggingface/transformers/tree/main/examples/distillation) and a German" " version of DistilBERT.\n1. **[ELECTRA](https://huggingface.co/transformers/model_doc/electra.html)**" " (from Google Research/Stanford University) released with the paper [ELECTRA: Pre-training text encoders" " as discriminators rather than generators](https://arxiv.org/abs/2003.10555) by Kevin Clark, Minh-Thang" " Luong, Quoc V. Le, Christopher D. Manning." ) _UpperCAmelCase = ( "1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (来自 Google Research and the" " Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of" " Language Representations](https://arxiv.org/abs/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian" " Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n" ) _UpperCAmelCase = ( "1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (来自 Google Research and the" " Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of" " Language Representations](https://arxiv.org/abs/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian" " Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n1." " **[DistilBERT](https://huggingface.co/transformers/model_doc/distilbert.html)** (来自 HuggingFace) 伴随论文" " [DistilBERT, a distilled version of BERT: smaller, faster, cheaper and" " lighter](https://arxiv.org/abs/1910.01108) 由 Victor Sanh, Lysandre Debut and Thomas Wolf 发布。 The same" " method has been applied to compress GPT2 into" " [DistilGPT2](https://github.com/huggingface/transformers/tree/main/examples/distillation), RoBERTa into" " [DistilRoBERTa](https://github.com/huggingface/transformers/tree/main/examples/distillation)," " Multilingual BERT into" " [DistilmBERT](https://github.com/huggingface/transformers/tree/main/examples/distillation) and a German" " version of DistilBERT.\n1. **[ELECTRA](https://huggingface.co/transformers/model_doc/electra.html)** (来自" " Google Research/Stanford University) 伴随论文 [ELECTRA: Pre-training text encoders as discriminators rather" " than generators](https://arxiv.org/abs/2003.10555) 由 Kevin Clark, Minh-Thang Luong, Quoc V. Le," " Christopher D. Manning 发布。\n" ) _UpperCAmelCase , _UpperCAmelCase = check_copies.convert_to_localized_md( snake_case_ , snake_case_ , localized_readme["format_model_list"] ) self.assertFalse(snake_case_ ) self.assertEqual(snake_case_ , snake_case_ ) _UpperCAmelCase , _UpperCAmelCase = check_copies.convert_to_localized_md( snake_case_ , snake_case_ , localized_readme["format_model_list"] ) # Check whether the number of models is equal to README.md after conversion. self.assertTrue(snake_case_ ) _UpperCAmelCase = ( "1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (from Google Research and the" " Toyota Technological Institute at Chicago) released with the paper [ALBERT: A Lite BERT for" " Self-supervised Learning of Language Representations](https://arxiv.org/abs/1909.11942), by Zhenzhong" " Lan, Mingda Chen, Sebastian Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut." ) _UpperCAmelCase = ( "1. **[ALBERT](https://huggingface.co/transformers/main/model_doc/albert.html)** (来自 Google Research and" " the Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of" " Language Representations](https://arxiv.org/abs/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian" " Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n" ) _UpperCAmelCase = ( "1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (来自 Google Research and the" " Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of" " Language Representations](https://arxiv.org/abs/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian" " Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n" ) _UpperCAmelCase , _UpperCAmelCase = check_copies.convert_to_localized_md( snake_case_ , snake_case_ , localized_readme["format_model_list"] ) # Check if the model link is synchronized. self.assertEqual(snake_case_ , snake_case_ )
22
import copy from typing import Dict, List, Optional from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING a ={ """facebook/mask2former-swin-small-coco-instance""": ( """https://huggingface.co/facebook/mask2former-swin-small-coco-instance/blob/main/config.json""" ) # See all Mask2Former models at https://huggingface.co/models?filter=mask2former } a =logging.get_logger(__name__) class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : Dict = '''mask2former''' _UpperCAmelCase : Dict = ['''swin'''] _UpperCAmelCase : Optional[int] = {'''hidden_size''': '''hidden_dim'''} def __init__( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : Optional[Dict] = None ,SCREAMING_SNAKE_CASE__ : int = 2_5_6 ,SCREAMING_SNAKE_CASE__ : int = 2_5_6 ,SCREAMING_SNAKE_CASE__ : int = 2_5_6 ,SCREAMING_SNAKE_CASE__ : int = 1_0_2_4 ,SCREAMING_SNAKE_CASE__ : str = "relu" ,SCREAMING_SNAKE_CASE__ : int = 6 ,SCREAMING_SNAKE_CASE__ : int = 1_0 ,SCREAMING_SNAKE_CASE__ : int = 8 ,SCREAMING_SNAKE_CASE__ : float = 0.0 ,SCREAMING_SNAKE_CASE__ : int = 2_0_4_8 ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : int = 4 ,SCREAMING_SNAKE_CASE__ : int = 2_5_5 ,SCREAMING_SNAKE_CASE__ : int = 1_0_0 ,SCREAMING_SNAKE_CASE__ : float = 0.1 ,SCREAMING_SNAKE_CASE__ : float = 2.0 ,SCREAMING_SNAKE_CASE__ : float = 5.0 ,SCREAMING_SNAKE_CASE__ : float = 5.0 ,SCREAMING_SNAKE_CASE__ : int = 1_2_5_4_4 ,SCREAMING_SNAKE_CASE__ : float = 3.0 ,SCREAMING_SNAKE_CASE__ : float = 0.75 ,SCREAMING_SNAKE_CASE__ : float = 0.02 ,SCREAMING_SNAKE_CASE__ : float = 1.0 ,SCREAMING_SNAKE_CASE__ : bool = True ,SCREAMING_SNAKE_CASE__ : List[int] = [4, 8, 1_6, 3_2] ,SCREAMING_SNAKE_CASE__ : bool = None ,**SCREAMING_SNAKE_CASE__ : Optional[Any] ,): if backbone_config is None: logger.info('`backbone_config` is `None`. Initializing the config with the default `Swin` backbone.') __lowerCamelCase : Optional[Any] = CONFIG_MAPPING['swin']( image_size=2_2_4 ,in_channels=3 ,patch_size=4 ,embed_dim=9_6 ,depths=[2, 2, 1_8, 2] ,num_heads=[3, 6, 1_2, 2_4] ,window_size=7 ,drop_path_rate=0.3 ,use_absolute_embeddings=SCREAMING_SNAKE_CASE__ ,out_features=['stage1', 'stage2', 'stage3', 'stage4'] ,) if isinstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__): __lowerCamelCase : Union[str, Any] = backbone_config.pop('model_type') __lowerCamelCase : Dict = CONFIG_MAPPING[backbone_model_type] __lowerCamelCase : int = config_class.from_dict(SCREAMING_SNAKE_CASE__) # verify that the backbone is supported if backbone_config.model_type not in self.backbones_supported: logger.warning_once( F"Backbone {backbone_config.model_type} is not a supported model and may not be compatible with Mask2Former. " F"Supported model types: {','.join(self.backbones_supported)}") __lowerCamelCase : Dict = backbone_config __lowerCamelCase : int = feature_size __lowerCamelCase : List[str] = mask_feature_size __lowerCamelCase : int = hidden_dim __lowerCamelCase : str = encoder_feedforward_dim __lowerCamelCase : Optional[int] = activation_function __lowerCamelCase : int = encoder_layers __lowerCamelCase : List[Any] = decoder_layers __lowerCamelCase : Union[str, Any] = num_attention_heads __lowerCamelCase : Tuple = dropout __lowerCamelCase : Dict = dim_feedforward __lowerCamelCase : Union[str, Any] = pre_norm __lowerCamelCase : List[str] = enforce_input_projection __lowerCamelCase : Optional[int] = common_stride __lowerCamelCase : Dict = ignore_value __lowerCamelCase : Optional[Any] = num_queries __lowerCamelCase : int = no_object_weight __lowerCamelCase : Optional[Any] = class_weight __lowerCamelCase : str = mask_weight __lowerCamelCase : List[str] = dice_weight __lowerCamelCase : Dict = train_num_points __lowerCamelCase : Optional[int] = oversample_ratio __lowerCamelCase : Optional[Any] = importance_sample_ratio __lowerCamelCase : List[Any] = init_std __lowerCamelCase : Tuple = init_xavier_std __lowerCamelCase : Union[str, Any] = use_auxiliary_loss __lowerCamelCase : List[Any] = feature_strides __lowerCamelCase : Any = output_auxiliary_logits __lowerCamelCase : List[Any] = decoder_layers super().__init__(**SCREAMING_SNAKE_CASE__) @classmethod def lowerCAmelCase ( cls : str ,SCREAMING_SNAKE_CASE__ : PretrainedConfig ,**SCREAMING_SNAKE_CASE__ : Tuple): return cls( backbone_config=SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__ ,) def lowerCAmelCase ( self : str): __lowerCamelCase : List[Any] = copy.deepcopy(self.__dict__) __lowerCamelCase : List[Any] = self.backbone_config.to_dict() __lowerCamelCase : Union[str, Any] = self.__class__.model_type return output
73
0
'''simple docstring''' def snake_case_ ( _lowerCAmelCase : int ) -> int: if a < 0: raise ValueError('''Input value must be a positive integer''' ) elif isinstance(_lowerCAmelCase , _lowerCAmelCase ): raise TypeError('''Input value must be a \'int\' type''' ) return bin(_lowerCAmelCase ).count('''1''' ) if __name__ == "__main__": import doctest doctest.testmod()
23
import string # frequency taken from https://en.wikipedia.org/wiki/Letter_frequency a ={ """E""": 12.70, """T""": 9.06, """A""": 8.17, """O""": 7.51, """I""": 6.97, """N""": 6.75, """S""": 6.33, """H""": 6.09, """R""": 5.99, """D""": 4.25, """L""": 4.03, """C""": 2.78, """U""": 2.76, """M""": 2.41, """W""": 2.36, """F""": 2.23, """G""": 2.02, """Y""": 1.97, """P""": 1.93, """B""": 1.29, """V""": 0.98, """K""": 0.77, """J""": 0.15, """X""": 0.15, """Q""": 0.10, """Z""": 0.07, } a ="""ETAOINSHRDLCUMWFGYPBVKJXQZ""" a ="""ABCDEFGHIJKLMNOPQRSTUVWXYZ""" def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> dict[str, int]: __lowerCamelCase : Tuple = {letter: 0 for letter in string.ascii_uppercase} for letter in message.upper(): if letter in LETTERS: letter_count[letter] += 1 return letter_count def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> str: return x[0] def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> str: __lowerCamelCase : List[str] = get_letter_count(lowerCamelCase__ ) __lowerCamelCase : dict[int, list[str]] = { freq: [] for letter, freq in letter_to_freq.items() } for letter in LETTERS: freq_to_letter[letter_to_freq[letter]].append(lowerCamelCase__ ) __lowerCamelCase : dict[int, str] = {} for freq in freq_to_letter: freq_to_letter[freq].sort(key=ETAOIN.find , reverse=lowerCamelCase__ ) __lowerCamelCase : Optional[Any] = ''.join(freq_to_letter[freq] ) __lowerCamelCase : int = list(freq_to_letter_str.items() ) freq_pairs.sort(key=lowerCamelCase__ , reverse=lowerCamelCase__ ) __lowerCamelCase : list[str] = [freq_pair[1] for freq_pair in freq_pairs] return "".join(lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> int: __lowerCamelCase : str = get_frequency_order(lowerCamelCase__ ) __lowerCamelCase : Optional[Any] = 0 for common_letter in ETAOIN[:6]: if common_letter in freq_order[:6]: match_score += 1 for uncommon_letter in ETAOIN[-6:]: if uncommon_letter in freq_order[-6:]: match_score += 1 return match_score if __name__ == "__main__": import doctest doctest.testmod()
73
0
import argparse import os import re snake_case_ = 'src/transformers/models/auto' # re pattern that matches mapping introductions: # SUPER_MODEL_MAPPING_NAMES = OrderedDict or SUPER_MODEL_MAPPING = OrderedDict snake_case_ = re.compile(R'[A-Z_]+_MAPPING(\s+|_[A-Z_]+\s+)=\s+OrderedDict') # re pattern that matches identifiers in mappings snake_case_ = re.compile(R'\s*\(\s*"(\S[^"]+)"') def lowerCamelCase__ ( snake_case_ : Union[str, Any] , snake_case_ : bool = False ) -> Optional[int]: with open(snake_case_ , '''r''' , encoding='''utf-8''' ) as f: __snake_case = f.read() __snake_case = content.split('''\n''' ) __snake_case = [] __snake_case = 0 while line_idx < len(snake_case_ ): if _re_intro_mapping.search(lines[line_idx] ) is not None: __snake_case = len(re.search(R'''^(\s*)\S''' , lines[line_idx] ).groups()[0] ) + 8 # Start of a new mapping! while not lines[line_idx].startswith(''' ''' * indent + '''(''' ): new_lines.append(lines[line_idx] ) line_idx += 1 __snake_case = [] while lines[line_idx].strip() != "]": # Blocks either fit in one line or not if lines[line_idx].strip() == "(": __snake_case = line_idx while not lines[line_idx].startswith(''' ''' * indent + ''')''' ): line_idx += 1 blocks.append('''\n'''.join(lines[start_idx : line_idx + 1] ) ) else: blocks.append(lines[line_idx] ) line_idx += 1 # Sort blocks by their identifiers __snake_case = sorted(snake_case_ , key=lambda snake_case_ : _re_identifier.search(snake_case_ ).groups()[0] ) new_lines += blocks else: new_lines.append(lines[line_idx] ) line_idx += 1 if overwrite: with open(snake_case_ , '''w''' , encoding='''utf-8''' ) as f: f.write('''\n'''.join(snake_case_ ) ) elif "\n".join(snake_case_ ) != content: return True def lowerCamelCase__ ( snake_case_ : bool = False ) -> Union[str, Any]: __snake_case = [os.path.join(snake_case_ , snake_case_ ) for f in os.listdir(snake_case_ ) if f.endswith('''.py''' )] __snake_case = [sort_auto_mapping(snake_case_ , overwrite=snake_case_ ) for fname in fnames] if not overwrite and any(snake_case_ ): __snake_case = [f for f, d in zip(snake_case_ , snake_case_ ) if d] raise ValueError( f"""The following files have auto mappings that need sorting: {', '.join(snake_case_ )}. Run `make style` to fix""" ''' this.''' ) if __name__ == "__main__": snake_case_ = argparse.ArgumentParser() parser.add_argument('--check_only', action='store_true', help='Whether to only check or fix style.') snake_case_ = parser.parse_args() sort_all_auto_mappings(not args.check_only)
24
# This is the module that test_patching.py uses to test patch_submodule() import os # noqa: this is just for tests import os as renamed_os # noqa: this is just for tests from os import path # noqa: this is just for tests from os import path as renamed_path # noqa: this is just for tests from os.path import join # noqa: this is just for tests from os.path import join as renamed_join # noqa: this is just for tests a =open # noqa: we just need to have a builtin inside this module to test it properly
73
0
"""simple docstring""" UpperCAmelCase__ : Tuple = [ 'DownloadConfig', 'DownloadManager', 'DownloadMode', 'StreamingDownloadManager', ] from .download_config import DownloadConfig from .download_manager import DownloadManager, DownloadMode from .streaming_download_manager import StreamingDownloadManager
25
# Function to print upper half of diamond (pyramid) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> str: for i in range(0 , lowerCamelCase__ ): for _ in range(0 , n - i - 1 ): # printing spaces print(' ' , end='' ) for _ in range(0 , i + 1 ): # printing stars print('* ' , end='' ) print() def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Tuple: for i in range(lowerCamelCase__ , 0 , -1 ): for _ in range(lowerCamelCase__ , 0 , -1 ): # printing stars print('* ' , end='' ) print() for _ in range(n - i + 1 , 0 , -1 ): # printing spaces print(' ' , end='' ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Any: if n <= 0: print(' ... .... nothing printing :(' ) return floyd(lowerCamelCase__ ) # upper half reverse_floyd(lowerCamelCase__ ) # lower half if __name__ == "__main__": print(r"""| /\ | |- | |- |--| |\ /| |-""") print(r"""|/ \| |- |_ |_ |__| | \/ | |_""") a =1 while K: a =int(input("""enter the number and , and see the magic : """)) print() pretty_print(user_number) a =int(input("""press 0 to exit... and 1 to continue...""")) print("""Good Bye...""")
73
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _snake_case = { "configuration_x_clip": [ "XCLIP_PRETRAINED_CONFIG_ARCHIVE_MAP", "XCLIPConfig", "XCLIPTextConfig", "XCLIPVisionConfig", ], "processing_x_clip": ["XCLIPProcessor"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _snake_case = [ "XCLIP_PRETRAINED_MODEL_ARCHIVE_LIST", "XCLIPModel", "XCLIPPreTrainedModel", "XCLIPTextModel", "XCLIPVisionModel", ] if TYPE_CHECKING: from .configuration_x_clip import ( XCLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, XCLIPConfig, XCLIPTextConfig, XCLIPVisionConfig, ) from .processing_x_clip import XCLIPProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_x_clip import ( XCLIP_PRETRAINED_MODEL_ARCHIVE_LIST, XCLIPModel, XCLIPPreTrainedModel, XCLIPTextModel, XCLIPVisionModel, ) else: import sys _snake_case = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
26
import re import warnings from contextlib import contextmanager from ...processing_utils import ProcessorMixin class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : Any = ['''image_processor''', '''tokenizer'''] _UpperCAmelCase : List[Any] = '''AutoImageProcessor''' _UpperCAmelCase : Dict = '''AutoTokenizer''' def __init__( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : Optional[int]=None ,SCREAMING_SNAKE_CASE__ : List[Any]=None ,**SCREAMING_SNAKE_CASE__ : Union[str, Any]): __lowerCamelCase : List[str] = None if "feature_extractor" in kwargs: warnings.warn( 'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`' ' instead.' ,SCREAMING_SNAKE_CASE__ ,) __lowerCamelCase : Union[str, Any] = kwargs.pop('feature_extractor') __lowerCamelCase : Dict = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('You need to specify an `image_processor`.') if tokenizer is None: raise ValueError('You need to specify a `tokenizer`.') super().__init__(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Dict = self.image_processor __lowerCamelCase : Optional[int] = False def __call__( self : int ,*SCREAMING_SNAKE_CASE__ : Union[str, Any] ,**SCREAMING_SNAKE_CASE__ : Union[str, Any]): # For backward compatibility if self._in_target_context_manager: return self.current_processor(*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[int] = kwargs.pop('images' ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Union[str, Any] = kwargs.pop('text' ,SCREAMING_SNAKE_CASE__) if len(SCREAMING_SNAKE_CASE__) > 0: __lowerCamelCase : int = args[0] __lowerCamelCase : List[str] = args[1:] if images is None and text is None: raise ValueError('You need to specify either an `images` or `text` input to process.') if images is not None: __lowerCamelCase : Optional[int] = self.image_processor(SCREAMING_SNAKE_CASE__ ,*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) if text is not None: __lowerCamelCase : List[Any] = self.tokenizer(SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) if text is None: return inputs elif images is None: return encodings else: __lowerCamelCase : Optional[Any] = encodings['input_ids'] return inputs def lowerCAmelCase ( self : int ,*SCREAMING_SNAKE_CASE__ : Union[str, Any] ,**SCREAMING_SNAKE_CASE__ : Dict): return self.tokenizer.batch_decode(*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Optional[Any] ,*SCREAMING_SNAKE_CASE__ : List[Any] ,**SCREAMING_SNAKE_CASE__ : Any): return self.tokenizer.decode(*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) @contextmanager def lowerCAmelCase ( self : Tuple): warnings.warn( '`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your ' 'labels by using the argument `text` of the regular `__call__` method (either in the same call as ' 'your images inputs, or in a separate call.') __lowerCamelCase : List[Any] = True __lowerCamelCase : str = self.tokenizer yield __lowerCamelCase : Tuple = self.image_processor __lowerCamelCase : Tuple = False def lowerCAmelCase ( self : Any ,SCREAMING_SNAKE_CASE__ : str ,SCREAMING_SNAKE_CASE__ : int=False ,SCREAMING_SNAKE_CASE__ : List[Any]=None): if added_vocab is None: __lowerCamelCase : str = self.tokenizer.get_added_vocab() __lowerCamelCase : Union[str, Any] = {} while tokens: __lowerCamelCase : Tuple = re.search(R'<s_(.*?)>' ,SCREAMING_SNAKE_CASE__ ,re.IGNORECASE) if start_token is None: break __lowerCamelCase : Dict = start_token.group(1) __lowerCamelCase : List[str] = re.search(RF"</s_{key}>" ,SCREAMING_SNAKE_CASE__ ,re.IGNORECASE) __lowerCamelCase : Optional[int] = start_token.group() if end_token is None: __lowerCamelCase : List[Any] = tokens.replace(SCREAMING_SNAKE_CASE__ ,'') else: __lowerCamelCase : Tuple = end_token.group() __lowerCamelCase : int = re.escape(SCREAMING_SNAKE_CASE__) __lowerCamelCase : str = re.escape(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Union[str, Any] = re.search(F"{start_token_escaped}(.*?){end_token_escaped}" ,SCREAMING_SNAKE_CASE__ ,re.IGNORECASE) if content is not None: __lowerCamelCase : List[Any] = content.group(1).strip() if r"<s_" in content and r"</s_" in content: # non-leaf node __lowerCamelCase : str = self.tokenajson(SCREAMING_SNAKE_CASE__ ,is_inner_value=SCREAMING_SNAKE_CASE__ ,added_vocab=SCREAMING_SNAKE_CASE__) if value: if len(SCREAMING_SNAKE_CASE__) == 1: __lowerCamelCase : Tuple = value[0] __lowerCamelCase : int = value else: # leaf nodes __lowerCamelCase : Tuple = [] for leaf in content.split(R'<sep/>'): __lowerCamelCase : List[Any] = leaf.strip() if leaf in added_vocab and leaf[0] == "<" and leaf[-2:] == "/>": __lowerCamelCase : str = leaf[1:-2] # for categorical special tokens output[key].append(SCREAMING_SNAKE_CASE__) if len(output[key]) == 1: __lowerCamelCase : Dict = output[key][0] __lowerCamelCase : Dict = tokens[tokens.find(SCREAMING_SNAKE_CASE__) + len(SCREAMING_SNAKE_CASE__) :].strip() if tokens[:6] == r"<sep/>": # non-leaf nodes return [output] + self.tokenajson(tokens[6:] ,is_inner_value=SCREAMING_SNAKE_CASE__ ,added_vocab=SCREAMING_SNAKE_CASE__) if len(SCREAMING_SNAKE_CASE__): return [output] if is_inner_value else output else: return [] if is_inner_value else {"text_sequence": tokens} @property def lowerCAmelCase ( self : List[str]): warnings.warn( '`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.' ,SCREAMING_SNAKE_CASE__ ,) return self.image_processor_class @property def lowerCAmelCase ( self : List[Any]): warnings.warn( '`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.' ,SCREAMING_SNAKE_CASE__ ,) return self.image_processor
73
0
'''simple docstring''' import contextlib from multiprocessing import Pool, RLock from tqdm.auto import tqdm from ..utils import experimental, logging __lowercase : List[Any] = logging.get_logger(__name__) class __UpperCamelCase : A_ = None @experimental def lowerCamelCase (_SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : Any , _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : Dict , _SCREAMING_SNAKE_CASE : Dict , _SCREAMING_SNAKE_CASE : Tuple , _SCREAMING_SNAKE_CASE : Union[str, Any] ): if ParallelBackendConfig.backend_name is None: return _map_with_multiprocessing_pool( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) return _map_with_joblib(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : Any , _SCREAMING_SNAKE_CASE : Tuple , _SCREAMING_SNAKE_CASE : Any , _SCREAMING_SNAKE_CASE : Tuple , _SCREAMING_SNAKE_CASE : Any , _SCREAMING_SNAKE_CASE : Optional[Any] , _SCREAMING_SNAKE_CASE : Optional[Any] ): __a : Optional[int] = num_proc if num_proc <= len(_SCREAMING_SNAKE_CASE ) else len(_SCREAMING_SNAKE_CASE ) __a : Optional[Any] = [] # We organize the splits ourselve (contiguous splits) for index in range(_SCREAMING_SNAKE_CASE ): __a : Union[str, Any] = len(_SCREAMING_SNAKE_CASE ) // num_proc __a : Optional[int] = len(_SCREAMING_SNAKE_CASE ) % num_proc __a : Optional[int] = div * index + min(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __a : Optional[int] = start + div + (1 if index < mod else 0) split_kwds.append((function, iterable[start:end], types, index, disable_tqdm, desc) ) if len(_SCREAMING_SNAKE_CASE ) != sum(len(i[1] ) for i in split_kwds ): raise ValueError( F"""Error dividing inputs iterable among processes. """ F"""Total number of objects {len(_SCREAMING_SNAKE_CASE )}, """ F"""length: {sum(len(i[1] ) for i in split_kwds )}""" ) logger.info( F"""Spawning {num_proc} processes for {len(_SCREAMING_SNAKE_CASE )} objects in slices of {[len(i[1] ) for i in split_kwds]}""" ) __a , __a : Union[str, Any] = None, None if not disable_tqdm: __a , __a : Tuple = (RLock(),), tqdm.set_lock with Pool(_SCREAMING_SNAKE_CASE , initargs=_SCREAMING_SNAKE_CASE , initializer=_SCREAMING_SNAKE_CASE ) as pool: __a : Union[str, Any] = pool.map(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) logger.info(F"""Finished {num_proc} processes""" ) __a : Optional[int] = [obj for proc_res in mapped for obj in proc_res] logger.info(F"""Unpacked {len(_SCREAMING_SNAKE_CASE )} objects""" ) return mapped def lowerCamelCase (_SCREAMING_SNAKE_CASE : Union[str, Any] , _SCREAMING_SNAKE_CASE : Tuple , _SCREAMING_SNAKE_CASE : List[Any] , _SCREAMING_SNAKE_CASE : Tuple , _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : Optional[int] , _SCREAMING_SNAKE_CASE : Optional[int] ): # progress bar is not yet supported for _map_with_joblib, because tqdm couldn't accurately be applied to joblib, # and it requires monkey-patching joblib internal classes which is subject to change import joblib with joblib.parallel_backend(ParallelBackendConfig.backend_name , n_jobs=_SCREAMING_SNAKE_CASE ): return joblib.Parallel()( joblib.delayed(_SCREAMING_SNAKE_CASE )((function, obj, types, None, True, None) ) for obj in iterable ) @experimental @contextlib.contextmanager def lowerCamelCase (_SCREAMING_SNAKE_CASE : str ): __a : Union[str, Any] = backend_name if backend_name == "spark": from joblibspark import register_spark register_spark() # TODO: call create_cache_and_write_probe if "download" in steps # TODO: raise NotImplementedError when Dataset.map etc is called try: yield finally: __a : Optional[int] = None
27
def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> int: __lowerCamelCase : Optional[int] = 0 __lowerCamelCase : Dict = len(lowerCamelCase__ ) - 1 while left <= right: # avoid divided by 0 during interpolation if sorted_collection[left] == sorted_collection[right]: if sorted_collection[left] == item: return left else: return None __lowerCamelCase : str = left + ((item - sorted_collection[left]) * (right - left)) // ( sorted_collection[right] - sorted_collection[left] ) # out of range check if point < 0 or point >= len(lowerCamelCase__ ): return None __lowerCamelCase : Tuple = sorted_collection[point] if current_item == item: return point else: if point < left: __lowerCamelCase : List[Any] = left __lowerCamelCase : Tuple = point elif point > right: __lowerCamelCase : Dict = right __lowerCamelCase : str = point else: if item < current_item: __lowerCamelCase : Dict = point - 1 else: __lowerCamelCase : Dict = point + 1 return None def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> Any: # avoid divided by 0 during interpolation if sorted_collection[left] == sorted_collection[right]: if sorted_collection[left] == item: return left else: return None __lowerCamelCase : Optional[int] = left + ((item - sorted_collection[left]) * (right - left)) // ( sorted_collection[right] - sorted_collection[left] ) # out of range check if point < 0 or point >= len(lowerCamelCase__ ): return None if sorted_collection[point] == item: return point elif point < left: return interpolation_search_by_recursion(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) elif point > right: return interpolation_search_by_recursion(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) else: if sorted_collection[point] > item: return interpolation_search_by_recursion( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , point - 1 ) else: return interpolation_search_by_recursion( lowerCamelCase__ , lowerCamelCase__ , point + 1 , lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Optional[Any]: if collection != sorted(lowerCamelCase__ ): raise ValueError('Collection must be ascending sorted' ) return True if __name__ == "__main__": import sys a =0 if debug == 1: a =[10, 30, 40, 45, 50, 66, 77, 93] try: __assert_sorted(collection) except ValueError: sys.exit("""Sequence must be ascending sorted to apply interpolation search""") a =67 a =interpolation_search(collection, target) if result is not None: print(F"""{target} found at positions: {result}""") else: print("""Not found""")
73
0
'''simple docstring''' import shutil import tempfile import unittest from transformers import ( SPIECE_UNDERLINE, AddedToken, BatchEncoding, NllbTokenizer, NllbTokenizerFast, is_torch_available, ) from transformers.testing_utils import ( get_tests_dir, nested_simplify, require_sentencepiece, require_tokenizers, require_torch, ) from ...test_tokenization_common import TokenizerTesterMixin _lowerCamelCase : List[str] = get_tests_dir("fixtures/test_sentencepiece.model") if is_torch_available(): from transformers.models.mam_aaa.modeling_mam_aaa import shift_tokens_right _lowerCamelCase : Optional[int] = 25_6047 _lowerCamelCase : Dict = 25_6145 @require_sentencepiece @require_tokenizers class SCREAMING_SNAKE_CASE ( _a , unittest.TestCase ): """simple docstring""" _SCREAMING_SNAKE_CASE = NllbTokenizer _SCREAMING_SNAKE_CASE = NllbTokenizerFast _SCREAMING_SNAKE_CASE = True _SCREAMING_SNAKE_CASE = True _SCREAMING_SNAKE_CASE = {} def A ( self : Optional[int] ): """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing UpperCamelCase = NllbTokenizer(UpperCamelCase__ , keep_accents=UpperCamelCase__ ) tokenizer.save_pretrained(self.tmpdirname ) def A ( self : int ): """simple docstring""" UpperCamelCase = NllbTokenizer(UpperCamelCase__ , keep_accents=UpperCamelCase__ ) UpperCamelCase = tokenizer.tokenize('This is a test' ) self.assertListEqual(UpperCamelCase__ , ['▁This', '▁is', '▁a', '▁t', 'est'] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(UpperCamelCase__ ) , [value + tokenizer.fairseq_offset for value in [2_8_5, 4_6, 1_0, 1_7_0, 3_8_2]] , ) UpperCamelCase = tokenizer.tokenize('I was born in 92000, and this is falsé.' ) self.assertListEqual( UpperCamelCase__ , [ SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '9', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', 'é', '.', ] , ) UpperCamelCase = tokenizer.convert_tokens_to_ids(UpperCamelCase__ ) self.assertListEqual( UpperCamelCase__ , [ value + tokenizer.fairseq_offset for value in [8, 2_1, 8_4, 5_5, 2_4, 1_9, 7, 2, 6_0_2, 3_4_7, 3_4_7, 3_4_7, 3, 1_2, 6_6, 4_6, 7_2, 8_0, 6, 2, 4] ] , ) UpperCamelCase = tokenizer.convert_ids_to_tokens(UpperCamelCase__ ) self.assertListEqual( UpperCamelCase__ , [ SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '<unk>', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', '<unk>', '.', ] , ) def A ( self : Dict ): """simple docstring""" UpperCamelCase = (self.rust_tokenizer_class, 'hf-internal-testing/tiny-random-nllb', {}) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): UpperCamelCase = self.rust_tokenizer_class.from_pretrained(UpperCamelCase__ , **UpperCamelCase__ ) UpperCamelCase = self.tokenizer_class.from_pretrained(UpperCamelCase__ , **UpperCamelCase__ ) UpperCamelCase = tempfile.mkdtemp() UpperCamelCase = tokenizer_r.save_pretrained(UpperCamelCase__ ) UpperCamelCase = tokenizer_p.save_pretrained(UpperCamelCase__ ) # Checks it save with the same files + the tokenizer.json file for the fast one self.assertTrue(any('tokenizer.json' in f for f in tokenizer_r_files ) ) UpperCamelCase = tuple(f for f in tokenizer_r_files if 'tokenizer.json' not in f ) self.assertSequenceEqual(UpperCamelCase__ , UpperCamelCase__ ) # Checks everything loads correctly in the same way UpperCamelCase = tokenizer_r.from_pretrained(UpperCamelCase__ ) UpperCamelCase = tokenizer_p.from_pretrained(UpperCamelCase__ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(UpperCamelCase__ , UpperCamelCase__ ) ) shutil.rmtree(UpperCamelCase__ ) # Save tokenizer rust, legacy_format=True UpperCamelCase = tempfile.mkdtemp() UpperCamelCase = tokenizer_r.save_pretrained(UpperCamelCase__ , legacy_format=UpperCamelCase__ ) UpperCamelCase = tokenizer_p.save_pretrained(UpperCamelCase__ ) # Checks it save with the same files self.assertSequenceEqual(UpperCamelCase__ , UpperCamelCase__ ) # Checks everything loads correctly in the same way UpperCamelCase = tokenizer_r.from_pretrained(UpperCamelCase__ ) UpperCamelCase = tokenizer_p.from_pretrained(UpperCamelCase__ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(UpperCamelCase__ , UpperCamelCase__ ) ) shutil.rmtree(UpperCamelCase__ ) # Save tokenizer rust, legacy_format=False UpperCamelCase = tempfile.mkdtemp() UpperCamelCase = tokenizer_r.save_pretrained(UpperCamelCase__ , legacy_format=UpperCamelCase__ ) UpperCamelCase = tokenizer_p.save_pretrained(UpperCamelCase__ ) # Checks it saved the tokenizer.json file self.assertTrue(any('tokenizer.json' in f for f in tokenizer_r_files ) ) # Checks everything loads correctly in the same way UpperCamelCase = tokenizer_r.from_pretrained(UpperCamelCase__ ) UpperCamelCase = tokenizer_p.from_pretrained(UpperCamelCase__ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(UpperCamelCase__ , UpperCamelCase__ ) ) shutil.rmtree(UpperCamelCase__ ) @require_torch def A ( self : Dict ): """simple docstring""" if not self.test_seqaseq: return UpperCamelCase = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(f"""{tokenizer.__class__.__name__}""" ): # Longer text that will definitely require truncation. UpperCamelCase = [ ' UN Chief Says There Is No Military Solution in Syria', ' Secretary-General Ban Ki-moon says his response to Russia\'s stepped up military support for' ' Syria is that \'there is no military solution\' to the nearly five-year conflict and more weapons' ' will only worsen the violence and misery for millions of people.', ] UpperCamelCase = [ 'Şeful ONU declară că nu există o soluţie militară în Siria', 'Secretarul General Ban Ki-moon declară că răspunsul său la intensificarea sprijinului militar al' ' Rusiei pentru Siria este că "nu există o soluţie militară" la conflictul de aproape cinci ani şi' ' că noi arme nu vor face decât să înrăutăţească violenţele şi mizeria pentru milioane de oameni.', ] try: UpperCamelCase = tokenizer.prepare_seqaseq_batch( src_texts=UpperCamelCase__ , tgt_texts=UpperCamelCase__ , max_length=3 , max_target_length=1_0 , return_tensors='pt' , src_lang='eng_Latn' , tgt_lang='ron_Latn' , ) except NotImplementedError: return self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.labels.shape[1] , 1_0 ) # max_target_length will default to max_length if not specified UpperCamelCase = tokenizer.prepare_seqaseq_batch( UpperCamelCase__ , tgt_texts=UpperCamelCase__ , max_length=3 , return_tensors='pt' ) self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.labels.shape[1] , 3 ) UpperCamelCase = tokenizer.prepare_seqaseq_batch( src_texts=UpperCamelCase__ , max_length=3 , max_target_length=1_0 , return_tensors='pt' ) self.assertEqual(batch_encoder_only.input_ids.shape[1] , 3 ) self.assertEqual(batch_encoder_only.attention_mask.shape[1] , 3 ) self.assertNotIn('decoder_input_ids' , UpperCamelCase__ ) @unittest.skip('Unfortunately way too slow to build a BPE with SentencePiece.' ) def A ( self : Optional[int] ): """simple docstring""" pass def A ( self : Optional[int] ): """simple docstring""" for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): UpperCamelCase = [AddedToken('<special>' , lstrip=UpperCamelCase__ )] UpperCamelCase = self.rust_tokenizer_class.from_pretrained( UpperCamelCase__ , additional_special_tokens=UpperCamelCase__ , **UpperCamelCase__ ) UpperCamelCase = tokenizer_r.encode('Hey this is a <special> token' ) UpperCamelCase = tokenizer_r.encode('<special>' , add_special_tokens=UpperCamelCase__ )[0] self.assertTrue(special_token_id in r_output ) if self.test_slow_tokenizer: UpperCamelCase = self.rust_tokenizer_class.from_pretrained( UpperCamelCase__ , additional_special_tokens=UpperCamelCase__ , **UpperCamelCase__ , ) UpperCamelCase = self.tokenizer_class.from_pretrained( UpperCamelCase__ , additional_special_tokens=UpperCamelCase__ , **UpperCamelCase__ ) UpperCamelCase = tokenizer_p.encode('Hey this is a <special> token' ) UpperCamelCase = tokenizer_cr.encode('Hey this is a <special> token' ) self.assertEqual(UpperCamelCase__ , UpperCamelCase__ ) self.assertEqual(UpperCamelCase__ , UpperCamelCase__ ) self.assertTrue(special_token_id in p_output ) self.assertTrue(special_token_id in cr_output ) @require_torch @require_sentencepiece @require_tokenizers class SCREAMING_SNAKE_CASE ( unittest.TestCase ): """simple docstring""" _SCREAMING_SNAKE_CASE = """facebook/nllb-200-distilled-600M""" _SCREAMING_SNAKE_CASE = [ """ UN Chief Says There Is No Military Solution in Syria""", """ Secretary-General Ban Ki-moon says his response to Russia's stepped up military support for Syria is that \"there is no military solution\" to the nearly five-year conflict and more weapons will only worsen the violence and misery for millions of people.""", ] _SCREAMING_SNAKE_CASE = [ """Şeful ONU declară că nu există o soluţie militară în Siria""", """Secretarul General Ban Ki-moon declară că răspunsul său la intensificarea sprijinului militar al Rusiei""" """ pentru Siria este că \"nu există o soluţie militară\" la conflictul de aproape cinci ani şi că noi arme nu vor""" """ face decât să înrăutăţească violenţele şi mizeria pentru milioane de oameni.""", ] _SCREAMING_SNAKE_CASE = [ 256_047, 16_297, 134_408, 8_165, 248_066, 14_734, 950, 1_135, 105_721, 3_573, 83, 27_352, 108, 49_486, 2, ] @classmethod def A ( cls : str ): """simple docstring""" UpperCamelCase = NllbTokenizer.from_pretrained( cls.checkpoint_name , src_lang='eng_Latn' , tgt_lang='ron_Latn' ) UpperCamelCase = 1 return cls def A ( self : Union[str, Any] ): """simple docstring""" self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['ace_Arab'] , 2_5_6_0_0_1 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['ace_Latn'] , 2_5_6_0_0_2 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['fra_Latn'] , 2_5_6_0_5_7 ) def A ( self : Optional[Any] ): """simple docstring""" UpperCamelCase = self.tokenizer.batch_encode_plus(self.src_text ).input_ids[0] self.assertListEqual(self.expected_src_tokens , UpperCamelCase__ ) def A ( self : Any ): """simple docstring""" self.assertIn(UpperCamelCase__ , self.tokenizer.all_special_ids ) # fmt: off UpperCamelCase = [RO_CODE, 4_2_5_4, 9_8_0_6_8, 1_1_2_9_2_3, 3_9_0_7_2, 3_9_0_9, 7_1_3, 1_0_2_7_6_7, 2_6, 1_7_3_1_4, 3_5_6_4_2, 1_4_6_8_3, 3_3_1_1_8, 2_0_2_2, 6_6_9_8_7, 2, 2_5_6_0_4_7] # fmt: on UpperCamelCase = self.tokenizer.decode(UpperCamelCase__ , skip_special_tokens=UpperCamelCase__ ) UpperCamelCase = self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=UpperCamelCase__ ) self.assertEqual(UpperCamelCase__ , UpperCamelCase__ ) self.assertNotIn(self.tokenizer.eos_token , UpperCamelCase__ ) def A ( self : Optional[Any] ): """simple docstring""" UpperCamelCase = ['this is gunna be a long sentence ' * 2_0] assert isinstance(src_text[0] , UpperCamelCase__ ) UpperCamelCase = 1_0 UpperCamelCase = self.tokenizer(UpperCamelCase__ , max_length=UpperCamelCase__ , truncation=UpperCamelCase__ ).input_ids[0] self.assertEqual(ids[-1] , 2 ) self.assertEqual(ids[0] , UpperCamelCase__ ) self.assertEqual(len(UpperCamelCase__ ) , UpperCamelCase__ ) def A ( self : int ): """simple docstring""" self.assertListEqual(self.tokenizer.convert_tokens_to_ids(['<mask>', 'ar_AR'] ) , [2_5_6_2_0_3, 3] ) def A ( self : List[str] ): """simple docstring""" UpperCamelCase = tempfile.mkdtemp() UpperCamelCase = self.tokenizer.fairseq_tokens_to_ids self.tokenizer.save_pretrained(UpperCamelCase__ ) UpperCamelCase = NllbTokenizer.from_pretrained(UpperCamelCase__ ) self.assertDictEqual(new_tok.fairseq_tokens_to_ids , UpperCamelCase__ ) @require_torch def A ( self : Any ): """simple docstring""" UpperCamelCase = self.tokenizer( self.src_text , text_target=self.tgt_text , padding=UpperCamelCase__ , truncation=UpperCamelCase__ , max_length=len(self.expected_src_tokens ) , return_tensors='pt' , ) UpperCamelCase = shift_tokens_right( batch['labels'] , self.tokenizer.pad_token_id , self.tokenizer.lang_code_to_id['ron_Latn'] ) self.assertIsInstance(UpperCamelCase__ , UpperCamelCase__ ) self.assertEqual((2, 1_5) , batch.input_ids.shape ) self.assertEqual((2, 1_5) , batch.attention_mask.shape ) UpperCamelCase = batch.input_ids.tolist()[0] self.assertListEqual(self.expected_src_tokens , UpperCamelCase__ ) self.assertEqual(UpperCamelCase__ , batch.decoder_input_ids[0, 0] ) # EOS # Test that special tokens are reset self.assertEqual(self.tokenizer.prefix_tokens , [EN_CODE] ) self.assertEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id] ) def A ( self : Union[str, Any] ): """simple docstring""" UpperCamelCase = self.tokenizer(self.src_text , padding=UpperCamelCase__ , truncation=UpperCamelCase__ , max_length=3 , return_tensors='pt' ) UpperCamelCase = self.tokenizer( text_target=self.tgt_text , padding=UpperCamelCase__ , truncation=UpperCamelCase__ , max_length=1_0 , return_tensors='pt' ) UpperCamelCase = targets['input_ids'] UpperCamelCase = shift_tokens_right( UpperCamelCase__ , self.tokenizer.pad_token_id , decoder_start_token_id=self.tokenizer.lang_code_to_id[self.tokenizer.tgt_lang] , ) self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.decoder_input_ids.shape[1] , 1_0 ) @require_torch def A ( self : str ): """simple docstring""" UpperCamelCase = self.tokenizer._build_translation_inputs( 'A test' , return_tensors='pt' , src_lang='eng_Latn' , tgt_lang='fra_Latn' ) self.assertEqual( nested_simplify(UpperCamelCase__ ) , { # A, test, EOS, en_XX 'input_ids': [[2_5_6_0_4_7, 7_0, 7_3_5_6, 2]], 'attention_mask': [[1, 1, 1, 1]], # ar_AR 'forced_bos_token_id': 2_5_6_0_5_7, } , ) @require_torch def A ( self : Dict ): """simple docstring""" UpperCamelCase = True UpperCamelCase = self.tokenizer( 'UN Chief says there is no military solution in Syria' , src_lang='eng_Latn' , tgt_lang='fra_Latn' ) self.assertEqual( inputs.input_ids , [1_6_2_9_7, 1_3_4_4_0_8, 2_5_6_5_3, 6_3_7_0, 2_4_8, 2_5_4, 1_0_3_9_2_9, 9_4_9_9_5, 1_0_8, 4_9_4_8_6, 2, 2_5_6_0_4_7] ) UpperCamelCase = False UpperCamelCase = self.tokenizer( 'UN Chief says there is no military solution in Syria' , src_lang='eng_Latn' , tgt_lang='fra_Latn' ) self.assertEqual( inputs.input_ids , [2_5_6_0_4_7, 1_6_2_9_7, 1_3_4_4_0_8, 2_5_6_5_3, 6_3_7_0, 2_4_8, 2_5_4, 1_0_3_9_2_9, 9_4_9_9_5, 1_0_8, 4_9_4_8_6, 2] )
28
import json import os import subprocess import unittest from ast import literal_eval import pytest from parameterized import parameterized, parameterized_class from . import is_sagemaker_available if is_sagemaker_available(): from sagemaker import Session, TrainingJobAnalytics from sagemaker.huggingface import HuggingFace @pytest.mark.skipif( literal_eval(os.getenv('''TEST_SAGEMAKER''' , '''False''' ) ) is not True , reason='''Skipping test because should only be run when releasing minor transformers version''' , ) @pytest.mark.usefixtures('''sm_env''' ) @parameterized_class( [ { '''framework''': '''pytorch''', '''script''': '''run_glue_model_parallelism.py''', '''model_name_or_path''': '''roberta-large''', '''instance_type''': '''ml.p3dn.24xlarge''', '''results''': {'''train_runtime''': 1_600, '''eval_accuracy''': 0.3, '''eval_loss''': 1.2}, }, { '''framework''': '''pytorch''', '''script''': '''run_glue.py''', '''model_name_or_path''': '''roberta-large''', '''instance_type''': '''ml.p3dn.24xlarge''', '''results''': {'''train_runtime''': 1_600, '''eval_accuracy''': 0.3, '''eval_loss''': 1.2}, }, ] ) class A_ ( unittest.TestCase ): def lowerCAmelCase ( self : Union[str, Any]): if self.framework == "pytorch": subprocess.run( F"cp ./examples/pytorch/text-classification/run_glue.py {self.env.test_path}/run_glue.py".split() ,encoding='utf-8' ,check=SCREAMING_SNAKE_CASE__ ,) assert hasattr(self ,'env') def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : int): # configuration for running training on smdistributed Model Parallel __lowerCamelCase : Any = { 'enabled': True, 'processes_per_host': 8, } __lowerCamelCase : List[Any] = { 'enabled': True, 'parameters': { 'microbatches': 4, 'placement_strategy': 'spread', 'pipeline': 'interleaved', 'optimize': 'speed', 'partitions': 4, 'ddp': True, }, } __lowerCamelCase : str = {'smdistributed': {'modelparallel': smp_options}, 'mpi': mpi_options} __lowerCamelCase : List[str] = 'trainer' if self.script == 'run_glue.py' else 'smtrainer' # creates estimator return HuggingFace( entry_point=self.script ,source_dir=self.env.test_path ,role=self.env.role ,image_uri=self.env.image_uri ,base_job_name=F"{self.env.base_job_name}-{instance_count}-smp-{name_extension}" ,instance_count=SCREAMING_SNAKE_CASE__ ,instance_type=self.instance_type ,debugger_hook_config=SCREAMING_SNAKE_CASE__ ,hyperparameters={ **self.env.hyperparameters, 'model_name_or_path': self.model_name_or_path, 'max_steps': 5_0_0, } ,metric_definitions=self.env.metric_definitions ,distribution=SCREAMING_SNAKE_CASE__ ,py_version='py36' ,) def lowerCAmelCase ( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : Any): TrainingJobAnalytics(SCREAMING_SNAKE_CASE__).export_csv(F"{self.env.test_path}/{job_name}_metrics.csv") @parameterized.expand([(1,)]) def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : Optional[Any]): # create estimator __lowerCamelCase : str = self.create_estimator(SCREAMING_SNAKE_CASE__) # run training estimator.fit() # result dataframe __lowerCamelCase : List[str] = TrainingJobAnalytics(estimator.latest_training_job.name).dataframe() # extract kpis __lowerCamelCase : Optional[int] = list(result_metrics_df[result_metrics_df.metric_name == 'eval_accuracy']['value']) __lowerCamelCase : Any = list(result_metrics_df[result_metrics_df.metric_name == 'eval_loss']['value']) # get train time from SageMaker job, this includes starting, preprocessing, stopping __lowerCamelCase : str = ( Session().describe_training_job(estimator.latest_training_job.name).get('TrainingTimeInSeconds' ,9_9_9_9_9_9) ) # assert kpis assert train_runtime <= self.results["train_runtime"] assert all(t >= self.results['eval_accuracy'] for t in eval_accuracy) assert all(t <= self.results['eval_loss'] for t in eval_loss) # dump tests result into json file to share in PR with open(F"{estimator.latest_training_job.name}.json" ,'w') as outfile: json.dump({'train_time': train_runtime, 'eval_accuracy': eval_accuracy, 'eval_loss': eval_loss} ,SCREAMING_SNAKE_CASE__)
73
0
import inspect import unittest from transformers import DPTConfig from transformers.file_utils import is_torch_available, is_vision_available from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_vision, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import MODEL_MAPPING, DPTForDepthEstimation, DPTForSemanticSegmentation, DPTModel from transformers.models.dpt.modeling_dpt import DPT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import DPTImageProcessor class lowerCamelCase : '''simple docstring''' def __init__( self , _UpperCamelCase , _UpperCamelCase=2 , _UpperCamelCase=3_2 , _UpperCamelCase=1_6 , _UpperCamelCase=3 , _UpperCamelCase=True , _UpperCamelCase=True , _UpperCamelCase=3_2 , _UpperCamelCase=4 , _UpperCamelCase=[0, 1, 2, 3] , _UpperCamelCase=4 , _UpperCamelCase=3_7 , _UpperCamelCase="gelu" , _UpperCamelCase=0.1 , _UpperCamelCase=0.1 , _UpperCamelCase=0.02 , _UpperCamelCase=3 , _UpperCamelCase=[1, 3_8_4, 2_4, 2_4] , _UpperCamelCase=True , _UpperCamelCase=None , ) -> List[str]: UpperCAmelCase_ : Any = parent UpperCAmelCase_ : Dict = batch_size UpperCAmelCase_ : Optional[Any] = image_size UpperCAmelCase_ : Union[str, Any] = patch_size UpperCAmelCase_ : List[Any] = num_channels UpperCAmelCase_ : int = is_training UpperCAmelCase_ : List[str] = use_labels UpperCAmelCase_ : Optional[int] = hidden_size UpperCAmelCase_ : Dict = num_hidden_layers UpperCAmelCase_ : Dict = backbone_out_indices UpperCAmelCase_ : Tuple = num_attention_heads UpperCAmelCase_ : List[str] = intermediate_size UpperCAmelCase_ : Dict = hidden_act UpperCAmelCase_ : List[str] = hidden_dropout_prob UpperCAmelCase_ : int = attention_probs_dropout_prob UpperCAmelCase_ : int = initializer_range UpperCAmelCase_ : Dict = num_labels UpperCAmelCase_ : List[Any] = backbone_featmap_shape UpperCAmelCase_ : Tuple = scope UpperCAmelCase_ : int = is_hybrid # sequence length of DPT = num_patches + 1 (we add 1 for the [CLS] token) UpperCAmelCase_ : List[Any] = (image_size // patch_size) ** 2 UpperCAmelCase_ : Tuple = num_patches + 1 def __UpperCAmelCase ( self ) -> int: UpperCAmelCase_ : Optional[int] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) UpperCAmelCase_ : Optional[Any] = None if self.use_labels: UpperCAmelCase_ : Optional[Any] = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels ) UpperCAmelCase_ : Optional[Any] = self.get_config() return config, pixel_values, labels def __UpperCAmelCase ( self ) -> Any: UpperCAmelCase_ : str = { 'global_padding': 'same', 'layer_type': 'bottleneck', 'depths': [3, 4, 9], 'out_features': ['stage1', 'stage2', 'stage3'], 'embedding_dynamic_padding': True, 'hidden_sizes': [9_6, 1_9_2, 3_8_4, 7_6_8], 'num_groups': 2, } return DPTConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , backbone_out_indices=self.backbone_out_indices , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=_UpperCamelCase , initializer_range=self.initializer_range , is_hybrid=self.is_hybrid , backbone_config=_UpperCamelCase , backbone_featmap_shape=self.backbone_featmap_shape , ) def __UpperCAmelCase ( self , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) -> Tuple: UpperCAmelCase_ : Tuple = DPTModel(config=_UpperCamelCase ) model.to(_UpperCamelCase ) model.eval() UpperCAmelCase_ : Optional[int] = model(_UpperCamelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __UpperCAmelCase ( self , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) -> Tuple: UpperCAmelCase_ : Optional[Any] = self.num_labels UpperCAmelCase_ : Any = DPTForDepthEstimation(_UpperCamelCase ) model.to(_UpperCamelCase ) model.eval() UpperCAmelCase_ : str = model(_UpperCamelCase ) self.parent.assertEqual(result.predicted_depth.shape , (self.batch_size, self.image_size, self.image_size) ) def __UpperCAmelCase ( self , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) -> List[Any]: UpperCAmelCase_ : Union[str, Any] = self.num_labels UpperCAmelCase_ : List[Any] = DPTForSemanticSegmentation(_UpperCamelCase ) model.to(_UpperCamelCase ) model.eval() UpperCAmelCase_ : int = model(_UpperCamelCase , labels=_UpperCamelCase ) self.parent.assertEqual( result.logits.shape , (self.batch_size, self.num_labels, self.image_size, self.image_size) ) def __UpperCAmelCase ( self ) -> Optional[Any]: UpperCAmelCase_ : List[str] = self.prepare_config_and_inputs() UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ : Optional[int] = config_and_inputs UpperCAmelCase_ : Tuple = {'pixel_values': pixel_values} return config, inputs_dict @require_torch class lowerCamelCase (_snake_case , _snake_case , unittest.TestCase ): '''simple docstring''' _snake_case : int = (DPTModel, DPTForDepthEstimation, DPTForSemanticSegmentation) if is_torch_available() else () _snake_case : List[str] = ( { '''depth-estimation''': DPTForDepthEstimation, '''feature-extraction''': DPTModel, '''image-segmentation''': DPTForSemanticSegmentation, } if is_torch_available() else {} ) _snake_case : Optional[int] = False _snake_case : List[str] = False _snake_case : Union[str, Any] = False def __UpperCAmelCase ( self ) -> Optional[Any]: UpperCAmelCase_ : List[Any] = DPTModelTester(self ) UpperCAmelCase_ : Any = ConfigTester(self , config_class=_UpperCamelCase , has_text_modality=_UpperCamelCase , hidden_size=3_7 ) def __UpperCAmelCase ( self ) -> Tuple: self.config_tester.run_common_tests() @unittest.skip(reason='DPT does not use inputs_embeds' ) def __UpperCAmelCase ( self ) -> str: pass def __UpperCAmelCase ( self ) -> Optional[int]: UpperCAmelCase_ , UpperCAmelCase_ : List[str] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCAmelCase_ : List[str] = model_class(_UpperCamelCase ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) UpperCAmelCase_ : Optional[Any] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(_UpperCamelCase , nn.Linear ) ) def __UpperCAmelCase ( self ) -> Dict: UpperCAmelCase_ , UpperCAmelCase_ : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCAmelCase_ : Dict = model_class(_UpperCamelCase ) UpperCAmelCase_ : List[str] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic UpperCAmelCase_ : Dict = [*signature.parameters.keys()] UpperCAmelCase_ : Optional[int] = ['pixel_values'] self.assertListEqual(arg_names[:1] , _UpperCamelCase ) def __UpperCAmelCase ( self ) -> Optional[int]: UpperCAmelCase_ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_UpperCamelCase ) def __UpperCAmelCase ( self ) -> int: UpperCAmelCase_ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_depth_estimation(*_UpperCamelCase ) def __UpperCAmelCase ( self ) -> List[str]: UpperCAmelCase_ : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*_UpperCamelCase ) def __UpperCAmelCase ( self ) -> Optional[Any]: for model_class in self.all_model_classes: if model_class.__name__ == "DPTForDepthEstimation": continue UpperCAmelCase_ , UpperCAmelCase_ : str = self.model_tester.prepare_config_and_inputs_for_common() UpperCAmelCase_ : str = True if model_class in get_values(_UpperCamelCase ): continue UpperCAmelCase_ : List[Any] = model_class(_UpperCamelCase ) model.to(_UpperCamelCase ) model.train() UpperCAmelCase_ : str = self._prepare_for_class(_UpperCamelCase , _UpperCamelCase , return_labels=_UpperCamelCase ) UpperCAmelCase_ : int = model(**_UpperCamelCase ).loss loss.backward() def __UpperCAmelCase ( self ) -> str: for model_class in self.all_model_classes: if model_class.__name__ == "DPTForDepthEstimation": continue UpperCAmelCase_ , UpperCAmelCase_ : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() UpperCAmelCase_ : List[str] = False UpperCAmelCase_ : int = True if model_class in get_values(_UpperCamelCase ) or not model_class.supports_gradient_checkpointing: continue UpperCAmelCase_ : List[Any] = model_class(_UpperCamelCase ) model.to(_UpperCamelCase ) model.gradient_checkpointing_enable() model.train() UpperCAmelCase_ : Union[str, Any] = self._prepare_for_class(_UpperCamelCase , _UpperCamelCase , return_labels=_UpperCamelCase ) UpperCAmelCase_ : List[str] = model(**_UpperCamelCase ).loss loss.backward() def __UpperCAmelCase ( self ) -> List[Any]: UpperCAmelCase_ , UpperCAmelCase_ : Tuple = self.model_tester.prepare_config_and_inputs_for_common() UpperCAmelCase_ : int = _config_zero_init(_UpperCamelCase ) for model_class in self.all_model_classes: UpperCAmelCase_ : Tuple = model_class(config=_UpperCamelCase ) # Skip the check for the backbone UpperCAmelCase_ : Optional[int] = [] for name, module in model.named_modules(): if module.__class__.__name__ == "DPTViTHybridEmbeddings": UpperCAmelCase_ : Optional[int] = [f"{name}.{key}" for key in module.state_dict().keys()] break for name, param in model.named_parameters(): if param.requires_grad: if name in backbone_params: continue self.assertIn( ((param.data.mean() * 1E9).round() / 1E9).item() , [0.0, 1.0] , msg=f"Parameter {name} of model {model_class} seems not properly initialized" , ) @unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.' ) def __UpperCAmelCase ( self ) -> int: pass @slow def __UpperCAmelCase ( self ) -> Optional[int]: for model_name in DPT_PRETRAINED_MODEL_ARCHIVE_LIST[1:]: UpperCAmelCase_ : Tuple = DPTModel.from_pretrained(_UpperCamelCase ) self.assertIsNotNone(_UpperCamelCase ) def __UpperCAmelCase ( self ) -> str: # We do this test only for DPTForDepthEstimation since it is the only model that uses readout_type UpperCAmelCase_ , UpperCAmelCase_ : Any = self.model_tester.prepare_config_and_inputs_for_common() UpperCAmelCase_ : Union[str, Any] = 'add' with self.assertRaises(_UpperCamelCase ): UpperCAmelCase_ : Any = DPTForDepthEstimation(_UpperCamelCase ) def lowercase__ ( ): '''simple docstring''' UpperCAmelCase_ : Optional[Any] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_torch @require_vision @slow class lowerCamelCase (unittest.TestCase ): '''simple docstring''' def __UpperCAmelCase ( self ) -> Optional[Any]: UpperCAmelCase_ : int = DPTImageProcessor.from_pretrained('Intel/dpt-hybrid-midas' ) UpperCAmelCase_ : int = DPTForDepthEstimation.from_pretrained('Intel/dpt-hybrid-midas' ).to(_UpperCamelCase ) UpperCAmelCase_ : str = prepare_img() UpperCAmelCase_ : List[Any] = image_processor(images=_UpperCamelCase , return_tensors='pt' ).to(_UpperCamelCase ) # forward pass with torch.no_grad(): UpperCAmelCase_ : Optional[Any] = model(**_UpperCamelCase ) UpperCAmelCase_ : Dict = outputs.predicted_depth # verify the predicted depth UpperCAmelCase_ : Optional[int] = torch.Size((1, 3_8_4, 3_8_4) ) self.assertEqual(predicted_depth.shape , _UpperCamelCase ) UpperCAmelCase_ : Optional[int] = torch.tensor( [[[5.64_37, 5.61_46, 5.65_11], [5.43_71, 5.56_49, 5.59_58], [5.52_15, 5.51_84, 5.52_93]]] ).to(_UpperCamelCase ) self.assertTrue(torch.allclose(outputs.predicted_depth[:3, :3, :3] / 1_0_0 , _UpperCamelCase , atol=1E-4 ) )
29
import unittest import numpy as np from transformers import DistilBertConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask if is_flax_available(): import jax.numpy as jnp from transformers.models.distilbert.modeling_flax_distilbert import ( FlaxDistilBertForMaskedLM, FlaxDistilBertForMultipleChoice, FlaxDistilBertForQuestionAnswering, FlaxDistilBertForSequenceClassification, FlaxDistilBertForTokenClassification, FlaxDistilBertModel, ) class A_ ( unittest.TestCase ): def __init__( self : Tuple ,SCREAMING_SNAKE_CASE__ : List[str] ,SCREAMING_SNAKE_CASE__ : Any=1_3 ,SCREAMING_SNAKE_CASE__ : int=7 ,SCREAMING_SNAKE_CASE__ : str=True ,SCREAMING_SNAKE_CASE__ : Dict=True ,SCREAMING_SNAKE_CASE__ : str=True ,SCREAMING_SNAKE_CASE__ : Dict=True ,SCREAMING_SNAKE_CASE__ : List[Any]=9_9 ,SCREAMING_SNAKE_CASE__ : List[Any]=3_2 ,SCREAMING_SNAKE_CASE__ : int=5 ,SCREAMING_SNAKE_CASE__ : List[Any]=4 ,SCREAMING_SNAKE_CASE__ : Optional[Any]=3_7 ,SCREAMING_SNAKE_CASE__ : Union[str, Any]="gelu" ,SCREAMING_SNAKE_CASE__ : int=0.1 ,SCREAMING_SNAKE_CASE__ : Optional[int]=0.1 ,SCREAMING_SNAKE_CASE__ : Optional[int]=5_1_2 ,SCREAMING_SNAKE_CASE__ : Dict=1_6 ,SCREAMING_SNAKE_CASE__ : Dict=2 ,SCREAMING_SNAKE_CASE__ : Optional[int]=0.02 ,SCREAMING_SNAKE_CASE__ : Dict=4 ,): __lowerCamelCase : int = parent __lowerCamelCase : Dict = batch_size __lowerCamelCase : Union[str, Any] = seq_length __lowerCamelCase : List[Any] = is_training __lowerCamelCase : Tuple = use_attention_mask __lowerCamelCase : List[str] = use_token_type_ids __lowerCamelCase : Any = use_labels __lowerCamelCase : List[str] = vocab_size __lowerCamelCase : Any = hidden_size __lowerCamelCase : Tuple = num_hidden_layers __lowerCamelCase : Union[str, Any] = num_attention_heads __lowerCamelCase : Union[str, Any] = intermediate_size __lowerCamelCase : List[Any] = hidden_act __lowerCamelCase : int = hidden_dropout_prob __lowerCamelCase : int = attention_probs_dropout_prob __lowerCamelCase : Union[str, Any] = max_position_embeddings __lowerCamelCase : Union[str, Any] = type_vocab_size __lowerCamelCase : List[str] = type_sequence_label_size __lowerCamelCase : Tuple = initializer_range __lowerCamelCase : Optional[int] = num_choices def lowerCAmelCase ( self : Union[str, Any]): __lowerCamelCase : Dict = ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size) __lowerCamelCase : Union[str, Any] = None if self.use_attention_mask: __lowerCamelCase : Any = random_attention_mask([self.batch_size, self.seq_length]) __lowerCamelCase : str = DistilBertConfig( vocab_size=self.vocab_size ,dim=self.hidden_size ,n_layers=self.num_hidden_layers ,n_heads=self.num_attention_heads ,hidden_dim=self.intermediate_size ,hidden_act=self.hidden_act ,dropout=self.hidden_dropout_prob ,attention_dropout=self.attention_probs_dropout_prob ,max_position_embeddings=self.max_position_embeddings ,initializer_range=self.initializer_range ,tie_weights_=SCREAMING_SNAKE_CASE__ ,) return config, input_ids, attention_mask def lowerCAmelCase ( self : List[Any]): __lowerCamelCase : List[str] = self.prepare_config_and_inputs() __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : Dict = config_and_inputs __lowerCamelCase : Any = {'input_ids': input_ids, 'attention_mask': attention_mask} return config, inputs_dict @require_flax class A_ ( SCREAMING_SNAKE_CASE , unittest.TestCase ): _UpperCAmelCase : Dict = ( ( FlaxDistilBertModel, FlaxDistilBertForMaskedLM, FlaxDistilBertForMultipleChoice, FlaxDistilBertForQuestionAnswering, FlaxDistilBertForSequenceClassification, FlaxDistilBertForTokenClassification, FlaxDistilBertForQuestionAnswering, ) if is_flax_available() else () ) def lowerCAmelCase ( self : Optional[Any]): __lowerCamelCase : Tuple = FlaxDistilBertModelTester(self) @slow def lowerCAmelCase ( self : int): for model_class_name in self.all_model_classes: __lowerCamelCase : List[Any] = model_class_name.from_pretrained('distilbert-base-uncased') __lowerCamelCase : List[str] = model(np.ones((1, 1))) self.assertIsNotNone(SCREAMING_SNAKE_CASE__) @require_flax class A_ ( unittest.TestCase ): @slow def lowerCAmelCase ( self : str): __lowerCamelCase : Union[str, Any] = FlaxDistilBertModel.from_pretrained('distilbert-base-uncased') __lowerCamelCase : str = np.array([[0, 3_4_5, 2_3_2, 3_2_8, 7_4_0, 1_4_0, 1_6_9_5, 6_9, 6_0_7_8, 1_5_8_8, 2]]) __lowerCamelCase : List[Any] = np.array([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]) __lowerCamelCase : Union[str, Any] = model(SCREAMING_SNAKE_CASE__ ,attention_mask=SCREAMING_SNAKE_CASE__)[0] __lowerCamelCase : Optional[int] = (1, 1_1, 7_6_8) self.assertEqual(output.shape ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Union[str, Any] = np.array([[[-0.1639, 0.3299, 0.1648], [-0.1746, 0.3289, 0.1710], [-0.1884, 0.3357, 0.1810]]]) self.assertTrue(jnp.allclose(output[:, 1:4, 1:4] ,SCREAMING_SNAKE_CASE__ ,atol=1E-4))
73
0
import json import os from functools import lru_cache from typing import List, Optional, Tuple import regex as re from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging __a = logging.get_logger(__name__) __a = {'vocab_file': 'vocab.json', 'merges_file': 'merges.txt'} __a = { 'vocab_file': { 'allenai/longformer-base-4096': 'https://huggingface.co/allenai/longformer-base-4096/resolve/main/vocab.json', 'allenai/longformer-large-4096': ( 'https://huggingface.co/allenai/longformer-large-4096/resolve/main/vocab.json' ), 'allenai/longformer-large-4096-finetuned-triviaqa': ( 'https://huggingface.co/allenai/longformer-large-4096-finetuned-triviaqa/resolve/main/vocab.json' ), 'allenai/longformer-base-4096-extra.pos.embd.only': ( 'https://huggingface.co/allenai/longformer-base-4096-extra.pos.embd.only/resolve/main/vocab.json' ), 'allenai/longformer-large-4096-extra.pos.embd.only': ( 'https://huggingface.co/allenai/longformer-large-4096-extra.pos.embd.only/resolve/main/vocab.json' ), }, 'merges_file': { 'allenai/longformer-base-4096': 'https://huggingface.co/allenai/longformer-base-4096/resolve/main/merges.txt', 'allenai/longformer-large-4096': ( 'https://huggingface.co/allenai/longformer-large-4096/resolve/main/merges.txt' ), 'allenai/longformer-large-4096-finetuned-triviaqa': ( 'https://huggingface.co/allenai/longformer-large-4096-finetuned-triviaqa/resolve/main/merges.txt' ), 'allenai/longformer-base-4096-extra.pos.embd.only': ( 'https://huggingface.co/allenai/longformer-base-4096-extra.pos.embd.only/resolve/main/merges.txt' ), 'allenai/longformer-large-4096-extra.pos.embd.only': ( 'https://huggingface.co/allenai/longformer-large-4096-extra.pos.embd.only/resolve/main/merges.txt' ), }, } __a = { 'allenai/longformer-base-4096': 4_0_9_6, 'allenai/longformer-large-4096': 4_0_9_6, 'allenai/longformer-large-4096-finetuned-triviaqa': 4_0_9_6, 'allenai/longformer-base-4096-extra.pos.embd.only': 4_0_9_6, 'allenai/longformer-large-4096-extra.pos.embd.only': 4_0_9_6, } @lru_cache() # Copied from transformers.models.roberta.tokenization_roberta.bytes_to_unicode def a ( ): '''simple docstring''' lowercase_ = ( list(range(ord('''!''' ) , ord('''~''' ) + 1 ) ) + list(range(ord('''¡''' ) , ord('''¬''' ) + 1 ) ) + list(range(ord('''®''' ) , ord('''ÿ''' ) + 1 ) ) ) lowercase_ = bs[:] lowercase_ = 0 for b in range(2**8 ): if b not in bs: bs.append(snake_case__ ) cs.append(2**8 + n ) n += 1 lowercase_ = [chr(snake_case__ ) for n in cs] return dict(zip(snake_case__ , snake_case__ ) ) def a ( snake_case__: Union[str, Any] ): '''simple docstring''' lowercase_ = set() lowercase_ = word[0] for char in word[1:]: pairs.add((prev_char, char) ) lowercase_ = char return pairs class lowercase__( UpperCAmelCase ): """simple docstring""" a :List[Any] = VOCAB_FILES_NAMES a :List[str] = PRETRAINED_VOCAB_FILES_MAP a :List[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES a :Dict = ['input_ids', 'attention_mask'] def __init__( self : Tuple , SCREAMING_SNAKE_CASE_ : Optional[Any] , SCREAMING_SNAKE_CASE_ : Dict , SCREAMING_SNAKE_CASE_ : Optional[Any]="replace" , SCREAMING_SNAKE_CASE_ : Any="<s>" , SCREAMING_SNAKE_CASE_ : Optional[Any]="</s>" , SCREAMING_SNAKE_CASE_ : Any="</s>" , SCREAMING_SNAKE_CASE_ : str="<s>" , SCREAMING_SNAKE_CASE_ : Tuple="<unk>" , SCREAMING_SNAKE_CASE_ : Union[str, Any]="<pad>" , SCREAMING_SNAKE_CASE_ : Optional[Any]="<mask>" , SCREAMING_SNAKE_CASE_ : str=False , **SCREAMING_SNAKE_CASE_ : Optional[Any] , ) -> Any: lowercase_ = AddedToken(SCREAMING_SNAKE_CASE_ , lstrip=SCREAMING_SNAKE_CASE_ , rstrip=SCREAMING_SNAKE_CASE_ ) if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else bos_token lowercase_ = AddedToken(SCREAMING_SNAKE_CASE_ , lstrip=SCREAMING_SNAKE_CASE_ , rstrip=SCREAMING_SNAKE_CASE_ ) if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else eos_token lowercase_ = AddedToken(SCREAMING_SNAKE_CASE_ , lstrip=SCREAMING_SNAKE_CASE_ , rstrip=SCREAMING_SNAKE_CASE_ ) if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else sep_token lowercase_ = AddedToken(SCREAMING_SNAKE_CASE_ , lstrip=SCREAMING_SNAKE_CASE_ , rstrip=SCREAMING_SNAKE_CASE_ ) if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else cls_token lowercase_ = AddedToken(SCREAMING_SNAKE_CASE_ , lstrip=SCREAMING_SNAKE_CASE_ , rstrip=SCREAMING_SNAKE_CASE_ ) if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else unk_token lowercase_ = AddedToken(SCREAMING_SNAKE_CASE_ , lstrip=SCREAMING_SNAKE_CASE_ , rstrip=SCREAMING_SNAKE_CASE_ ) if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else pad_token # Mask token behave like a normal word, i.e. include the space before it lowercase_ = AddedToken(SCREAMING_SNAKE_CASE_ , lstrip=SCREAMING_SNAKE_CASE_ , rstrip=SCREAMING_SNAKE_CASE_ ) if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else mask_token super().__init__( errors=SCREAMING_SNAKE_CASE_ , bos_token=SCREAMING_SNAKE_CASE_ , eos_token=SCREAMING_SNAKE_CASE_ , unk_token=SCREAMING_SNAKE_CASE_ , sep_token=SCREAMING_SNAKE_CASE_ , cls_token=SCREAMING_SNAKE_CASE_ , pad_token=SCREAMING_SNAKE_CASE_ , mask_token=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) with open(SCREAMING_SNAKE_CASE_ , encoding='''utf-8''' ) as vocab_handle: lowercase_ = json.load(SCREAMING_SNAKE_CASE_ ) lowercase_ = {v: k for k, v in self.encoder.items()} lowercase_ = errors # how to handle errors in decoding lowercase_ = bytes_to_unicode() lowercase_ = {v: k for k, v in self.byte_encoder.items()} with open(SCREAMING_SNAKE_CASE_ , encoding='''utf-8''' ) as merges_handle: lowercase_ = merges_handle.read().split('''\n''' )[1:-1] lowercase_ = [tuple(merge.split() ) for merge in bpe_merges] lowercase_ = dict(zip(SCREAMING_SNAKE_CASE_ , range(len(SCREAMING_SNAKE_CASE_ ) ) ) ) lowercase_ = {} lowercase_ = add_prefix_space # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions lowercase_ = re.compile(R'''\'s|\'t|\'re|\'ve|\'m|\'ll|\'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+''' ) @property def _lowercase ( self : str ) -> List[Any]: return len(self.encoder ) def _lowercase ( self : Union[str, Any] ) -> Dict: return dict(self.encoder , **self.added_tokens_encoder ) def _lowercase ( self : Any , SCREAMING_SNAKE_CASE_ : Optional[int] ) -> List[Any]: if token in self.cache: return self.cache[token] lowercase_ = tuple(SCREAMING_SNAKE_CASE_ ) lowercase_ = get_pairs(SCREAMING_SNAKE_CASE_ ) if not pairs: return token while True: lowercase_ = min(SCREAMING_SNAKE_CASE_ , key=lambda SCREAMING_SNAKE_CASE_ : self.bpe_ranks.get(SCREAMING_SNAKE_CASE_ , float('''inf''' ) ) ) if bigram not in self.bpe_ranks: break lowercase_ , lowercase_ = bigram lowercase_ = [] lowercase_ = 0 while i < len(SCREAMING_SNAKE_CASE_ ): try: lowercase_ = word.index(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) lowercase_ = j if word[i] == first and i < len(SCREAMING_SNAKE_CASE_ ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 lowercase_ = tuple(SCREAMING_SNAKE_CASE_ ) lowercase_ = new_word if len(SCREAMING_SNAKE_CASE_ ) == 1: break else: lowercase_ = get_pairs(SCREAMING_SNAKE_CASE_ ) lowercase_ = ''' '''.join(SCREAMING_SNAKE_CASE_ ) lowercase_ = word return word def _lowercase ( self : Union[str, Any] , SCREAMING_SNAKE_CASE_ : Optional[Any] ) -> List[str]: lowercase_ = [] for token in re.findall(self.pat , SCREAMING_SNAKE_CASE_ ): lowercase_ = ''''''.join( self.byte_encoder[b] for b in token.encode('''utf-8''' ) ) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case) bpe_tokens.extend(bpe_token for bpe_token in self.bpe(SCREAMING_SNAKE_CASE_ ).split(''' ''' ) ) return bpe_tokens def _lowercase ( self : Optional[Any] , SCREAMING_SNAKE_CASE_ : Union[str, Any] ) -> List[str]: return self.encoder.get(SCREAMING_SNAKE_CASE_ , self.encoder.get(self.unk_token ) ) def _lowercase ( self : Optional[int] , SCREAMING_SNAKE_CASE_ : Union[str, Any] ) -> Union[str, Any]: return self.decoder.get(SCREAMING_SNAKE_CASE_ ) def _lowercase ( self : Tuple , SCREAMING_SNAKE_CASE_ : Tuple ) -> Union[str, Any]: lowercase_ = ''''''.join(SCREAMING_SNAKE_CASE_ ) lowercase_ = bytearray([self.byte_decoder[c] for c in text] ).decode('''utf-8''' , errors=self.errors ) return text def _lowercase ( self : Union[str, Any] , SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : Optional[str] = None ) -> Tuple[str]: if not os.path.isdir(SCREAMING_SNAKE_CASE_ ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return lowercase_ = os.path.join( SCREAMING_SNAKE_CASE_ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) lowercase_ = os.path.join( SCREAMING_SNAKE_CASE_ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''merges_file'''] ) with open(SCREAMING_SNAKE_CASE_ , '''w''' , encoding='''utf-8''' ) as f: f.write(json.dumps(self.encoder , indent=2 , sort_keys=SCREAMING_SNAKE_CASE_ , ensure_ascii=SCREAMING_SNAKE_CASE_ ) + '''\n''' ) lowercase_ = 0 with open(SCREAMING_SNAKE_CASE_ , '''w''' , encoding='''utf-8''' ) as writer: writer.write('''#version: 0.2\n''' ) for bpe_tokens, token_index in sorted(self.bpe_ranks.items() , key=lambda SCREAMING_SNAKE_CASE_ : kv[1] ): if index != token_index: logger.warning( f'''Saving vocabulary to {merge_file}: BPE merge indices are not consecutive.''' ''' Please check that the tokenizer is not corrupted!''' ) lowercase_ = token_index writer.write(''' '''.join(SCREAMING_SNAKE_CASE_ ) + '''\n''' ) index += 1 return vocab_file, merge_file def _lowercase ( self : int , SCREAMING_SNAKE_CASE_ : List[int] , SCREAMING_SNAKE_CASE_ : Optional[List[int]] = None ) -> List[int]: if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] lowercase_ = [self.cls_token_id] lowercase_ = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def _lowercase ( self : Tuple , SCREAMING_SNAKE_CASE_ : List[int] , SCREAMING_SNAKE_CASE_ : Optional[List[int]] = None , SCREAMING_SNAKE_CASE_ : bool = False ) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=SCREAMING_SNAKE_CASE_ , token_ids_a=SCREAMING_SNAKE_CASE_ , already_has_special_tokens=SCREAMING_SNAKE_CASE_ ) if token_ids_a is None: return [1] + ([0] * len(SCREAMING_SNAKE_CASE_ )) + [1] return [1] + ([0] * len(SCREAMING_SNAKE_CASE_ )) + [1, 1] + ([0] * len(SCREAMING_SNAKE_CASE_ )) + [1] def _lowercase ( self : List[Any] , SCREAMING_SNAKE_CASE_ : List[int] , SCREAMING_SNAKE_CASE_ : Optional[List[int]] = None ) -> List[int]: lowercase_ = [self.sep_token_id] lowercase_ = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def _lowercase ( self : List[Any] , SCREAMING_SNAKE_CASE_ : Dict , SCREAMING_SNAKE_CASE_ : Optional[int]=False , **SCREAMING_SNAKE_CASE_ : List[Any] ) -> str: lowercase_ = kwargs.pop('''add_prefix_space''' , self.add_prefix_space ) if (is_split_into_words or add_prefix_space) and (len(SCREAMING_SNAKE_CASE_ ) > 0 and not text[0].isspace()): lowercase_ = ''' ''' + text return (text, kwargs)
30
import csv import tweepy # Twitter API credentials a ="""""" a ="""""" a ="""""" a ="""""" def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> None: # authorize twitter, initialize tweepy __lowerCamelCase : Tuple = tweepy.OAuthHandler(lowerCamelCase__ , lowerCamelCase__ ) auth.set_access_token(lowerCamelCase__ , lowerCamelCase__ ) __lowerCamelCase : Optional[int] = tweepy.API(lowerCamelCase__ ) # initialize a list to hold all the tweepy Tweets __lowerCamelCase : str = [] # make initial request for most recent tweets (200 is the maximum allowed count) __lowerCamelCase : Union[str, Any] = api.user_timeline(screen_name=lowerCamelCase__ , count=2_0_0 ) # save most recent tweets alltweets.extend(lowerCamelCase__ ) # save the id of the oldest tweet less one __lowerCamelCase : Any = alltweets[-1].id - 1 # keep grabbing tweets until there are no tweets left to grab while len(lowerCamelCase__ ) > 0: print(F"getting tweets before {oldest}" ) # all subsequent requests use the max_id param to prevent duplicates __lowerCamelCase : str = api.user_timeline( screen_name=lowerCamelCase__ , count=2_0_0 , max_id=lowerCamelCase__ ) # save most recent tweets alltweets.extend(lowerCamelCase__ ) # update the id of the oldest tweet less one __lowerCamelCase : Optional[int] = alltweets[-1].id - 1 print(F"...{len(lowerCamelCase__ )} tweets downloaded so far" ) # transform the tweepy tweets into a 2D array that will populate the csv __lowerCamelCase : str = [[tweet.id_str, tweet.created_at, tweet.text] for tweet in alltweets] # write the csv with open(F"new_{screen_name}_tweets.csv" , 'w' ) as f: __lowerCamelCase : Any = csv.writer(lowerCamelCase__ ) writer.writerow(['id', 'created_at', 'text'] ) writer.writerows(lowerCamelCase__ ) if __name__ == "__main__": # pass in the username of the account you want to download get_all_tweets("""FirePing32""")
73
0
'''simple docstring''' from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices __SCREAMING_SNAKE_CASE : List[Any] = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE : str = { """microsoft/resnet-50""": """https://huggingface.co/microsoft/resnet-50/blob/main/config.json""", } class lowerCamelCase_ (snake_case__ , snake_case__ ): '''simple docstring''' __UpperCamelCase: Tuple = "resnet" __UpperCamelCase: Union[str, Any] = ["basic", "bottleneck"] def __init__( self : Tuple , A : Optional[int]=3 , A : Union[str, Any]=64 , A : Dict=[256, 512, 1024, 2048] , A : Tuple=[3, 4, 6, 3] , A : Optional[Any]="bottleneck" , A : int="relu" , A : List[Any]=False , A : Optional[int]=None , A : Union[str, Any]=None , **A : List[Any] , ): super().__init__(**A ) if layer_type not in self.layer_types: raise ValueError(F"""layer_type={layer_type} is not one of {','.join(self.layer_types )}""" ) _UpperCAmelCase : Tuple = num_channels _UpperCAmelCase : int = embedding_size _UpperCAmelCase : Union[str, Any] = hidden_sizes _UpperCAmelCase : int = depths _UpperCAmelCase : Any = layer_type _UpperCAmelCase : Optional[Any] = hidden_act _UpperCAmelCase : Union[str, Any] = downsample_in_first_stage _UpperCAmelCase : Dict = ["stem"] + [F"""stage{idx}""" for idx in range(1 , len(A ) + 1 )] _UpperCAmelCase , _UpperCAmelCase : str = get_aligned_output_features_output_indices( out_features=A , out_indices=A , stage_names=self.stage_names ) class lowerCamelCase_ (snake_case__ ): '''simple docstring''' __UpperCamelCase: List[str] = version.parse("1.11" ) @property def _A ( self : Dict ): return OrderedDict( [ ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}), ] ) @property def _A ( self : Dict ): return 1E-3
31
import numpy as np from scipy.spatial.distance import cdist from sklearn.metrics import fa_score import datasets a ="""\ @inproceedings{kakwani2020indicnlpsuite, title={{IndicNLPSuite: Monolingual Corpora, Evaluation Benchmarks and Pre-trained Multilingual Language Models for Indian Languages}}, author={Divyanshu Kakwani and Anoop Kunchukuttan and Satish Golla and Gokul N.C. and Avik Bhattacharyya and Mitesh M. Khapra and Pratyush Kumar}, year={2020}, booktitle={Findings of EMNLP}, } """ a ="""\ IndicGLUE is a natural language understanding benchmark for Indian languages. It contains a wide variety of tasks and covers 11 major Indian languages - as, bn, gu, hi, kn, ml, mr, or, pa, ta, te. """ a =""" Compute IndicGLUE evaluation metric associated to each IndicGLUE dataset. Args: predictions: list of predictions to score (as int64), except for 'cvit-mkb-clsr' where each prediction is a vector (of float32). references: list of ground truth labels corresponding to the predictions (as int64), except for 'cvit-mkb-clsr' where each reference is a vector (of float32). Returns: depending on the IndicGLUE subset, one or several of: \"accuracy\": Accuracy \"f1\": F1 score \"precision\": Precision@10 Examples: >>> indic_glue_metric = datasets.load_metric('indic_glue', 'wnli') # 'wnli' or any of [\"copa\", \"sna\", \"csqa\", \"wstp\", \"inltkh\", \"bbca\", \"iitp-mr\", \"iitp-pr\", \"actsa-sc\", \"md\"] >>> references = [0, 1] >>> predictions = [0, 1] >>> results = indic_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {'accuracy': 1.0} >>> indic_glue_metric = datasets.load_metric('indic_glue', 'wiki-ner') >>> references = [0, 1] >>> predictions = [0, 1] >>> results = indic_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {'accuracy': 1.0, 'f1': 1.0} >>> indic_glue_metric = datasets.load_metric('indic_glue', 'cvit-mkb-clsr') >>> references = [[0.5, 0.5, 0.5], [0.1, 0.2, 0.3]] >>> predictions = [[0.5, 0.5, 0.5], [0.1, 0.2, 0.3]] >>> results = indic_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {'precision@10': 1.0} """ def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> List[str]: return float((preds == labels).mean() ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> List[str]: __lowerCamelCase : Optional[Any] = simple_accuracy(lowerCamelCase__ , lowerCamelCase__ ) __lowerCamelCase : Tuple = float(fa_score(y_true=lowerCamelCase__ , y_pred=lowerCamelCase__ ) ) return { "accuracy": acc, "f1": fa, } def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> Optional[Any]: __lowerCamelCase : Any = np.array(lowerCamelCase__ ) __lowerCamelCase : List[Any] = np.array(lowerCamelCase__ ) __lowerCamelCase : Any = en_sentvecs.shape[0] # mean centering __lowerCamelCase : Union[str, Any] = en_sentvecs - np.mean(lowerCamelCase__ , axis=0 ) __lowerCamelCase : Dict = in_sentvecs - np.mean(lowerCamelCase__ , axis=0 ) __lowerCamelCase : Optional[int] = cdist(lowerCamelCase__ , lowerCamelCase__ , 'cosine' ) __lowerCamelCase : Optional[Any] = np.array(range(lowerCamelCase__ ) ) __lowerCamelCase : Dict = sim.argsort(axis=1 )[:, :1_0] __lowerCamelCase : Optional[int] = np.any(preds == actual[:, None] , axis=1 ) return float(matches.mean() ) @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class A_ ( datasets.Metric ): def lowerCAmelCase ( self : Optional[Any]): if self.config_name not in [ "wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", "cvit-mkb-clsr", "iitp-mr", "iitp-pr", "actsa-sc", "md", "wiki-ner", ]: raise KeyError( 'You should supply a configuration name selected in ' '["wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", ' '"cvit-mkb-clsr", "iitp-mr", "iitp-pr", "actsa-sc", "md", ' '"wiki-ner"]') return datasets.MetricInfo( description=_DESCRIPTION ,citation=_CITATION ,inputs_description=_KWARGS_DESCRIPTION ,features=datasets.Features( { 'predictions': datasets.Value('int64') if self.config_name != 'cvit-mkb-clsr' else datasets.Sequence(datasets.Value('float32')), 'references': datasets.Value('int64') if self.config_name != 'cvit-mkb-clsr' else datasets.Sequence(datasets.Value('float32')), }) ,codebase_urls=[] ,reference_urls=[] ,format='numpy' if self.config_name != 'cvit-mkb-clsr' else None ,) def lowerCAmelCase ( self : Any ,SCREAMING_SNAKE_CASE__ : Tuple ,SCREAMING_SNAKE_CASE__ : Optional[Any]): if self.config_name == "cvit-mkb-clsr": return {"precision@10": precision_at_aa(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__)} elif self.config_name in ["wiki-ner"]: return acc_and_fa(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) elif self.config_name in [ "wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", "iitp-mr", "iitp-pr", "actsa-sc", "md", ]: return {"accuracy": simple_accuracy(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__)} else: raise KeyError( 'You should supply a configuration name selected in ' '["wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", ' '"cvit-mkb-clsr", "iitp-mr", "iitp-pr", "actsa-sc", "md", ' '"wiki-ner"]')
73
0
import jax.numpy as jnp from ...utils import logging from ..ta.modeling_flax_ta import FlaxTaEncoderModel, FlaxTaForConditionalGeneration, FlaxTaModel from .configuration_mta import MTaConfig UpperCAmelCase_ : Optional[Any] = logging.get_logger(__name__) UpperCAmelCase_ : str = 'T5Config' def SCREAMING_SNAKE_CASE_ ( __A : jnp.array , __A : int , __A : int ) -> jnp.ndarray: """simple docstring""" a_ : Dict = jnp.zeros_like(__A ) a_ : Dict = shifted_input_ids.at[:, 1:].set(input_ids[:, :-1] ) a_ : str = shifted_input_ids.at[:, 0].set(__A ) a_ : int = jnp.where(shifted_input_ids == -1_00 , __A , __A ) return shifted_input_ids class SCREAMING_SNAKE_CASE__ ( lowercase__ ): snake_case__ : str = '''mt5''' snake_case__ : List[Any] = MTaConfig class SCREAMING_SNAKE_CASE__ ( lowercase__ ): snake_case__ : str = '''mt5''' snake_case__ : List[str] = MTaConfig class SCREAMING_SNAKE_CASE__ ( lowercase__ ): snake_case__ : Any = '''mt5''' snake_case__ : Union[str, Any] = MTaConfig
32
from __future__ import annotations from scipy.special import comb # type: ignore class A_ : def __init__( self : List[str] ,SCREAMING_SNAKE_CASE__ : list[tuple[float, float]]): __lowerCamelCase : Union[str, Any] = list_of_points # Degree determines the flexibility of the curve. # Degree = 1 will produce a straight line. __lowerCamelCase : int = len(SCREAMING_SNAKE_CASE__) - 1 def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : float): assert 0 <= t <= 1, "Time t must be between 0 and 1." __lowerCamelCase : list[float] = [] for i in range(len(self.list_of_points)): # basis function for each i output_values.append( comb(self.degree ,SCREAMING_SNAKE_CASE__) * ((1 - t) ** (self.degree - i)) * (t**i)) # the basis must sum up to 1 for it to produce a valid Bezier curve. assert round(sum(SCREAMING_SNAKE_CASE__) ,5) == 1 return output_values def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : float): assert 0 <= t <= 1, "Time t must be between 0 and 1." __lowerCamelCase : Tuple = self.basis_function(SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = 0.0 __lowerCamelCase : Optional[Any] = 0.0 for i in range(len(self.list_of_points)): # For all points, sum up the product of i-th basis function and i-th point. x += basis_function[i] * self.list_of_points[i][0] y += basis_function[i] * self.list_of_points[i][1] return (x, y) def lowerCAmelCase ( self : int ,SCREAMING_SNAKE_CASE__ : float = 0.01): from matplotlib import pyplot as plt # type: ignore __lowerCamelCase : list[float] = [] # x coordinates of points to plot __lowerCamelCase : list[float] = [] # y coordinates of points to plot __lowerCamelCase : Any = 0.0 while t <= 1: __lowerCamelCase : List[Any] = self.bezier_curve_function(SCREAMING_SNAKE_CASE__) to_plot_x.append(value[0]) to_plot_y.append(value[1]) t += step_size __lowerCamelCase : Optional[Any] = [i[0] for i in self.list_of_points] __lowerCamelCase : List[str] = [i[1] for i in self.list_of_points] plt.plot( SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,color='blue' ,label='Curve of Degree ' + str(self.degree) ,) plt.scatter(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,color='red' ,label='Control Points') plt.legend() plt.show() if __name__ == "__main__": import doctest doctest.testmod() BezierCurve([(1, 2), (3, 5)]).plot_curve() # degree 1 BezierCurve([(0, 0), (5, 5), (5, 0)]).plot_curve() # degree 2 BezierCurve([(0, 0), (5, 5), (5, 0), (2.5, -2.5)]).plot_curve() # degree 3
73
0
"""simple docstring""" from __future__ import annotations import bisect def lowercase ( __snake_case : list[int] , __snake_case : int , __snake_case : int = 0 , __snake_case : int = -1 ): if hi < 0: lowercase_ : List[Any] = len(__snake_case ) while lo < hi: lowercase_ : Union[str, Any] = lo + (hi - lo) // 2 if sorted_collection[mid] < item: lowercase_ : str = mid + 1 else: lowercase_ : List[str] = mid return lo def lowercase ( __snake_case : list[int] , __snake_case : int , __snake_case : int = 0 , __snake_case : int = -1 ): if hi < 0: lowercase_ : Any = len(__snake_case ) while lo < hi: lowercase_ : Dict = lo + (hi - lo) // 2 if sorted_collection[mid] <= item: lowercase_ : Optional[int] = mid + 1 else: lowercase_ : Any = mid return lo def lowercase ( __snake_case : list[int] , __snake_case : int , __snake_case : int = 0 , __snake_case : int = -1 ): sorted_collection.insert(bisect_left(__snake_case , __snake_case , __snake_case , __snake_case ) , __snake_case ) def lowercase ( __snake_case : list[int] , __snake_case : int , __snake_case : int = 0 , __snake_case : int = -1 ): sorted_collection.insert(bisect_right(__snake_case , __snake_case , __snake_case , __snake_case ) , __snake_case ) def lowercase ( __snake_case : list[int] , __snake_case : int ): lowercase_ : Optional[int] = 0 lowercase_ : Tuple = len(__snake_case ) - 1 while left <= right: lowercase_ : str = left + (right - left) // 2 lowercase_ : Dict = sorted_collection[midpoint] if current_item == item: return midpoint elif item < current_item: lowercase_ : Dict = midpoint - 1 else: lowercase_ : Tuple = midpoint + 1 return None def lowercase ( __snake_case : list[int] , __snake_case : int ): lowercase_ : int = bisect.bisect_left(__snake_case , __snake_case ) if index != len(__snake_case ) and sorted_collection[index] == item: return index return None def lowercase ( __snake_case : list[int] , __snake_case : int , __snake_case : int , __snake_case : int ): if right < left: return None lowercase_ : List[str] = left + (right - left) // 2 if sorted_collection[midpoint] == item: return midpoint elif sorted_collection[midpoint] > item: return binary_search_by_recursion(__snake_case , __snake_case , __snake_case , midpoint - 1 ) else: return binary_search_by_recursion(__snake_case , __snake_case , midpoint + 1 , __snake_case ) if __name__ == "__main__": __A : Dict = input('''Enter numbers separated by comma:\n''').strip() __A : List[str] = sorted(int(item) for item in user_input.split(''',''')) __A : Optional[int] = int(input('''Enter a single number to be found in the list:\n''')) __A : int = binary_search(collection, target) if result is None: print(F"""{target} was not found in {collection}.""") else: print(F"""{target} was found at position {result} in {collection}.""")
33
from __future__ import annotations import time a =list[tuple[int, int]] a =[ [0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles [0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0], [1, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0], ] a =[[-1, 0], [0, -1], [1, 0], [0, 1]] # up, left, down, right class A_ : def __init__( self : List[str] ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : Node | None): __lowerCamelCase : Tuple = pos_x __lowerCamelCase : List[str] = pos_y __lowerCamelCase : str = (pos_y, pos_x) __lowerCamelCase : str = goal_x __lowerCamelCase : int = goal_y __lowerCamelCase : List[Any] = parent class A_ : def __init__( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : tuple[int, int] ,SCREAMING_SNAKE_CASE__ : tuple[int, int]): __lowerCamelCase : Any = Node(start[1] ,start[0] ,goal[1] ,goal[0] ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = Node(goal[1] ,goal[0] ,goal[1] ,goal[0] ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Union[str, Any] = [self.start] __lowerCamelCase : List[str] = False def lowerCAmelCase ( self : List[Any]): while self.node_queue: __lowerCamelCase : Any = self.node_queue.pop(0) if current_node.pos == self.target.pos: __lowerCamelCase : Dict = True return self.retrace_path(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Tuple = self.get_successors(SCREAMING_SNAKE_CASE__) for node in successors: self.node_queue.append(SCREAMING_SNAKE_CASE__) if not self.reached: return [self.start.pos] return None def lowerCAmelCase ( self : str ,SCREAMING_SNAKE_CASE__ : Node): __lowerCamelCase : Union[str, Any] = [] for action in delta: __lowerCamelCase : Optional[Any] = parent.pos_x + action[1] __lowerCamelCase : Optional[int] = parent.pos_y + action[0] if not (0 <= pos_x <= len(grid[0]) - 1 and 0 <= pos_y <= len(SCREAMING_SNAKE_CASE__) - 1): continue if grid[pos_y][pos_x] != 0: continue successors.append( Node(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,self.target.pos_y ,self.target.pos_x ,SCREAMING_SNAKE_CASE__)) return successors def lowerCAmelCase ( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : Node | None): __lowerCamelCase : List[Any] = node __lowerCamelCase : int = [] while current_node is not None: path.append((current_node.pos_y, current_node.pos_x)) __lowerCamelCase : int = current_node.parent path.reverse() return path class A_ : def __init__( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : int): __lowerCamelCase : int = BreadthFirstSearch(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = BreadthFirstSearch(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = False def lowerCAmelCase ( self : str): while self.fwd_bfs.node_queue or self.bwd_bfs.node_queue: __lowerCamelCase : Any = self.fwd_bfs.node_queue.pop(0) __lowerCamelCase : Any = self.bwd_bfs.node_queue.pop(0) if current_bwd_node.pos == current_fwd_node.pos: __lowerCamelCase : List[str] = True return self.retrace_bidirectional_path( SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = current_bwd_node __lowerCamelCase : int = current_fwd_node __lowerCamelCase : str = { self.fwd_bfs: self.fwd_bfs.get_successors(SCREAMING_SNAKE_CASE__), self.bwd_bfs: self.bwd_bfs.get_successors(SCREAMING_SNAKE_CASE__), } for bfs in [self.fwd_bfs, self.bwd_bfs]: for node in successors[bfs]: bfs.node_queue.append(SCREAMING_SNAKE_CASE__) if not self.reached: return [self.fwd_bfs.start.pos] return None def lowerCAmelCase ( self : Dict ,SCREAMING_SNAKE_CASE__ : Node ,SCREAMING_SNAKE_CASE__ : Node): __lowerCamelCase : List[Any] = self.fwd_bfs.retrace_path(SCREAMING_SNAKE_CASE__) __lowerCamelCase : str = self.bwd_bfs.retrace_path(SCREAMING_SNAKE_CASE__) bwd_path.pop() bwd_path.reverse() __lowerCamelCase : List[Any] = fwd_path + bwd_path return path if __name__ == "__main__": # all coordinates are given in format [y,x] import doctest doctest.testmod() a =(0, 0) a =(len(grid) - 1, len(grid[0]) - 1) for elem in grid: print(elem) a =time.time() a =BreadthFirstSearch(init, goal) a =bfs.search() a =time.time() - start_bfs_time print("""Unidirectional BFS computation time : """, bfs_time) a =time.time() a =BidirectionalBreadthFirstSearch(init, goal) a =bd_bfs.search() a =time.time() - start_bd_bfs_time print("""Bidirectional BFS computation time : """, bd_bfs_time)
73
0
'''simple docstring''' from PIL import Image def snake_case_ (_a : Image , _a : int ): UpperCAmelCase = (2_5_9 * (level + 2_5_5)) / (2_5_5 * (2_5_9 - level)) def contrast(_a : int ) -> int: return int(1_2_8 + factor * (c - 1_2_8) ) return img.point(_a ) if __name__ == "__main__": # Load image with Image.open('image_data/lena.jpg') as img: # Change contrast to 170 A =change_contrast(img, 1_70) cont_img.save('image_data/lena_high_contrast.png', format='png')
34
import qiskit def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> qiskit.result.counts.Counts: __lowerCamelCase : Optional[int] = qiskit.Aer.get_backend('aer_simulator' ) # Create a Quantum Circuit acting on the q register __lowerCamelCase : List[str] = qiskit.QuantumCircuit(lowerCamelCase__ , lowerCamelCase__ ) # Map the quantum measurement to the classical bits circuit.measure([0] , [0] ) # Execute the circuit on the simulator __lowerCamelCase : List[Any] = qiskit.execute(lowerCamelCase__ , lowerCamelCase__ , shots=1_0_0_0 ) # Return the histogram data of the results of the experiment. return job.result().get_counts(lowerCamelCase__ ) if __name__ == "__main__": print(F"""Total count for various states are: {single_qubit_measure(1, 1)}""")
73
0
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging __a = logging.get_logger(__name__) __a = { "microsoft/swinv2-tiny-patch4-window8-256": ( "https://huggingface.co/microsoft/swinv2-tiny-patch4-window8-256/resolve/main/config.json" ), } class UpperCAmelCase_ ( _a ): """simple docstring""" lowercase = "swinv2" lowercase = { "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers", } def __init__( self : Any , snake_case_ : int=224 , snake_case_ : List[Any]=4 , snake_case_ : List[Any]=3 , snake_case_ : Optional[Any]=96 , snake_case_ : str=[2, 2, 6, 2] , snake_case_ : Tuple=[3, 6, 12, 24] , snake_case_ : Optional[Any]=7 , snake_case_ : List[str]=4.0 , snake_case_ : Optional[int]=True , snake_case_ : Any=0.0 , snake_case_ : Tuple=0.0 , snake_case_ : Union[str, Any]=0.1 , snake_case_ : Any="gelu" , snake_case_ : Optional[Any]=False , snake_case_ : List[str]=0.02 , snake_case_ : Dict=1E-5 , snake_case_ : Optional[int]=32 , **snake_case_ : Dict , ): super().__init__(**snake_case_ ) snake_case__ : Optional[int] = image_size snake_case__ : Union[str, Any] = patch_size snake_case__ : Optional[int] = num_channels snake_case__ : str = embed_dim snake_case__ : List[str] = depths snake_case__ : int = len(snake_case_ ) snake_case__ : Union[str, Any] = num_heads snake_case__ : Tuple = window_size snake_case__ : str = mlp_ratio snake_case__ : Optional[Any] = qkv_bias snake_case__ : Union[str, Any] = hidden_dropout_prob snake_case__ : Dict = attention_probs_dropout_prob snake_case__ : Optional[Any] = drop_path_rate snake_case__ : Tuple = hidden_act snake_case__ : str = use_absolute_embeddings snake_case__ : List[str] = layer_norm_eps snake_case__ : Optional[int] = initializer_range snake_case__ : Dict = encoder_stride # we set the hidden_size attribute in order to make Swinv2 work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model snake_case__ : List[str] = int(embed_dim * 2 ** (len(snake_case_ ) - 1) ) snake_case__ : Tuple = (0, 0, 0, 0)
35
import os import sys a =os.path.join(os.path.dirname(__file__), """src""") sys.path.append(SRC_DIR) from transformers import ( AutoConfig, AutoModel, AutoModelForCausalLM, AutoModelForMaskedLM, AutoModelForQuestionAnswering, AutoModelForSequenceClassification, AutoTokenizer, add_start_docstrings, ) a =[ """torch""", """numpy""", """tokenizers""", """filelock""", """requests""", """tqdm""", """regex""", """sentencepiece""", """sacremoses""", """importlib_metadata""", """huggingface_hub""", ] @add_start_docstrings(AutoConfig.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> int: return AutoConfig.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ ) @add_start_docstrings(AutoTokenizer.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> Optional[Any]: return AutoTokenizer.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ ) @add_start_docstrings(AutoModel.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> List[str]: return AutoModel.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ ) @add_start_docstrings(AutoModelForCausalLM.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> Any: return AutoModelForCausalLM.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ ) @add_start_docstrings(AutoModelForMaskedLM.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> List[str]: return AutoModelForMaskedLM.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ ) @add_start_docstrings(AutoModelForSequenceClassification.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> List[str]: return AutoModelForSequenceClassification.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ ) @add_start_docstrings(AutoModelForQuestionAnswering.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> Tuple: return AutoModelForQuestionAnswering.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ )
73
0
import math from typing import Dict, Iterable, List, Optional, Tuple, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import normalize, rescale, resize, to_channel_dimension_format from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, get_image_size, is_torch_available, is_torch_tensor, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_torch_available(): import torch if is_vision_available(): import PIL _snake_case = logging.get_logger(__name__) def A ( _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ): '''simple docstring''' def constraint_to_multiple_of(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase=0 , _lowerCamelCase=None ): _lowerCAmelCase : Tuple = round(val / multiple ) * multiple if max_val is not None and x > max_val: _lowerCAmelCase : Optional[int] = math.floor(val / multiple ) * multiple if x < min_val: _lowerCAmelCase : List[str] = math.ceil(val / multiple ) * multiple return x _lowerCAmelCase : Union[str, Any] = (output_size, output_size) if isinstance(_lowerCamelCase , _lowerCamelCase ) else output_size _lowerCAmelCase , _lowerCAmelCase : Optional[Any] = get_image_size(_lowerCamelCase ) _lowerCAmelCase , _lowerCAmelCase : Any = output_size # determine new height and width _lowerCAmelCase : List[Any] = output_height / input_height _lowerCAmelCase : Any = output_width / input_width if keep_aspect_ratio: # scale as little as possible if abs(1 - scale_width ) < abs(1 - scale_height ): # fit width _lowerCAmelCase : Union[str, Any] = scale_width else: # fit height _lowerCAmelCase : Union[str, Any] = scale_height _lowerCAmelCase : List[str] = constraint_to_multiple_of(scale_height * input_height , multiple=_lowerCamelCase ) _lowerCAmelCase : Dict = constraint_to_multiple_of(scale_width * input_width , multiple=_lowerCamelCase ) return (new_height, new_width) class UpperCAmelCase_ ( a): lowerCamelCase__ = ['pixel_values'] def __init__( self, __a = True, __a = None, __a = PILImageResampling.BILINEAR, __a = False, __a = 1, __a = True, __a = 1 / 255, __a = True, __a = None, __a = None, **__a, ): '''simple docstring''' super().__init__(**__a) _lowerCAmelCase : Any = size if size is not None else {"height": 384, "width": 384} _lowerCAmelCase : Optional[int] = get_size_dict(__a) _lowerCAmelCase : Optional[Any] = do_resize _lowerCAmelCase : Dict = size _lowerCAmelCase : Any = keep_aspect_ratio _lowerCAmelCase : str = ensure_multiple_of _lowerCAmelCase : str = resample _lowerCAmelCase : Dict = do_rescale _lowerCAmelCase : Optional[int] = rescale_factor _lowerCAmelCase : Dict = do_normalize _lowerCAmelCase : Dict = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN _lowerCAmelCase : int = image_std if image_std is not None else IMAGENET_STANDARD_STD def snake_case__ ( self, __a, __a, __a = False, __a = 1, __a = PILImageResampling.BICUBIC, __a = None, **__a, ): '''simple docstring''' _lowerCAmelCase : List[Any] = get_size_dict(__a) if "height" not in size or "width" not in size: raise ValueError(f"The size dictionary must contain the keys 'height' and 'width'. Got {size.keys()}") _lowerCAmelCase : List[Any] = get_resize_output_image_size( __a, output_size=(size["height"], size["width"]), keep_aspect_ratio=__a, multiple=__a, ) return resize(__a, size=__a, resample=__a, data_format=__a, **__a) def snake_case__ ( self, __a, __a, __a = None, **__a, ): '''simple docstring''' return rescale(__a, scale=__a, data_format=__a, **__a) def snake_case__ ( self, __a, __a, __a, __a = None, **__a, ): '''simple docstring''' return normalize(__a, mean=__a, std=__a, data_format=__a, **__a) def snake_case__ ( self, __a, __a = None, __a = None, __a = None, __a = None, __a = None, __a = None, __a = None, __a = None, __a = None, __a = None, __a = None, __a = ChannelDimension.FIRST, **__a, ): '''simple docstring''' _lowerCAmelCase : int = do_resize if do_resize is not None else self.do_resize _lowerCAmelCase : List[Any] = size if size is not None else self.size _lowerCAmelCase : str = get_size_dict(__a) _lowerCAmelCase : Dict = keep_aspect_ratio if keep_aspect_ratio is not None else self.keep_aspect_ratio _lowerCAmelCase : Any = ensure_multiple_of if ensure_multiple_of is not None else self.ensure_multiple_of _lowerCAmelCase : int = resample if resample is not None else self.resample _lowerCAmelCase : Union[str, Any] = do_rescale if do_rescale is not None else self.do_rescale _lowerCAmelCase : Tuple = rescale_factor if rescale_factor is not None else self.rescale_factor _lowerCAmelCase : List[str] = do_normalize if do_normalize is not None else self.do_normalize _lowerCAmelCase : Dict = image_mean if image_mean is not None else self.image_mean _lowerCAmelCase : List[str] = image_std if image_std is not None else self.image_std _lowerCAmelCase : Optional[Any] = make_list_of_images(__a) if not valid_images(__a): raise ValueError( "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, " "torch.Tensor, tf.Tensor or jax.ndarray.") if do_resize and size is None or resample is None: raise ValueError("Size and resample must be specified if do_resize is True.") if do_rescale and rescale_factor is None: raise ValueError("Rescale factor must be specified if do_rescale is True.") if do_normalize and (image_mean is None or image_std is None): raise ValueError("Image mean and std must be specified if do_normalize is True.") # All transformations expect numpy arrays. _lowerCAmelCase : List[Any] = [to_numpy_array(__a) for image in images] if do_resize: _lowerCAmelCase : Any = [self.resize(image=__a, size=__a, resample=__a) for image in images] if do_rescale: _lowerCAmelCase : List[str] = [self.rescale(image=__a, scale=__a) for image in images] if do_normalize: _lowerCAmelCase : Dict = [self.normalize(image=__a, mean=__a, std=__a) for image in images] _lowerCAmelCase : List[str] = [to_channel_dimension_format(__a, __a) for image in images] _lowerCAmelCase : Optional[Any] = {"pixel_values": images} return BatchFeature(data=__a, tensor_type=__a) def snake_case__ ( self, __a, __a = None): '''simple docstring''' _lowerCAmelCase : Optional[Any] = outputs.logits # Resize logits and compute semantic segmentation maps if target_sizes is not None: if len(__a) != len(__a): raise ValueError( "Make sure that you pass in as many target sizes as the batch dimension of the logits") if is_torch_tensor(__a): _lowerCAmelCase : List[Any] = target_sizes.numpy() _lowerCAmelCase : Dict = [] for idx in range(len(__a)): _lowerCAmelCase : int = torch.nn.functional.interpolate( logits[idx].unsqueeze(dim=0), size=target_sizes[idx], mode="bilinear", align_corners=__a) _lowerCAmelCase : int = resized_logits[0].argmax(dim=0) semantic_segmentation.append(__a) else: _lowerCAmelCase : Dict = logits.argmax(dim=1) _lowerCAmelCase : str = [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0])] return semantic_segmentation
36
from typing import Optional from urllib.parse import quote import huggingface_hub as hfh from packaging import version def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ = None ) -> str: if version.parse(hfh.__version__ ).release < version.parse('0.11.0' ).release: # old versions of hfh don't url-encode the file path __lowerCamelCase : int = quote(lowerCamelCase__ ) return hfh.hf_hub_url(lowerCamelCase__ , lowerCamelCase__ , repo_type='dataset' , revision=lowerCamelCase__ )
73
0
'''simple docstring''' import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging _lowerCAmelCase = logging.get_logger(__name__) _lowerCAmelCase = {'''vocab_file''': '''spm_char.model'''} _lowerCAmelCase = { '''vocab_file''': { '''microsoft/speecht5_asr''': '''https://huggingface.co/microsoft/speecht5_asr/resolve/main/spm_char.model''', '''microsoft/speecht5_tts''': '''https://huggingface.co/microsoft/speecht5_tts/resolve/main/spm_char.model''', '''microsoft/speecht5_vc''': '''https://huggingface.co/microsoft/speecht5_vc/resolve/main/spm_char.model''', } } _lowerCAmelCase = { '''microsoft/speecht5_asr''': 1024, '''microsoft/speecht5_tts''': 1024, '''microsoft/speecht5_vc''': 1024, } class lowerCAmelCase_( SCREAMING_SNAKE_CASE_ ): '''simple docstring''' __lowercase : Dict = VOCAB_FILES_NAMES __lowercase : Optional[Any] = PRETRAINED_VOCAB_FILES_MAP __lowercase : Optional[int] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __lowercase : str = ['''input_ids''', '''attention_mask'''] def __init__( self ,__UpperCAmelCase ,__UpperCAmelCase="<s>" ,__UpperCAmelCase="</s>" ,__UpperCAmelCase="<unk>" ,__UpperCAmelCase="<pad>" ,__UpperCAmelCase = None ,**__UpperCAmelCase ,) -> None: lowerCAmelCase__ : Any = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=__UpperCAmelCase ,eos_token=__UpperCAmelCase ,unk_token=__UpperCAmelCase ,pad_token=__UpperCAmelCase ,sp_model_kwargs=self.sp_model_kwargs ,**__UpperCAmelCase ,) lowerCAmelCase__ : Dict = vocab_file lowerCAmelCase__ : int = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(__UpperCAmelCase ) @property def UpperCAmelCase_ ( self ) -> Union[str, Any]: return self.sp_model.get_piece_size() def UpperCAmelCase_ ( self ) -> Optional[int]: lowerCAmelCase__ : List[str] = {self.convert_ids_to_tokens(__UpperCAmelCase ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self ) -> List[str]: lowerCAmelCase__ : Any = self.__dict__.copy() lowerCAmelCase__ : Dict = None return state def __setstate__( self ,__UpperCAmelCase ) -> List[str]: lowerCAmelCase__ : List[str] = d # for backward compatibility if not hasattr(self ,"""sp_model_kwargs""" ): lowerCAmelCase__ : int = {} lowerCAmelCase__ : Optional[int] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def UpperCAmelCase_ ( self ,__UpperCAmelCase ) -> List[str]: return self.sp_model.encode(__UpperCAmelCase ,out_type=__UpperCAmelCase ) def UpperCAmelCase_ ( self ,__UpperCAmelCase ) -> str: return self.sp_model.piece_to_id(__UpperCAmelCase ) def UpperCAmelCase_ ( self ,__UpperCAmelCase ) -> str: lowerCAmelCase__ : Tuple = self.sp_model.IdToPiece(__UpperCAmelCase ) return token def UpperCAmelCase_ ( self ,__UpperCAmelCase ) -> str: lowerCAmelCase__ : Union[str, Any] = [] lowerCAmelCase__ : Optional[Any] = """""" for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: out_string += self.sp_model.decode(__UpperCAmelCase ) + token lowerCAmelCase__ : Dict = [] else: current_sub_tokens.append(__UpperCAmelCase ) out_string += self.sp_model.decode(__UpperCAmelCase ) return out_string.strip() def UpperCAmelCase_ ( self ,__UpperCAmelCase ,__UpperCAmelCase=None ) -> List[int]: if token_ids_a is None: return token_ids_a + [self.eos_token_id] # We don't expect to process pairs, but leave the pair logic for API consistency return token_ids_a + token_ids_a + [self.eos_token_id] def UpperCAmelCase_ ( self ,__UpperCAmelCase ,__UpperCAmelCase = None ,__UpperCAmelCase = False ) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__UpperCAmelCase ,token_ids_a=__UpperCAmelCase ,already_has_special_tokens=__UpperCAmelCase ) lowerCAmelCase__ : str = [1] if token_ids_a is None: return ([0] * len(__UpperCAmelCase )) + suffix_ones return ([0] * len(__UpperCAmelCase )) + ([0] * len(__UpperCAmelCase )) + suffix_ones def UpperCAmelCase_ ( self ,__UpperCAmelCase ,__UpperCAmelCase = None ) -> Tuple[str]: if not os.path.isdir(__UpperCAmelCase ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return lowerCAmelCase__ : Dict = os.path.join( __UpperCAmelCase ,(filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__UpperCAmelCase ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file ,__UpperCAmelCase ) elif not os.path.isfile(self.vocab_file ): with open(__UpperCAmelCase ,"""wb""" ) as fi: lowerCAmelCase__ : str = self.sp_model.serialized_model_proto() fi.write(__UpperCAmelCase ) return (out_vocab_file,)
37
def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , ) -> float: __lowerCamelCase : Dict = [redshift, radiation_density, matter_density, dark_energy] if any(p < 0 for p in parameters ): raise ValueError('All input parameters must be positive' ) if any(p > 1 for p in parameters[1:4] ): raise ValueError('Relative densities cannot be greater than one' ) else: __lowerCamelCase : Dict = 1 - (matter_density + radiation_density + dark_energy) __lowerCamelCase : Union[str, Any] = ( radiation_density * (redshift + 1) ** 4 + matter_density * (redshift + 1) ** 3 + curvature * (redshift + 1) ** 2 + dark_energy ) __lowerCamelCase : List[Any] = hubble_constant * e_a ** (1 / 2) return hubble if __name__ == "__main__": import doctest # run doctest doctest.testmod() # demo LCDM approximation a =0.3 print( hubble_parameter( hubble_constant=68.3, radiation_density=1E-4, matter_density=matter_density, dark_energy=1 - matter_density, redshift=0, ) )
73
0
import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import Audio, Features, Value from .base import TaskTemplate @dataclass(frozen=_a ) class _SCREAMING_SNAKE_CASE ( _a ): snake_case__ : str = field(default="""automatic-speech-recognition""" , metadata={"""include_in_asdict_even_if_is_default""": True} ) snake_case__ : ClassVar[Features] = Features({"""audio""": Audio()} ) snake_case__ : ClassVar[Features] = Features({"""transcription""": Value("""string""" )} ) snake_case__ : str = "audio" snake_case__ : str = "transcription" def _A ( self : List[str] , __lowerCamelCase : Dict ): if self.audio_column not in features: raise ValueError(F"""Column {self.audio_column} is not present in features.""" ) if not isinstance(features[self.audio_column] , __lowerCamelCase ): raise ValueError(F"""Column {self.audio_column} is not an Audio type.""" ) UpperCamelCase :int = copy.deepcopy(self ) UpperCamelCase :Any = self.input_schema.copy() UpperCamelCase :List[str] = features[self.audio_column] UpperCamelCase :List[Any] = input_schema return task_template @property def _A ( self : Optional[int] ): return {self.audio_column: "audio", self.transcription_column: "transcription"}
38
from typing import List, Optional, Union from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : Optional[Any] = ['''image_processor''', '''tokenizer'''] _UpperCAmelCase : Union[str, Any] = '''Pix2StructImageProcessor''' _UpperCAmelCase : Any = ('''T5Tokenizer''', '''T5TokenizerFast''') def __init__( self : List[str] ,SCREAMING_SNAKE_CASE__ : str ,SCREAMING_SNAKE_CASE__ : int): __lowerCamelCase : List[Any] = False super().__init__(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) def __call__( self : str ,SCREAMING_SNAKE_CASE__ : Any=None ,SCREAMING_SNAKE_CASE__ : Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None ,SCREAMING_SNAKE_CASE__ : bool = True ,SCREAMING_SNAKE_CASE__ : Union[bool, str, PaddingStrategy] = False ,SCREAMING_SNAKE_CASE__ : Union[bool, str, TruncationStrategy] = None ,SCREAMING_SNAKE_CASE__ : Optional[int] = None ,SCREAMING_SNAKE_CASE__ : Optional[int] = 2_0_4_8 ,SCREAMING_SNAKE_CASE__ : int = 0 ,SCREAMING_SNAKE_CASE__ : Optional[int] = None ,SCREAMING_SNAKE_CASE__ : Optional[bool] = None ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = True ,SCREAMING_SNAKE_CASE__ : Optional[Union[str, TensorType]] = None ,**SCREAMING_SNAKE_CASE__ : Dict ,): if images is None and text is None: raise ValueError('You have to specify either images or text.') # Get only text if images is None and not self.image_processor.is_vqa: __lowerCamelCase : Tuple = self.tokenizer __lowerCamelCase : Dict = self.tokenizer( text=SCREAMING_SNAKE_CASE__ ,add_special_tokens=SCREAMING_SNAKE_CASE__ ,padding=SCREAMING_SNAKE_CASE__ ,truncation=SCREAMING_SNAKE_CASE__ ,max_length=SCREAMING_SNAKE_CASE__ ,stride=SCREAMING_SNAKE_CASE__ ,pad_to_multiple_of=SCREAMING_SNAKE_CASE__ ,return_attention_mask=SCREAMING_SNAKE_CASE__ ,return_overflowing_tokens=SCREAMING_SNAKE_CASE__ ,return_special_tokens_mask=SCREAMING_SNAKE_CASE__ ,return_offsets_mapping=SCREAMING_SNAKE_CASE__ ,return_token_type_ids=SCREAMING_SNAKE_CASE__ ,return_length=SCREAMING_SNAKE_CASE__ ,verbose=SCREAMING_SNAKE_CASE__ ,return_tensors=SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__ ,) return text_encoding if not self.image_processor.is_vqa: # add pixel_values __lowerCamelCase : List[Any] = self.image_processor( SCREAMING_SNAKE_CASE__ ,return_tensors=SCREAMING_SNAKE_CASE__ ,max_patches=SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) else: # add pixel_values and bbox __lowerCamelCase : List[Any] = self.image_processor( SCREAMING_SNAKE_CASE__ ,return_tensors=SCREAMING_SNAKE_CASE__ ,max_patches=SCREAMING_SNAKE_CASE__ ,header_text=SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) if text is not None and not self.image_processor.is_vqa: __lowerCamelCase : List[Any] = self.tokenizer( text=SCREAMING_SNAKE_CASE__ ,add_special_tokens=SCREAMING_SNAKE_CASE__ ,padding=SCREAMING_SNAKE_CASE__ ,truncation=SCREAMING_SNAKE_CASE__ ,max_length=SCREAMING_SNAKE_CASE__ ,stride=SCREAMING_SNAKE_CASE__ ,pad_to_multiple_of=SCREAMING_SNAKE_CASE__ ,return_attention_mask=SCREAMING_SNAKE_CASE__ ,return_overflowing_tokens=SCREAMING_SNAKE_CASE__ ,return_special_tokens_mask=SCREAMING_SNAKE_CASE__ ,return_offsets_mapping=SCREAMING_SNAKE_CASE__ ,return_token_type_ids=SCREAMING_SNAKE_CASE__ ,return_length=SCREAMING_SNAKE_CASE__ ,verbose=SCREAMING_SNAKE_CASE__ ,return_tensors=SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__ ,) if "attention_mask" in text_encoding: __lowerCamelCase : List[Any] = text_encoding.pop('attention_mask') if "input_ids" in text_encoding: __lowerCamelCase : Dict = text_encoding.pop('input_ids') else: __lowerCamelCase : Optional[int] = None if text_encoding is not None: encoding_image_processor.update(SCREAMING_SNAKE_CASE__) return encoding_image_processor def lowerCAmelCase ( self : Dict ,*SCREAMING_SNAKE_CASE__ : str ,**SCREAMING_SNAKE_CASE__ : int): return self.tokenizer.batch_decode(*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : List[str] ,*SCREAMING_SNAKE_CASE__ : int ,**SCREAMING_SNAKE_CASE__ : Dict): return self.tokenizer.decode(*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) @property def lowerCAmelCase ( self : int): __lowerCamelCase : Dict = self.tokenizer.model_input_names __lowerCamelCase : int = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
73
0
def __A ( __lowerCAmelCase = 100 )-> int: """simple docstring""" _UpperCAmelCase = (n * (n + 1) // 2) ** 2 _UpperCAmelCase = n * (n + 1) * (2 * n + 1) // 6 return sum_cubes - sum_squares if __name__ == "__main__": print(F'''{solution() = }''')
39
from bisect import bisect from itertools import accumulate def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> Union[str, Any]: __lowerCamelCase : Optional[Any] = sorted(zip(lowerCamelCase__ , lowerCamelCase__ ) , key=lambda lowerCamelCase__ : x[0] / x[1] , reverse=lowerCamelCase__ ) __lowerCamelCase , __lowerCamelCase : Any = [i[0] for i in r], [i[1] for i in r] __lowerCamelCase : List[str] = list(accumulate(lowerCamelCase__ ) ) __lowerCamelCase : Union[str, Any] = bisect(lowerCamelCase__ , lowerCamelCase__ ) return ( 0 if k == 0 else sum(vl[:k] ) + (w - acc[k - 1]) * (vl[k]) / (wt[k]) if k != n else sum(vl[:k] ) ) if __name__ == "__main__": import doctest doctest.testmod()
73
0
"""simple docstring""" def lowercase ( A_ )-> bool: '''simple docstring''' return number & 1 == 0 if __name__ == "__main__": import doctest doctest.testmod()
40
from __future__ import annotations import math def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> list: if len(lowerCamelCase__ ) != 2 or len(a[0] ) != 2 or len(lowerCamelCase__ ) != 2 or len(b[0] ) != 2: raise Exception('Matrices are not 2x2' ) __lowerCamelCase : Optional[int] = [ [a[0][0] * b[0][0] + a[0][1] * b[1][0], a[0][0] * b[0][1] + a[0][1] * b[1][1]], [a[1][0] * b[0][0] + a[1][1] * b[1][0], a[1][0] * b[0][1] + a[1][1] * b[1][1]], ] return new_matrix def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> Optional[int]: return [ [matrix_a[row][col] + matrix_b[row][col] for col in range(len(matrix_a[row] ) )] for row in range(len(lowerCamelCase__ ) ) ] def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> List[str]: return [ [matrix_a[row][col] - matrix_b[row][col] for col in range(len(matrix_a[row] ) )] for row in range(len(lowerCamelCase__ ) ) ] def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> tuple[list, list, list, list]: if len(lowerCamelCase__ ) % 2 != 0 or len(a[0] ) % 2 != 0: raise Exception('Odd matrices are not supported!' ) __lowerCamelCase : Tuple = len(lowerCamelCase__ ) __lowerCamelCase : List[Any] = matrix_length // 2 __lowerCamelCase : Dict = [[a[i][j] for j in range(lowerCamelCase__ , lowerCamelCase__ )] for i in range(lowerCamelCase__ )] __lowerCamelCase : str = [ [a[i][j] for j in range(lowerCamelCase__ , lowerCamelCase__ )] for i in range(lowerCamelCase__ , lowerCamelCase__ ) ] __lowerCamelCase : Dict = [[a[i][j] for j in range(lowerCamelCase__ )] for i in range(lowerCamelCase__ )] __lowerCamelCase : Optional[Any] = [[a[i][j] for j in range(lowerCamelCase__ )] for i in range(lowerCamelCase__ , lowerCamelCase__ )] return top_left, top_right, bot_left, bot_right def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> tuple[int, int]: return len(lowerCamelCase__ ), len(matrix[0] ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> None: print('\n'.join(str(lowerCamelCase__ ) for line in matrix ) ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> list: if matrix_dimensions(lowerCamelCase__ ) == (2, 2): return default_matrix_multiplication(lowerCamelCase__ , lowerCamelCase__ ) __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : Optional[Any] = split_matrix(lowerCamelCase__ ) __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : Optional[Any] = split_matrix(lowerCamelCase__ ) __lowerCamelCase : str = actual_strassen(lowerCamelCase__ , matrix_subtraction(lowerCamelCase__ , lowerCamelCase__ ) ) __lowerCamelCase : List[str] = actual_strassen(matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) , lowerCamelCase__ ) __lowerCamelCase : List[Any] = actual_strassen(matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) , lowerCamelCase__ ) __lowerCamelCase : Tuple = actual_strassen(lowerCamelCase__ , matrix_subtraction(lowerCamelCase__ , lowerCamelCase__ ) ) __lowerCamelCase : Optional[int] = actual_strassen(matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) , matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) ) __lowerCamelCase : Dict = actual_strassen(matrix_subtraction(lowerCamelCase__ , lowerCamelCase__ ) , matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) ) __lowerCamelCase : Tuple = actual_strassen(matrix_subtraction(lowerCamelCase__ , lowerCamelCase__ ) , matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) ) __lowerCamelCase : Dict = matrix_addition(matrix_subtraction(matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) , lowerCamelCase__ ) , lowerCamelCase__ ) __lowerCamelCase : Tuple = matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) __lowerCamelCase : List[str] = matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) __lowerCamelCase : Any = matrix_subtraction(matrix_subtraction(matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) , lowerCamelCase__ ) , lowerCamelCase__ ) # construct the new matrix from our 4 quadrants __lowerCamelCase : List[Any] = [] for i in range(len(lowerCamelCase__ ) ): new_matrix.append(top_left[i] + top_right[i] ) for i in range(len(lowerCamelCase__ ) ): new_matrix.append(bot_left[i] + bot_right[i] ) return new_matrix def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> list: if matrix_dimensions(lowerCamelCase__ )[1] != matrix_dimensions(lowerCamelCase__ )[0]: __lowerCamelCase : Any = ( 'Unable to multiply these matrices, please check the dimensions.\n' F"Matrix A: {matrixa}\n" F"Matrix B: {matrixa}" ) raise Exception(lowerCamelCase__ ) __lowerCamelCase : str = matrix_dimensions(lowerCamelCase__ ) __lowerCamelCase : List[str] = matrix_dimensions(lowerCamelCase__ ) if dimensiona[0] == dimensiona[1] and dimensiona[0] == dimensiona[1]: return [matrixa, matrixa] __lowerCamelCase : str = max(*lowerCamelCase__ , *lowerCamelCase__ ) __lowerCamelCase : List[str] = int(math.pow(2 , math.ceil(math.loga(lowerCamelCase__ ) ) ) ) __lowerCamelCase : Any = matrixa __lowerCamelCase : int = matrixa # Adding zeros to the matrices so that the arrays dimensions are the same and also # power of 2 for i in range(0 , lowerCamelCase__ ): if i < dimensiona[0]: for _ in range(dimensiona[1] , lowerCamelCase__ ): new_matrixa[i].append(0 ) else: new_matrixa.append([0] * maxim ) if i < dimensiona[0]: for _ in range(dimensiona[1] , lowerCamelCase__ ): new_matrixa[i].append(0 ) else: new_matrixa.append([0] * maxim ) __lowerCamelCase : List[str] = actual_strassen(lowerCamelCase__ , lowerCamelCase__ ) # Removing the additional zeros for i in range(0 , lowerCamelCase__ ): if i < dimensiona[0]: for _ in range(dimensiona[1] , lowerCamelCase__ ): final_matrix[i].pop() else: final_matrix.pop() return final_matrix if __name__ == "__main__": a =[ [2, 3, 4, 5], [6, 4, 3, 1], [2, 3, 6, 7], [3, 1, 2, 4], [2, 3, 4, 5], [6, 4, 3, 1], [2, 3, 6, 7], [3, 1, 2, 4], [2, 3, 4, 5], [6, 2, 3, 1], ] a =[[0, 2, 1, 1], [16, 2, 3, 3], [2, 2, 7, 7], [13, 11, 22, 4]] print(strassen(matrixa, matrixa))
73
0
'''simple docstring''' import torch from diffusers import DDPMParallelScheduler from .test_schedulers import SchedulerCommonTest class _lowercase ( _lowercase ): a = (DDPMParallelScheduler,) def lowerCamelCase_ ( self: Union[str, Any] , **UpperCamelCase__: str ): lowerCamelCase__ : str = { """num_train_timesteps""": 1_000, """beta_start""": 0.0_001, """beta_end""": 0.02, """beta_schedule""": """linear""", """variance_type""": """fixed_small""", """clip_sample""": True, } config.update(**UpperCamelCase__ ) return config def lowerCamelCase_ ( self: Tuple ): for timesteps in [1, 5, 100, 1_000]: self.check_over_configs(num_train_timesteps=UpperCamelCase__ ) def lowerCamelCase_ ( self: List[str] ): for beta_start, beta_end in zip([0.0_001, 0.001, 0.01, 0.1] , [0.002, 0.02, 0.2, 2] ): self.check_over_configs(beta_start=UpperCamelCase__ , beta_end=UpperCamelCase__ ) def lowerCamelCase_ ( self: Optional[int] ): for schedule in ["linear", "squaredcos_cap_v2"]: self.check_over_configs(beta_schedule=UpperCamelCase__ ) def lowerCamelCase_ ( self: List[Any] ): for variance in ["fixed_small", "fixed_large", "other"]: self.check_over_configs(variance_type=UpperCamelCase__ ) def lowerCamelCase_ ( self: Dict ): for clip_sample in [True, False]: self.check_over_configs(clip_sample=UpperCamelCase__ ) def lowerCamelCase_ ( self: Union[str, Any] ): self.check_over_configs(thresholding=UpperCamelCase__ ) for threshold in [0.5, 1.0, 2.0]: for prediction_type in ["epsilon", "sample", "v_prediction"]: self.check_over_configs( thresholding=UpperCamelCase__ , prediction_type=UpperCamelCase__ , sample_max_value=UpperCamelCase__ , ) def lowerCamelCase_ ( self: str ): for prediction_type in ["epsilon", "sample", "v_prediction"]: self.check_over_configs(prediction_type=UpperCamelCase__ ) def lowerCamelCase_ ( self: List[Any] ): for t in [0, 500, 999]: self.check_over_forward(time_step=UpperCamelCase__ ) def lowerCamelCase_ ( self: int ): lowerCamelCase__ : int = self.scheduler_classes[0] lowerCamelCase__ : Union[str, Any] = self.get_scheduler_config() lowerCamelCase__ : Union[str, Any] = scheduler_class(**UpperCamelCase__ ) assert torch.sum(torch.abs(scheduler._get_variance(0 ) - 0.0 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(487 ) - 0.00_979 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(999 ) - 0.02 ) ) < 1e-5 def lowerCamelCase_ ( self: List[str] ): lowerCamelCase__ : int = self.scheduler_classes[0] lowerCamelCase__ : List[Any] = self.get_scheduler_config() lowerCamelCase__ : List[str] = scheduler_class(**UpperCamelCase__ ) lowerCamelCase__ : str = len(UpperCamelCase__ ) lowerCamelCase__ : str = self.dummy_model() lowerCamelCase__ : int = self.dummy_sample_deter lowerCamelCase__ : Optional[int] = self.dummy_sample_deter + 0.1 lowerCamelCase__ : Optional[int] = self.dummy_sample_deter - 0.1 lowerCamelCase__ : Union[str, Any] = samplea.shape[0] lowerCamelCase__ : Union[str, Any] = torch.stack([samplea, samplea, samplea] , dim=0 ) lowerCamelCase__ : str = torch.arange(UpperCamelCase__ )[0:3, None].repeat(1 , UpperCamelCase__ ) lowerCamelCase__ : Tuple = model(samples.flatten(0 , 1 ) , timesteps.flatten(0 , 1 ) ) lowerCamelCase__ : Dict = scheduler.batch_step_no_noise(UpperCamelCase__ , timesteps.flatten(0 , 1 ) , samples.flatten(0 , 1 ) ) lowerCamelCase__ : Union[str, Any] = torch.sum(torch.abs(UpperCamelCase__ ) ) lowerCamelCase__ : List[str] = torch.mean(torch.abs(UpperCamelCase__ ) ) assert abs(result_sum.item() - 1_153.1_833 ) < 1e-2 assert abs(result_mean.item() - 0.5_005 ) < 1e-3 def lowerCamelCase_ ( self: List[Any] ): lowerCamelCase__ : List[Any] = self.scheduler_classes[0] lowerCamelCase__ : Dict = self.get_scheduler_config() lowerCamelCase__ : List[Any] = scheduler_class(**UpperCamelCase__ ) lowerCamelCase__ : List[Any] = len(UpperCamelCase__ ) lowerCamelCase__ : Optional[int] = self.dummy_model() lowerCamelCase__ : int = self.dummy_sample_deter lowerCamelCase__ : Optional[int] = torch.manual_seed(0 ) for t in reversed(range(UpperCamelCase__ ) ): # 1. predict noise residual lowerCamelCase__ : Dict = model(UpperCamelCase__ , UpperCamelCase__ ) # 2. predict previous mean of sample x_t-1 lowerCamelCase__ : Any = scheduler.step(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , generator=UpperCamelCase__ ).prev_sample lowerCamelCase__ : List[str] = pred_prev_sample lowerCamelCase__ : List[Any] = torch.sum(torch.abs(UpperCamelCase__ ) ) lowerCamelCase__ : Optional[int] = torch.mean(torch.abs(UpperCamelCase__ ) ) assert abs(result_sum.item() - 258.9_606 ) < 1e-2 assert abs(result_mean.item() - 0.3_372 ) < 1e-3 def lowerCamelCase_ ( self: Optional[Any] ): lowerCamelCase__ : Optional[Any] = self.scheduler_classes[0] lowerCamelCase__ : Any = self.get_scheduler_config(prediction_type="""v_prediction""" ) lowerCamelCase__ : Any = scheduler_class(**UpperCamelCase__ ) lowerCamelCase__ : int = len(UpperCamelCase__ ) lowerCamelCase__ : Optional[int] = self.dummy_model() lowerCamelCase__ : List[Any] = self.dummy_sample_deter lowerCamelCase__ : List[str] = torch.manual_seed(0 ) for t in reversed(range(UpperCamelCase__ ) ): # 1. predict noise residual lowerCamelCase__ : Optional[Any] = model(UpperCamelCase__ , UpperCamelCase__ ) # 2. predict previous mean of sample x_t-1 lowerCamelCase__ : List[str] = scheduler.step(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , generator=UpperCamelCase__ ).prev_sample lowerCamelCase__ : List[Any] = pred_prev_sample lowerCamelCase__ : Union[str, Any] = torch.sum(torch.abs(UpperCamelCase__ ) ) lowerCamelCase__ : List[str] = torch.mean(torch.abs(UpperCamelCase__ ) ) assert abs(result_sum.item() - 202.0_296 ) < 1e-2 assert abs(result_mean.item() - 0.2_631 ) < 1e-3 def lowerCamelCase_ ( self: List[str] ): lowerCamelCase__ : Dict = self.scheduler_classes[0] lowerCamelCase__ : List[str] = self.get_scheduler_config() lowerCamelCase__ : Optional[int] = scheduler_class(**UpperCamelCase__ ) lowerCamelCase__ : List[str] = [100, 87, 50, 1, 0] scheduler.set_timesteps(timesteps=UpperCamelCase__ ) lowerCamelCase__ : Any = scheduler.timesteps for i, timestep in enumerate(UpperCamelCase__ ): if i == len(UpperCamelCase__ ) - 1: lowerCamelCase__ : List[str] = -1 else: lowerCamelCase__ : int = timesteps[i + 1] lowerCamelCase__ : List[Any] = scheduler.previous_timestep(UpperCamelCase__ ) lowerCamelCase__ : Union[str, Any] = prev_t.item() self.assertEqual(UpperCamelCase__ , UpperCamelCase__ ) def lowerCamelCase_ ( self: Any ): lowerCamelCase__ : Optional[int] = self.scheduler_classes[0] lowerCamelCase__ : Union[str, Any] = self.get_scheduler_config() lowerCamelCase__ : Any = scheduler_class(**UpperCamelCase__ ) lowerCamelCase__ : List[str] = [100, 87, 50, 51, 0] with self.assertRaises(UpperCamelCase__ , msg="""`custom_timesteps` must be in descending order.""" ): scheduler.set_timesteps(timesteps=UpperCamelCase__ ) def lowerCamelCase_ ( self: Tuple ): lowerCamelCase__ : Tuple = self.scheduler_classes[0] lowerCamelCase__ : Dict = self.get_scheduler_config() lowerCamelCase__ : str = scheduler_class(**UpperCamelCase__ ) lowerCamelCase__ : Dict = [100, 87, 50, 1, 0] lowerCamelCase__ : List[str] = len(UpperCamelCase__ ) with self.assertRaises(UpperCamelCase__ , msg="""Can only pass one of `num_inference_steps` or `custom_timesteps`.""" ): scheduler.set_timesteps(num_inference_steps=UpperCamelCase__ , timesteps=UpperCamelCase__ ) def lowerCamelCase_ ( self: str ): lowerCamelCase__ : Union[str, Any] = self.scheduler_classes[0] lowerCamelCase__ : Tuple = self.get_scheduler_config() lowerCamelCase__ : List[Any] = scheduler_class(**UpperCamelCase__ ) lowerCamelCase__ : Union[str, Any] = [scheduler.config.num_train_timesteps] with self.assertRaises( UpperCamelCase__ , msg="""`timesteps` must start before `self.config.train_timesteps`: {scheduler.config.num_train_timesteps}}""" , ): scheduler.set_timesteps(timesteps=UpperCamelCase__ )
41
from math import isclose, sqrt def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> tuple[float, float, float]: __lowerCamelCase : Tuple = point_y / 4 / point_x __lowerCamelCase : Tuple = 2 * normal_gradient / (1 + normal_gradient * normal_gradient) __lowerCamelCase : List[Any] = (1 - normal_gradient * normal_gradient) / ( 1 + normal_gradient * normal_gradient ) __lowerCamelCase : int = (sa - ca * incoming_gradient) / (ca + sa * incoming_gradient) # to find the next point, solve the simultaeneous equations: # y^2 + 4x^2 = 100 # y - b = m * (x - a) # ==> A x^2 + B x + C = 0 __lowerCamelCase : Any = outgoing_gradient**2 + 4 __lowerCamelCase : Optional[int] = 2 * outgoing_gradient * (point_y - outgoing_gradient * point_x) __lowerCamelCase : str = (point_y - outgoing_gradient * point_x) ** 2 - 1_0_0 __lowerCamelCase : str = ( -linear_term - sqrt(linear_term**2 - 4 * quadratic_term * constant_term ) ) / (2 * quadratic_term) __lowerCamelCase : Optional[Any] = ( -linear_term + sqrt(linear_term**2 - 4 * quadratic_term * constant_term ) ) / (2 * quadratic_term) # two solutions, one of which is our input point __lowerCamelCase : Optional[Any] = x_minus if isclose(lowerCamelCase__ , lowerCamelCase__ ) else x_plus __lowerCamelCase : Tuple = point_y + outgoing_gradient * (next_x - point_x) return next_x, next_y, outgoing_gradient def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ = 1.4 , lowerCamelCase__ = -9.6 ) -> int: __lowerCamelCase : int = 0 __lowerCamelCase : float = first_x_coord __lowerCamelCase : float = first_y_coord __lowerCamelCase : float = (10.1 - point_y) / (0.0 - point_x) while not (-0.01 <= point_x <= 0.01 and point_y > 0): __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : Any = next_point(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) num_reflections += 1 return num_reflections if __name__ == "__main__": print(F"""{solution() = }""")
73
0
'''simple docstring''' import argparse import glob import logging import os from argparse import Namespace from importlib import import_module import numpy as np import torch from lightning_base import BaseTransformer, add_generic_args, generic_train from seqeval.metrics import accuracy_score, fa_score, precision_score, recall_score from torch.nn import CrossEntropyLoss from torch.utils.data import DataLoader, TensorDataset from utils_ner import TokenClassificationTask lowercase : Tuple = logging.getLogger(__name__) class __UpperCAmelCase ( _lowerCamelCase ): __lowercase = """token-classification""" def __init__( self , lowerCAmelCase_ ): """simple docstring""" if type(lowerCAmelCase_ ) == dict: _snake_case = Namespace(**lowerCAmelCase_ ) _snake_case = import_module('tasks' ) try: _snake_case = getattr(lowerCAmelCase_ , hparams.task_type ) _snake_case = token_classification_task_clazz() except AttributeError: raise ValueError( F'Task {hparams.task_type} needs to be defined as a TokenClassificationTask subclass in {module}. ' F'Available tasks classes are: {TokenClassificationTask.__subclasses__()}' ) _snake_case = self.token_classification_task.get_labels(hparams.labels ) _snake_case = CrossEntropyLoss().ignore_index super().__init__(lowerCAmelCase_ , len(self.labels ) , self.mode ) def lowerCamelCase ( self , **lowerCAmelCase_ ): """simple docstring""" return self.model(**lowerCAmelCase_ ) def lowerCamelCase ( self , lowerCAmelCase_ , lowerCAmelCase_ ): """simple docstring""" _snake_case = {'input_ids': batch[0], 'attention_mask': batch[1], 'labels': batch[3]} if self.config.model_type != "distilbert": _snake_case = ( batch[2] if self.config.model_type in ['bert', 'xlnet'] else None ) # XLM and RoBERTa don"t use token_type_ids _snake_case = self(**lowerCAmelCase_ ) _snake_case = outputs[0] # tensorboard_logs = {"loss": loss, "rate": self.lr_scheduler.get_last_lr()[-1]} return {"loss": loss} def lowerCamelCase ( self ): """simple docstring""" _snake_case = self.hparams for mode in ["train", "dev", "test"]: _snake_case = self._feature_file(lowerCAmelCase_ ) if os.path.exists(lowerCAmelCase_ ) and not args.overwrite_cache: logger.info('Loading features from cached file %s' , lowerCAmelCase_ ) _snake_case = torch.load(lowerCAmelCase_ ) else: logger.info('Creating features from dataset file at %s' , args.data_dir ) _snake_case = self.token_classification_task.read_examples_from_file(args.data_dir , lowerCAmelCase_ ) _snake_case = self.token_classification_task.convert_examples_to_features( lowerCAmelCase_ , self.labels , args.max_seq_length , self.tokenizer , cls_token_at_end=bool(self.config.model_type in ['xlnet'] ) , cls_token=self.tokenizer.cls_token , cls_token_segment_id=2 if self.config.model_type in ['xlnet'] else 0 , sep_token=self.tokenizer.sep_token , sep_token_extra=lowerCAmelCase_ , pad_on_left=bool(self.config.model_type in ['xlnet'] ) , pad_token=self.tokenizer.pad_token_id , pad_token_segment_id=self.tokenizer.pad_token_type_id , pad_token_label_id=self.pad_token_label_id , ) logger.info('Saving features into cached file %s' , lowerCAmelCase_ ) torch.save(lowerCAmelCase_ , lowerCAmelCase_ ) def lowerCamelCase ( self , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ = False ): """simple docstring""" _snake_case = self._feature_file(lowerCAmelCase_ ) logger.info('Loading features from cached file %s' , lowerCAmelCase_ ) _snake_case = torch.load(lowerCAmelCase_ ) _snake_case = torch.tensor([f.input_ids for f in features] , dtype=torch.long ) _snake_case = torch.tensor([f.attention_mask for f in features] , dtype=torch.long ) if features[0].token_type_ids is not None: _snake_case = torch.tensor([f.token_type_ids for f in features] , dtype=torch.long ) else: _snake_case = torch.tensor([0 for f in features] , dtype=torch.long ) # HACK(we will not use this anymore soon) _snake_case = torch.tensor([f.label_ids for f in features] , dtype=torch.long ) return DataLoader( TensorDataset(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) , batch_size=lowerCAmelCase_ ) def lowerCamelCase ( self , lowerCAmelCase_ , lowerCAmelCase_ ): """simple docstring""" """Compute validation""" "" _snake_case = {'input_ids': batch[0], 'attention_mask': batch[1], 'labels': batch[3]} if self.config.model_type != "distilbert": _snake_case = ( batch[2] if self.config.model_type in ['bert', 'xlnet'] else None ) # XLM and RoBERTa don"t use token_type_ids _snake_case = self(**lowerCAmelCase_ ) _snake_case , _snake_case = outputs[:2] _snake_case = logits.detach().cpu().numpy() _snake_case = inputs['labels'].detach().cpu().numpy() return {"val_loss": tmp_eval_loss.detach().cpu(), "pred": preds, "target": out_label_ids} def lowerCamelCase ( self , lowerCAmelCase_ ): """simple docstring""" _snake_case = torch.stack([x['val_loss'] for x in outputs] ).mean() _snake_case = np.concatenate([x['pred'] for x in outputs] , axis=0 ) _snake_case = np.argmax(lowerCAmelCase_ , axis=2 ) _snake_case = np.concatenate([x['target'] for x in outputs] , axis=0 ) _snake_case = dict(enumerate(self.labels ) ) _snake_case = [[] for _ in range(out_label_ids.shape[0] )] _snake_case = [[] for _ in range(out_label_ids.shape[0] )] for i in range(out_label_ids.shape[0] ): for j in range(out_label_ids.shape[1] ): if out_label_ids[i, j] != self.pad_token_label_id: out_label_list[i].append(label_map[out_label_ids[i][j]] ) preds_list[i].append(label_map[preds[i][j]] ) _snake_case = { 'val_loss': val_loss_mean, 'accuracy_score': accuracy_score(lowerCAmelCase_ , lowerCAmelCase_ ), 'precision': precision_score(lowerCAmelCase_ , lowerCAmelCase_ ), 'recall': recall_score(lowerCAmelCase_ , lowerCAmelCase_ ), 'f1': fa_score(lowerCAmelCase_ , lowerCAmelCase_ ), } _snake_case = dict(results.items() ) _snake_case = results return ret, preds_list, out_label_list def lowerCamelCase ( self , lowerCAmelCase_ ): """simple docstring""" _snake_case , _snake_case , _snake_case = self._eval_end(lowerCAmelCase_ ) _snake_case = ret['log'] return {"val_loss": logs["val_loss"], "log": logs, "progress_bar": logs} def lowerCamelCase ( self , lowerCAmelCase_ ): """simple docstring""" _snake_case , _snake_case , _snake_case = self._eval_end(lowerCAmelCase_ ) # Converting to the dict required by pl # https://github.com/PyTorchLightning/pytorch-lightning/blob/master/\ # pytorch_lightning/trainer/logging.py#L139 _snake_case = ret['log'] # `val_loss` is the key returned by `self._eval_end()` but actually refers to `test_loss` return {"avg_test_loss": logs["val_loss"], "log": logs, "progress_bar": logs} @staticmethod def lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ ): """simple docstring""" BaseTransformer.add_model_specific_args(lowerCAmelCase_ , lowerCAmelCase_ ) parser.add_argument( '--task_type' , default='NER' , type=lowerCAmelCase_ , help='Task type to fine tune in training (e.g. NER, POS, etc)' ) parser.add_argument( '--max_seq_length' , default=1_28 , type=lowerCAmelCase_ , help=( 'The maximum total input sequence length after tokenization. Sequences longer ' 'than this will be truncated, sequences shorter will be padded.' ) , ) parser.add_argument( '--labels' , default='' , type=lowerCAmelCase_ , help='Path to a file containing all labels. If not specified, CoNLL-2003 labels are used.' , ) parser.add_argument( '--gpus' , default=0 , type=lowerCAmelCase_ , help='The number of GPUs allocated for this, it is by default 0 meaning none' , ) parser.add_argument( '--overwrite_cache' , action='store_true' , help='Overwrite the cached training and evaluation sets' ) return parser if __name__ == "__main__": lowercase : List[Any] = argparse.ArgumentParser() add_generic_args(parser, os.getcwd()) lowercase : Union[str, Any] = NERTransformer.add_model_specific_args(parser, os.getcwd()) lowercase : Dict = parser.parse_args() lowercase : List[Any] = NERTransformer(args) lowercase : List[Any] = generic_train(model, args) if args.do_predict: # See https://github.com/huggingface/transformers/issues/3159 # pl use this default format to create a checkpoint: # https://github.com/PyTorchLightning/pytorch-lightning/blob/master\ # /pytorch_lightning/callbacks/model_checkpoint.py#L322 lowercase : int = sorted(glob.glob(os.path.join(args.output_dir, "checkpoint-epoch=*.ckpt"), recursive=True)) lowercase : Dict = model.load_from_checkpoint(checkpoints[-1]) trainer.test(model)
42
import os import unicodedata from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging a =logging.get_logger(__name__) a ={"""vocab_file""": """spiece.model"""} a ={ """vocab_file""": { """albert-base-v1""": """https://huggingface.co/albert-base-v1/resolve/main/spiece.model""", """albert-large-v1""": """https://huggingface.co/albert-large-v1/resolve/main/spiece.model""", """albert-xlarge-v1""": """https://huggingface.co/albert-xlarge-v1/resolve/main/spiece.model""", """albert-xxlarge-v1""": """https://huggingface.co/albert-xxlarge-v1/resolve/main/spiece.model""", """albert-base-v2""": """https://huggingface.co/albert-base-v2/resolve/main/spiece.model""", """albert-large-v2""": """https://huggingface.co/albert-large-v2/resolve/main/spiece.model""", """albert-xlarge-v2""": """https://huggingface.co/albert-xlarge-v2/resolve/main/spiece.model""", """albert-xxlarge-v2""": """https://huggingface.co/albert-xxlarge-v2/resolve/main/spiece.model""", } } a ={ """albert-base-v1""": 512, """albert-large-v1""": 512, """albert-xlarge-v1""": 512, """albert-xxlarge-v1""": 512, """albert-base-v2""": 512, """albert-large-v2""": 512, """albert-xlarge-v2""": 512, """albert-xxlarge-v2""": 512, } a ="""▁""" class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : List[Any] = VOCAB_FILES_NAMES _UpperCAmelCase : List[str] = PRETRAINED_VOCAB_FILES_MAP _UpperCAmelCase : Optional[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self : str ,SCREAMING_SNAKE_CASE__ : Optional[int] ,SCREAMING_SNAKE_CASE__ : Tuple=True ,SCREAMING_SNAKE_CASE__ : str=True ,SCREAMING_SNAKE_CASE__ : List[str]=False ,SCREAMING_SNAKE_CASE__ : Any="[CLS]" ,SCREAMING_SNAKE_CASE__ : Optional[int]="[SEP]" ,SCREAMING_SNAKE_CASE__ : Optional[Any]="<unk>" ,SCREAMING_SNAKE_CASE__ : Any="[SEP]" ,SCREAMING_SNAKE_CASE__ : Optional[int]="<pad>" ,SCREAMING_SNAKE_CASE__ : Any="[CLS]" ,SCREAMING_SNAKE_CASE__ : Union[str, Any]="[MASK]" ,SCREAMING_SNAKE_CASE__ : Optional[Dict[str, Any]] = None ,**SCREAMING_SNAKE_CASE__ : Dict ,): # Mask token behave like a normal word, i.e. include the space before it and # is included in the raw text, there should be a match in a non-normalized sentence. __lowerCamelCase : Dict = ( AddedToken(SCREAMING_SNAKE_CASE__ ,lstrip=SCREAMING_SNAKE_CASE__ ,rstrip=SCREAMING_SNAKE_CASE__ ,normalized=SCREAMING_SNAKE_CASE__) if isinstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) else mask_token ) __lowerCamelCase : str = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( do_lower_case=SCREAMING_SNAKE_CASE__ ,remove_space=SCREAMING_SNAKE_CASE__ ,keep_accents=SCREAMING_SNAKE_CASE__ ,bos_token=SCREAMING_SNAKE_CASE__ ,eos_token=SCREAMING_SNAKE_CASE__ ,unk_token=SCREAMING_SNAKE_CASE__ ,sep_token=SCREAMING_SNAKE_CASE__ ,pad_token=SCREAMING_SNAKE_CASE__ ,cls_token=SCREAMING_SNAKE_CASE__ ,mask_token=SCREAMING_SNAKE_CASE__ ,sp_model_kwargs=self.sp_model_kwargs ,**SCREAMING_SNAKE_CASE__ ,) __lowerCamelCase : Any = do_lower_case __lowerCamelCase : Union[str, Any] = remove_space __lowerCamelCase : Tuple = keep_accents __lowerCamelCase : Dict = vocab_file __lowerCamelCase : str = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.Load(SCREAMING_SNAKE_CASE__) @property def lowerCAmelCase ( self : Optional[Any]): return len(self.sp_model) def lowerCAmelCase ( self : Optional[Any]): __lowerCamelCase : Optional[int] = {self.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__): i for i in range(self.vocab_size)} vocab.update(self.added_tokens_encoder) return vocab def __getstate__( self : Union[str, Any]): __lowerCamelCase : str = self.__dict__.copy() __lowerCamelCase : Tuple = None return state def __setstate__( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : str): __lowerCamelCase : List[str] = d # for backward compatibility if not hasattr(self ,'sp_model_kwargs'): __lowerCamelCase : List[str] = {} __lowerCamelCase : int = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.Load(self.vocab_file) def lowerCAmelCase ( self : Dict ,SCREAMING_SNAKE_CASE__ : List[Any]): if self.remove_space: __lowerCamelCase : Dict = ' '.join(inputs.strip().split()) else: __lowerCamelCase : Optional[Any] = inputs __lowerCamelCase : Tuple = outputs.replace('``' ,'"').replace('\'\'' ,'"') if not self.keep_accents: __lowerCamelCase : List[str] = unicodedata.normalize('NFKD' ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : str = ''.join([c for c in outputs if not unicodedata.combining(SCREAMING_SNAKE_CASE__)]) if self.do_lower_case: __lowerCamelCase : Optional[Any] = outputs.lower() return outputs def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : str): __lowerCamelCase : Tuple = self.preprocess_text(SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = self.sp_model.encode(SCREAMING_SNAKE_CASE__ ,out_type=SCREAMING_SNAKE_CASE__) __lowerCamelCase : Tuple = [] for piece in pieces: if len(SCREAMING_SNAKE_CASE__) > 1 and piece[-1] == str(',') and piece[-2].isdigit(): __lowerCamelCase : int = self.sp_model.EncodeAsPieces(piece[:-1].replace(SCREAMING_SNAKE_CASE__ ,'')) if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE: if len(cur_pieces[0]) == 1: __lowerCamelCase : Union[str, Any] = cur_pieces[1:] else: __lowerCamelCase : Dict = cur_pieces[0][1:] cur_pieces.append(piece[-1]) new_pieces.extend(SCREAMING_SNAKE_CASE__) else: new_pieces.append(SCREAMING_SNAKE_CASE__) return new_pieces def lowerCAmelCase ( self : Any ,SCREAMING_SNAKE_CASE__ : List[str]): return self.sp_model.PieceToId(SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : str ,SCREAMING_SNAKE_CASE__ : Any): return self.sp_model.IdToPiece(SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Tuple ,SCREAMING_SNAKE_CASE__ : int): __lowerCamelCase : Optional[Any] = [] __lowerCamelCase : int = '' __lowerCamelCase : Optional[int] = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(SCREAMING_SNAKE_CASE__) + token __lowerCamelCase : List[Any] = True __lowerCamelCase : Any = [] else: current_sub_tokens.append(SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = False out_string += self.sp_model.decode(SCREAMING_SNAKE_CASE__) return out_string.strip() def lowerCAmelCase ( self : Dict ,SCREAMING_SNAKE_CASE__ : List[int] ,SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None): __lowerCamelCase : Union[str, Any] = [self.sep_token_id] __lowerCamelCase : int = [self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def lowerCAmelCase ( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : List[int] ,SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ,SCREAMING_SNAKE_CASE__ : bool = False): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=SCREAMING_SNAKE_CASE__ ,token_ids_a=SCREAMING_SNAKE_CASE__ ,already_has_special_tokens=SCREAMING_SNAKE_CASE__) if token_ids_a is not None: return [1] + ([0] * len(SCREAMING_SNAKE_CASE__)) + [1] + ([0] * len(SCREAMING_SNAKE_CASE__)) + [1] return [1] + ([0] * len(SCREAMING_SNAKE_CASE__)) + [1] def lowerCAmelCase ( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : List[int] ,SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None): __lowerCamelCase : Tuple = [self.sep_token_id] __lowerCamelCase : List[Any] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep) * [0] return len(cls + token_ids_a + sep) * [0] + len(token_ids_a + sep) * [1] def lowerCAmelCase ( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : str ,SCREAMING_SNAKE_CASE__ : Optional[str] = None): if not os.path.isdir(SCREAMING_SNAKE_CASE__): logger.error(F"Vocabulary path ({save_directory}) should be a directory") return __lowerCamelCase : List[str] = os.path.join( SCREAMING_SNAKE_CASE__ ,(filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file']) if os.path.abspath(self.vocab_file) != os.path.abspath(SCREAMING_SNAKE_CASE__) and os.path.isfile(self.vocab_file): copyfile(self.vocab_file ,SCREAMING_SNAKE_CASE__) elif not os.path.isfile(self.vocab_file): with open(SCREAMING_SNAKE_CASE__ ,'wb') as fi: __lowerCamelCase : str = self.sp_model.serialized_model_proto() fi.write(SCREAMING_SNAKE_CASE__) return (out_vocab_file,)
73
0
from torch import nn def lowerCamelCase ( SCREAMING_SNAKE_CASE ): '''simple docstring''' if act_fn in ["swish", "silu"]: return nn.SiLU() elif act_fn == "mish": return nn.Mish() elif act_fn == "gelu": return nn.GELU() else: raise ValueError(f"""Unsupported activation function: {act_fn}""" )
43
def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> float: if discount_rate < 0: raise ValueError('Discount rate cannot be negative' ) if not cash_flows: raise ValueError('Cash flows list cannot be empty' ) __lowerCamelCase : int = sum( cash_flow / ((1 + discount_rate) ** i) for i, cash_flow in enumerate(lowerCamelCase__ ) ) return round(lowerCamelCase__ , ndigits=2 ) if __name__ == "__main__": import doctest doctest.testmod()
73
0
"""simple docstring""" import inspect import unittest import warnings from math import ceil, floor from transformers import LevitConfig from transformers.file_utils import cached_property, is_torch_available, is_vision_available from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_vision, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING, MODEL_MAPPING, LevitForImageClassification, LevitForImageClassificationWithTeacher, LevitModel, ) from transformers.models.levit.modeling_levit import LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import LevitImageProcessor class __A ( SCREAMING_SNAKE_CASE_ ): def __A ( self ): _lowerCAmelCase : int = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(a__ , """hidden_sizes""" ) ) self.parent.assertTrue(hasattr(a__ , """num_attention_heads""" ) ) class __A : def __init__( self , a__ , a__=13 , a__=64 , a__=3 , a__=3 , a__=2 , a__=1 , a__=16 , a__=[128, 256, 384] , a__=[4, 6, 8] , a__=[2, 3, 4] , a__=[16, 16, 16] , a__=0 , a__=[2, 2, 2] , a__=[2, 2, 2] , a__=0.0_2 , a__=True , a__=True , a__=2 , ): _lowerCAmelCase : int = parent _lowerCAmelCase : List[str] = batch_size _lowerCAmelCase : Optional[Any] = image_size _lowerCAmelCase : Optional[int] = num_channels _lowerCAmelCase : Optional[Any] = kernel_size _lowerCAmelCase : str = stride _lowerCAmelCase : List[Any] = padding _lowerCAmelCase : Tuple = hidden_sizes _lowerCAmelCase : Tuple = num_attention_heads _lowerCAmelCase : Any = depths _lowerCAmelCase : List[Any] = key_dim _lowerCAmelCase : Any = drop_path_rate _lowerCAmelCase : Dict = patch_size _lowerCAmelCase : List[Any] = attention_ratio _lowerCAmelCase : Any = mlp_ratio _lowerCAmelCase : Tuple = initializer_range _lowerCAmelCase : Any = [ ["""Subsample""", key_dim[0], hidden_sizes[0] // key_dim[0], 4, 2, 2], ["""Subsample""", key_dim[0], hidden_sizes[1] // key_dim[0], 4, 2, 2], ] _lowerCAmelCase : Optional[Any] = is_training _lowerCAmelCase : Dict = use_labels _lowerCAmelCase : Union[str, Any] = num_labels _lowerCAmelCase : List[Any] = initializer_range def __A ( self ): _lowerCAmelCase : Optional[int] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) _lowerCAmelCase : Optional[int] = None if self.use_labels: _lowerCAmelCase : Any = ids_tensor([self.batch_size] , self.num_labels ) _lowerCAmelCase : List[str] = self.get_config() return config, pixel_values, labels def __A ( self ): return LevitConfig( image_size=self.image_size , num_channels=self.num_channels , kernel_size=self.kernel_size , stride=self.stride , padding=self.padding , patch_size=self.patch_size , hidden_sizes=self.hidden_sizes , num_attention_heads=self.num_attention_heads , depths=self.depths , key_dim=self.key_dim , drop_path_rate=self.drop_path_rate , mlp_ratio=self.mlp_ratio , attention_ratio=self.attention_ratio , initializer_range=self.initializer_range , down_ops=self.down_ops , ) def __A ( self , a__ , a__ , a__ ): _lowerCAmelCase : List[str] = LevitModel(config=a__ ) model.to(a__ ) model.eval() _lowerCAmelCase : List[Any] = model(a__ ) _lowerCAmelCase : List[Any] = (self.image_size, self.image_size) _lowerCAmelCase , _lowerCAmelCase : Optional[int] = image_size[0], image_size[1] for _ in range(4 ): _lowerCAmelCase : Tuple = floor(((height + 2 * self.padding - self.kernel_size) / self.stride) + 1 ) _lowerCAmelCase : Tuple = floor(((width + 2 * self.padding - self.kernel_size) / self.stride) + 1 ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, ceil(height / 4 ) * ceil(width / 4 ), self.hidden_sizes[-1]) , ) def __A ( self , a__ , a__ , a__ ): _lowerCAmelCase : List[Any] = self.num_labels _lowerCAmelCase : str = LevitForImageClassification(a__ ) model.to(a__ ) model.eval() _lowerCAmelCase : Dict = model(a__ , labels=a__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __A ( self ): _lowerCAmelCase : Optional[int] = self.prepare_config_and_inputs() _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase : Any = config_and_inputs _lowerCAmelCase : Tuple = {"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class __A ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , unittest.TestCase ): _UpperCamelCase : Optional[Any] = ( (LevitModel, LevitForImageClassification, LevitForImageClassificationWithTeacher) if is_torch_available() else () ) _UpperCamelCase : Optional[Any] = ( { "feature-extraction": LevitModel, "image-classification": (LevitForImageClassification, LevitForImageClassificationWithTeacher), } if is_torch_available() else {} ) _UpperCamelCase : Dict = False _UpperCamelCase : Optional[int] = False _UpperCamelCase : Optional[int] = False _UpperCamelCase : str = False _UpperCamelCase : Union[str, Any] = False def __A ( self ): _lowerCAmelCase : Union[str, Any] = LevitModelTester(self ) _lowerCAmelCase : str = ConfigTester(self , config_class=a__ , has_text_modality=a__ , hidden_size=37 ) def __A ( self ): self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def __A ( self ): return @unittest.skip(reason="""Levit does not use inputs_embeds""" ) def __A ( self ): pass @unittest.skip(reason="""Levit does not support input and output embeddings""" ) def __A ( self ): pass @unittest.skip(reason="""Levit does not output attentions""" ) def __A ( self ): pass def __A ( self ): _lowerCAmelCase , _lowerCAmelCase : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _lowerCAmelCase : str = model_class(a__ ) _lowerCAmelCase : str = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic _lowerCAmelCase : int = [*signature.parameters.keys()] _lowerCAmelCase : Tuple = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , a__ ) def __A ( self ): def check_hidden_states_output(a__ , a__ , a__ ): _lowerCAmelCase : Any = model_class(a__ ) model.to(a__ ) model.eval() with torch.no_grad(): _lowerCAmelCase : int = model(**self._prepare_for_class(a__ , a__ ) ) _lowerCAmelCase : Optional[Any] = outputs.hidden_states _lowerCAmelCase : List[str] = len(self.model_tester.depths ) + 1 self.assertEqual(len(a__ ) , a__ ) _lowerCAmelCase : Dict = (self.model_tester.image_size, self.model_tester.image_size) _lowerCAmelCase , _lowerCAmelCase : List[str] = image_size[0], image_size[1] for _ in range(4 ): _lowerCAmelCase : Union[str, Any] = floor( ( (height + 2 * self.model_tester.padding - self.model_tester.kernel_size) / self.model_tester.stride ) + 1 ) _lowerCAmelCase : Optional[Any] = floor( ( (width + 2 * self.model_tester.padding - self.model_tester.kernel_size) / self.model_tester.stride ) + 1 ) # verify the first hidden states (first block) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [ height * width, self.model_tester.hidden_sizes[0], ] , ) _lowerCAmelCase , _lowerCAmelCase : str = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _lowerCAmelCase : List[str] = True check_hidden_states_output(a__ , a__ , a__ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] _lowerCAmelCase : str = True check_hidden_states_output(a__ , a__ , a__ ) @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""" ) def __A ( self ): pass def __A ( self , a__ , a__ , a__=False ): _lowerCAmelCase : Dict = super()._prepare_for_class(a__ , a__ , return_labels=a__ ) if return_labels: if model_class.__name__ == "LevitForImageClassificationWithTeacher": del inputs_dict["labels"] return inputs_dict def __A ( self ): _lowerCAmelCase : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a__ ) def __A ( self ): _lowerCAmelCase : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*a__ ) def __A ( self ): if not self.model_tester.is_training: return _lowerCAmelCase , _lowerCAmelCase : str = self.model_tester.prepare_config_and_inputs_for_common() _lowerCAmelCase : int = True for model_class in self.all_model_classes: # LevitForImageClassificationWithTeacher supports inference-only if ( model_class in get_values(a__ ) or model_class.__name__ == "LevitForImageClassificationWithTeacher" ): continue _lowerCAmelCase : Dict = model_class(a__ ) model.to(a__ ) model.train() _lowerCAmelCase : Optional[Any] = self._prepare_for_class(a__ , a__ , return_labels=a__ ) _lowerCAmelCase : Optional[Any] = model(**a__ ).loss loss.backward() def __A ( self ): _lowerCAmelCase , _lowerCAmelCase : Any = self.model_tester.prepare_config_and_inputs_for_common() if not self.model_tester.is_training: return _lowerCAmelCase : List[Any] = False _lowerCAmelCase : Tuple = True for model_class in self.all_model_classes: if model_class in get_values(a__ ) or not model_class.supports_gradient_checkpointing: continue # LevitForImageClassificationWithTeacher supports inference-only if model_class.__name__ == "LevitForImageClassificationWithTeacher": continue _lowerCAmelCase : List[str] = model_class(a__ ) model.gradient_checkpointing_enable() model.to(a__ ) model.train() _lowerCAmelCase : Optional[Any] = self._prepare_for_class(a__ , a__ , return_labels=a__ ) _lowerCAmelCase : Tuple = model(**a__ ).loss loss.backward() def __A ( self ): _lowerCAmelCase , _lowerCAmelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() _lowerCAmelCase : Optional[Any] = [ {"""title""": """multi_label_classification""", """num_labels""": 2, """dtype""": torch.float}, {"""title""": """single_label_classification""", """num_labels""": 1, """dtype""": torch.long}, {"""title""": """regression""", """num_labels""": 1, """dtype""": torch.float}, ] for model_class in self.all_model_classes: if ( model_class not in [ *get_values(a__ ), ] or model_class.__name__ == "LevitForImageClassificationWithTeacher" ): continue for problem_type in problem_types: with self.subTest(msg=F"Testing {model_class} with {problem_type['title']}" ): _lowerCAmelCase : Optional[int] = problem_type["""title"""] _lowerCAmelCase : List[Any] = problem_type["""num_labels"""] _lowerCAmelCase : Optional[int] = model_class(a__ ) model.to(a__ ) model.train() _lowerCAmelCase : Optional[int] = self._prepare_for_class(a__ , a__ , return_labels=a__ ) if problem_type["num_labels"] > 1: _lowerCAmelCase : str = inputs["""labels"""].unsqueeze(1 ).repeat(1 , problem_type["""num_labels"""] ) _lowerCAmelCase : Any = inputs["""labels"""].to(problem_type["""dtype"""] ) # This tests that we do not trigger the warning form PyTorch "Using a target size that is different # to the input size. This will likely lead to incorrect results due to broadcasting. Please ensure # they have the same size." which is a symptom something in wrong for the regression problem. # See https://github.com/huggingface/transformers/issues/11780 with warnings.catch_warnings(record=a__ ) as warning_list: _lowerCAmelCase : Optional[int] = model(**a__ ).loss for w in warning_list: if "Using a target size that is different to the input size" in str(w.message ): raise ValueError( F"Something is going wrong in the regression problem: intercepted {w.message}" ) loss.backward() @slow def __A ( self ): for model_name in LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _lowerCAmelCase : Optional[Any] = LevitModel.from_pretrained(a__ ) self.assertIsNotNone(a__ ) def SCREAMING_SNAKE_CASE ( ) -> Tuple: _lowerCAmelCase : str = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch @require_vision class __A ( unittest.TestCase ): @cached_property def __A ( self ): return LevitImageProcessor.from_pretrained(LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) @slow def __A ( self ): _lowerCAmelCase : int = LevitForImageClassificationWithTeacher.from_pretrained(LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ).to( a__ ) _lowerCAmelCase : Tuple = self.default_image_processor _lowerCAmelCase : List[str] = prepare_img() _lowerCAmelCase : int = image_processor(images=a__ , return_tensors="""pt""" ).to(a__ ) # forward pass with torch.no_grad(): _lowerCAmelCase : Any = model(**a__ ) # verify the logits _lowerCAmelCase : int = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , a__ ) _lowerCAmelCase : Dict = torch.tensor([1.0_4_4_8, -0.3_7_4_5, -1.8_3_1_7] ).to(a__ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , a__ , atol=1e-4 ) )
44
import copy from typing import Dict, List, Optional from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING a ={ """facebook/mask2former-swin-small-coco-instance""": ( """https://huggingface.co/facebook/mask2former-swin-small-coco-instance/blob/main/config.json""" ) # See all Mask2Former models at https://huggingface.co/models?filter=mask2former } a =logging.get_logger(__name__) class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : Dict = '''mask2former''' _UpperCAmelCase : Dict = ['''swin'''] _UpperCAmelCase : Optional[int] = {'''hidden_size''': '''hidden_dim'''} def __init__( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : Optional[Dict] = None ,SCREAMING_SNAKE_CASE__ : int = 2_5_6 ,SCREAMING_SNAKE_CASE__ : int = 2_5_6 ,SCREAMING_SNAKE_CASE__ : int = 2_5_6 ,SCREAMING_SNAKE_CASE__ : int = 1_0_2_4 ,SCREAMING_SNAKE_CASE__ : str = "relu" ,SCREAMING_SNAKE_CASE__ : int = 6 ,SCREAMING_SNAKE_CASE__ : int = 1_0 ,SCREAMING_SNAKE_CASE__ : int = 8 ,SCREAMING_SNAKE_CASE__ : float = 0.0 ,SCREAMING_SNAKE_CASE__ : int = 2_0_4_8 ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : int = 4 ,SCREAMING_SNAKE_CASE__ : int = 2_5_5 ,SCREAMING_SNAKE_CASE__ : int = 1_0_0 ,SCREAMING_SNAKE_CASE__ : float = 0.1 ,SCREAMING_SNAKE_CASE__ : float = 2.0 ,SCREAMING_SNAKE_CASE__ : float = 5.0 ,SCREAMING_SNAKE_CASE__ : float = 5.0 ,SCREAMING_SNAKE_CASE__ : int = 1_2_5_4_4 ,SCREAMING_SNAKE_CASE__ : float = 3.0 ,SCREAMING_SNAKE_CASE__ : float = 0.75 ,SCREAMING_SNAKE_CASE__ : float = 0.02 ,SCREAMING_SNAKE_CASE__ : float = 1.0 ,SCREAMING_SNAKE_CASE__ : bool = True ,SCREAMING_SNAKE_CASE__ : List[int] = [4, 8, 1_6, 3_2] ,SCREAMING_SNAKE_CASE__ : bool = None ,**SCREAMING_SNAKE_CASE__ : Optional[Any] ,): if backbone_config is None: logger.info('`backbone_config` is `None`. Initializing the config with the default `Swin` backbone.') __lowerCamelCase : Optional[Any] = CONFIG_MAPPING['swin']( image_size=2_2_4 ,in_channels=3 ,patch_size=4 ,embed_dim=9_6 ,depths=[2, 2, 1_8, 2] ,num_heads=[3, 6, 1_2, 2_4] ,window_size=7 ,drop_path_rate=0.3 ,use_absolute_embeddings=SCREAMING_SNAKE_CASE__ ,out_features=['stage1', 'stage2', 'stage3', 'stage4'] ,) if isinstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__): __lowerCamelCase : Union[str, Any] = backbone_config.pop('model_type') __lowerCamelCase : Dict = CONFIG_MAPPING[backbone_model_type] __lowerCamelCase : int = config_class.from_dict(SCREAMING_SNAKE_CASE__) # verify that the backbone is supported if backbone_config.model_type not in self.backbones_supported: logger.warning_once( F"Backbone {backbone_config.model_type} is not a supported model and may not be compatible with Mask2Former. " F"Supported model types: {','.join(self.backbones_supported)}") __lowerCamelCase : Dict = backbone_config __lowerCamelCase : int = feature_size __lowerCamelCase : List[str] = mask_feature_size __lowerCamelCase : int = hidden_dim __lowerCamelCase : str = encoder_feedforward_dim __lowerCamelCase : Optional[int] = activation_function __lowerCamelCase : int = encoder_layers __lowerCamelCase : List[Any] = decoder_layers __lowerCamelCase : Union[str, Any] = num_attention_heads __lowerCamelCase : Tuple = dropout __lowerCamelCase : Dict = dim_feedforward __lowerCamelCase : Union[str, Any] = pre_norm __lowerCamelCase : List[str] = enforce_input_projection __lowerCamelCase : Optional[int] = common_stride __lowerCamelCase : Dict = ignore_value __lowerCamelCase : Optional[Any] = num_queries __lowerCamelCase : int = no_object_weight __lowerCamelCase : Optional[Any] = class_weight __lowerCamelCase : str = mask_weight __lowerCamelCase : List[str] = dice_weight __lowerCamelCase : Dict = train_num_points __lowerCamelCase : Optional[int] = oversample_ratio __lowerCamelCase : Optional[Any] = importance_sample_ratio __lowerCamelCase : List[Any] = init_std __lowerCamelCase : Tuple = init_xavier_std __lowerCamelCase : Union[str, Any] = use_auxiliary_loss __lowerCamelCase : List[Any] = feature_strides __lowerCamelCase : Any = output_auxiliary_logits __lowerCamelCase : List[Any] = decoder_layers super().__init__(**SCREAMING_SNAKE_CASE__) @classmethod def lowerCAmelCase ( cls : str ,SCREAMING_SNAKE_CASE__ : PretrainedConfig ,**SCREAMING_SNAKE_CASE__ : Tuple): return cls( backbone_config=SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__ ,) def lowerCAmelCase ( self : str): __lowerCamelCase : List[Any] = copy.deepcopy(self.__dict__) __lowerCamelCase : List[Any] = self.backbone_config.to_dict() __lowerCamelCase : Union[str, Any] = self.__class__.model_type return output
73
0
"""simple docstring""" import inspect import unittest from huggingface_hub import hf_hub_download from transformers import ASTConfig from transformers.testing_utils import require_torch, require_torchaudio, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_torchaudio_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ASTForAudioClassification, ASTModel from transformers.models.audio_spectrogram_transformer.modeling_audio_spectrogram_transformer import ( AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, ) if is_torchaudio_available(): import torchaudio from transformers import ASTFeatureExtractor class __lowerCAmelCase : '''simple docstring''' def __init__( self , _a , _a=13 , _a=2 , _a=24 , _a=16 , _a=True , _a=True , _a=32 , _a=5 , _a=4 , _a=37 , _a="gelu" , _a=0.1 , _a=0.1 , _a=10 , _a=0.02 , _a=None , _a=2 , _a=2 , ): __a = parent __a = batch_size __a = patch_size __a = max_length __a = num_mel_bins __a = is_training __a = use_labels __a = hidden_size __a = num_hidden_layers __a = num_attention_heads __a = intermediate_size __a = hidden_act __a = hidden_dropout_prob __a = attention_probs_dropout_prob __a = type_sequence_label_size __a = initializer_range __a = scope __a = frequency_stride __a = time_stride # in AST, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distillation tokens) __a = (self.num_mel_bins - self.patch_size) // self.frequency_stride + 1 __a = (self.max_length - self.patch_size) // self.time_stride + 1 __a = frequency_out_dimension * time_out_dimension __a = num_patches + 2 def __UpperCAmelCase ( self ): __a = floats_tensor([self.batch_size, self.max_length, self.num_mel_bins] ) __a = None if self.use_labels: __a = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __a = self.get_config() return config, input_values, labels def __UpperCAmelCase ( self ): return ASTConfig( patch_size=self.patch_size , max_length=self.max_length , num_mel_bins=self.num_mel_bins , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=_a , initializer_range=self.initializer_range , frequency_stride=self.frequency_stride , time_stride=self.time_stride , ) def __UpperCAmelCase ( self , _a , _a , _a ): __a = ASTModel(config=_a ) model.to(_a ) model.eval() __a = model(_a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __UpperCAmelCase ( self ): __a = self.prepare_config_and_inputs() ( ( __a ) , ( __a ) , ( __a ) , ) = config_and_inputs __a = {'''input_values''': input_values} return config, inputs_dict @require_torch class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' __UpperCAmelCase : Optional[int] = ( ( ASTModel, ASTForAudioClassification, ) if is_torch_available() else () ) __UpperCAmelCase : Union[str, Any] = ( {'audio-classification': ASTForAudioClassification, 'feature-extraction': ASTModel} if is_torch_available() else {} ) __UpperCAmelCase : Optional[int] = False __UpperCAmelCase : str = False __UpperCAmelCase : Any = False __UpperCAmelCase : List[str] = False def __UpperCAmelCase ( self , _a , _a , _a , _a , _a ): if pipeline_test_casse_name == "AudioClassificationPipelineTests": return True return False def __UpperCAmelCase ( self ): __a = ASTModelTester(self ) __a = ConfigTester(self , config_class=_a , has_text_modality=_a , hidden_size=37 ) def __UpperCAmelCase ( self ): self.config_tester.run_common_tests() @unittest.skip(reason='''AST does not use inputs_embeds''' ) def __UpperCAmelCase ( self ): pass def __UpperCAmelCase ( self ): __a , __a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a = model_class(_a ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) __a = model.get_output_embeddings() self.assertTrue(x is None or isinstance(_a , nn.Linear ) ) def __UpperCAmelCase ( self ): __a , __a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a = model_class(_a ) __a = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __a = [*signature.parameters.keys()] __a = ['''input_values'''] self.assertListEqual(arg_names[:1] , _a ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_a ) @slow def __UpperCAmelCase ( self ): for model_name in AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __a = ASTModel.from_pretrained(_a ) self.assertIsNotNone(_a ) def lowercase ( ) -> int: __a = hf_hub_download( repo_id='''nielsr/audio-spectogram-transformer-checkpoint''' , filename='''sample_audio.flac''' , repo_type='''dataset''' ) __a , __a = torchaudio.load(lowerCAmelCase__ ) return audio, sampling_rate @require_torch @require_torchaudio class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' @cached_property def __UpperCAmelCase ( self ): return ( ASTFeatureExtractor.from_pretrained('''MIT/ast-finetuned-audioset-10-10-0.4593''' ) if is_torchaudio_available() else None ) @slow def __UpperCAmelCase ( self ): __a = self.default_feature_extractor __a = ASTForAudioClassification.from_pretrained('''MIT/ast-finetuned-audioset-10-10-0.4593''' ).to(_a ) __a = self.default_feature_extractor __a , __a = prepare_audio() __a = audio.squeeze().numpy() __a = feature_extractor(_a , sampling_rate=_a , return_tensors='''pt''' ).to(_a ) # forward pass with torch.no_grad(): __a = model(**_a ) # verify the logits __a = torch.Size((1, 527) ) self.assertEqual(outputs.logits.shape , _a ) __a = torch.tensor([-0.8760, -7.0042, -8.6602] ).to(_a ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , _a , atol=1E-4 ) )
45
import string # frequency taken from https://en.wikipedia.org/wiki/Letter_frequency a ={ """E""": 12.70, """T""": 9.06, """A""": 8.17, """O""": 7.51, """I""": 6.97, """N""": 6.75, """S""": 6.33, """H""": 6.09, """R""": 5.99, """D""": 4.25, """L""": 4.03, """C""": 2.78, """U""": 2.76, """M""": 2.41, """W""": 2.36, """F""": 2.23, """G""": 2.02, """Y""": 1.97, """P""": 1.93, """B""": 1.29, """V""": 0.98, """K""": 0.77, """J""": 0.15, """X""": 0.15, """Q""": 0.10, """Z""": 0.07, } a ="""ETAOINSHRDLCUMWFGYPBVKJXQZ""" a ="""ABCDEFGHIJKLMNOPQRSTUVWXYZ""" def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> dict[str, int]: __lowerCamelCase : Tuple = {letter: 0 for letter in string.ascii_uppercase} for letter in message.upper(): if letter in LETTERS: letter_count[letter] += 1 return letter_count def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> str: return x[0] def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> str: __lowerCamelCase : List[str] = get_letter_count(lowerCamelCase__ ) __lowerCamelCase : dict[int, list[str]] = { freq: [] for letter, freq in letter_to_freq.items() } for letter in LETTERS: freq_to_letter[letter_to_freq[letter]].append(lowerCamelCase__ ) __lowerCamelCase : dict[int, str] = {} for freq in freq_to_letter: freq_to_letter[freq].sort(key=ETAOIN.find , reverse=lowerCamelCase__ ) __lowerCamelCase : Optional[Any] = ''.join(freq_to_letter[freq] ) __lowerCamelCase : int = list(freq_to_letter_str.items() ) freq_pairs.sort(key=lowerCamelCase__ , reverse=lowerCamelCase__ ) __lowerCamelCase : list[str] = [freq_pair[1] for freq_pair in freq_pairs] return "".join(lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> int: __lowerCamelCase : str = get_frequency_order(lowerCamelCase__ ) __lowerCamelCase : Optional[Any] = 0 for common_letter in ETAOIN[:6]: if common_letter in freq_order[:6]: match_score += 1 for uncommon_letter in ETAOIN[-6:]: if uncommon_letter in freq_order[-6:]: match_score += 1 return match_score if __name__ == "__main__": import doctest doctest.testmod()
73
0
"""simple docstring""" import os import re import unicodedata from shutil import copyfile from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import is_torch_available, logging if is_torch_available(): import torch if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation SCREAMING_SNAKE_CASE__ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ = {"vocab_file": "spiece.model"} SCREAMING_SNAKE_CASE__ = { "vocab_file": { "AI-Sweden/gpt-sw3-126m": "https://huggingface.co/AI-Sweden/gpt-sw3-126m/resolve/main/spiece.model", "AI-Sweden/gpt-sw3-350m": "https://huggingface.co/AI-Sweden/gpt-sw3-350m/resolve/main/spiece.model", "AI-Sweden/gpt-sw3-1.6b": "https://huggingface.co/AI-Sweden/gpt-sw3-1.6b/resolve/main/spiece.model", "AI-Sweden/gpt-sw3-6.7b": "https://huggingface.co/AI-Sweden/gpt-sw3-6.7b/resolve/main/spiece.model", "AI-Sweden/gpt-sw3-20b": "https://huggingface.co/AI-Sweden/gpt-sw3-20b/resolve/main/spiece.model", } } SCREAMING_SNAKE_CASE__ = { "AI-Sweden/gpt-sw3-126m": 2_048, "AI-Sweden/gpt-sw3-350m": 2_048, "AI-Sweden/gpt-sw3-1.6b": 2_048, "AI-Sweden/gpt-sw3-6.7b": 2_048, "AI-Sweden/gpt-sw3-20b": 2_048, } class lowercase ( _UpperCAmelCase ): _SCREAMING_SNAKE_CASE = VOCAB_FILES_NAMES _SCREAMING_SNAKE_CASE = PRETRAINED_VOCAB_FILES_MAP _SCREAMING_SNAKE_CASE = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _SCREAMING_SNAKE_CASE = ['input_ids', 'attention_mask'] def __init__( self , lowercase , lowercase=False , lowercase=False , lowercase=False , lowercase=None , lowercase=None , lowercase=None , lowercase=None , lowercase = None , **lowercase , ) -> None: lowerCAmelCase = {} if sp_model_kwargs is None else sp_model_kwargs lowerCAmelCase = kwargs.get("""name_or_path""" ) if name_or_path is None: logger.warning( """name_or_path not provided, will work for all GPTSw3 models except gpt-sw3-7b,""" """ you are testing the model, this can safely be ignored""" ) lowerCAmelCase = """None""" # Default definitions for our 2 tokenizer versions, with None-checks to enable proper testing lowerCAmelCase = """<|endoftext|>""" if eos_token is None else eos_token lowerCAmelCase = """<unk>""" if unk_token is None else unk_token if "gpt-sw3-7b" in name_or_path: lowerCAmelCase = unk_token if pad_token is None else pad_token lowerCAmelCase = eos_token if bos_token is None else bos_token else: lowerCAmelCase = """<pad>""" if pad_token is None else pad_token lowerCAmelCase = """<s>""" if bos_token is None else bos_token super().__init__( do_lower_case=lowercase , remove_space=lowercase , keep_accents=lowercase , bos_token=lowercase , eos_token=lowercase , unk_token=lowercase , pad_token=lowercase , sp_model_kwargs=self.sp_model_kwargs , **lowercase , ) lowerCAmelCase = do_lower_case lowerCAmelCase = remove_space lowerCAmelCase = keep_accents lowerCAmelCase = vocab_file lowerCAmelCase = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(lowercase ) # Used for whitespace normalization in input texts # fmt : off lowerCAmelCase = {""" """, """ """, """ """, """ """, """ """, """ """, """ """, """ """, """ """, """ """, """""", """„"""} # fmt : on # Regular expression to remove non-printing characters (e.g. some unicode control chars) in preprocessing lowerCAmelCase = re.compile( f'[{"".join(map(lowercase , list(range(0 , 9 ) ) + list(range(11 , 32 ) ) + list(range(127 , 160 ) ) + [160, 173, 8_203] ) )}]' ) def __getstate__( self ) -> Optional[int]: lowerCAmelCase = self.__dict__.copy() lowerCAmelCase = None return state def __setstate__( self , lowercase ) -> str: lowerCAmelCase = d # for backward compatibility if not hasattr(self , """sp_model_kwargs""" ): lowerCAmelCase = {} lowerCAmelCase = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) @property # Copied from transformers.models.albert.tokenization_albert.AlbertTokenizer.vocab_size def _snake_case ( self ) -> int: return len(self.sp_model ) def _snake_case ( self , lowercase ) -> str: lowerCAmelCase = self.non_printing_characters_re.sub("""""" , lowercase ) # Normalize whitespaces lowerCAmelCase = """""".join([char if char not in self.whitespaces else """ """ for char in text] ) # NFC Unicode normalization lowerCAmelCase = unicodedata.normalize("""NFC""" , lowercase ) return text def _snake_case ( self , lowercase , **lowercase ) -> List[str]: lowerCAmelCase = self.preprocess_text(lowercase ) return self.sp_model.encode(lowercase , out_type=lowercase ) def _snake_case ( self , lowercase ) -> int: return self.sp_model.PieceToId(lowercase ) def _snake_case ( self , lowercase ) -> str: return self.sp_model.IdToPiece(lowercase ) @staticmethod def _snake_case ( lowercase ) -> str: return out_string def _snake_case ( self , lowercase ) -> str: lowerCAmelCase = [] lowerCAmelCase = """""" lowerCAmelCase = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: # TODO: Check if this is needed, as it ensures that decode(encode(doc)) != doc by adding extra whitespace in the decoded document if not prev_is_special: out_string += " " out_string += self.sp_model.decode(lowercase ) + token lowerCAmelCase = True lowerCAmelCase = [] else: current_sub_tokens.append(lowercase ) lowerCAmelCase = False out_string += self.sp_model.decode(lowercase ) return out_string def _snake_case ( self ) -> Dict[str, int]: lowerCAmelCase = {self.convert_ids_to_tokens(lowercase ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def _snake_case ( self , lowercase , lowercase = None ) -> Tuple[str]: if not os.path.isdir(lowercase ): logger.error(f'Vocabulary path ({save_directory}) should be a directory' ) return lowerCAmelCase = os.path.join( lowercase , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(lowercase ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , lowercase ) elif not os.path.isfile(self.vocab_file ): with open(lowercase , """wb""" ) as fi: lowerCAmelCase = self.sp_model.serialized_model_proto() fi.write(lowercase ) return (out_vocab_file,) def _snake_case ( self , lowercase , lowercase = False ) -> Union[List[int], List[List[int]], "torch.Tensor"]: if isinstance(lowercase , lowercase ): lowerCAmelCase = self.preprocess_text(lowercase ) lowerCAmelCase = self.sp_model.encode(lowercase ) else: lowerCAmelCase = [self.preprocess_text(lowercase ) for t in text] lowerCAmelCase = self.sp_model.encode(lowercase ) if return_tensors is True or return_tensors == "pt": lowerCAmelCase = torch.tensor(lowercase ) return token_ids def _snake_case ( self , lowercase ) -> str: return self.sp_model.decode(lowercase ) def _snake_case ( self , lowercase ) -> List[int]: lowerCAmelCase = [f'User: {text}' if is_user else f'Bot: {text}' for is_user, text in conversation.iter_texts()] lowerCAmelCase = ( f'{self.eos_token}{self.bos_token}' + f'{self.bos_token}'.join(lowercase ) + f'{self.bos_token}Bot:' ) return self.encode(text=lowercase )
46
# This is the module that test_patching.py uses to test patch_submodule() import os # noqa: this is just for tests import os as renamed_os # noqa: this is just for tests from os import path # noqa: this is just for tests from os import path as renamed_path # noqa: this is just for tests from os.path import join # noqa: this is just for tests from os.path import join as renamed_join # noqa: this is just for tests a =open # noqa: we just need to have a builtin inside this module to test it properly
73
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowerCamelCase : Optional[Any] = { "configuration_jukebox": [ "JUKEBOX_PRETRAINED_CONFIG_ARCHIVE_MAP", "JukeboxConfig", "JukeboxPriorConfig", "JukeboxVQVAEConfig", ], "tokenization_jukebox": ["JukeboxTokenizer"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : Tuple = [ "JUKEBOX_PRETRAINED_MODEL_ARCHIVE_LIST", "JukeboxModel", "JukeboxPreTrainedModel", "JukeboxVQVAE", "JukeboxPrior", ] if TYPE_CHECKING: from .configuration_jukebox import ( JUKEBOX_PRETRAINED_CONFIG_ARCHIVE_MAP, JukeboxConfig, JukeboxPriorConfig, JukeboxVQVAEConfig, ) from .tokenization_jukebox import JukeboxTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_jukebox import ( JUKEBOX_PRETRAINED_MODEL_ARCHIVE_LIST, JukeboxModel, JukeboxPreTrainedModel, JukeboxPrior, JukeboxVQVAE, ) else: import sys lowerCamelCase : Tuple = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
47
# Function to print upper half of diamond (pyramid) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> str: for i in range(0 , lowerCamelCase__ ): for _ in range(0 , n - i - 1 ): # printing spaces print(' ' , end='' ) for _ in range(0 , i + 1 ): # printing stars print('* ' , end='' ) print() def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Tuple: for i in range(lowerCamelCase__ , 0 , -1 ): for _ in range(lowerCamelCase__ , 0 , -1 ): # printing stars print('* ' , end='' ) print() for _ in range(n - i + 1 , 0 , -1 ): # printing spaces print(' ' , end='' ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Any: if n <= 0: print(' ... .... nothing printing :(' ) return floyd(lowerCamelCase__ ) # upper half reverse_floyd(lowerCamelCase__ ) # lower half if __name__ == "__main__": print(r"""| /\ | |- | |- |--| |\ /| |-""") print(r"""|/ \| |- |_ |_ |__| | \/ | |_""") a =1 while K: a =int(input("""enter the number and , and see the magic : """)) print() pretty_print(user_number) a =int(input("""press 0 to exit... and 1 to continue...""")) print("""Good Bye...""")
73
0
def A ( _SCREAMING_SNAKE_CASE ) -> int: lowerCamelCase : list[list[int]] = [[0 for _ in range(_SCREAMING_SNAKE_CASE )] for _ in range(m + 1 )] for i in range(m + 1 ): lowerCamelCase : Optional[int] = 1 for n in range(m + 1 ): for k in range(1 ,_SCREAMING_SNAKE_CASE ): memo[n][k] += memo[n][k - 1] if n - k > 0: memo[n][k] += memo[n - k - 1][k] return memo[m][m - 1] if __name__ == "__main__": import sys if len(sys.argv) == 1: try: SCREAMING_SNAKE_CASE__ : List[str] = int(input('Enter a number: ').strip()) print(partition(n)) except ValueError: print('Please enter a number.') else: try: SCREAMING_SNAKE_CASE__ : Optional[Any] = int(sys.argv[1]) print(partition(n)) except ValueError: print('Please pass a number.')
48
import re import warnings from contextlib import contextmanager from ...processing_utils import ProcessorMixin class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : Any = ['''image_processor''', '''tokenizer'''] _UpperCAmelCase : List[Any] = '''AutoImageProcessor''' _UpperCAmelCase : Dict = '''AutoTokenizer''' def __init__( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : Optional[int]=None ,SCREAMING_SNAKE_CASE__ : List[Any]=None ,**SCREAMING_SNAKE_CASE__ : Union[str, Any]): __lowerCamelCase : List[str] = None if "feature_extractor" in kwargs: warnings.warn( 'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`' ' instead.' ,SCREAMING_SNAKE_CASE__ ,) __lowerCamelCase : Union[str, Any] = kwargs.pop('feature_extractor') __lowerCamelCase : Dict = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('You need to specify an `image_processor`.') if tokenizer is None: raise ValueError('You need to specify a `tokenizer`.') super().__init__(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Dict = self.image_processor __lowerCamelCase : Optional[int] = False def __call__( self : int ,*SCREAMING_SNAKE_CASE__ : Union[str, Any] ,**SCREAMING_SNAKE_CASE__ : Union[str, Any]): # For backward compatibility if self._in_target_context_manager: return self.current_processor(*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[int] = kwargs.pop('images' ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Union[str, Any] = kwargs.pop('text' ,SCREAMING_SNAKE_CASE__) if len(SCREAMING_SNAKE_CASE__) > 0: __lowerCamelCase : int = args[0] __lowerCamelCase : List[str] = args[1:] if images is None and text is None: raise ValueError('You need to specify either an `images` or `text` input to process.') if images is not None: __lowerCamelCase : Optional[int] = self.image_processor(SCREAMING_SNAKE_CASE__ ,*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) if text is not None: __lowerCamelCase : List[Any] = self.tokenizer(SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) if text is None: return inputs elif images is None: return encodings else: __lowerCamelCase : Optional[Any] = encodings['input_ids'] return inputs def lowerCAmelCase ( self : int ,*SCREAMING_SNAKE_CASE__ : Union[str, Any] ,**SCREAMING_SNAKE_CASE__ : Dict): return self.tokenizer.batch_decode(*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Optional[Any] ,*SCREAMING_SNAKE_CASE__ : List[Any] ,**SCREAMING_SNAKE_CASE__ : Any): return self.tokenizer.decode(*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) @contextmanager def lowerCAmelCase ( self : Tuple): warnings.warn( '`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your ' 'labels by using the argument `text` of the regular `__call__` method (either in the same call as ' 'your images inputs, or in a separate call.') __lowerCamelCase : List[Any] = True __lowerCamelCase : str = self.tokenizer yield __lowerCamelCase : Tuple = self.image_processor __lowerCamelCase : Tuple = False def lowerCAmelCase ( self : Any ,SCREAMING_SNAKE_CASE__ : str ,SCREAMING_SNAKE_CASE__ : int=False ,SCREAMING_SNAKE_CASE__ : List[Any]=None): if added_vocab is None: __lowerCamelCase : str = self.tokenizer.get_added_vocab() __lowerCamelCase : Union[str, Any] = {} while tokens: __lowerCamelCase : Tuple = re.search(R'<s_(.*?)>' ,SCREAMING_SNAKE_CASE__ ,re.IGNORECASE) if start_token is None: break __lowerCamelCase : Dict = start_token.group(1) __lowerCamelCase : List[str] = re.search(RF"</s_{key}>" ,SCREAMING_SNAKE_CASE__ ,re.IGNORECASE) __lowerCamelCase : Optional[int] = start_token.group() if end_token is None: __lowerCamelCase : List[Any] = tokens.replace(SCREAMING_SNAKE_CASE__ ,'') else: __lowerCamelCase : Tuple = end_token.group() __lowerCamelCase : int = re.escape(SCREAMING_SNAKE_CASE__) __lowerCamelCase : str = re.escape(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Union[str, Any] = re.search(F"{start_token_escaped}(.*?){end_token_escaped}" ,SCREAMING_SNAKE_CASE__ ,re.IGNORECASE) if content is not None: __lowerCamelCase : List[Any] = content.group(1).strip() if r"<s_" in content and r"</s_" in content: # non-leaf node __lowerCamelCase : str = self.tokenajson(SCREAMING_SNAKE_CASE__ ,is_inner_value=SCREAMING_SNAKE_CASE__ ,added_vocab=SCREAMING_SNAKE_CASE__) if value: if len(SCREAMING_SNAKE_CASE__) == 1: __lowerCamelCase : Tuple = value[0] __lowerCamelCase : int = value else: # leaf nodes __lowerCamelCase : Tuple = [] for leaf in content.split(R'<sep/>'): __lowerCamelCase : List[Any] = leaf.strip() if leaf in added_vocab and leaf[0] == "<" and leaf[-2:] == "/>": __lowerCamelCase : str = leaf[1:-2] # for categorical special tokens output[key].append(SCREAMING_SNAKE_CASE__) if len(output[key]) == 1: __lowerCamelCase : Dict = output[key][0] __lowerCamelCase : Dict = tokens[tokens.find(SCREAMING_SNAKE_CASE__) + len(SCREAMING_SNAKE_CASE__) :].strip() if tokens[:6] == r"<sep/>": # non-leaf nodes return [output] + self.tokenajson(tokens[6:] ,is_inner_value=SCREAMING_SNAKE_CASE__ ,added_vocab=SCREAMING_SNAKE_CASE__) if len(SCREAMING_SNAKE_CASE__): return [output] if is_inner_value else output else: return [] if is_inner_value else {"text_sequence": tokens} @property def lowerCAmelCase ( self : List[str]): warnings.warn( '`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.' ,SCREAMING_SNAKE_CASE__ ,) return self.image_processor_class @property def lowerCAmelCase ( self : List[Any]): warnings.warn( '`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.' ,SCREAMING_SNAKE_CASE__ ,) return self.image_processor
73
0
import dataclasses import json import warnings from dataclasses import dataclass, field from time import time from typing import List from ..utils import logging __snake_case :Optional[Any] = logging.get_logger(__name__) def __snake_case ( _UpperCAmelCase=None , _UpperCAmelCase=None ): return field(default_factory=lambda: default , metadata=_UpperCAmelCase ) @dataclass class _A : UpperCamelCase__ : List[str] = list_field( default=[] ,metadata={ '''help''': ( '''Model checkpoints to be provided to the AutoModel classes. Leave blank to benchmark the base version''' ''' of all available models''' ) } ,) UpperCamelCase__ : List[int] = list_field( default=[8] ,metadata={'''help''': '''List of batch sizes for which memory and time performance will be evaluated'''} ) UpperCamelCase__ : List[int] = list_field( default=[8, 32, 128, 512] ,metadata={'''help''': '''List of sequence lengths for which memory and time performance will be evaluated'''} ,) UpperCamelCase__ : bool = field( default=__UpperCAmelCase ,metadata={'''help''': '''Whether to benchmark inference of model. Inference can be disabled via --no-inference.'''} ,) UpperCamelCase__ : bool = field( default=__UpperCAmelCase ,metadata={'''help''': '''Whether to run on available cuda devices. Cuda can be disabled via --no-cuda.'''} ,) UpperCamelCase__ : bool = field( default=__UpperCAmelCase ,metadata={'''help''': '''Whether to run on available tpu devices. TPU can be disabled via --no-tpu.'''} ) UpperCamelCase__ : bool = field(default=__UpperCAmelCase ,metadata={'''help''': '''Use FP16 to accelerate inference.'''} ) UpperCamelCase__ : bool = field(default=__UpperCAmelCase ,metadata={'''help''': '''Benchmark training of model'''} ) UpperCamelCase__ : bool = field(default=__UpperCAmelCase ,metadata={'''help''': '''Verbose memory tracing'''} ) UpperCamelCase__ : bool = field( default=__UpperCAmelCase ,metadata={'''help''': '''Whether to perform speed measurements. Speed measurements can be disabled via --no-speed.'''} ,) UpperCamelCase__ : bool = field( default=__UpperCAmelCase ,metadata={ '''help''': '''Whether to perform memory measurements. Memory measurements can be disabled via --no-memory''' } ,) UpperCamelCase__ : bool = field(default=__UpperCAmelCase ,metadata={'''help''': '''Trace memory line by line'''} ) UpperCamelCase__ : bool = field(default=__UpperCAmelCase ,metadata={'''help''': '''Save result to a CSV file'''} ) UpperCamelCase__ : bool = field(default=__UpperCAmelCase ,metadata={'''help''': '''Save all print statements in a log file'''} ) UpperCamelCase__ : bool = field(default=__UpperCAmelCase ,metadata={'''help''': '''Whether to print environment information'''} ) UpperCamelCase__ : bool = field( default=__UpperCAmelCase ,metadata={ '''help''': ( '''Whether to use multiprocessing for memory and speed measurement. It is highly recommended to use''' ''' multiprocessing for accurate CPU and GPU memory measurements. This option should only be disabled''' ''' for debugging / testing and on TPU.''' ) } ,) UpperCamelCase__ : str = field( default=F'''inference_time_{round(time() )}.csv''' ,metadata={'''help''': '''CSV filename used if saving time results to csv.'''} ,) UpperCamelCase__ : str = field( default=F'''inference_memory_{round(time() )}.csv''' ,metadata={'''help''': '''CSV filename used if saving memory results to csv.'''} ,) UpperCamelCase__ : str = field( default=F'''train_time_{round(time() )}.csv''' ,metadata={'''help''': '''CSV filename used if saving time results to csv for training.'''} ,) UpperCamelCase__ : str = field( default=F'''train_memory_{round(time() )}.csv''' ,metadata={'''help''': '''CSV filename used if saving memory results to csv for training.'''} ,) UpperCamelCase__ : str = field( default=F'''env_info_{round(time() )}.csv''' ,metadata={'''help''': '''CSV filename used if saving environment information.'''} ,) UpperCamelCase__ : str = field( default=F'''log_{round(time() )}.csv''' ,metadata={'''help''': '''Log filename used if print statements are saved in log.'''} ,) UpperCamelCase__ : int = field(default=3 ,metadata={'''help''': '''Times an experiment will be run.'''} ) UpperCamelCase__ : bool = field( default=__UpperCAmelCase ,metadata={ '''help''': ( '''Instead of loading the model as defined in `config.architectures` if exists, just load the pretrain''' ''' model weights.''' ) } ,) def _lowerCamelCase ( self : List[str]): '''simple docstring''' warnings.warn( F'The class {self.__class__} is deprecated. Hugging Face Benchmarking utils' ''' are deprecated in general and it is advised to use external Benchmarking libraries ''' ''' to benchmark Transformer models.''' , __SCREAMING_SNAKE_CASE , ) def _lowerCamelCase ( self : Tuple): '''simple docstring''' return json.dumps(dataclasses.asdict(self) , indent=2) @property def _lowerCamelCase ( self : str): '''simple docstring''' if len(self.models) <= 0: raise ValueError( '''Please make sure you provide at least one model name / model identifier, *e.g.* `--models''' ''' bert-base-cased` or `args.models = [\'bert-base-cased\'].''') return self.models @property def _lowerCamelCase ( self : int): '''simple docstring''' if not self.multi_process: return False elif self.is_tpu: logger.info('''Multiprocessing is currently not possible on TPU.''') return False else: return True
49
def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> int: __lowerCamelCase : Optional[int] = 0 __lowerCamelCase : Dict = len(lowerCamelCase__ ) - 1 while left <= right: # avoid divided by 0 during interpolation if sorted_collection[left] == sorted_collection[right]: if sorted_collection[left] == item: return left else: return None __lowerCamelCase : str = left + ((item - sorted_collection[left]) * (right - left)) // ( sorted_collection[right] - sorted_collection[left] ) # out of range check if point < 0 or point >= len(lowerCamelCase__ ): return None __lowerCamelCase : Tuple = sorted_collection[point] if current_item == item: return point else: if point < left: __lowerCamelCase : List[Any] = left __lowerCamelCase : Tuple = point elif point > right: __lowerCamelCase : Dict = right __lowerCamelCase : str = point else: if item < current_item: __lowerCamelCase : Dict = point - 1 else: __lowerCamelCase : Dict = point + 1 return None def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> Any: # avoid divided by 0 during interpolation if sorted_collection[left] == sorted_collection[right]: if sorted_collection[left] == item: return left else: return None __lowerCamelCase : Optional[int] = left + ((item - sorted_collection[left]) * (right - left)) // ( sorted_collection[right] - sorted_collection[left] ) # out of range check if point < 0 or point >= len(lowerCamelCase__ ): return None if sorted_collection[point] == item: return point elif point < left: return interpolation_search_by_recursion(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) elif point > right: return interpolation_search_by_recursion(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) else: if sorted_collection[point] > item: return interpolation_search_by_recursion( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , point - 1 ) else: return interpolation_search_by_recursion( lowerCamelCase__ , lowerCamelCase__ , point + 1 , lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Optional[Any]: if collection != sorted(lowerCamelCase__ ): raise ValueError('Collection must be ascending sorted' ) return True if __name__ == "__main__": import sys a =0 if debug == 1: a =[10, 30, 40, 45, 50, 66, 77, 93] try: __assert_sorted(collection) except ValueError: sys.exit("""Sequence must be ascending sorted to apply interpolation search""") a =67 a =interpolation_search(collection, target) if result is not None: print(F"""{target} found at positions: {result}""") else: print("""Not found""")
73
0
import unittest from transformers import LiltConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( LiltForQuestionAnswering, LiltForSequenceClassification, LiltForTokenClassification, LiltModel, ) from transformers.models.lilt.modeling_lilt import LILT_PRETRAINED_MODEL_ARCHIVE_LIST class lowerCAmelCase : def __init__( self : int , UpperCAmelCase : Optional[int] , UpperCAmelCase : Union[str, Any]=13 , UpperCAmelCase : Optional[int]=7 , UpperCAmelCase : int=True , UpperCAmelCase : Any=True , UpperCAmelCase : Union[str, Any]=True , UpperCAmelCase : List[Any]=True , UpperCAmelCase : int=99 , UpperCAmelCase : Tuple=24 , UpperCAmelCase : Any=2 , UpperCAmelCase : Tuple=6 , UpperCAmelCase : int=37 , UpperCAmelCase : Optional[Any]="gelu" , UpperCAmelCase : Optional[Any]=0.1 , UpperCAmelCase : List[str]=0.1 , UpperCAmelCase : str=512 , UpperCAmelCase : List[str]=16 , UpperCAmelCase : int=2 , UpperCAmelCase : List[str]=0.0_2 , UpperCAmelCase : int=3 , UpperCAmelCase : Optional[Any]=None , UpperCAmelCase : str=1000 , ) -> int: lowerCamelCase__ : List[str] = parent lowerCamelCase__ : Union[str, Any] = batch_size lowerCamelCase__ : Tuple = seq_length lowerCamelCase__ : Any = is_training lowerCamelCase__ : Optional[int] = use_input_mask lowerCamelCase__ : Any = use_token_type_ids lowerCamelCase__ : int = use_labels lowerCamelCase__ : str = vocab_size lowerCamelCase__ : int = hidden_size lowerCamelCase__ : Dict = num_hidden_layers lowerCamelCase__ : List[Any] = num_attention_heads lowerCamelCase__ : str = intermediate_size lowerCamelCase__ : int = hidden_act lowerCamelCase__ : str = hidden_dropout_prob lowerCamelCase__ : List[Any] = attention_probs_dropout_prob lowerCamelCase__ : Union[str, Any] = max_position_embeddings lowerCamelCase__ : Optional[Any] = type_vocab_size lowerCamelCase__ : int = type_sequence_label_size lowerCamelCase__ : str = initializer_range lowerCamelCase__ : List[Any] = num_labels lowerCamelCase__ : List[str] = scope lowerCamelCase__ : str = range_bbox def A_ ( self : Tuple ) -> Tuple: lowerCamelCase__ : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) lowerCamelCase__ : Any = ids_tensor([self.batch_size, self.seq_length, 4] , self.range_bbox ) # Ensure that bbox is legal for i in range(bbox.shape[0] ): for j in range(bbox.shape[1] ): if bbox[i, j, 3] < bbox[i, j, 1]: lowerCamelCase__ : Union[str, Any] = bbox[i, j, 3] lowerCamelCase__ : List[str] = bbox[i, j, 1] lowerCamelCase__ : Any = t if bbox[i, j, 2] < bbox[i, j, 0]: lowerCamelCase__ : Optional[int] = bbox[i, j, 2] lowerCamelCase__ : str = bbox[i, j, 0] lowerCamelCase__ : str = t lowerCamelCase__ : Any = None if self.use_input_mask: lowerCamelCase__ : Dict = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) lowerCamelCase__ : List[Any] = None if self.use_token_type_ids: lowerCamelCase__ : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) lowerCamelCase__ : Optional[int] = None lowerCamelCase__ : List[str] = None if self.use_labels: lowerCamelCase__ : Any = ids_tensor([self.batch_size] , self.type_sequence_label_size ) lowerCamelCase__ : int = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) lowerCamelCase__ : Tuple = self.get_config() return config, input_ids, bbox, token_type_ids, input_mask, sequence_labels, token_labels def A_ ( self : List[str] ) -> Tuple: return LiltConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , ) def A_ ( self : Optional[Any] , UpperCAmelCase : Optional[Any] , UpperCAmelCase : str , UpperCAmelCase : Union[str, Any] , UpperCAmelCase : Any , UpperCAmelCase : Any , UpperCAmelCase : List[str] , UpperCAmelCase : Any , ) -> List[str]: lowerCamelCase__ : str = LiltModel(config=UpperCAmelCase ) model.to(UpperCAmelCase ) model.eval() lowerCamelCase__ : str = model(UpperCAmelCase , bbox=UpperCAmelCase , attention_mask=UpperCAmelCase , token_type_ids=UpperCAmelCase ) lowerCamelCase__ : int = model(UpperCAmelCase , bbox=UpperCAmelCase , token_type_ids=UpperCAmelCase ) lowerCamelCase__ : List[Any] = model(UpperCAmelCase , bbox=UpperCAmelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def A_ ( self : Tuple , UpperCAmelCase : str , UpperCAmelCase : List[Any] , UpperCAmelCase : Union[str, Any] , UpperCAmelCase : Union[str, Any] , UpperCAmelCase : int , UpperCAmelCase : Union[str, Any] , UpperCAmelCase : Tuple , ) -> int: lowerCamelCase__ : Tuple = self.num_labels lowerCamelCase__ : List[str] = LiltForTokenClassification(config=UpperCAmelCase ) model.to(UpperCAmelCase ) model.eval() lowerCamelCase__ : Dict = model( UpperCAmelCase , bbox=UpperCAmelCase , attention_mask=UpperCAmelCase , token_type_ids=UpperCAmelCase , labels=UpperCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def A_ ( self : List[str] , UpperCAmelCase : int , UpperCAmelCase : Optional[Any] , UpperCAmelCase : List[str] , UpperCAmelCase : str , UpperCAmelCase : str , UpperCAmelCase : Any , UpperCAmelCase : Union[str, Any] , ) -> Any: lowerCamelCase__ : Optional[int] = LiltForQuestionAnswering(config=UpperCAmelCase ) model.to(UpperCAmelCase ) model.eval() lowerCamelCase__ : Optional[int] = model( UpperCAmelCase , bbox=UpperCAmelCase , attention_mask=UpperCAmelCase , token_type_ids=UpperCAmelCase , start_positions=UpperCAmelCase , end_positions=UpperCAmelCase , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def A_ ( self : Tuple ) -> Tuple: lowerCamelCase__ : Tuple = self.prepare_config_and_inputs() ( ( lowerCamelCase__ ) , ( lowerCamelCase__ ) , ( lowerCamelCase__ ) , ( lowerCamelCase__ ) , ( lowerCamelCase__ ) , ( lowerCamelCase__ ) , ( lowerCamelCase__ ) , ) : Optional[int] = config_and_inputs lowerCamelCase__ : Any = { 'input_ids': input_ids, 'bbox': bbox, 'token_type_ids': token_type_ids, 'attention_mask': input_mask, } return config, inputs_dict @require_torch class lowerCAmelCase ( __UpperCamelCase, __UpperCamelCase, __UpperCamelCase, unittest.TestCase ): UpperCAmelCase__ = ( ( LiltModel, LiltForSequenceClassification, LiltForTokenClassification, LiltForQuestionAnswering, ) if is_torch_available() else () ) UpperCAmelCase__ = ( { """feature-extraction""": LiltModel, """question-answering""": LiltForQuestionAnswering, """text-classification""": LiltForSequenceClassification, """token-classification""": LiltForTokenClassification, """zero-shot""": LiltForSequenceClassification, } if is_torch_available() else {} ) UpperCAmelCase__ = False UpperCAmelCase__ = False def A_ ( self : Dict , UpperCAmelCase : List[Any] , UpperCAmelCase : int , UpperCAmelCase : Any , UpperCAmelCase : str , UpperCAmelCase : List[str] ) -> Tuple: return True def A_ ( self : Union[str, Any] ) -> int: lowerCamelCase__ : int = LiltModelTester(self ) lowerCamelCase__ : Tuple = ConfigTester(self , config_class=UpperCAmelCase , hidden_size=37 ) def A_ ( self : int ) -> Tuple: self.config_tester.run_common_tests() def A_ ( self : int ) -> Any: lowerCamelCase__ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCAmelCase ) def A_ ( self : Dict ) -> List[Any]: lowerCamelCase__ : int = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: lowerCamelCase__ : Union[str, Any] = type self.model_tester.create_and_check_model(*UpperCAmelCase ) def A_ ( self : Optional[int] ) -> Tuple: lowerCamelCase__ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*UpperCAmelCase ) def A_ ( self : Union[str, Any] ) -> Tuple: lowerCamelCase__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*UpperCAmelCase ) @slow def A_ ( self : List[str] ) -> Tuple: for model_name in LILT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowerCamelCase__ : Optional[int] = LiltModel.from_pretrained(UpperCAmelCase ) self.assertIsNotNone(UpperCAmelCase ) @require_torch @slow class lowerCAmelCase ( unittest.TestCase ): def A_ ( self : str ) -> Dict: lowerCamelCase__ : List[str] = LiltModel.from_pretrained('SCUT-DLVCLab/lilt-roberta-en-base' ).to(UpperCAmelCase ) lowerCamelCase__ : List[Any] = torch.tensor([[1, 2]] , device=UpperCAmelCase ) lowerCamelCase__ : List[Any] = torch.tensor([[[1, 2, 3, 4], [5, 6, 7, 8]]] , device=UpperCAmelCase ) # forward pass with torch.no_grad(): lowerCamelCase__ : str = model(input_ids=UpperCAmelCase , bbox=UpperCAmelCase ) lowerCamelCase__ : List[str] = torch.Size([1, 2, 768] ) lowerCamelCase__ : Any = torch.tensor( [[-0.0_6_5_3, 0.0_9_5_0, -0.0_0_6_1], [-0.0_5_4_5, 0.0_9_2_6, -0.0_3_2_4]] , device=UpperCAmelCase , ) self.assertTrue(outputs.last_hidden_state.shape , UpperCAmelCase ) self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :, :3] , UpperCAmelCase , atol=1e-3 ) )
50
import json import os import subprocess import unittest from ast import literal_eval import pytest from parameterized import parameterized, parameterized_class from . import is_sagemaker_available if is_sagemaker_available(): from sagemaker import Session, TrainingJobAnalytics from sagemaker.huggingface import HuggingFace @pytest.mark.skipif( literal_eval(os.getenv('''TEST_SAGEMAKER''' , '''False''' ) ) is not True , reason='''Skipping test because should only be run when releasing minor transformers version''' , ) @pytest.mark.usefixtures('''sm_env''' ) @parameterized_class( [ { '''framework''': '''pytorch''', '''script''': '''run_glue_model_parallelism.py''', '''model_name_or_path''': '''roberta-large''', '''instance_type''': '''ml.p3dn.24xlarge''', '''results''': {'''train_runtime''': 1_600, '''eval_accuracy''': 0.3, '''eval_loss''': 1.2}, }, { '''framework''': '''pytorch''', '''script''': '''run_glue.py''', '''model_name_or_path''': '''roberta-large''', '''instance_type''': '''ml.p3dn.24xlarge''', '''results''': {'''train_runtime''': 1_600, '''eval_accuracy''': 0.3, '''eval_loss''': 1.2}, }, ] ) class A_ ( unittest.TestCase ): def lowerCAmelCase ( self : Union[str, Any]): if self.framework == "pytorch": subprocess.run( F"cp ./examples/pytorch/text-classification/run_glue.py {self.env.test_path}/run_glue.py".split() ,encoding='utf-8' ,check=SCREAMING_SNAKE_CASE__ ,) assert hasattr(self ,'env') def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : int): # configuration for running training on smdistributed Model Parallel __lowerCamelCase : Any = { 'enabled': True, 'processes_per_host': 8, } __lowerCamelCase : List[Any] = { 'enabled': True, 'parameters': { 'microbatches': 4, 'placement_strategy': 'spread', 'pipeline': 'interleaved', 'optimize': 'speed', 'partitions': 4, 'ddp': True, }, } __lowerCamelCase : str = {'smdistributed': {'modelparallel': smp_options}, 'mpi': mpi_options} __lowerCamelCase : List[str] = 'trainer' if self.script == 'run_glue.py' else 'smtrainer' # creates estimator return HuggingFace( entry_point=self.script ,source_dir=self.env.test_path ,role=self.env.role ,image_uri=self.env.image_uri ,base_job_name=F"{self.env.base_job_name}-{instance_count}-smp-{name_extension}" ,instance_count=SCREAMING_SNAKE_CASE__ ,instance_type=self.instance_type ,debugger_hook_config=SCREAMING_SNAKE_CASE__ ,hyperparameters={ **self.env.hyperparameters, 'model_name_or_path': self.model_name_or_path, 'max_steps': 5_0_0, } ,metric_definitions=self.env.metric_definitions ,distribution=SCREAMING_SNAKE_CASE__ ,py_version='py36' ,) def lowerCAmelCase ( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : Any): TrainingJobAnalytics(SCREAMING_SNAKE_CASE__).export_csv(F"{self.env.test_path}/{job_name}_metrics.csv") @parameterized.expand([(1,)]) def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : Optional[Any]): # create estimator __lowerCamelCase : str = self.create_estimator(SCREAMING_SNAKE_CASE__) # run training estimator.fit() # result dataframe __lowerCamelCase : List[str] = TrainingJobAnalytics(estimator.latest_training_job.name).dataframe() # extract kpis __lowerCamelCase : Optional[int] = list(result_metrics_df[result_metrics_df.metric_name == 'eval_accuracy']['value']) __lowerCamelCase : Any = list(result_metrics_df[result_metrics_df.metric_name == 'eval_loss']['value']) # get train time from SageMaker job, this includes starting, preprocessing, stopping __lowerCamelCase : str = ( Session().describe_training_job(estimator.latest_training_job.name).get('TrainingTimeInSeconds' ,9_9_9_9_9_9) ) # assert kpis assert train_runtime <= self.results["train_runtime"] assert all(t >= self.results['eval_accuracy'] for t in eval_accuracy) assert all(t <= self.results['eval_loss'] for t in eval_loss) # dump tests result into json file to share in PR with open(F"{estimator.latest_training_job.name}.json" ,'w') as outfile: json.dump({'train_time': train_runtime, 'eval_accuracy': eval_accuracy, 'eval_loss': eval_loss} ,SCREAMING_SNAKE_CASE__)
73
0
import json import os from collections import Counter import torch import torchvision import torchvision.transforms as transforms from PIL import Image from torch import nn from torch.utils.data import Dataset snake_case_ : Any = {1: (1, 1), 2: (2, 1), 3: (3, 1), 4: (2, 2), 5: (5, 1), 6: (3, 2), 7: (7, 1), 8: (4, 2), 9: (3, 3)} class __snake_case ( nn.Module ): def __init__( self : List[Any] , _snake_case : Any): """simple docstring""" super().__init__() UpperCAmelCase_ = torchvision.models.resnetaaa(pretrained=_snake_case) UpperCAmelCase_ = list(model.children())[:-2] UpperCAmelCase_ = nn.Sequential(*_snake_case) UpperCAmelCase_ = nn.AdaptiveAvgPoolad(POOLING_BREAKDOWN[args.num_image_embeds]) def lowerCamelCase ( self : Optional[Any] , _snake_case : Tuple): """simple docstring""" UpperCAmelCase_ = self.pool(self.model(_snake_case)) UpperCAmelCase_ = torch.flatten(_snake_case , start_dim=2) UpperCAmelCase_ = out.transpose(1 , 2).contiguous() return out # BxNx2048 class __snake_case ( a ): def __init__( self : int , _snake_case : List[Any] , _snake_case : List[str] , _snake_case : Optional[Any] , _snake_case : List[Any] , _snake_case : Optional[Any]): """simple docstring""" UpperCAmelCase_ = [json.loads(_snake_case) for l in open(_snake_case)] UpperCAmelCase_ = os.path.dirname(_snake_case) UpperCAmelCase_ = tokenizer UpperCAmelCase_ = labels UpperCAmelCase_ = len(_snake_case) UpperCAmelCase_ = max_seq_length UpperCAmelCase_ = transforms def __len__( self : Union[str, Any]): """simple docstring""" return len(self.data) def __getitem__( self : Dict , _snake_case : Tuple): """simple docstring""" UpperCAmelCase_ = torch.LongTensor(self.tokenizer.encode(self.data[index]['''text'''] , add_special_tokens=_snake_case)) UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ = sentence[0], sentence[1:-1], sentence[-1] UpperCAmelCase_ = sentence[: self.max_seq_length] UpperCAmelCase_ = torch.zeros(self.n_classes) UpperCAmelCase_ = 1 UpperCAmelCase_ = Image.open(os.path.join(self.data_dir , self.data[index]['''img'''])).convert('''RGB''') UpperCAmelCase_ = self.transforms(_snake_case) return { "image_start_token": start_token, "image_end_token": end_token, "sentence": sentence, "image": image, "label": label, } def lowerCamelCase ( self : Optional[int]): """simple docstring""" UpperCAmelCase_ = Counter() for row in self.data: label_freqs.update(row['''label''']) return label_freqs def A (__A : List[str] ) -> Union[str, Any]: """simple docstring""" UpperCAmelCase_ = [len(row['''sentence'''] ) for row in batch] UpperCAmelCase_ , UpperCAmelCase_ = len(__A ), max(__A ) UpperCAmelCase_ = torch.zeros(__A , __A , dtype=torch.long ) UpperCAmelCase_ = torch.zeros(__A , __A , dtype=torch.long ) for i_batch, (input_row, length) in enumerate(zip(__A , __A ) ): UpperCAmelCase_ = input_row['''sentence'''] UpperCAmelCase_ = 1 UpperCAmelCase_ = torch.stack([row['''image'''] for row in batch] ) UpperCAmelCase_ = torch.stack([row['''label'''] for row in batch] ) UpperCAmelCase_ = torch.stack([row['''image_start_token'''] for row in batch] ) UpperCAmelCase_ = torch.stack([row['''image_end_token'''] for row in batch] ) return text_tensor, mask_tensor, img_tensor, img_start_token, img_end_token, tgt_tensor def A () -> Dict: """simple docstring""" return [ "Crime", "Drama", "Thriller", "Action", "Comedy", "Romance", "Documentary", "Short", "Mystery", "History", "Family", "Adventure", "Fantasy", "Sci-Fi", "Western", "Horror", "Sport", "War", "Music", "Musical", "Animation", "Biography", "Film-Noir", ] def A () -> Optional[Any]: """simple docstring""" return transforms.Compose( [ transforms.Resize(256 ), transforms.CenterCrop(224 ), transforms.ToTensor(), transforms.Normalize( mean=[0.46_777_044, 0.44_531_429, 0.40_661_017] , std=[0.12_221_994, 0.12_145_835, 0.14_380_469] , ), ] )
51
import unittest import numpy as np from transformers import DistilBertConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask if is_flax_available(): import jax.numpy as jnp from transformers.models.distilbert.modeling_flax_distilbert import ( FlaxDistilBertForMaskedLM, FlaxDistilBertForMultipleChoice, FlaxDistilBertForQuestionAnswering, FlaxDistilBertForSequenceClassification, FlaxDistilBertForTokenClassification, FlaxDistilBertModel, ) class A_ ( unittest.TestCase ): def __init__( self : Tuple ,SCREAMING_SNAKE_CASE__ : List[str] ,SCREAMING_SNAKE_CASE__ : Any=1_3 ,SCREAMING_SNAKE_CASE__ : int=7 ,SCREAMING_SNAKE_CASE__ : str=True ,SCREAMING_SNAKE_CASE__ : Dict=True ,SCREAMING_SNAKE_CASE__ : str=True ,SCREAMING_SNAKE_CASE__ : Dict=True ,SCREAMING_SNAKE_CASE__ : List[Any]=9_9 ,SCREAMING_SNAKE_CASE__ : List[Any]=3_2 ,SCREAMING_SNAKE_CASE__ : int=5 ,SCREAMING_SNAKE_CASE__ : List[Any]=4 ,SCREAMING_SNAKE_CASE__ : Optional[Any]=3_7 ,SCREAMING_SNAKE_CASE__ : Union[str, Any]="gelu" ,SCREAMING_SNAKE_CASE__ : int=0.1 ,SCREAMING_SNAKE_CASE__ : Optional[int]=0.1 ,SCREAMING_SNAKE_CASE__ : Optional[int]=5_1_2 ,SCREAMING_SNAKE_CASE__ : Dict=1_6 ,SCREAMING_SNAKE_CASE__ : Dict=2 ,SCREAMING_SNAKE_CASE__ : Optional[int]=0.02 ,SCREAMING_SNAKE_CASE__ : Dict=4 ,): __lowerCamelCase : int = parent __lowerCamelCase : Dict = batch_size __lowerCamelCase : Union[str, Any] = seq_length __lowerCamelCase : List[Any] = is_training __lowerCamelCase : Tuple = use_attention_mask __lowerCamelCase : List[str] = use_token_type_ids __lowerCamelCase : Any = use_labels __lowerCamelCase : List[str] = vocab_size __lowerCamelCase : Any = hidden_size __lowerCamelCase : Tuple = num_hidden_layers __lowerCamelCase : Union[str, Any] = num_attention_heads __lowerCamelCase : Union[str, Any] = intermediate_size __lowerCamelCase : List[Any] = hidden_act __lowerCamelCase : int = hidden_dropout_prob __lowerCamelCase : int = attention_probs_dropout_prob __lowerCamelCase : Union[str, Any] = max_position_embeddings __lowerCamelCase : Union[str, Any] = type_vocab_size __lowerCamelCase : List[str] = type_sequence_label_size __lowerCamelCase : Tuple = initializer_range __lowerCamelCase : Optional[int] = num_choices def lowerCAmelCase ( self : Union[str, Any]): __lowerCamelCase : Dict = ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size) __lowerCamelCase : Union[str, Any] = None if self.use_attention_mask: __lowerCamelCase : Any = random_attention_mask([self.batch_size, self.seq_length]) __lowerCamelCase : str = DistilBertConfig( vocab_size=self.vocab_size ,dim=self.hidden_size ,n_layers=self.num_hidden_layers ,n_heads=self.num_attention_heads ,hidden_dim=self.intermediate_size ,hidden_act=self.hidden_act ,dropout=self.hidden_dropout_prob ,attention_dropout=self.attention_probs_dropout_prob ,max_position_embeddings=self.max_position_embeddings ,initializer_range=self.initializer_range ,tie_weights_=SCREAMING_SNAKE_CASE__ ,) return config, input_ids, attention_mask def lowerCAmelCase ( self : List[Any]): __lowerCamelCase : List[str] = self.prepare_config_and_inputs() __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : Dict = config_and_inputs __lowerCamelCase : Any = {'input_ids': input_ids, 'attention_mask': attention_mask} return config, inputs_dict @require_flax class A_ ( SCREAMING_SNAKE_CASE , unittest.TestCase ): _UpperCAmelCase : Dict = ( ( FlaxDistilBertModel, FlaxDistilBertForMaskedLM, FlaxDistilBertForMultipleChoice, FlaxDistilBertForQuestionAnswering, FlaxDistilBertForSequenceClassification, FlaxDistilBertForTokenClassification, FlaxDistilBertForQuestionAnswering, ) if is_flax_available() else () ) def lowerCAmelCase ( self : Optional[Any]): __lowerCamelCase : Tuple = FlaxDistilBertModelTester(self) @slow def lowerCAmelCase ( self : int): for model_class_name in self.all_model_classes: __lowerCamelCase : List[Any] = model_class_name.from_pretrained('distilbert-base-uncased') __lowerCamelCase : List[str] = model(np.ones((1, 1))) self.assertIsNotNone(SCREAMING_SNAKE_CASE__) @require_flax class A_ ( unittest.TestCase ): @slow def lowerCAmelCase ( self : str): __lowerCamelCase : Union[str, Any] = FlaxDistilBertModel.from_pretrained('distilbert-base-uncased') __lowerCamelCase : str = np.array([[0, 3_4_5, 2_3_2, 3_2_8, 7_4_0, 1_4_0, 1_6_9_5, 6_9, 6_0_7_8, 1_5_8_8, 2]]) __lowerCamelCase : List[Any] = np.array([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]) __lowerCamelCase : Union[str, Any] = model(SCREAMING_SNAKE_CASE__ ,attention_mask=SCREAMING_SNAKE_CASE__)[0] __lowerCamelCase : Optional[int] = (1, 1_1, 7_6_8) self.assertEqual(output.shape ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Union[str, Any] = np.array([[[-0.1639, 0.3299, 0.1648], [-0.1746, 0.3289, 0.1710], [-0.1884, 0.3357, 0.1810]]]) self.assertTrue(jnp.allclose(output[:, 1:4, 1:4] ,SCREAMING_SNAKE_CASE__ ,atol=1E-4))
73
0
import logging from dataclasses import dataclass, field from typing import Optional from seqaseq_trainer import arg_to_scheduler from transformers import TrainingArguments __lowerCamelCase : Optional[Any] = logging.getLogger(__name__) @dataclass class A__ ( __snake_case ): _UpperCAmelCase :Optional[float] = field( default=0.0 , metadata={'help': 'The label smoothing epsilon to apply (if not zero).'} ) _UpperCAmelCase :bool = field(default=__snake_case , metadata={'help': 'Whether to SortishSamler or not.'} ) _UpperCAmelCase :bool = field( default=__snake_case , metadata={'help': 'Whether to use generate to calculate generative metrics (ROUGE, BLEU).'} ) _UpperCAmelCase :bool = field(default=__snake_case , metadata={'help': 'whether to use adafactor'} ) _UpperCAmelCase :Optional[float] = field( default=__snake_case , metadata={'help': 'Encoder layer dropout probability. Goes into model.config.'} ) _UpperCAmelCase :Optional[float] = field( default=__snake_case , metadata={'help': 'Decoder layer dropout probability. Goes into model.config.'} ) _UpperCAmelCase :Optional[float] = field(default=__snake_case , metadata={'help': 'Dropout probability. Goes into model.config.'} ) _UpperCAmelCase :Optional[float] = field( default=__snake_case , metadata={'help': 'Attention dropout probability. Goes into model.config.'} ) _UpperCAmelCase :Optional[str] = field( default='linear' , metadata={'help': f"Which lr scheduler to use. Selected in {sorted(arg_to_scheduler.keys() )}"} , )
52
import csv import tweepy # Twitter API credentials a ="""""" a ="""""" a ="""""" a ="""""" def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> None: # authorize twitter, initialize tweepy __lowerCamelCase : Tuple = tweepy.OAuthHandler(lowerCamelCase__ , lowerCamelCase__ ) auth.set_access_token(lowerCamelCase__ , lowerCamelCase__ ) __lowerCamelCase : Optional[int] = tweepy.API(lowerCamelCase__ ) # initialize a list to hold all the tweepy Tweets __lowerCamelCase : str = [] # make initial request for most recent tweets (200 is the maximum allowed count) __lowerCamelCase : Union[str, Any] = api.user_timeline(screen_name=lowerCamelCase__ , count=2_0_0 ) # save most recent tweets alltweets.extend(lowerCamelCase__ ) # save the id of the oldest tweet less one __lowerCamelCase : Any = alltweets[-1].id - 1 # keep grabbing tweets until there are no tweets left to grab while len(lowerCamelCase__ ) > 0: print(F"getting tweets before {oldest}" ) # all subsequent requests use the max_id param to prevent duplicates __lowerCamelCase : str = api.user_timeline( screen_name=lowerCamelCase__ , count=2_0_0 , max_id=lowerCamelCase__ ) # save most recent tweets alltweets.extend(lowerCamelCase__ ) # update the id of the oldest tweet less one __lowerCamelCase : Optional[int] = alltweets[-1].id - 1 print(F"...{len(lowerCamelCase__ )} tweets downloaded so far" ) # transform the tweepy tweets into a 2D array that will populate the csv __lowerCamelCase : str = [[tweet.id_str, tweet.created_at, tweet.text] for tweet in alltweets] # write the csv with open(F"new_{screen_name}_tweets.csv" , 'w' ) as f: __lowerCamelCase : Any = csv.writer(lowerCamelCase__ ) writer.writerow(['id', 'created_at', 'text'] ) writer.writerows(lowerCamelCase__ ) if __name__ == "__main__": # pass in the username of the account you want to download get_all_tweets("""FirePing32""")
73
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) a__ : int ={'''configuration_xglm''': ['''XGLM_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''XGLMConfig''']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : str =['''XGLMTokenizer'''] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Optional[Any] =['''XGLMTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Optional[int] =[ '''XGLM_PRETRAINED_MODEL_ARCHIVE_LIST''', '''XGLMForCausalLM''', '''XGLMModel''', '''XGLMPreTrainedModel''', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Union[str, Any] =[ '''FlaxXGLMForCausalLM''', '''FlaxXGLMModel''', '''FlaxXGLMPreTrainedModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : List[Any] =[ '''TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFXGLMForCausalLM''', '''TFXGLMModel''', '''TFXGLMPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_xglm import XGLM_PRETRAINED_CONFIG_ARCHIVE_MAP, XGLMConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xglm import XGLMTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xglm_fast import XGLMTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xglm import XGLM_PRETRAINED_MODEL_ARCHIVE_LIST, XGLMForCausalLM, XGLMModel, XGLMPreTrainedModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_xglm import FlaxXGLMForCausalLM, FlaxXGLMModel, FlaxXGLMPreTrainedModel try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_xglm import ( TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST, TFXGLMForCausalLM, TFXGLMModel, TFXGLMPreTrainedModel, ) else: import sys a__ : Tuple =_LazyModule(__name__, globals()['''__file__'''], _import_structure)
53
import numpy as np from scipy.spatial.distance import cdist from sklearn.metrics import fa_score import datasets a ="""\ @inproceedings{kakwani2020indicnlpsuite, title={{IndicNLPSuite: Monolingual Corpora, Evaluation Benchmarks and Pre-trained Multilingual Language Models for Indian Languages}}, author={Divyanshu Kakwani and Anoop Kunchukuttan and Satish Golla and Gokul N.C. and Avik Bhattacharyya and Mitesh M. Khapra and Pratyush Kumar}, year={2020}, booktitle={Findings of EMNLP}, } """ a ="""\ IndicGLUE is a natural language understanding benchmark for Indian languages. It contains a wide variety of tasks and covers 11 major Indian languages - as, bn, gu, hi, kn, ml, mr, or, pa, ta, te. """ a =""" Compute IndicGLUE evaluation metric associated to each IndicGLUE dataset. Args: predictions: list of predictions to score (as int64), except for 'cvit-mkb-clsr' where each prediction is a vector (of float32). references: list of ground truth labels corresponding to the predictions (as int64), except for 'cvit-mkb-clsr' where each reference is a vector (of float32). Returns: depending on the IndicGLUE subset, one or several of: \"accuracy\": Accuracy \"f1\": F1 score \"precision\": Precision@10 Examples: >>> indic_glue_metric = datasets.load_metric('indic_glue', 'wnli') # 'wnli' or any of [\"copa\", \"sna\", \"csqa\", \"wstp\", \"inltkh\", \"bbca\", \"iitp-mr\", \"iitp-pr\", \"actsa-sc\", \"md\"] >>> references = [0, 1] >>> predictions = [0, 1] >>> results = indic_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {'accuracy': 1.0} >>> indic_glue_metric = datasets.load_metric('indic_glue', 'wiki-ner') >>> references = [0, 1] >>> predictions = [0, 1] >>> results = indic_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {'accuracy': 1.0, 'f1': 1.0} >>> indic_glue_metric = datasets.load_metric('indic_glue', 'cvit-mkb-clsr') >>> references = [[0.5, 0.5, 0.5], [0.1, 0.2, 0.3]] >>> predictions = [[0.5, 0.5, 0.5], [0.1, 0.2, 0.3]] >>> results = indic_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {'precision@10': 1.0} """ def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> List[str]: return float((preds == labels).mean() ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> List[str]: __lowerCamelCase : Optional[Any] = simple_accuracy(lowerCamelCase__ , lowerCamelCase__ ) __lowerCamelCase : Tuple = float(fa_score(y_true=lowerCamelCase__ , y_pred=lowerCamelCase__ ) ) return { "accuracy": acc, "f1": fa, } def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> Optional[Any]: __lowerCamelCase : Any = np.array(lowerCamelCase__ ) __lowerCamelCase : List[Any] = np.array(lowerCamelCase__ ) __lowerCamelCase : Any = en_sentvecs.shape[0] # mean centering __lowerCamelCase : Union[str, Any] = en_sentvecs - np.mean(lowerCamelCase__ , axis=0 ) __lowerCamelCase : Dict = in_sentvecs - np.mean(lowerCamelCase__ , axis=0 ) __lowerCamelCase : Optional[int] = cdist(lowerCamelCase__ , lowerCamelCase__ , 'cosine' ) __lowerCamelCase : Optional[Any] = np.array(range(lowerCamelCase__ ) ) __lowerCamelCase : Dict = sim.argsort(axis=1 )[:, :1_0] __lowerCamelCase : Optional[int] = np.any(preds == actual[:, None] , axis=1 ) return float(matches.mean() ) @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class A_ ( datasets.Metric ): def lowerCAmelCase ( self : Optional[Any]): if self.config_name not in [ "wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", "cvit-mkb-clsr", "iitp-mr", "iitp-pr", "actsa-sc", "md", "wiki-ner", ]: raise KeyError( 'You should supply a configuration name selected in ' '["wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", ' '"cvit-mkb-clsr", "iitp-mr", "iitp-pr", "actsa-sc", "md", ' '"wiki-ner"]') return datasets.MetricInfo( description=_DESCRIPTION ,citation=_CITATION ,inputs_description=_KWARGS_DESCRIPTION ,features=datasets.Features( { 'predictions': datasets.Value('int64') if self.config_name != 'cvit-mkb-clsr' else datasets.Sequence(datasets.Value('float32')), 'references': datasets.Value('int64') if self.config_name != 'cvit-mkb-clsr' else datasets.Sequence(datasets.Value('float32')), }) ,codebase_urls=[] ,reference_urls=[] ,format='numpy' if self.config_name != 'cvit-mkb-clsr' else None ,) def lowerCAmelCase ( self : Any ,SCREAMING_SNAKE_CASE__ : Tuple ,SCREAMING_SNAKE_CASE__ : Optional[Any]): if self.config_name == "cvit-mkb-clsr": return {"precision@10": precision_at_aa(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__)} elif self.config_name in ["wiki-ner"]: return acc_and_fa(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) elif self.config_name in [ "wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", "iitp-mr", "iitp-pr", "actsa-sc", "md", ]: return {"accuracy": simple_accuracy(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__)} else: raise KeyError( 'You should supply a configuration name selected in ' '["wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", ' '"cvit-mkb-clsr", "iitp-mr", "iitp-pr", "actsa-sc", "md", ' '"wiki-ner"]')
73
0
"""simple docstring""" from abc import ABC, abstractmethod from argparse import ArgumentParser class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" @staticmethod @abstractmethod def UpperCAmelCase_ ( UpperCAmelCase__ : ArgumentParser ) -> int: raise NotImplementedError() @abstractmethod def UpperCAmelCase_ ( self : int ) -> Optional[int]: raise NotImplementedError()
54
from __future__ import annotations from scipy.special import comb # type: ignore class A_ : def __init__( self : List[str] ,SCREAMING_SNAKE_CASE__ : list[tuple[float, float]]): __lowerCamelCase : Union[str, Any] = list_of_points # Degree determines the flexibility of the curve. # Degree = 1 will produce a straight line. __lowerCamelCase : int = len(SCREAMING_SNAKE_CASE__) - 1 def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : float): assert 0 <= t <= 1, "Time t must be between 0 and 1." __lowerCamelCase : list[float] = [] for i in range(len(self.list_of_points)): # basis function for each i output_values.append( comb(self.degree ,SCREAMING_SNAKE_CASE__) * ((1 - t) ** (self.degree - i)) * (t**i)) # the basis must sum up to 1 for it to produce a valid Bezier curve. assert round(sum(SCREAMING_SNAKE_CASE__) ,5) == 1 return output_values def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : float): assert 0 <= t <= 1, "Time t must be between 0 and 1." __lowerCamelCase : Tuple = self.basis_function(SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = 0.0 __lowerCamelCase : Optional[Any] = 0.0 for i in range(len(self.list_of_points)): # For all points, sum up the product of i-th basis function and i-th point. x += basis_function[i] * self.list_of_points[i][0] y += basis_function[i] * self.list_of_points[i][1] return (x, y) def lowerCAmelCase ( self : int ,SCREAMING_SNAKE_CASE__ : float = 0.01): from matplotlib import pyplot as plt # type: ignore __lowerCamelCase : list[float] = [] # x coordinates of points to plot __lowerCamelCase : list[float] = [] # y coordinates of points to plot __lowerCamelCase : Any = 0.0 while t <= 1: __lowerCamelCase : List[Any] = self.bezier_curve_function(SCREAMING_SNAKE_CASE__) to_plot_x.append(value[0]) to_plot_y.append(value[1]) t += step_size __lowerCamelCase : Optional[Any] = [i[0] for i in self.list_of_points] __lowerCamelCase : List[str] = [i[1] for i in self.list_of_points] plt.plot( SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,color='blue' ,label='Curve of Degree ' + str(self.degree) ,) plt.scatter(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,color='red' ,label='Control Points') plt.legend() plt.show() if __name__ == "__main__": import doctest doctest.testmod() BezierCurve([(1, 2), (3, 5)]).plot_curve() # degree 1 BezierCurve([(0, 0), (5, 5), (5, 0)]).plot_curve() # degree 2 BezierCurve([(0, 0), (5, 5), (5, 0), (2.5, -2.5)]).plot_curve() # degree 3
73
0
'''simple docstring''' import json import os import unittest from transformers import MgpstrTokenizer from transformers.models.mgp_str.tokenization_mgp_str import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class snake_case ( lowercase , unittest.TestCase ): """simple docstring""" _lowerCamelCase = MgpstrTokenizer _lowerCamelCase = False _lowerCamelCase = {} _lowerCamelCase = False def snake_case ( self ): """simple docstring""" super().setUp() # fmt: off lowerCamelCase_ = ["[GO]", "[s]", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"] # fmt: on lowerCamelCase_ = dict(zip(UpperCamelCase , range(len(UpperCamelCase ) ) ) ) lowerCamelCase_ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as fp: fp.write(json.dumps(UpperCamelCase ) + "\n" ) def snake_case ( self , **UpperCamelCase ): """simple docstring""" return MgpstrTokenizer.from_pretrained(self.tmpdirname , **UpperCamelCase ) def snake_case ( self , UpperCamelCase ): """simple docstring""" lowerCamelCase_ = "tester" lowerCamelCase_ = "tester" return input_text, output_text @unittest.skip("MGP-STR always lower cases letters." ) def snake_case ( self ): """simple docstring""" pass def snake_case ( self ): """simple docstring""" lowerCamelCase_ = self.get_tokenizers(do_lower_case=UpperCamelCase ) for tokenizer in tokenizers: with self.subTest(f'''{tokenizer.__class__.__name__}''' ): lowerCamelCase_ = "[SPECIAL_TOKEN]" tokenizer.add_special_tokens({"cls_token": special_token} ) lowerCamelCase_ = tokenizer.encode([special_token] , add_special_tokens=UpperCamelCase ) self.assertEqual(len(UpperCamelCase ) , 1 ) lowerCamelCase_ = tokenizer.decode(UpperCamelCase , skip_special_tokens=UpperCamelCase ) self.assertTrue(special_token not in decoded ) def snake_case ( self ): """simple docstring""" lowerCamelCase_ = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(f'''{tokenizer.__class__.__name__}''' ): lowerCamelCase_ ,lowerCamelCase_ = self.get_input_output_texts(UpperCamelCase ) lowerCamelCase_ = tokenizer.tokenize(UpperCamelCase ) lowerCamelCase_ = tokenizer.convert_tokens_to_ids(UpperCamelCase ) lowerCamelCase_ = tokenizer.encode(UpperCamelCase , add_special_tokens=UpperCamelCase ) self.assertListEqual(UpperCamelCase , UpperCamelCase ) lowerCamelCase_ = tokenizer.convert_ids_to_tokens(UpperCamelCase ) self.assertNotEqual(len(UpperCamelCase ) , 0 ) lowerCamelCase_ = tokenizer.decode(UpperCamelCase ) self.assertIsInstance(UpperCamelCase , UpperCamelCase ) self.assertEqual(text_a.replace(" " , "" ) , UpperCamelCase ) @unittest.skip("MGP-STR tokenizer only handles one sequence." ) def snake_case ( self ): """simple docstring""" pass @unittest.skip("inputs cannot be pretokenized in MgpstrTokenizer" ) def snake_case ( self ): """simple docstring""" pass
55
from __future__ import annotations import time a =list[tuple[int, int]] a =[ [0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles [0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0], [1, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0], ] a =[[-1, 0], [0, -1], [1, 0], [0, 1]] # up, left, down, right class A_ : def __init__( self : List[str] ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : Node | None): __lowerCamelCase : Tuple = pos_x __lowerCamelCase : List[str] = pos_y __lowerCamelCase : str = (pos_y, pos_x) __lowerCamelCase : str = goal_x __lowerCamelCase : int = goal_y __lowerCamelCase : List[Any] = parent class A_ : def __init__( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : tuple[int, int] ,SCREAMING_SNAKE_CASE__ : tuple[int, int]): __lowerCamelCase : Any = Node(start[1] ,start[0] ,goal[1] ,goal[0] ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = Node(goal[1] ,goal[0] ,goal[1] ,goal[0] ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Union[str, Any] = [self.start] __lowerCamelCase : List[str] = False def lowerCAmelCase ( self : List[Any]): while self.node_queue: __lowerCamelCase : Any = self.node_queue.pop(0) if current_node.pos == self.target.pos: __lowerCamelCase : Dict = True return self.retrace_path(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Tuple = self.get_successors(SCREAMING_SNAKE_CASE__) for node in successors: self.node_queue.append(SCREAMING_SNAKE_CASE__) if not self.reached: return [self.start.pos] return None def lowerCAmelCase ( self : str ,SCREAMING_SNAKE_CASE__ : Node): __lowerCamelCase : Union[str, Any] = [] for action in delta: __lowerCamelCase : Optional[Any] = parent.pos_x + action[1] __lowerCamelCase : Optional[int] = parent.pos_y + action[0] if not (0 <= pos_x <= len(grid[0]) - 1 and 0 <= pos_y <= len(SCREAMING_SNAKE_CASE__) - 1): continue if grid[pos_y][pos_x] != 0: continue successors.append( Node(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,self.target.pos_y ,self.target.pos_x ,SCREAMING_SNAKE_CASE__)) return successors def lowerCAmelCase ( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : Node | None): __lowerCamelCase : List[Any] = node __lowerCamelCase : int = [] while current_node is not None: path.append((current_node.pos_y, current_node.pos_x)) __lowerCamelCase : int = current_node.parent path.reverse() return path class A_ : def __init__( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : int): __lowerCamelCase : int = BreadthFirstSearch(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = BreadthFirstSearch(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = False def lowerCAmelCase ( self : str): while self.fwd_bfs.node_queue or self.bwd_bfs.node_queue: __lowerCamelCase : Any = self.fwd_bfs.node_queue.pop(0) __lowerCamelCase : Any = self.bwd_bfs.node_queue.pop(0) if current_bwd_node.pos == current_fwd_node.pos: __lowerCamelCase : List[str] = True return self.retrace_bidirectional_path( SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = current_bwd_node __lowerCamelCase : int = current_fwd_node __lowerCamelCase : str = { self.fwd_bfs: self.fwd_bfs.get_successors(SCREAMING_SNAKE_CASE__), self.bwd_bfs: self.bwd_bfs.get_successors(SCREAMING_SNAKE_CASE__), } for bfs in [self.fwd_bfs, self.bwd_bfs]: for node in successors[bfs]: bfs.node_queue.append(SCREAMING_SNAKE_CASE__) if not self.reached: return [self.fwd_bfs.start.pos] return None def lowerCAmelCase ( self : Dict ,SCREAMING_SNAKE_CASE__ : Node ,SCREAMING_SNAKE_CASE__ : Node): __lowerCamelCase : List[Any] = self.fwd_bfs.retrace_path(SCREAMING_SNAKE_CASE__) __lowerCamelCase : str = self.bwd_bfs.retrace_path(SCREAMING_SNAKE_CASE__) bwd_path.pop() bwd_path.reverse() __lowerCamelCase : List[Any] = fwd_path + bwd_path return path if __name__ == "__main__": # all coordinates are given in format [y,x] import doctest doctest.testmod() a =(0, 0) a =(len(grid) - 1, len(grid[0]) - 1) for elem in grid: print(elem) a =time.time() a =BreadthFirstSearch(init, goal) a =bfs.search() a =time.time() - start_bfs_time print("""Unidirectional BFS computation time : """, bfs_time) a =time.time() a =BidirectionalBreadthFirstSearch(init, goal) a =bd_bfs.search() a =time.time() - start_bd_bfs_time print("""Bidirectional BFS computation time : """, bd_bfs_time)
73
0
'''simple docstring''' import json import os import pickle import shutil import tempfile from unittest import TestCase from unittest.mock import patch import numpy as np from datasets import Dataset from transformers import is_faiss_available from transformers.models.bart.configuration_bart import BartConfig from transformers.models.bart.tokenization_bart import BartTokenizer from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES as DPR_VOCAB_FILES_NAMES from transformers.models.dpr.configuration_dpr import DPRConfig from transformers.models.dpr.tokenization_dpr import DPRContextEncoderTokenizer, DPRQuestionEncoderTokenizer from transformers.models.rag.configuration_rag import RagConfig from transformers.models.rag.retrieval_rag import CustomHFIndex, RagRetriever from transformers.models.roberta.tokenization_roberta import VOCAB_FILES_NAMES as BART_VOCAB_FILES_NAMES from transformers.testing_utils import require_faiss, require_sentencepiece, require_tokenizers, require_torch if is_faiss_available(): import faiss @require_faiss class a ( _lowerCamelCase ): def A_ ( self : str ): snake_case_ = tempfile.mkdtemp() snake_case_ = 8 # DPR tok snake_case_ = [ '''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest''', ] snake_case_ = os.path.join(self.tmpdirname , '''dpr_tokenizer''' ) os.makedirs(lowercase_ , exist_ok=lowercase_ ) snake_case_ = os.path.join(lowercase_ , DPR_VOCAB_FILES_NAMES['''vocab_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) ) # BART tok snake_case_ = [ '''l''', '''o''', '''w''', '''e''', '''r''', '''s''', '''t''', '''i''', '''d''', '''n''', '''\u0120''', '''\u0120l''', '''\u0120n''', '''\u0120lo''', '''\u0120low''', '''er''', '''\u0120lowest''', '''\u0120newer''', '''\u0120wider''', '''<unk>''', ] snake_case_ = dict(zip(lowercase_ , range(len(lowercase_ ) ) ) ) snake_case_ = ['''#version: 0.2''', '''\u0120 l''', '''\u0120l o''', '''\u0120lo w''', '''e r''', ''''''] snake_case_ = {'''unk_token''': '''<unk>'''} snake_case_ = os.path.join(self.tmpdirname , '''bart_tokenizer''' ) os.makedirs(lowercase_ , exist_ok=lowercase_ ) snake_case_ = os.path.join(lowercase_ , BART_VOCAB_FILES_NAMES['''vocab_file'''] ) snake_case_ = os.path.join(lowercase_ , BART_VOCAB_FILES_NAMES['''merges_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write(json.dumps(lowercase_ ) + '''\n''' ) with open(self.merges_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write('''\n'''.join(lowercase_ ) ) def A_ ( self : Union[str, Any] ): return DPRQuestionEncoderTokenizer.from_pretrained(os.path.join(self.tmpdirname , '''dpr_tokenizer''' ) ) def A_ ( self : Union[str, Any] ): return DPRContextEncoderTokenizer.from_pretrained(os.path.join(self.tmpdirname , '''dpr_tokenizer''' ) ) def A_ ( self : int ): return BartTokenizer.from_pretrained(os.path.join(self.tmpdirname , '''bart_tokenizer''' ) ) def A_ ( self : str ): shutil.rmtree(self.tmpdirname ) def A_ ( self : str ): snake_case_ = Dataset.from_dict( { '''id''': ['''0''', '''1'''], '''text''': ['''foo''', '''bar'''], '''title''': ['''Foo''', '''Bar'''], '''embeddings''': [np.ones(self.retrieval_vector_size ), 2 * np.ones(self.retrieval_vector_size )], } ) dataset.add_faiss_index('''embeddings''' , string_factory='''Flat''' , metric_type=faiss.METRIC_INNER_PRODUCT ) return dataset def A_ ( self : str ): snake_case_ = self.get_dummy_dataset() snake_case_ = RagConfig( retrieval_vector_size=self.retrieval_vector_size , question_encoder=DPRConfig().to_dict() , generator=BartConfig().to_dict() , ) with patch('''transformers.models.rag.retrieval_rag.load_dataset''' ) as mock_load_dataset: snake_case_ = dataset snake_case_ = RagRetriever( lowercase_ , question_encoder_tokenizer=self.get_dpr_tokenizer() , generator_tokenizer=self.get_bart_tokenizer() , ) return retriever def A_ ( self : str , lowercase_ : bool ): snake_case_ = self.get_dummy_dataset() snake_case_ = RagConfig( retrieval_vector_size=self.retrieval_vector_size , question_encoder=DPRConfig().to_dict() , generator=BartConfig().to_dict() , index_name='''custom''' , ) if from_disk: snake_case_ = os.path.join(self.tmpdirname , '''dataset''' ) snake_case_ = os.path.join(self.tmpdirname , '''index.faiss''' ) dataset.get_index('''embeddings''' ).save(os.path.join(self.tmpdirname , '''index.faiss''' ) ) dataset.drop_index('''embeddings''' ) dataset.save_to_disk(os.path.join(self.tmpdirname , '''dataset''' ) ) del dataset snake_case_ = RagRetriever( lowercase_ , question_encoder_tokenizer=self.get_dpr_tokenizer() , generator_tokenizer=self.get_bart_tokenizer() , ) else: snake_case_ = RagRetriever( lowercase_ , question_encoder_tokenizer=self.get_dpr_tokenizer() , generator_tokenizer=self.get_bart_tokenizer() , index=CustomHFIndex(config.retrieval_vector_size , lowercase_ ) , ) return retriever def A_ ( self : Tuple ): snake_case_ = Dataset.from_dict( { '''id''': ['''0''', '''1'''], '''text''': ['''foo''', '''bar'''], '''title''': ['''Foo''', '''Bar'''], '''embeddings''': [np.ones(self.retrieval_vector_size + 1 ), 2 * np.ones(self.retrieval_vector_size + 1 )], } ) dataset.add_faiss_index('''embeddings''' , string_factory='''Flat''' , metric_type=faiss.METRIC_INNER_PRODUCT ) snake_case_ = os.path.join(self.tmpdirname , '''hf_bert_base.hnswSQ8_correct_phi_128.c_index''' ) dataset.save_faiss_index('''embeddings''' , index_file_name + '''.index.dpr''' ) pickle.dump(dataset['''id'''] , open(index_file_name + '''.index_meta.dpr''' , '''wb''' ) ) snake_case_ = os.path.join(self.tmpdirname , '''psgs_w100.tsv.pkl''' ) snake_case_ = {sample['''id''']: [sample['''text'''], sample['''title''']] for sample in dataset} pickle.dump(lowercase_ , open(lowercase_ , '''wb''' ) ) snake_case_ = RagConfig( retrieval_vector_size=self.retrieval_vector_size , question_encoder=DPRConfig().to_dict() , generator=BartConfig().to_dict() , index_name='''legacy''' , index_path=self.tmpdirname , ) snake_case_ = RagRetriever( lowercase_ , question_encoder_tokenizer=self.get_dpr_tokenizer() , generator_tokenizer=self.get_bart_tokenizer() ) return retriever def A_ ( self : Optional[Any] ): snake_case_ = 1 snake_case_ = self.get_dummy_canonical_hf_index_retriever() snake_case_ = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) snake_case_ ,snake_case_ ,snake_case_ = retriever.retrieve(lowercase_ , n_docs=lowercase_ ) self.assertEqual(retrieved_doc_embeds.shape , (2, n_docs, self.retrieval_vector_size) ) self.assertEqual(len(lowercase_ ) , 2 ) self.assertEqual(sorted(doc_dicts[0] ) , ['''embeddings''', '''id''', '''text''', '''title'''] ) self.assertEqual(len(doc_dicts[0]['''id'''] ) , lowercase_ ) self.assertEqual(doc_dicts[0]['''id'''][0] , '''1''' ) # max inner product is reached with second doc self.assertEqual(doc_dicts[1]['''id'''][0] , '''0''' ) # max inner product is reached with first doc self.assertListEqual(doc_ids.tolist() , [[1], [0]] ) def A_ ( self : str ): snake_case_ = self.get_dummy_canonical_hf_index_retriever() with tempfile.TemporaryDirectory() as tmp_dirname: with patch('''transformers.models.rag.retrieval_rag.load_dataset''' ) as mock_load_dataset: snake_case_ = self.get_dummy_dataset() retriever.save_pretrained(lowercase_ ) snake_case_ = RagRetriever.from_pretrained(lowercase_ ) self.assertIsInstance(lowercase_ , lowercase_ ) snake_case_ = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) snake_case_ = retriever.retrieve(lowercase_ , n_docs=1 ) self.assertTrue(out is not None ) def A_ ( self : int ): snake_case_ = 1 snake_case_ = self.get_dummy_custom_hf_index_retriever(from_disk=lowercase_ ) snake_case_ = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) snake_case_ ,snake_case_ ,snake_case_ = retriever.retrieve(lowercase_ , n_docs=lowercase_ ) self.assertEqual(retrieved_doc_embeds.shape , (2, n_docs, self.retrieval_vector_size) ) self.assertEqual(len(lowercase_ ) , 2 ) self.assertEqual(sorted(doc_dicts[0] ) , ['''embeddings''', '''id''', '''text''', '''title'''] ) self.assertEqual(len(doc_dicts[0]['''id'''] ) , lowercase_ ) self.assertEqual(doc_dicts[0]['''id'''][0] , '''1''' ) # max inner product is reached with second doc self.assertEqual(doc_dicts[1]['''id'''][0] , '''0''' ) # max inner product is reached with first doc self.assertListEqual(doc_ids.tolist() , [[1], [0]] ) def A_ ( self : int ): snake_case_ = self.get_dummy_custom_hf_index_retriever(from_disk=lowercase_ ) with tempfile.TemporaryDirectory() as tmp_dirname: retriever.save_pretrained(lowercase_ ) snake_case_ = RagRetriever.from_pretrained(lowercase_ ) self.assertIsInstance(lowercase_ , lowercase_ ) snake_case_ = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) snake_case_ = retriever.retrieve(lowercase_ , n_docs=1 ) self.assertTrue(out is not None ) def A_ ( self : str ): snake_case_ = 1 snake_case_ = self.get_dummy_custom_hf_index_retriever(from_disk=lowercase_ ) snake_case_ = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) snake_case_ ,snake_case_ ,snake_case_ = retriever.retrieve(lowercase_ , n_docs=lowercase_ ) self.assertEqual(retrieved_doc_embeds.shape , (2, n_docs, self.retrieval_vector_size) ) self.assertEqual(len(lowercase_ ) , 2 ) self.assertEqual(sorted(doc_dicts[0] ) , ['''embeddings''', '''id''', '''text''', '''title'''] ) self.assertEqual(len(doc_dicts[0]['''id'''] ) , lowercase_ ) self.assertEqual(doc_dicts[0]['''id'''][0] , '''1''' ) # max inner product is reached with second doc self.assertEqual(doc_dicts[1]['''id'''][0] , '''0''' ) # max inner product is reached with first doc self.assertListEqual(doc_ids.tolist() , [[1], [0]] ) def A_ ( self : Any ): snake_case_ = self.get_dummy_custom_hf_index_retriever(from_disk=lowercase_ ) with tempfile.TemporaryDirectory() as tmp_dirname: retriever.save_pretrained(lowercase_ ) snake_case_ = RagRetriever.from_pretrained(lowercase_ ) self.assertIsInstance(lowercase_ , lowercase_ ) snake_case_ = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) snake_case_ = retriever.retrieve(lowercase_ , n_docs=1 ) self.assertTrue(out is not None ) def A_ ( self : Any ): snake_case_ = 1 snake_case_ = self.get_dummy_legacy_index_retriever() snake_case_ = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) snake_case_ ,snake_case_ ,snake_case_ = retriever.retrieve(lowercase_ , n_docs=lowercase_ ) self.assertEqual(retrieved_doc_embeds.shape , (2, n_docs, self.retrieval_vector_size) ) self.assertEqual(len(lowercase_ ) , 2 ) self.assertEqual(sorted(doc_dicts[0] ) , ['''text''', '''title'''] ) self.assertEqual(len(doc_dicts[0]['''text'''] ) , lowercase_ ) self.assertEqual(doc_dicts[0]['''text'''][0] , '''bar''' ) # max inner product is reached with second doc self.assertEqual(doc_dicts[1]['''text'''][0] , '''foo''' ) # max inner product is reached with first doc self.assertListEqual(doc_ids.tolist() , [[1], [0]] ) def A_ ( self : int ): snake_case_ = self.get_dummy_legacy_index_retriever() with tempfile.TemporaryDirectory() as tmp_dirname: retriever.save_pretrained(lowercase_ ) snake_case_ = RagRetriever.from_pretrained(lowercase_ ) self.assertIsInstance(lowercase_ , lowercase_ ) snake_case_ = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) snake_case_ = retriever.retrieve(lowercase_ , n_docs=1 ) self.assertTrue(out is not None ) @require_torch @require_tokenizers @require_sentencepiece def A_ ( self : List[str] ): import torch snake_case_ = 1 snake_case_ = self.get_dummy_canonical_hf_index_retriever() snake_case_ = [[5, 7], [10, 11]] snake_case_ = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) snake_case_ = retriever(lowercase_ , lowercase_ , prefix=retriever.config.generator.prefix , n_docs=lowercase_ ) snake_case_ ,snake_case_ ,snake_case_ = ( out['''context_input_ids'''], out['''context_attention_mask'''], out['''retrieved_doc_embeds'''], ) self.assertEqual(retrieved_doc_embeds.shape , (2, n_docs, self.retrieval_vector_size) ) self.assertIsInstance(lowercase_ , lowercase_ ) self.assertIsInstance(lowercase_ , lowercase_ ) self.assertIsInstance(lowercase_ , np.ndarray ) snake_case_ = retriever( lowercase_ , lowercase_ , prefix=retriever.config.generator.prefix , n_docs=lowercase_ , return_tensors='''pt''' , ) snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ = ( # noqa: F841 out['''context_input_ids'''], out['''context_attention_mask'''], out['''retrieved_doc_embeds'''], out['''doc_ids'''], ) self.assertEqual(retrieved_doc_embeds.shape , (2, n_docs, self.retrieval_vector_size) ) self.assertIsInstance(lowercase_ , torch.Tensor ) self.assertIsInstance(lowercase_ , torch.Tensor ) self.assertIsInstance(lowercase_ , torch.Tensor ) @require_torch @require_tokenizers @require_sentencepiece def A_ ( self : Tuple ): snake_case_ = self.get_dpr_ctx_encoder_tokenizer() snake_case_ = 1 snake_case_ = self.get_dummy_custom_hf_index_retriever(from_disk=lowercase_ ) retriever.set_ctx_encoder_tokenizer(lowercase_ ) snake_case_ = [[5, 7], [10, 11]] snake_case_ = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) snake_case_ = retriever(lowercase_ , lowercase_ , prefix=retriever.config.generator.prefix , n_docs=lowercase_ ) self.assertEqual( len(lowercase_ ) , 6 ) # check whether the retriever output consist of 6 attributes including tokenized docs self.assertEqual( all(k in out for k in ('''tokenized_doc_ids''', '''tokenized_doc_attention_mask''') ) , lowercase_ ) # check for doc token related keys in dictionary.
56
import qiskit def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> qiskit.result.counts.Counts: __lowerCamelCase : Optional[int] = qiskit.Aer.get_backend('aer_simulator' ) # Create a Quantum Circuit acting on the q register __lowerCamelCase : List[str] = qiskit.QuantumCircuit(lowerCamelCase__ , lowerCamelCase__ ) # Map the quantum measurement to the classical bits circuit.measure([0] , [0] ) # Execute the circuit on the simulator __lowerCamelCase : List[Any] = qiskit.execute(lowerCamelCase__ , lowerCamelCase__ , shots=1_0_0_0 ) # Return the histogram data of the results of the experiment. return job.result().get_counts(lowerCamelCase__ ) if __name__ == "__main__": print(F"""Total count for various states are: {single_qubit_measure(1, 1)}""")
73
0
"""simple docstring""" import argparse import os import torch from diffusers import ( CMStochasticIterativeScheduler, ConsistencyModelPipeline, UNetaDModel, ) A : List[str] = { "sample_size": 3_2, "in_channels": 3, "out_channels": 3, "layers_per_block": 2, "num_class_embeds": 1_0_0_0, "block_out_channels": [3_2, 6_4], "attention_head_dim": 8, "down_block_types": [ "ResnetDownsampleBlock2D", "AttnDownBlock2D", ], "up_block_types": [ "AttnUpBlock2D", "ResnetUpsampleBlock2D", ], "resnet_time_scale_shift": "scale_shift", "upsample_type": "resnet", "downsample_type": "resnet", } A : Tuple = { "sample_size": 6_4, "in_channels": 3, "out_channels": 3, "layers_per_block": 3, "num_class_embeds": 1_0_0_0, "block_out_channels": [1_9_2, 1_9_2 * 2, 1_9_2 * 3, 1_9_2 * 4], "attention_head_dim": 6_4, "down_block_types": [ "ResnetDownsampleBlock2D", "AttnDownBlock2D", "AttnDownBlock2D", "AttnDownBlock2D", ], "up_block_types": [ "AttnUpBlock2D", "AttnUpBlock2D", "AttnUpBlock2D", "ResnetUpsampleBlock2D", ], "resnet_time_scale_shift": "scale_shift", "upsample_type": "resnet", "downsample_type": "resnet", } A : Dict = { "sample_size": 2_5_6, "in_channels": 3, "out_channels": 3, "layers_per_block": 2, "num_class_embeds": None, "block_out_channels": [2_5_6, 2_5_6, 2_5_6 * 2, 2_5_6 * 2, 2_5_6 * 4, 2_5_6 * 4], "attention_head_dim": 6_4, "down_block_types": [ "ResnetDownsampleBlock2D", "ResnetDownsampleBlock2D", "ResnetDownsampleBlock2D", "AttnDownBlock2D", "AttnDownBlock2D", "AttnDownBlock2D", ], "up_block_types": [ "AttnUpBlock2D", "AttnUpBlock2D", "AttnUpBlock2D", "ResnetUpsampleBlock2D", "ResnetUpsampleBlock2D", "ResnetUpsampleBlock2D", ], "resnet_time_scale_shift": "default", "upsample_type": "resnet", "downsample_type": "resnet", } A : Optional[Any] = { "num_train_timesteps": 4_0, "sigma_min": 0.002, "sigma_max": 80.0, } A : List[str] = { "num_train_timesteps": 2_0_1, "sigma_min": 0.002, "sigma_max": 80.0, } A : Optional[Any] = { "num_train_timesteps": 1_5_1, "sigma_min": 0.002, "sigma_max": 80.0, } def _lowerCamelCase ( _UpperCamelCase ): '''simple docstring''' if isinstance(_UpperCamelCase , _UpperCamelCase ): return v if v.lower() in ("yes", "true", "t", "y", "1"): return True elif v.lower() in ("no", "false", "f", "n", "0"): return False else: raise argparse.ArgumentTypeError("boolean value expected" ) def _lowerCamelCase ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase=False ): '''simple docstring''' __lowerCAmelCase = checkpoint[f"{old_prefix}.in_layers.0.weight"] __lowerCAmelCase = checkpoint[f"{old_prefix}.in_layers.0.bias"] __lowerCAmelCase = checkpoint[f"{old_prefix}.in_layers.2.weight"] __lowerCAmelCase = checkpoint[f"{old_prefix}.in_layers.2.bias"] __lowerCAmelCase = checkpoint[f"{old_prefix}.emb_layers.1.weight"] __lowerCAmelCase = checkpoint[f"{old_prefix}.emb_layers.1.bias"] __lowerCAmelCase = checkpoint[f"{old_prefix}.out_layers.0.weight"] __lowerCAmelCase = checkpoint[f"{old_prefix}.out_layers.0.bias"] __lowerCAmelCase = checkpoint[f"{old_prefix}.out_layers.3.weight"] __lowerCAmelCase = checkpoint[f"{old_prefix}.out_layers.3.bias"] if has_skip: __lowerCAmelCase = checkpoint[f"{old_prefix}.skip_connection.weight"] __lowerCAmelCase = checkpoint[f"{old_prefix}.skip_connection.bias"] return new_checkpoint def _lowerCamelCase ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase=None ): '''simple docstring''' __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = checkpoint[f"{old_prefix}.qkv.weight"].chunk(3 , dim=0 ) __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = checkpoint[f"{old_prefix}.qkv.bias"].chunk(3 , dim=0 ) __lowerCAmelCase = checkpoint[f"{old_prefix}.norm.weight"] __lowerCAmelCase = checkpoint[f"{old_prefix}.norm.bias"] __lowerCAmelCase = weight_q.squeeze(-1 ).squeeze(-1 ) __lowerCAmelCase = bias_q.squeeze(-1 ).squeeze(-1 ) __lowerCAmelCase = weight_k.squeeze(-1 ).squeeze(-1 ) __lowerCAmelCase = bias_k.squeeze(-1 ).squeeze(-1 ) __lowerCAmelCase = weight_v.squeeze(-1 ).squeeze(-1 ) __lowerCAmelCase = bias_v.squeeze(-1 ).squeeze(-1 ) __lowerCAmelCase = ( checkpoint[f"{old_prefix}.proj_out.weight"].squeeze(-1 ).squeeze(-1 ) ) __lowerCAmelCase = checkpoint[f"{old_prefix}.proj_out.bias"].squeeze(-1 ).squeeze(-1 ) return new_checkpoint def _lowerCamelCase ( _UpperCamelCase , _UpperCamelCase ): '''simple docstring''' __lowerCAmelCase = torch.load(_UpperCamelCase , map_location="cpu" ) __lowerCAmelCase = {} __lowerCAmelCase = checkpoint["time_embed.0.weight"] __lowerCAmelCase = checkpoint["time_embed.0.bias"] __lowerCAmelCase = checkpoint["time_embed.2.weight"] __lowerCAmelCase = checkpoint["time_embed.2.bias"] if unet_config["num_class_embeds"] is not None: __lowerCAmelCase = checkpoint["label_emb.weight"] __lowerCAmelCase = checkpoint["input_blocks.0.0.weight"] __lowerCAmelCase = checkpoint["input_blocks.0.0.bias"] __lowerCAmelCase = unet_config["down_block_types"] __lowerCAmelCase = unet_config["layers_per_block"] __lowerCAmelCase = unet_config["attention_head_dim"] __lowerCAmelCase = unet_config["block_out_channels"] __lowerCAmelCase = 1 __lowerCAmelCase = channels_list[0] for i, layer_type in enumerate(_UpperCamelCase ): __lowerCAmelCase = channels_list[i] __lowerCAmelCase = current_channels != prev_channels if layer_type == "ResnetDownsampleBlock2D": for j in range(_UpperCamelCase ): __lowerCAmelCase = f"down_blocks.{i}.resnets.{j}" __lowerCAmelCase = f"input_blocks.{current_layer}.0" __lowerCAmelCase = True if j == 0 and downsample_block_has_skip else False __lowerCAmelCase = convert_resnet(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , has_skip=_UpperCamelCase ) current_layer += 1 elif layer_type == "AttnDownBlock2D": for j in range(_UpperCamelCase ): __lowerCAmelCase = f"down_blocks.{i}.resnets.{j}" __lowerCAmelCase = f"input_blocks.{current_layer}.0" __lowerCAmelCase = True if j == 0 and downsample_block_has_skip else False __lowerCAmelCase = convert_resnet(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , has_skip=_UpperCamelCase ) __lowerCAmelCase = f"down_blocks.{i}.attentions.{j}" __lowerCAmelCase = f"input_blocks.{current_layer}.1" __lowerCAmelCase = convert_attention( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) current_layer += 1 if i != len(_UpperCamelCase ) - 1: __lowerCAmelCase = f"down_blocks.{i}.downsamplers.0" __lowerCAmelCase = f"input_blocks.{current_layer}.0" __lowerCAmelCase = convert_resnet(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) current_layer += 1 __lowerCAmelCase = current_channels # hardcoded the mid-block for now __lowerCAmelCase = "mid_block.resnets.0" __lowerCAmelCase = "middle_block.0" __lowerCAmelCase = convert_resnet(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) __lowerCAmelCase = "mid_block.attentions.0" __lowerCAmelCase = "middle_block.1" __lowerCAmelCase = convert_attention(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) __lowerCAmelCase = "mid_block.resnets.1" __lowerCAmelCase = "middle_block.2" __lowerCAmelCase = convert_resnet(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) __lowerCAmelCase = 0 __lowerCAmelCase = unet_config["up_block_types"] for i, layer_type in enumerate(_UpperCamelCase ): if layer_type == "ResnetUpsampleBlock2D": for j in range(layers_per_block + 1 ): __lowerCAmelCase = f"up_blocks.{i}.resnets.{j}" __lowerCAmelCase = f"output_blocks.{current_layer}.0" __lowerCAmelCase = convert_resnet(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , has_skip=_UpperCamelCase ) current_layer += 1 if i != len(_UpperCamelCase ) - 1: __lowerCAmelCase = f"up_blocks.{i}.upsamplers.0" __lowerCAmelCase = f"output_blocks.{current_layer-1}.1" __lowerCAmelCase = convert_resnet(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) elif layer_type == "AttnUpBlock2D": for j in range(layers_per_block + 1 ): __lowerCAmelCase = f"up_blocks.{i}.resnets.{j}" __lowerCAmelCase = f"output_blocks.{current_layer}.0" __lowerCAmelCase = convert_resnet(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , has_skip=_UpperCamelCase ) __lowerCAmelCase = f"up_blocks.{i}.attentions.{j}" __lowerCAmelCase = f"output_blocks.{current_layer}.1" __lowerCAmelCase = convert_attention( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) current_layer += 1 if i != len(_UpperCamelCase ) - 1: __lowerCAmelCase = f"up_blocks.{i}.upsamplers.0" __lowerCAmelCase = f"output_blocks.{current_layer-1}.2" __lowerCAmelCase = convert_resnet(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) __lowerCAmelCase = checkpoint["out.0.weight"] __lowerCAmelCase = checkpoint["out.0.bias"] __lowerCAmelCase = checkpoint["out.2.weight"] __lowerCAmelCase = checkpoint["out.2.bias"] return new_checkpoint if __name__ == "__main__": A : Dict = argparse.ArgumentParser() parser.add_argument("--unet_path", default=None, type=str, required=True, help="Path to the unet.pt to convert.") parser.add_argument( "--dump_path", default=None, type=str, required=True, help="Path to output the converted UNet model." ) parser.add_argument("--class_cond", default=True, type=str, help="Whether the model is class-conditional.") A : Optional[Any] = parser.parse_args() A : int = strabool(args.class_cond) A : Dict = os.path.basename(args.unet_path) print(f'''Checkpoint: {ckpt_name}''') # Get U-Net config if "imagenet64" in ckpt_name: A : Union[str, Any] = IMAGENET_64_UNET_CONFIG elif "256" in ckpt_name and (("bedroom" in ckpt_name) or ("cat" in ckpt_name)): A : Any = LSUN_256_UNET_CONFIG elif "test" in ckpt_name: A : Union[str, Any] = TEST_UNET_CONFIG else: raise ValueError(f'''Checkpoint type {ckpt_name} is not currently supported.''') if not args.class_cond: A : Union[str, Any] = None A : int = con_pt_to_diffuser(args.unet_path, unet_config) A : Tuple = UNetaDModel(**unet_config) image_unet.load_state_dict(converted_unet_ckpt) # Get scheduler config if "cd" in ckpt_name or "test" in ckpt_name: A : Union[str, Any] = CD_SCHEDULER_CONFIG elif "ct" in ckpt_name and "imagenet64" in ckpt_name: A : Any = CT_IMAGENET_64_SCHEDULER_CONFIG elif "ct" in ckpt_name and "256" in ckpt_name and (("bedroom" in ckpt_name) or ("cat" in ckpt_name)): A : Any = CT_LSUN_256_SCHEDULER_CONFIG else: raise ValueError(f'''Checkpoint type {ckpt_name} is not currently supported.''') A : Optional[int] = CMStochasticIterativeScheduler(**scheduler_config) A : Optional[Any] = ConsistencyModelPipeline(unet=image_unet, scheduler=cm_scheduler) consistency_model.save_pretrained(args.dump_path)
57
import os import sys a =os.path.join(os.path.dirname(__file__), """src""") sys.path.append(SRC_DIR) from transformers import ( AutoConfig, AutoModel, AutoModelForCausalLM, AutoModelForMaskedLM, AutoModelForQuestionAnswering, AutoModelForSequenceClassification, AutoTokenizer, add_start_docstrings, ) a =[ """torch""", """numpy""", """tokenizers""", """filelock""", """requests""", """tqdm""", """regex""", """sentencepiece""", """sacremoses""", """importlib_metadata""", """huggingface_hub""", ] @add_start_docstrings(AutoConfig.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> int: return AutoConfig.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ ) @add_start_docstrings(AutoTokenizer.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> Optional[Any]: return AutoTokenizer.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ ) @add_start_docstrings(AutoModel.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> List[str]: return AutoModel.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ ) @add_start_docstrings(AutoModelForCausalLM.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> Any: return AutoModelForCausalLM.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ ) @add_start_docstrings(AutoModelForMaskedLM.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> List[str]: return AutoModelForMaskedLM.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ ) @add_start_docstrings(AutoModelForSequenceClassification.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> List[str]: return AutoModelForSequenceClassification.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ ) @add_start_docstrings(AutoModelForQuestionAnswering.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> Tuple: return AutoModelForQuestionAnswering.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ )
73
0
'''simple docstring''' lowercase_ = [4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] lowercase_ = [3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] lowercase_ = { 0: """Sunday""", 1: """Monday""", 2: """Tuesday""", 3: """Wednesday""", 4: """Thursday""", 5: """Friday""", 6: """Saturday""", } def lowerCamelCase ( __lowerCamelCase : int , __lowerCamelCase : int , __lowerCamelCase : int ) ->str: assert len(str(__lowerCamelCase ) ) > 2, "year should be in YYYY format" assert 1 <= month <= 12, "month should be between 1 to 12" assert 1 <= day <= 31, "day should be between 1 to 31" # Doomsday algorithm: _SCREAMING_SNAKE_CASE = year // 100 _SCREAMING_SNAKE_CASE = (5 * (century % 4) + 2) % 7 _SCREAMING_SNAKE_CASE = year % 100 _SCREAMING_SNAKE_CASE = centurian % 12 _SCREAMING_SNAKE_CASE = ( (centurian // 12) + centurian_m + (centurian_m // 4) + century_anchor ) % 7 _SCREAMING_SNAKE_CASE = ( DOOMSDAY_NOT_LEAP[month - 1] if (year % 4 != 0) or (centurian == 0 and (year % 400) == 0) else DOOMSDAY_LEAP[month - 1] ) _SCREAMING_SNAKE_CASE = (dooms_day + day - day_anchor) % 7 return WEEK_DAY_NAMES[week_day] if __name__ == "__main__": import doctest doctest.testmod()
58
from typing import Optional from urllib.parse import quote import huggingface_hub as hfh from packaging import version def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ = None ) -> str: if version.parse(hfh.__version__ ).release < version.parse('0.11.0' ).release: # old versions of hfh don't url-encode the file path __lowerCamelCase : int = quote(lowerCamelCase__ ) return hfh.hf_hub_url(lowerCamelCase__ , lowerCamelCase__ , repo_type='dataset' , revision=lowerCamelCase__ )
73
0
import os def UpperCamelCase ( __lowerCamelCase : Optional[int] ): snake_case : Union[str, Any] = len(grid[0] ) snake_case : int = len(__lowerCamelCase ) snake_case : List[Any] = 0 snake_case : Dict = 0 snake_case : int = 0 # Check vertically, horizontally, diagonally at the same time (only works # for nxn grid) for i in range(__lowerCamelCase ): for j in range(n_rows - 3 ): snake_case : int = grid[j][i] * grid[j + 1][i] * grid[j + 2][i] * grid[j + 3][i] snake_case : Dict = grid[i][j] * grid[i][j + 1] * grid[i][j + 2] * grid[i][j + 3] # Left-to-right diagonal (\) product if i < n_columns - 3: snake_case : List[str] = ( grid[i][j] * grid[i + 1][j + 1] * grid[i + 2][j + 2] * grid[i + 3][j + 3] ) # Right-to-left diagonal(/) product if i > 2: snake_case : Tuple = ( grid[i][j] * grid[i - 1][j + 1] * grid[i - 2][j + 2] * grid[i - 3][j + 3] ) snake_case : Any = max( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) if max_product > largest: snake_case : List[str] = max_product return largest def UpperCamelCase ( ): snake_case : Optional[int] = [] with open(os.path.dirname(__lowerCamelCase ) + "/grid.txt" ) as file: for line in file: grid.append(line.strip("\n" ).split(" " ) ) snake_case : Optional[int] = [[int(__lowerCamelCase ) for i in grid[j]] for j in range(len(__lowerCamelCase ) )] return largest_product(__lowerCamelCase ) if __name__ == "__main__": print(solution())
59
def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , ) -> float: __lowerCamelCase : Dict = [redshift, radiation_density, matter_density, dark_energy] if any(p < 0 for p in parameters ): raise ValueError('All input parameters must be positive' ) if any(p > 1 for p in parameters[1:4] ): raise ValueError('Relative densities cannot be greater than one' ) else: __lowerCamelCase : Dict = 1 - (matter_density + radiation_density + dark_energy) __lowerCamelCase : Union[str, Any] = ( radiation_density * (redshift + 1) ** 4 + matter_density * (redshift + 1) ** 3 + curvature * (redshift + 1) ** 2 + dark_energy ) __lowerCamelCase : List[Any] = hubble_constant * e_a ** (1 / 2) return hubble if __name__ == "__main__": import doctest # run doctest doctest.testmod() # demo LCDM approximation a =0.3 print( hubble_parameter( hubble_constant=68.3, radiation_density=1E-4, matter_density=matter_density, dark_energy=1 - matter_density, redshift=0, ) )
73
0