code
stringlengths
82
54.1k
code_codestyle
int64
0
699
style_context
stringlengths
111
35.6k
style_context_codestyle
int64
0
699
label
int64
0
1
"""simple docstring""" import unittest import torch from torch import nn from diffusers.models.activations import get_activation class snake_case_ ( unittest.TestCase ): def snake_case_ ( self ): a_ : Tuple = get_activation("swish" ) self.assertIsInstance(snake_case_ , nn.SiLU ) self.assertEqual(act(torch.tensor(-1_0_0 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(2_0 , dtype=torch.floataa ) ).item() , 2_0 ) def snake_case_ ( self ): a_ : List[Any] = get_activation("silu" ) self.assertIsInstance(snake_case_ , nn.SiLU ) self.assertEqual(act(torch.tensor(-1_0_0 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(2_0 , dtype=torch.floataa ) ).item() , 2_0 ) def snake_case_ ( self ): a_ : str = get_activation("mish" ) self.assertIsInstance(snake_case_ , nn.Mish ) self.assertEqual(act(torch.tensor(-2_0_0 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(2_0 , dtype=torch.floataa ) ).item() , 2_0 ) def snake_case_ ( self ): a_ : List[str] = get_activation("gelu" ) self.assertIsInstance(snake_case_ , nn.GELU ) self.assertEqual(act(torch.tensor(-1_0_0 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(2_0 , dtype=torch.floataa ) ).item() , 2_0 )
237
'''simple docstring''' import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging _UpperCAmelCase : Any = logging.get_logger(__name__) _UpperCAmelCase : Dict = { '''google/pix2struct-textcaps-base''': ( '''https://huggingface.co/google/pix2struct-textcaps-base/resolve/main/config.json''' ), } class __magic_name__ ( __SCREAMING_SNAKE_CASE ): UpperCamelCase__ = 'pix2struct_text_model' UpperCamelCase__ = ['past_key_values'] UpperCamelCase__ = { 'hidden_size': 'hidden_size', 'num_attention_heads': 'num_heads', 'num_hidden_layers': 'num_layers', } def __init__( self , snake_case_=5_02_44 , snake_case_=7_68 , snake_case_=64 , snake_case_=20_48 , snake_case_=12 , snake_case_=12 , snake_case_=32 , snake_case_=1_28 , snake_case_=0.1 , snake_case_=1E-6 , snake_case_=1.0 , snake_case_="gelu_new" , snake_case_=0 , snake_case_=False , snake_case_=0 , snake_case_=1 , snake_case_=False , snake_case_=True , **snake_case_ , ): lowercase =vocab_size lowercase =hidden_size lowercase =d_kv lowercase =d_ff lowercase =num_layers lowercase =num_heads lowercase =relative_attention_num_buckets lowercase =relative_attention_max_distance lowercase =dropout_rate lowercase =layer_norm_epsilon lowercase =initializer_factor lowercase =use_cache lowercase =eos_token_id lowercase =decoder_start_token_id # for backwards compatibility lowercase =dense_act_fn super().__init__( pad_token_id=snake_case_ , eos_token_id=snake_case_ , decoder_start_token_id=snake_case_ , tie_word_embeddings=snake_case_ , is_decoder=snake_case_ , **snake_case_ , ) @classmethod def _A( cls , snake_case_ , **snake_case_ ): cls._set_token_in_kwargs(snake_case_ ) lowercase , lowercase =cls.get_config_dict(snake_case_ , **snake_case_ ) # get the text config dict if we are loading from Pix2StructConfig if config_dict.get('''model_type''' ) == "pix2struct": lowercase =config_dict['''text_config'''] if "model_type" in config_dict and hasattr(cls , '''model_type''' ) and config_dict["model_type"] != cls.model_type: logger.warning( f'You are using a model of type {config_dict["model_type"]} to instantiate a model of type ' f'{cls.model_type}. This is not supported for all configurations of models and can yield errors.' ) return cls.from_dict(snake_case_ , **snake_case_ ) class __magic_name__ ( __SCREAMING_SNAKE_CASE ): UpperCamelCase__ = 'pix2struct_vision_model' def __init__( self , snake_case_=7_68 , snake_case_=7_68 , snake_case_=20_48 , snake_case_=64 , snake_case_=12 , snake_case_=12 , snake_case_="gelu_new" , snake_case_=1E-6 , snake_case_=0.0 , snake_case_=0.0 , snake_case_=1E-10 , snake_case_=1.0 , snake_case_=40_96 , snake_case_=32 , snake_case_=1_28 , **snake_case_ , ): super().__init__(**snake_case_ ) lowercase =hidden_size lowercase =patch_embed_hidden_size lowercase =d_ff lowercase =dropout_rate lowercase =num_hidden_layers lowercase =num_attention_heads lowercase =initializer_range lowercase =initializer_factor lowercase =attention_dropout lowercase =layer_norm_eps lowercase =dense_act_fn lowercase =seq_len lowercase =relative_attention_num_buckets lowercase =relative_attention_max_distance lowercase =d_kv @classmethod def _A( cls , snake_case_ , **snake_case_ ): cls._set_token_in_kwargs(snake_case_ ) lowercase , lowercase =cls.get_config_dict(snake_case_ , **snake_case_ ) # get the vision config dict if we are loading from Pix2StructConfig if config_dict.get('''model_type''' ) == "pix2struct": lowercase =config_dict['''vision_config'''] if "model_type" in config_dict and hasattr(cls , '''model_type''' ) and config_dict["model_type"] != cls.model_type: logger.warning( f'You are using a model of type {config_dict["model_type"]} to instantiate a model of type ' f'{cls.model_type}. This is not supported for all configurations of models and can yield errors.' ) return cls.from_dict(snake_case_ , **snake_case_ ) class __magic_name__ ( __SCREAMING_SNAKE_CASE ): UpperCamelCase__ = 'pix2struct' UpperCamelCase__ = True def __init__( self , snake_case_=None , snake_case_=None , snake_case_=1.0 , snake_case_=0.02 , snake_case_=False , snake_case_=False , snake_case_=True , **snake_case_ , ): super().__init__(tie_word_embeddings=snake_case_ , is_encoder_decoder=snake_case_ , **snake_case_ ) if text_config is None: lowercase ={} logger.info('''text_config is None. Initializing the Pix2StructTextConfig with default values.''' ) if vision_config is None: lowercase ={} logger.info('''vision_config is None. Initializing the Pix2StructVisionConfig with default values.''' ) lowercase =PixaStructTextConfig(**snake_case_ ) lowercase =PixaStructVisionConfig(**snake_case_ ) lowercase =self.text_config.decoder_start_token_id lowercase =self.text_config.pad_token_id lowercase =self.text_config.eos_token_id lowercase =initializer_factor lowercase =initializer_range lowercase =self.initializer_range lowercase =self.initializer_range lowercase =is_vqa @classmethod def _A( cls , snake_case_ , snake_case_ , **snake_case_ ): return cls(text_config=text_config.to_dict() , vision_config=vision_config.to_dict() , **snake_case_ ) def _A( self ): lowercase =copy.deepcopy(self.__dict__ ) lowercase =self.text_config.to_dict() lowercase =self.vision_config.to_dict() lowercase =self.__class__.model_type return output
72
0
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCamelCase = logging.get_logger(__name__) UpperCamelCase = { '''tanreinama/GPTSAN-2.8B-spout_is_uniform''': ( '''https://huggingface.co/tanreinama/GPTSAN-2.8B-spout_is_uniform/resolve/main/config.json''' ), } class UpperCamelCase__ ( __SCREAMING_SNAKE_CASE ): """simple docstring""" A__ : Dict = "gptsan-japanese" A__ : List[Any] = [ "past_key_values", ] A__ : Tuple = { "hidden_size": "d_model", "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers", } def __init__( self , SCREAMING_SNAKE_CASE__=36000 , SCREAMING_SNAKE_CASE__=1280 , SCREAMING_SNAKE_CASE__=1024 , SCREAMING_SNAKE_CASE__=8192 , SCREAMING_SNAKE_CASE__=4096 , SCREAMING_SNAKE_CASE__=128 , SCREAMING_SNAKE_CASE__=10 , SCREAMING_SNAKE_CASE__=0 , SCREAMING_SNAKE_CASE__=16 , SCREAMING_SNAKE_CASE__=16 , SCREAMING_SNAKE_CASE__=128 , SCREAMING_SNAKE_CASE__=0.0 , SCREAMING_SNAKE_CASE__=1e-5 , SCREAMING_SNAKE_CASE__=False , SCREAMING_SNAKE_CASE__=0.0 , SCREAMING_SNAKE_CASE__="float32" , SCREAMING_SNAKE_CASE__=False , SCREAMING_SNAKE_CASE__=False , SCREAMING_SNAKE_CASE__=False , SCREAMING_SNAKE_CASE__=0.0_0_2 , SCREAMING_SNAKE_CASE__=False , SCREAMING_SNAKE_CASE__=True , SCREAMING_SNAKE_CASE__=35998 , SCREAMING_SNAKE_CASE__=35995 , SCREAMING_SNAKE_CASE__=35999 , **SCREAMING_SNAKE_CASE__ , ) -> Optional[int]: A__ = vocab_size A__ = max_position_embeddings A__ = d_model A__ = d_ff A__ = d_ext A__ = d_spout A__ = num_switch_layers A__ = num_ext_layers A__ = num_switch_layers + num_ext_layers A__ = num_heads A__ = num_experts A__ = expert_capacity A__ = dropout_rate A__ = layer_norm_epsilon A__ = router_bias A__ = router_jitter_noise A__ = router_dtype A__ = router_ignore_padding_tokens A__ = output_hidden_states A__ = output_attentions A__ = initializer_factor A__ = output_router_logits A__ = use_cache super().__init__( separator_token_id=snake_case_ , pad_token_id=snake_case_ , eos_token_id=snake_case_ , **snake_case_ , )
104
'''simple docstring''' def UpperCamelCase ( ) -> int: '''simple docstring''' return 1 def UpperCamelCase ( lowercase_ : int ) -> int: '''simple docstring''' return 0 if x < 0 else two_pence(x - 2 ) + one_pence() def UpperCamelCase ( lowercase_ : int ) -> int: '''simple docstring''' return 0 if x < 0 else five_pence(x - 5 ) + two_pence(lowercase_ ) def UpperCamelCase ( lowercase_ : int ) -> int: '''simple docstring''' return 0 if x < 0 else ten_pence(x - 1_0 ) + five_pence(lowercase_ ) def UpperCamelCase ( lowercase_ : int ) -> int: '''simple docstring''' return 0 if x < 0 else twenty_pence(x - 2_0 ) + ten_pence(lowercase_ ) def UpperCamelCase ( lowercase_ : int ) -> int: '''simple docstring''' return 0 if x < 0 else fifty_pence(x - 5_0 ) + twenty_pence(lowercase_ ) def UpperCamelCase ( lowercase_ : int ) -> int: '''simple docstring''' return 0 if x < 0 else one_pound(x - 1_0_0 ) + fifty_pence(lowercase_ ) def UpperCamelCase ( lowercase_ : int ) -> int: '''simple docstring''' return 0 if x < 0 else two_pound(x - 2_0_0 ) + one_pound(lowercase_ ) def UpperCamelCase ( lowercase_ : int = 2_0_0 ) -> int: '''simple docstring''' return two_pound(lowercase_ ) if __name__ == "__main__": print(solution(int(input().strip())))
72
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""") _A = logging.getLogger(__name__) @dataclass class lowerCamelCase : '''simple docstring''' SCREAMING_SNAKE_CASE = field( default='tab_fact' , metadata={'help': 'The name of the dataset to use (via the datasets library).'} ) SCREAMING_SNAKE_CASE = field( default='tab_fact' , metadata={'help': 'The configuration name of the dataset to use (via the datasets library).'} , ) SCREAMING_SNAKE_CASE = 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.' ) } , ) SCREAMING_SNAKE_CASE = field( default=__SCREAMING_SNAKE_CASE , metadata={'help': 'Overwrite the cached preprocessed datasets or not.'} ) SCREAMING_SNAKE_CASE = field( default=__SCREAMING_SNAKE_CASE , 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.' ) } , ) SCREAMING_SNAKE_CASE = field( default=__SCREAMING_SNAKE_CASE , metadata={ 'help': ( 'For debugging purposes or quicker training, truncate the number of training examples to this ' 'value if set.' ) } , ) SCREAMING_SNAKE_CASE = field( default=__SCREAMING_SNAKE_CASE , metadata={ 'help': ( 'For debugging purposes or quicker training, truncate the number of evaluation examples to this ' 'value if set.' ) } , ) SCREAMING_SNAKE_CASE = field( default=__SCREAMING_SNAKE_CASE , metadata={ 'help': ( 'For debugging purposes or quicker training, truncate the number of prediction examples to this ' 'value if set.' ) } , ) SCREAMING_SNAKE_CASE = field( default=__SCREAMING_SNAKE_CASE , metadata={'help': 'A csv or a json file containing the training data.'} ) SCREAMING_SNAKE_CASE = field( default=__SCREAMING_SNAKE_CASE , metadata={'help': 'A csv or a json file containing the validation data.'} ) SCREAMING_SNAKE_CASE = field(default=__SCREAMING_SNAKE_CASE , metadata={'help': 'A csv or a json file containing the test data.'} ) def _a (self ): """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: UpperCAmelCase__ : List[str] = self.train_file.split(""".""" )[-1] assert train_extension in ["csv", "json"], "`train_file` should be a csv or a json file." UpperCAmelCase__ : List[str] = 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 lowerCamelCase : '''simple docstring''' SCREAMING_SNAKE_CASE = field( default=__SCREAMING_SNAKE_CASE , metadata={'help': 'Path to pretrained model or model identifier from huggingface.co/models'} ) SCREAMING_SNAKE_CASE = field( default=__SCREAMING_SNAKE_CASE , metadata={'help': 'Pretrained config name or path if not the same as model_name'} ) SCREAMING_SNAKE_CASE = field( default=__SCREAMING_SNAKE_CASE , metadata={'help': 'Pretrained tokenizer name or path if not the same as model_name'} ) SCREAMING_SNAKE_CASE = field( default=__SCREAMING_SNAKE_CASE , metadata={'help': 'Where do you want to store the pretrained models downloaded from huggingface.co'} , ) SCREAMING_SNAKE_CASE = field( default=__SCREAMING_SNAKE_CASE , metadata={'help': 'Whether to use one of the fast tokenizer (backed by the tokenizers library) or not.'} , ) SCREAMING_SNAKE_CASE = field( default='main' , metadata={'help': 'The specific model version to use (can be a branch name, tag name or commit id).'} , ) SCREAMING_SNAKE_CASE = field( default=__SCREAMING_SNAKE_CASE , metadata={ 'help': ( 'Will use the token generated when running `huggingface-cli login` (necessary to use this script ' 'with private models).' ) } , ) def a__ ( ) -> Optional[int]: UpperCAmelCase__ : List[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. UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ : Tuple = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ : str = 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 )] , ) UpperCAmelCase__ : str = training_args.get_process_log_level() logger.setLevel(lowercase_ ) datasets.utils.logging.set_verbosity(lowercase_ ) transformers.utils.logging.set_verbosity(lowercase_ ) 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. UpperCAmelCase__ : int = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: UpperCAmelCase__ : str = 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. UpperCAmelCase__ : 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. UpperCAmelCase__ : int = {"""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: UpperCAmelCase__ : List[str] = data_args.train_file.split(""".""" )[-1] UpperCAmelCase__ : Union[str, Any] = data_args.test_file.split(""".""" )[-1] assert ( test_extension == train_extension ), "`test_file` should have the same extension (csv or json) as `train_file`." UpperCAmelCase__ : Any = 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 UpperCAmelCase__ : Any = load_dataset("""csv""" , data_files=lowercase_ , cache_dir=model_args.cache_dir ) else: # Loading a dataset from local json files UpperCAmelCase__ : Tuple = load_dataset("""json""" , data_files=lowercase_ , 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 UpperCAmelCase__ : Union[str, Any] = raw_datasets["""train"""].features["""label"""].names UpperCAmelCase__ : Optional[Any] = len(lowercase_ ) # Load pretrained model and tokenizer # # In distributed training, the .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. UpperCAmelCase__ : Optional[Any] = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , num_labels=lowercase_ , 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 UpperCAmelCase__ : 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=lowercase_ , ) UpperCAmelCase__ : int = BartForSequenceClassification.from_pretrained( model_args.model_name_or_path , from_tf=bool(""".ckpt""" in model_args.model_name_or_path ) , config=lowercase_ , 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: UpperCAmelCase__ : List[Any] = """max_length""" else: # We will pad later, dynamically at batch creation, to the max sequence length in each batch UpperCAmelCase__ : Dict = False # Some models have set the order of the labels to use, so let's make sure we do use it. UpperCAmelCase__ : List[str] = {"""Refused""": 0, """Entailed""": 1} UpperCAmelCase__ : Optional[int] = {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}.""" ) UpperCAmelCase__ : 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 ): UpperCAmelCase__ : str = [_table_row.split("""#""" ) for _table_row in _table_text.strip("""\n""" ).split("""\n""" )] UpperCAmelCase__ : Optional[Any] = pd.DataFrame.from_records(_table_content[1:] , columns=_table_content[0] ) return _table_pd UpperCAmelCase__ : str = examples["""statement"""] UpperCAmelCase__ : Optional[int] = list(map(_convert_table_text_to_pandas , examples["""table_text"""] ) ) UpperCAmelCase__ : Tuple = tokenizer(lowercase_ , lowercase_ , padding=lowercase_ , max_length=lowercase_ , truncation=lowercase_ ) UpperCAmelCase__ : List[str] = examples["""label"""] return result with training_args.main_process_first(desc="""dataset map pre-processing""" ): UpperCAmelCase__ : Optional[Any] = raw_datasets.map( lowercase_ , batched=lowercase_ , 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""" ) UpperCAmelCase__ : str = raw_datasets["""train"""] if data_args.max_train_samples is not None: UpperCAmelCase__ : List[str] = 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""" ) UpperCAmelCase__ : Any = raw_datasets["""validation"""] if data_args.max_eval_samples is not None: UpperCAmelCase__ : List[str] = 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""" ) UpperCAmelCase__ : Tuple = raw_datasets["""test"""] if data_args.max_predict_samples is not None: UpperCAmelCase__ : Any = 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(lowercase_ ) ) , 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 ): UpperCAmelCase__ : Any = p.predictions[0] if isinstance(p.predictions , lowercase_ ) else p.predictions UpperCAmelCase__ : List[Any] = np.argmax(lowercase_ , 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: UpperCAmelCase__ : Union[str, Any] = default_data_collator elif training_args.fpaa: UpperCAmelCase__ : int = DataCollatorWithPadding(lowercase_ , pad_to_multiple_of=8 ) else: UpperCAmelCase__ : str = None # Initialize our Trainer UpperCAmelCase__ : int = Trainer( model=lowercase_ , args=lowercase_ , train_dataset=train_dataset if training_args.do_train else None , eval_dataset=eval_dataset if training_args.do_eval else None , compute_metrics=lowercase_ , tokenizer=lowercase_ , data_collator=lowercase_ , ) # Training if training_args.do_train: UpperCAmelCase__ : Dict = None if training_args.resume_from_checkpoint is not None: UpperCAmelCase__ : Tuple = training_args.resume_from_checkpoint elif last_checkpoint is not None: UpperCAmelCase__ : str = last_checkpoint UpperCAmelCase__ : Union[str, Any] = trainer.train(resume_from_checkpoint=lowercase_ ) UpperCAmelCase__ : Optional[int] = train_result.metrics UpperCAmelCase__ : Tuple = ( data_args.max_train_samples if data_args.max_train_samples is not None else len(lowercase_ ) ) UpperCAmelCase__ : List[str] = min(lowercase_ , len(lowercase_ ) ) trainer.save_model() # Saves the tokenizer too for easy upload trainer.log_metrics("""train""" , lowercase_ ) trainer.save_metrics("""train""" , lowercase_ ) trainer.save_state() # Evaluation if training_args.do_eval: logger.info("""*** Evaluate ***""" ) UpperCAmelCase__ : Dict = trainer.evaluate(eval_dataset=lowercase_ ) UpperCAmelCase__ : Optional[int] = data_args.max_eval_samples if data_args.max_eval_samples is not None else len(lowercase_ ) UpperCAmelCase__ : int = min(lowercase_ , len(lowercase_ ) ) trainer.log_metrics("""eval""" , lowercase_ ) trainer.save_metrics("""eval""" , lowercase_ ) if training_args.do_predict: logger.info("""*** Predict ***""" ) # Removing the `label` columns because it contains -1 and Trainer won't like that. UpperCAmelCase__ : Optional[int] = predict_dataset.remove_columns("""label""" ) UpperCAmelCase__ : Optional[int] = trainer.predict(lowercase_ , metric_key_prefix="""predict""" ).predictions UpperCAmelCase__ : Dict = np.argmax(lowercase_ , axis=1 ) UpperCAmelCase__ : Optional[Any] = os.path.join(training_args.output_dir , """predict_results_tabfact.txt""" ) if trainer.is_world_process_zero(): with open(lowercase_ , """w""" ) as writer: logger.info("""***** Predict Results *****""" ) writer.write("""index\tprediction\n""" ) for index, item in enumerate(lowercase_ ): UpperCAmelCase__ : Tuple = label_list[item] writer.write(F"""{index}\t{item}\n""" ) UpperCAmelCase__ : List[Any] = {"""finetuned_from""": model_args.model_name_or_path, """tasks""": """text-classification"""} if training_args.push_to_hub: trainer.push_to_hub(**lowercase_ ) else: trainer.create_model_card(**lowercase_ ) def a__ ( lowerCAmelCase ) -> str: main() if __name__ == "__main__": main()
182
'''simple docstring''' import os from typing import List, Optional, Union from ...image_processing_utils import BatchFeature from ...image_utils import ImageInput from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType from ..auto import AutoTokenizer class __magic_name__ ( __SCREAMING_SNAKE_CASE ): UpperCamelCase__ = ['image_processor', 'tokenizer'] UpperCamelCase__ = 'BlipImageProcessor' UpperCamelCase__ = 'AutoTokenizer' def __init__( self , snake_case_ , snake_case_ , snake_case_ ): super().__init__(snake_case_ , snake_case_ ) # add QFormer tokenizer lowercase =qformer_tokenizer def __call__( self , snake_case_ = None , snake_case_ = None , snake_case_ = True , snake_case_ = False , snake_case_ = None , snake_case_ = None , snake_case_ = 0 , snake_case_ = None , snake_case_ = None , snake_case_ = False , snake_case_ = False , snake_case_ = False , snake_case_ = False , snake_case_ = False , snake_case_ = True , snake_case_ = None , **snake_case_ , ): if images is None and text is None: raise ValueError('''You have to specify at least images or text.''' ) lowercase =BatchFeature() if text is not None: lowercase =self.tokenizer( text=snake_case_ , add_special_tokens=snake_case_ , padding=snake_case_ , truncation=snake_case_ , max_length=snake_case_ , stride=snake_case_ , pad_to_multiple_of=snake_case_ , return_attention_mask=snake_case_ , return_overflowing_tokens=snake_case_ , return_special_tokens_mask=snake_case_ , return_offsets_mapping=snake_case_ , return_token_type_ids=snake_case_ , return_length=snake_case_ , verbose=snake_case_ , return_tensors=snake_case_ , **snake_case_ , ) encoding.update(snake_case_ ) lowercase =self.qformer_tokenizer( text=snake_case_ , add_special_tokens=snake_case_ , padding=snake_case_ , truncation=snake_case_ , max_length=snake_case_ , stride=snake_case_ , pad_to_multiple_of=snake_case_ , return_attention_mask=snake_case_ , return_overflowing_tokens=snake_case_ , return_special_tokens_mask=snake_case_ , return_offsets_mapping=snake_case_ , return_token_type_ids=snake_case_ , return_length=snake_case_ , verbose=snake_case_ , return_tensors=snake_case_ , **snake_case_ , ) lowercase =qformer_text_encoding.pop('''input_ids''' ) lowercase =qformer_text_encoding.pop('''attention_mask''' ) if images is not None: lowercase =self.image_processor(snake_case_ , return_tensors=snake_case_ ) encoding.update(snake_case_ ) return encoding def _A( self , *snake_case_ , **snake_case_ ): return self.tokenizer.batch_decode(*snake_case_ , **snake_case_ ) def _A( self , *snake_case_ , **snake_case_ ): return self.tokenizer.decode(*snake_case_ , **snake_case_ ) @property # Copied from transformers.models.blip.processing_blip.BlipProcessor.model_input_names def _A( self ): lowercase =self.tokenizer.model_input_names lowercase =self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) ) def _A( self , snake_case_ , **snake_case_ ): if os.path.isfile(snake_case_ ): raise ValueError(f'Provided path ({save_directory}) should be a directory, not a file' ) os.makedirs(snake_case_ , exist_ok=snake_case_ ) lowercase =os.path.join(snake_case_ , '''qformer_tokenizer''' ) self.qformer_tokenizer.save_pretrained(snake_case_ ) return super().save_pretrained(snake_case_ , **snake_case_ ) @classmethod def _A( cls , snake_case_ , **snake_case_ ): lowercase =AutoTokenizer.from_pretrained(snake_case_ , subfolder='''qformer_tokenizer''' ) lowercase =cls._get_arguments_from_pretrained(snake_case_ , **snake_case_ ) args.append(snake_case_ ) return cls(*snake_case_ )
72
0
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 SCREAMING_SNAKE_CASE : str = '''▁''' SCREAMING_SNAKE_CASE : Union[str, Any] = {'''vocab_file''': '''spiece.model'''} SCREAMING_SNAKE_CASE : Union[str, Any] = { '''vocab_file''': {'''google/pegasus-xsum''': '''https://huggingface.co/google/pegasus-xsum/resolve/main/spiece.model'''} } SCREAMING_SNAKE_CASE : List[Any] = { '''google/pegasus-xsum''': 512, } SCREAMING_SNAKE_CASE : Optional[int] = logging.get_logger(__name__) class _lowerCamelCase( __SCREAMING_SNAKE_CASE ): lowercase_ : Any = VOCAB_FILES_NAMES lowercase_ : Dict = VOCAB_FILES_NAMES lowercase_ : Optional[int] = PRETRAINED_VOCAB_FILES_MAP lowercase_ : Optional[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowercase_ : Tuple = ["""input_ids""", """attention_mask"""] def __init__( self, lowerCamelCase, lowerCamelCase="<pad>", lowerCamelCase="</s>", lowerCamelCase="<unk>", lowerCamelCase="<mask_2>", lowerCamelCase="<mask_1>", lowerCamelCase=None, lowerCamelCase=1_03, lowerCamelCase = None, **lowerCamelCase, ) -> int: """simple docstring""" _lowercase : Union[str, Any] = offset if additional_special_tokens is not None: if not isinstance(snake_case_, snake_case_): raise TypeError( F'''additional_special_tokens should be of type {type(snake_case_)}, but is''' F''' {type(snake_case_)}''') _lowercase : Optional[int] = ( ([mask_token_sent] + additional_special_tokens) if mask_token_sent not in additional_special_tokens and mask_token_sent is not None else additional_special_tokens ) # fill additional tokens with ..., <unk_token_102> in case not all additional tokens are already taken additional_special_tokens_extended += [ F'''<unk_{i}>''' for i in range(len(snake_case_), self.offset - 1) ] if len(set(snake_case_)) != len(snake_case_): raise ValueError( 'Please make sure that the provided additional_special_tokens do not contain an incorrectly' F''' shifted list of <unk_x> tokens. Found {additional_special_tokens_extended}.''') _lowercase : Optional[int] = additional_special_tokens_extended else: _lowercase : Any = [mask_token_sent] if mask_token_sent is not None else [] additional_special_tokens += [F'''<unk_{i}>''' for i in range(2, self.offset)] _lowercase : List[Any] = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( eos_token=snake_case_, unk_token=snake_case_, mask_token=snake_case_, pad_token=snake_case_, mask_token_sent=snake_case_, offset=snake_case_, additional_special_tokens=snake_case_, sp_model_kwargs=self.sp_model_kwargs, **snake_case_, ) _lowercase : Union[str, Any] = mask_token_sent _lowercase : List[str] = vocab_file _lowercase : List[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.Load(snake_case_) # add special tokens to encoder dict _lowercase : Optional[Any] = { 0: self.pad_token, 1: self.eos_token, } if self.mask_token_sent is not None: self.encoder.update( { 2: self.mask_token_sent, 3: self.mask_token, }) if self.offset > 0: # entries 2-104 are only used for pretraining and called <mask_1>, <mask_2>, unk_2, ...unk_102 # mask_token_sent is already added to list -> so start at 1 self.encoder.update({i + 3: additional_special_tokens[i] for i in range(1, self.offset - 1)}) _lowercase : Union[str, Any] = {v: k for k, v in self.encoder.items()} @property def UpperCamelCase ( self) -> Any: """simple docstring""" return len(self.sp_model) + self.offset def UpperCamelCase ( self) -> Optional[int]: """simple docstring""" _lowercase : Optional[int] = {self.convert_ids_to_tokens(snake_case_): i for i in range(self.vocab_size)} vocab.update(self.added_tokens_encoder) return vocab def __getstate__( self) -> Dict: """simple docstring""" _lowercase : List[str] = self.__dict__.copy() _lowercase : List[Any] = None return state def __setstate__( self, lowerCamelCase) -> Union[str, Any]: """simple docstring""" _lowercase : str = d # for backward compatibility if not hasattr(self, 'sp_model_kwargs'): _lowercase : Tuple = {} _lowercase : List[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.Load(self.vocab_file) def UpperCamelCase ( self, lowerCamelCase) -> Optional[Any]: """simple docstring""" return self.sp_model.encode(snake_case_, out_type=snake_case_) def UpperCamelCase ( self, lowerCamelCase) -> List[Any]: """simple docstring""" if token in self.decoder: return self.decoder[token] elif token in self.added_tokens_decoder: return self.added_tokens_decoder[token] _lowercase : Optional[Any] = self.sp_model.piece_to_id(snake_case_) return sp_id + self.offset def UpperCamelCase ( self, lowerCamelCase) -> Optional[Any]: """simple docstring""" if index in self.encoder: return self.encoder[index] elif index in self.added_tokens_encoder: return self.added_tokens_encoder[index] else: _lowercase : str = self.sp_model.IdToPiece(index - self.offset) return token def UpperCamelCase ( self, lowerCamelCase) -> Tuple: """simple docstring""" _lowercase : List[Any] = [] _lowercase : str = '' 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(snake_case_) + token _lowercase : List[Any] = [] else: current_sub_tokens.append(snake_case_) out_string += self.sp_model.decode(snake_case_) return out_string.strip() def UpperCamelCase ( self, lowerCamelCase=False) -> List[str]: """simple docstring""" return 1 def UpperCamelCase ( self, lowerCamelCase) -> int: """simple docstring""" _lowercase : str = set(self.all_special_ids) # call it once instead of inside list comp all_special_ids.remove(self.unk_token_id) # <unk> is only sometimes special return [1 if x in all_special_ids else 0 for x in seq] def UpperCamelCase ( self, lowerCamelCase, lowerCamelCase = None, lowerCamelCase = False) -> int: """simple docstring""" if already_has_special_tokens: return self._special_token_mask(snake_case_) elif token_ids_a is None: return self._special_token_mask(snake_case_) + [1] else: return self._special_token_mask(token_ids_a + token_ids_a) + [1] def UpperCamelCase ( self, lowerCamelCase, lowerCamelCase=None) -> List[str]: """simple docstring""" 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, lowerCamelCase, lowerCamelCase = None) -> Union[str, Any]: """simple docstring""" if not os.path.isdir(snake_case_): logger.error(F'''Vocabulary path ({save_directory}) should be a directory''') return _lowercase : List[str] = os.path.join( snake_case_, (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file']) if os.path.abspath(self.vocab_file) != os.path.abspath(snake_case_) and os.path.isfile(self.vocab_file): copyfile(self.vocab_file, snake_case_) elif not os.path.isfile(self.vocab_file): with open(snake_case_, 'wb') as fi: _lowercase : Tuple = self.sp_model.serialized_model_proto() fi.write(snake_case_) return (out_vocab_file,)
89
'''simple docstring''' import absl # noqa: F401 # Here to have a nice missing dependency error message early on import nltk # noqa: F401 # Here to have a nice missing dependency error message early on import numpy # noqa: F401 # Here to have a nice missing dependency error message early on import six # noqa: F401 # Here to have a nice missing dependency error message early on from rouge_score import rouge_scorer, scoring import datasets _UpperCAmelCase : Dict = '''\ @inproceedings{lin-2004-rouge, title = "{ROUGE}: A Package for Automatic Evaluation of Summaries", author = "Lin, Chin-Yew", booktitle = "Text Summarization Branches Out", month = jul, year = "2004", address = "Barcelona, Spain", publisher = "Association for Computational Linguistics", url = "https://www.aclweb.org/anthology/W04-1013", pages = "74--81", } ''' _UpperCAmelCase : Union[str, Any] = '''\ ROUGE, or Recall-Oriented Understudy for Gisting Evaluation, is a set of metrics and a software package used for evaluating automatic summarization and machine translation software in natural language processing. The metrics compare an automatically produced summary or translation against a reference or a set of references (human-produced) summary or translation. Note that ROUGE is case insensitive, meaning that upper case letters are treated the same way as lower case letters. This metrics is a wrapper around Google Research reimplementation of ROUGE: https://github.com/google-research/google-research/tree/master/rouge ''' _UpperCAmelCase : Dict = ''' Calculates average rouge scores for a list of hypotheses and references Args: predictions: list of predictions to score. Each prediction should be a string with tokens separated by spaces. references: list of reference for each prediction. Each reference should be a string with tokens separated by spaces. rouge_types: A list of rouge types to calculate. Valid names: `"rouge{n}"` (e.g. `"rouge1"`, `"rouge2"`) where: {n} is the n-gram based scoring, `"rougeL"`: Longest common subsequence based scoring. `"rougeLSum"`: rougeLsum splits text using `"\n"`. See details in https://github.com/huggingface/datasets/issues/617 use_stemmer: Bool indicating whether Porter stemmer should be used to strip word suffixes. use_aggregator: Return aggregates if this is set to True Returns: rouge1: rouge_1 (precision, recall, f1), rouge2: rouge_2 (precision, recall, f1), rougeL: rouge_l (precision, recall, f1), rougeLsum: rouge_lsum (precision, recall, f1) Examples: >>> rouge = datasets.load_metric(\'rouge\') >>> predictions = ["hello there", "general kenobi"] >>> references = ["hello there", "general kenobi"] >>> results = rouge.compute(predictions=predictions, references=references) >>> print(list(results.keys())) [\'rouge1\', \'rouge2\', \'rougeL\', \'rougeLsum\'] >>> print(results["rouge1"]) AggregateScore(low=Score(precision=1.0, recall=1.0, fmeasure=1.0), mid=Score(precision=1.0, recall=1.0, fmeasure=1.0), high=Score(precision=1.0, recall=1.0, fmeasure=1.0)) >>> print(results["rouge1"].mid.fmeasure) 1.0 ''' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class __magic_name__ ( datasets.Metric ): def _A( self ): return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Value('''string''' , id='''sequence''' ), '''references''': datasets.Value('''string''' , id='''sequence''' ), } ) , codebase_urls=['''https://github.com/google-research/google-research/tree/master/rouge'''] , reference_urls=[ '''https://en.wikipedia.org/wiki/ROUGE_(metric)''', '''https://github.com/google-research/google-research/tree/master/rouge''', ] , ) def _A( self , snake_case_ , snake_case_ , snake_case_=None , snake_case_=True , snake_case_=False ): if rouge_types is None: lowercase =['''rouge1''', '''rouge2''', '''rougeL''', '''rougeLsum'''] lowercase =rouge_scorer.RougeScorer(rouge_types=snake_case_ , use_stemmer=snake_case_ ) if use_aggregator: lowercase =scoring.BootstrapAggregator() else: lowercase =[] for ref, pred in zip(snake_case_ , snake_case_ ): lowercase =scorer.score(snake_case_ , snake_case_ ) if use_aggregator: aggregator.add_scores(snake_case_ ) else: scores.append(snake_case_ ) if use_aggregator: lowercase =aggregator.aggregate() else: lowercase ={} for key in scores[0]: lowercase =[score[key] for score in scores] return result
72
0
import os def __UpperCAmelCase( ): with open(os.path.dirname(lowercase_ ) + '''/grid.txt''' ) as f: _lowerCamelCase : Tuple = [] # noqa: E741 for _ in range(20 ): l.append([int(lowercase_ ) for x in f.readline().split()] ) _lowerCamelCase : int = 0 # right for i in range(20 ): for j in range(17 ): _lowerCamelCase : Union[str, Any] = l[i][j] * l[i][j + 1] * l[i][j + 2] * l[i][j + 3] if temp > maximum: _lowerCamelCase : str = temp # down for i in range(17 ): for j in range(20 ): _lowerCamelCase : Tuple = l[i][j] * l[i + 1][j] * l[i + 2][j] * l[i + 3][j] if temp > maximum: _lowerCamelCase : int = temp # diagonal 1 for i in range(17 ): for j in range(17 ): _lowerCamelCase : Tuple = l[i][j] * l[i + 1][j + 1] * l[i + 2][j + 2] * l[i + 3][j + 3] if temp > maximum: _lowerCamelCase : Optional[int] = temp # diagonal 2 for i in range(17 ): for j in range(3 , 20 ): _lowerCamelCase : Optional[int] = l[i][j] * l[i + 1][j - 1] * l[i + 2][j - 2] * l[i + 3][j - 3] if temp > maximum: _lowerCamelCase : int = temp return maximum if __name__ == "__main__": print(solution())
114
'''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 _UpperCAmelCase : str = '''▁''' _UpperCAmelCase : Union[str, Any] = {'''vocab_file''': '''spiece.model'''} _UpperCAmelCase : Union[str, Any] = { '''vocab_file''': {'''google/pegasus-xsum''': '''https://huggingface.co/google/pegasus-xsum/resolve/main/spiece.model'''} } _UpperCAmelCase : List[Any] = { '''google/pegasus-xsum''': 5_12, } _UpperCAmelCase : Optional[int] = logging.get_logger(__name__) class __magic_name__ ( __SCREAMING_SNAKE_CASE ): UpperCamelCase__ = VOCAB_FILES_NAMES UpperCamelCase__ = VOCAB_FILES_NAMES UpperCamelCase__ = PRETRAINED_VOCAB_FILES_MAP UpperCamelCase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCamelCase__ = ['input_ids', 'attention_mask'] def __init__( self , snake_case_ , snake_case_="<pad>" , snake_case_="</s>" , snake_case_="<unk>" , snake_case_="<mask_2>" , snake_case_="<mask_1>" , snake_case_=None , snake_case_=1_03 , snake_case_ = None , **snake_case_ , ): lowercase =offset if additional_special_tokens is not None: if not isinstance(snake_case_ , snake_case_ ): raise TypeError( f'additional_special_tokens should be of type {type(snake_case_ )}, but is' f' {type(snake_case_ )}' ) lowercase =( ([mask_token_sent] + additional_special_tokens) if mask_token_sent not in additional_special_tokens and mask_token_sent is not None else additional_special_tokens ) # fill additional tokens with ..., <unk_token_102> in case not all additional tokens are already taken additional_special_tokens_extended += [ f'<unk_{i}>' for i in range(len(snake_case_ ) , self.offset - 1 ) ] if len(set(snake_case_ ) ) != len(snake_case_ ): raise ValueError( '''Please make sure that the provided additional_special_tokens do not contain an incorrectly''' f' shifted list of <unk_x> tokens. Found {additional_special_tokens_extended}.' ) lowercase =additional_special_tokens_extended else: lowercase =[mask_token_sent] if mask_token_sent is not None else [] additional_special_tokens += [f'<unk_{i}>' for i in range(2 , self.offset )] lowercase ={} if sp_model_kwargs is None else sp_model_kwargs super().__init__( eos_token=snake_case_ , unk_token=snake_case_ , mask_token=snake_case_ , pad_token=snake_case_ , mask_token_sent=snake_case_ , offset=snake_case_ , additional_special_tokens=snake_case_ , sp_model_kwargs=self.sp_model_kwargs , **snake_case_ , ) lowercase =mask_token_sent lowercase =vocab_file lowercase =spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(snake_case_ ) # add special tokens to encoder dict lowercase ={ 0: self.pad_token, 1: self.eos_token, } if self.mask_token_sent is not None: self.encoder.update( { 2: self.mask_token_sent, 3: self.mask_token, } ) if self.offset > 0: # entries 2-104 are only used for pretraining and called <mask_1>, <mask_2>, unk_2, ...unk_102 # mask_token_sent is already added to list -> so start at 1 self.encoder.update({i + 3: additional_special_tokens[i] for i in range(1 , self.offset - 1 )} ) lowercase ={v: k for k, v in self.encoder.items()} @property def _A( self ): return len(self.sp_model ) + self.offset def _A( self ): lowercase ={self.convert_ids_to_tokens(snake_case_ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self ): lowercase =self.__dict__.copy() lowercase =None return state def __setstate__( self , snake_case_ ): lowercase =d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): lowercase ={} lowercase =spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def _A( self , snake_case_ ): return self.sp_model.encode(snake_case_ , out_type=snake_case_ ) def _A( self , snake_case_ ): if token in self.decoder: return self.decoder[token] elif token in self.added_tokens_decoder: return self.added_tokens_decoder[token] lowercase =self.sp_model.piece_to_id(snake_case_ ) return sp_id + self.offset def _A( self , snake_case_ ): if index in self.encoder: return self.encoder[index] elif index in self.added_tokens_encoder: return self.added_tokens_encoder[index] else: lowercase =self.sp_model.IdToPiece(index - self.offset ) return token def _A( self , snake_case_ ): lowercase =[] lowercase ='''''' 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(snake_case_ ) + token lowercase =[] else: current_sub_tokens.append(snake_case_ ) out_string += self.sp_model.decode(snake_case_ ) return out_string.strip() def _A( self , snake_case_=False ): return 1 def _A( self , snake_case_ ): lowercase =set(self.all_special_ids ) # call it once instead of inside list comp all_special_ids.remove(self.unk_token_id ) # <unk> is only sometimes special return [1 if x in all_special_ids else 0 for x in seq] def _A( self , snake_case_ , snake_case_ = None , snake_case_ = False ): if already_has_special_tokens: return self._special_token_mask(snake_case_ ) elif token_ids_a is None: return self._special_token_mask(snake_case_ ) + [1] else: return self._special_token_mask(token_ids_a + token_ids_a ) + [1] def _A( self , snake_case_ , snake_case_=None ): 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 _A( self , snake_case_ , snake_case_ = None ): if not os.path.isdir(snake_case_ ): logger.error(f'Vocabulary path ({save_directory}) should be a directory' ) return lowercase =os.path.join( snake_case_ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(snake_case_ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , snake_case_ ) elif not os.path.isfile(self.vocab_file ): with open(snake_case_ , '''wb''' ) as fi: lowercase =self.sp_model.serialized_model_proto() fi.write(snake_case_ ) return (out_vocab_file,)
72
0
from __future__ import annotations from pprint import pformat from typing import Generic, TypeVar _UpperCAmelCase = TypeVar("""T""") class UpperCAmelCase ( Generic[T] ): '''simple docstring''' def __init__( self , lowercase = True ): """simple docstring""" A_ : str = {} # dictionary of lists A_ : Tuple = directed def lowerCAmelCase_ ( self , lowercase , lowercase ): """simple docstring""" if not self.directed: # For undirected graphs # if both source vertex and destination vertex are both present in the # adjacency list, add destination vertex to source vertex list of adjacent # vertices and add source vertex to destination vertex list of adjacent # vertices. if source_vertex in self.adj_list and destination_vertex in self.adj_list: self.adj_list[source_vertex].append(snake_case_ ) self.adj_list[destination_vertex].append(snake_case_ ) # if only source vertex is present in adjacency list, add destination vertex # to source vertex list of adjacent vertices, then create a new vertex with # destination vertex as key and assign a list containing the source vertex # as it's first adjacent vertex. elif source_vertex in self.adj_list: self.adj_list[source_vertex].append(snake_case_ ) A_ : str = [source_vertex] # if only destination vertex is present in adjacency list, add source vertex # to destination vertex list of adjacent vertices, then create a new vertex # with source vertex as key and assign a list containing the source vertex # as it's first adjacent vertex. elif destination_vertex in self.adj_list: self.adj_list[destination_vertex].append(snake_case_ ) A_ : Union[str, Any] = [destination_vertex] # if both source vertex and destination vertex are not present in adjacency # list, create a new vertex with source vertex as key and assign a list # containing the destination vertex as it's first adjacent vertex also # create a new vertex with destination vertex as key and assign a list # containing the source vertex as it's first adjacent vertex. else: A_ : Optional[int] = [destination_vertex] A_ : Optional[Any] = [source_vertex] else: # For directed graphs # if both source vertex and destination vertex are present in adjacency # list, add destination vertex to source vertex list of adjacent vertices. if source_vertex in self.adj_list and destination_vertex in self.adj_list: self.adj_list[source_vertex].append(snake_case_ ) # if only source vertex is present in adjacency list, add destination # vertex to source vertex list of adjacent vertices and create a new vertex # with destination vertex as key, which has no adjacent vertex elif source_vertex in self.adj_list: self.adj_list[source_vertex].append(snake_case_ ) A_ : str = [] # if only destination vertex is present in adjacency list, create a new # vertex with source vertex as key and assign a list containing destination # vertex as first adjacent vertex elif destination_vertex in self.adj_list: A_ : List[Any] = [destination_vertex] # if both source vertex and destination vertex are not present in adjacency # list, create a new vertex with source vertex as key and a list containing # destination vertex as it's first adjacent vertex. Then create a new vertex # with destination vertex as key, which has no adjacent vertex else: A_ : List[str] = [destination_vertex] A_ : Union[str, Any] = [] return self def __repr__( self ): """simple docstring""" return pformat(self.adj_list )
558
'''simple docstring''' def UpperCamelCase ( lowercase_ : int , lowercase_ : int ) -> str: '''simple docstring''' return "\n".join( f'{number} * {i} = {number * i}' for i in range(1 , number_of_terms + 1 ) ) if __name__ == "__main__": print(multiplication_table(number=5, number_of_terms=10))
72
0
'''simple docstring''' from __future__ import annotations UpperCamelCase_ = '''Muhammad Umer Farooq''' UpperCamelCase_ = '''MIT''' UpperCamelCase_ = '''1.0.0''' UpperCamelCase_ = '''Muhammad Umer Farooq''' UpperCamelCase_ = '''contact@muhammadumerfarooq.me''' UpperCamelCase_ = '''Alpha''' import re from html.parser import HTMLParser from urllib import parse import requests class a_ (__SCREAMING_SNAKE_CASE ): def __init__( self , snake_case_ ): super().__init__() _lowerCAmelCase : str = [] _lowerCAmelCase : str = domain def __UpperCamelCase ( self , snake_case_ , snake_case_ ): # Only parse the 'anchor' tag. if tag == "a": # Check the list of defined attributes. for name, value in attrs: # If href is defined, and not empty nor # print it. if name == "href" and value != "#" and value != "": # If not already in urls. if value not in self.urls: _lowerCAmelCase : Dict = parse.urljoin(self.domain , snake_case_ ) self.urls.append(snake_case_ ) def _UpperCAmelCase ( _lowerCamelCase : str ) -> str: return ".".join(get_sub_domain_name(lowercase_ ).split(""".""" )[-2:] ) def _UpperCAmelCase ( _lowerCamelCase : str ) -> str: return parse.urlparse(lowercase_ ).netloc def _UpperCAmelCase ( _lowerCamelCase : str = "https://github.com" ) -> list[str]: _lowerCAmelCase : List[Any] = get_domain_name(lowercase_ ) # Initialize the parser _lowerCAmelCase : int = Parser(lowercase_ ) try: # Open URL _lowerCAmelCase : Any = requests.get(lowercase_ ) # pass the raw HTML to the parser to get links parser.feed(r.text ) # Get links and loop through _lowerCAmelCase : Tuple = set() for link in parser.urls: # open URL. # read = requests.get(link) try: _lowerCAmelCase : str = requests.get(lowercase_ ) # Get the valid email. _lowerCAmelCase : str = re.findall("""[a-zA-Z0-9]+@""" + domain , read.text ) # If not in list then append it. for email in emails: valid_emails.add(lowercase_ ) except ValueError: pass except ValueError: raise SystemExit(1 ) # Finally return a sorted list of email addresses with no duplicates. return sorted(lowercase_ ) if __name__ == "__main__": UpperCamelCase_ = emails_from_url("""https://github.com""") print(F'{len(emails)} emails found:') print("""\n""".join(sorted(emails)))
384
'''simple docstring''' import unicodedata from dataclasses import dataclass from typing import Optional, Union import numpy as np from transformers.data.data_collator import DataCollatorMixin from transformers.file_utils import PaddingStrategy from transformers.tokenization_utils_base import PreTrainedTokenizerBase def UpperCamelCase ( lowercase_ : List[str] , lowercase_ : Union[str, Any] , lowercase_ : Dict , lowercase_ : Tuple ) -> List[Any]: '''simple docstring''' if isinstance(lowercase_ , lowercase_ ): lowercase =np.full((len(lowercase_ ), sequence_length, 2) , lowercase_ ) else: lowercase =np.full((len(lowercase_ ), sequence_length) , lowercase_ ) for i, tensor in enumerate(lowercase_ ): if padding_side == "right": if isinstance(lowercase_ , lowercase_ ): lowercase =tensor[:sequence_length] else: lowercase =tensor[:sequence_length] else: if isinstance(lowercase_ , lowercase_ ): lowercase =tensor[:sequence_length] else: lowercase =tensor[:sequence_length] return out_tensor.tolist() def UpperCamelCase ( lowercase_ : Optional[Any] ) -> str: '''simple docstring''' lowercase =ord(lowercase_ ) if (cp >= 3_3 and cp <= 4_7) or (cp >= 5_8 and cp <= 6_4) or (cp >= 9_1 and cp <= 9_6) or (cp >= 1_2_3 and cp <= 1_2_6): return True lowercase =unicodedata.category(lowercase_ ) if cat.startswith('''P''' ): return True return False @dataclass class __magic_name__ ( __SCREAMING_SNAKE_CASE ): UpperCamelCase__ = 42 UpperCamelCase__ = True UpperCamelCase__ = None UpperCamelCase__ = None UpperCamelCase__ = -1_00 UpperCamelCase__ = "pt" def _A( self , snake_case_ ): import torch lowercase ='''label''' if '''label''' in features[0].keys() else '''labels''' lowercase =[feature[label_name] for feature in features] if label_name in features[0].keys() else None lowercase =self.tokenizer.pad( snake_case_ , padding=self.padding , max_length=self.max_length , pad_to_multiple_of=self.pad_to_multiple_of , return_tensors='''pt''' if labels is None else None , ) if labels is None: return batch lowercase =torch.tensor(batch['''entity_ids'''] ).shape[1] lowercase =self.tokenizer.padding_side if padding_side == "right": lowercase =[ list(snake_case_ ) + [self.label_pad_token_id] * (sequence_length - len(snake_case_ )) for label in labels ] else: lowercase =[ [self.label_pad_token_id] * (sequence_length - len(snake_case_ )) + list(snake_case_ ) for label in labels ] lowercase =[feature['''ner_tags'''] for feature in features] lowercase =padding_tensor(snake_case_ , -1 , snake_case_ , snake_case_ ) lowercase =[feature['''original_entity_spans'''] for feature in features] lowercase =padding_tensor(snake_case_ , (-1, -1) , snake_case_ , snake_case_ ) lowercase ={k: torch.tensor(snake_case_ , dtype=torch.intaa ) for k, v in batch.items()} return batch
72
0
"""simple docstring""" import math import torch from torch import nn from ..configuration_utils import ConfigMixin, register_to_config from .attention_processor import Attention from .embeddings import get_timestep_embedding from .modeling_utils import ModelMixin class a__ ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): @register_to_config def __init__( self : Tuple ,a__ : str = 128 ,a__ : int = 256 ,a__ : Tuple = 2000.0 ,a__ : Union[str, Any] = 768 ,a__ : Optional[Any] = 12 ,a__ : Any = 12 ,a__ : Optional[Any] = 64 ,a__ : Union[str, Any] = 2048 ,a__ : Tuple = 0.1 ,) -> Dict: """simple docstring""" super().__init__() _lowerCAmelCase:Union[str, Any] = nn.Sequential( nn.Linear(snake_case_ ,d_model * 4 ,bias=snake_case_) ,nn.SiLU() ,nn.Linear(d_model * 4 ,d_model * 4 ,bias=snake_case_) ,nn.SiLU() ,) _lowerCAmelCase:Any = nn.Embedding(snake_case_ ,snake_case_) _lowerCAmelCase:Optional[int] = False _lowerCAmelCase:Optional[Any] = nn.Linear(snake_case_ ,snake_case_ ,bias=snake_case_) _lowerCAmelCase:Optional[Any] = nn.Dropout(p=snake_case_) _lowerCAmelCase:Optional[int] = nn.ModuleList() for lyr_num in range(snake_case_): # FiLM conditional T5 decoder _lowerCAmelCase:Union[str, Any] = DecoderLayer(d_model=snake_case_ ,d_kv=snake_case_ ,num_heads=snake_case_ ,d_ff=snake_case_ ,dropout_rate=snake_case_) self.decoders.append(snake_case_) _lowerCAmelCase:Tuple = TaLayerNorm(snake_case_) _lowerCAmelCase:Dict = nn.Dropout(p=snake_case_) _lowerCAmelCase:List[str] = nn.Linear(snake_case_ ,snake_case_ ,bias=snake_case_) def __UpperCamelCase ( self : int ,a__ : List[Any] ,a__ : Any) -> Any: """simple docstring""" _lowerCAmelCase:int = torch.mul(query_input.unsqueeze(-1) ,key_input.unsqueeze(-2)) return mask.unsqueeze(-3) def __UpperCamelCase ( self : Optional[int] ,a__ : Dict ,a__ : str ,a__ : Tuple) -> Optional[int]: """simple docstring""" _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase:str = decoder_input_tokens.shape assert decoder_noise_time.shape == (batch,) # decoder_noise_time is in [0, 1), so rescale to expected timing range. _lowerCAmelCase:Dict = get_timestep_embedding( decoder_noise_time * self.config.max_decoder_noise_time ,embedding_dim=self.config.d_model ,max_period=self.config.max_decoder_noise_time ,).to(dtype=self.dtype) _lowerCAmelCase:List[str] = self.conditioning_emb(snake_case_).unsqueeze(1) assert conditioning_emb.shape == (batch, 1, self.config.d_model * 4) _lowerCAmelCase:int = decoder_input_tokens.shape[1] # If we want to use relative positions for audio context, we can just offset # this sequence by the length of encodings_and_masks. _lowerCAmelCase:Any = torch.broadcast_to( torch.arange(snake_case_ ,device=decoder_input_tokens.device) ,(batch, seq_length) ,) _lowerCAmelCase:Dict = self.position_encoding(snake_case_) _lowerCAmelCase:int = self.continuous_inputs_projection(snake_case_) inputs += position_encodings _lowerCAmelCase:List[Any] = self.dropout(snake_case_) # decoder: No padding present. _lowerCAmelCase:Tuple = torch.ones( decoder_input_tokens.shape[:2] ,device=decoder_input_tokens.device ,dtype=inputs.dtype) # Translate encoding masks to encoder-decoder masks. _lowerCAmelCase:Dict = [(x, self.encoder_decoder_mask(snake_case_ ,snake_case_)) for x, y in encodings_and_masks] # cross attend style: concat encodings _lowerCAmelCase:Dict = torch.cat([x[0] for x in encodings_and_encdec_masks] ,dim=1) _lowerCAmelCase:Optional[int] = torch.cat([x[1] for x in encodings_and_encdec_masks] ,dim=-1) for lyr in self.decoders: _lowerCAmelCase:Optional[Any] = lyr( snake_case_ ,conditioning_emb=snake_case_ ,encoder_hidden_states=snake_case_ ,encoder_attention_mask=snake_case_ ,)[0] _lowerCAmelCase:List[str] = self.decoder_norm(snake_case_) _lowerCAmelCase:Any = self.post_dropout(snake_case_) _lowerCAmelCase:int = self.spec_out(snake_case_) return spec_out class a__ ( nn.Module ): def __init__( self : int ,a__ : str ,a__ : Dict ,a__ : Tuple ,a__ : List[str] ,a__ : Optional[Any] ,a__ : Union[str, Any]=1E-6) -> List[Any]: """simple docstring""" super().__init__() _lowerCAmelCase:Union[str, Any] = nn.ModuleList() # cond self attention: layer 0 self.layer.append( TaLayerSelfAttentionCond(d_model=snake_case_ ,d_kv=snake_case_ ,num_heads=snake_case_ ,dropout_rate=snake_case_)) # cross attention: layer 1 self.layer.append( TaLayerCrossAttention( d_model=snake_case_ ,d_kv=snake_case_ ,num_heads=snake_case_ ,dropout_rate=snake_case_ ,layer_norm_epsilon=snake_case_ ,)) # Film Cond MLP + dropout: last layer self.layer.append( TaLayerFFCond(d_model=snake_case_ ,d_ff=snake_case_ ,dropout_rate=snake_case_ ,layer_norm_epsilon=snake_case_)) def __UpperCamelCase ( self : Optional[Any] ,a__ : str ,a__ : Optional[int]=None ,a__ : Optional[int]=None ,a__ : Optional[int]=None ,a__ : int=None ,a__ : List[Any]=None ,) -> List[Any]: """simple docstring""" _lowerCAmelCase:str = self.layer[0]( snake_case_ ,conditioning_emb=snake_case_ ,attention_mask=snake_case_ ,) if encoder_hidden_states is not None: _lowerCAmelCase:Union[str, Any] = torch.where(encoder_attention_mask > 0 ,0 ,-1E10).to( encoder_hidden_states.dtype) _lowerCAmelCase:Optional[Any] = self.layer[1]( snake_case_ ,key_value_states=snake_case_ ,attention_mask=snake_case_ ,) # Apply Film Conditional Feed Forward layer _lowerCAmelCase:List[str] = self.layer[-1](snake_case_ ,snake_case_) return (hidden_states,) class a__ ( nn.Module ): def __init__( self : List[str] ,a__ : Tuple ,a__ : Optional[Any] ,a__ : str ,a__ : Optional[Any]) -> List[str]: """simple docstring""" super().__init__() _lowerCAmelCase:int = TaLayerNorm(snake_case_) _lowerCAmelCase:Optional[int] = TaFiLMLayer(in_features=d_model * 4 ,out_features=snake_case_) _lowerCAmelCase:Optional[Any] = Attention(query_dim=snake_case_ ,heads=snake_case_ ,dim_head=snake_case_ ,out_bias=snake_case_ ,scale_qk=snake_case_) _lowerCAmelCase:List[Any] = nn.Dropout(snake_case_) def __UpperCamelCase ( self : List[str] ,a__ : Dict ,a__ : Optional[Any]=None ,a__ : Tuple=None ,) -> Dict: """simple docstring""" _lowerCAmelCase:Optional[Any] = self.layer_norm(snake_case_) if conditioning_emb is not None: _lowerCAmelCase:Union[str, Any] = self.FiLMLayer(snake_case_ ,snake_case_) # Self-attention block _lowerCAmelCase:Optional[int] = self.attention(snake_case_) _lowerCAmelCase:Optional[Any] = hidden_states + self.dropout(snake_case_) return hidden_states class a__ ( nn.Module ): def __init__( self : int ,a__ : Dict ,a__ : Optional[Any] ,a__ : str ,a__ : Tuple ,a__ : str) -> Optional[Any]: """simple docstring""" super().__init__() _lowerCAmelCase:Optional[Any] = Attention(query_dim=snake_case_ ,heads=snake_case_ ,dim_head=snake_case_ ,out_bias=snake_case_ ,scale_qk=snake_case_) _lowerCAmelCase:List[Any] = TaLayerNorm(snake_case_ ,eps=snake_case_) _lowerCAmelCase:Optional[int] = nn.Dropout(snake_case_) def __UpperCamelCase ( self : Union[str, Any] ,a__ : List[str] ,a__ : List[Any]=None ,a__ : int=None ,) -> Dict: """simple docstring""" _lowerCAmelCase:Union[str, Any] = self.layer_norm(snake_case_) _lowerCAmelCase:Tuple = self.attention( snake_case_ ,encoder_hidden_states=snake_case_ ,attention_mask=attention_mask.squeeze(1) ,) _lowerCAmelCase:List[Any] = hidden_states + self.dropout(snake_case_) return layer_output class a__ ( nn.Module ): def __init__( self : List[str] ,a__ : List[str] ,a__ : Union[str, Any] ,a__ : Optional[int] ,a__ : Any) -> str: """simple docstring""" super().__init__() _lowerCAmelCase:List[str] = TaDenseGatedActDense(d_model=snake_case_ ,d_ff=snake_case_ ,dropout_rate=snake_case_) _lowerCAmelCase:Dict = TaFiLMLayer(in_features=d_model * 4 ,out_features=snake_case_) _lowerCAmelCase:int = TaLayerNorm(snake_case_ ,eps=snake_case_) _lowerCAmelCase:str = nn.Dropout(snake_case_) def __UpperCamelCase ( self : int ,a__ : List[Any] ,a__ : Optional[Any]=None) -> str: """simple docstring""" _lowerCAmelCase:Tuple = self.layer_norm(snake_case_) if conditioning_emb is not None: _lowerCAmelCase:Tuple = self.film(snake_case_ ,snake_case_) _lowerCAmelCase:Union[str, Any] = self.DenseReluDense(snake_case_) _lowerCAmelCase:List[Any] = hidden_states + self.dropout(snake_case_) return hidden_states class a__ ( nn.Module ): def __init__( self : List[Any] ,a__ : Any ,a__ : Optional[Any] ,a__ : Any) -> str: """simple docstring""" super().__init__() _lowerCAmelCase:List[Any] = nn.Linear(snake_case_ ,snake_case_ ,bias=snake_case_) _lowerCAmelCase:List[Any] = nn.Linear(snake_case_ ,snake_case_ ,bias=snake_case_) _lowerCAmelCase:Optional[int] = nn.Linear(snake_case_ ,snake_case_ ,bias=snake_case_) _lowerCAmelCase:Optional[Any] = nn.Dropout(snake_case_) _lowerCAmelCase:Tuple = NewGELUActivation() def __UpperCamelCase ( self : Optional[int] ,a__ : int) -> List[str]: """simple docstring""" _lowerCAmelCase:Tuple = self.act(self.wi_a(snake_case_)) _lowerCAmelCase:Tuple = self.wi_a(snake_case_) _lowerCAmelCase:List[Any] = hidden_gelu * hidden_linear _lowerCAmelCase:Optional[int] = self.dropout(snake_case_) _lowerCAmelCase:Tuple = self.wo(snake_case_) return hidden_states class a__ ( nn.Module ): def __init__( self : Optional[int] ,a__ : str ,a__ : Optional[int]=1E-6) -> str: """simple docstring""" super().__init__() _lowerCAmelCase:Dict = nn.Parameter(torch.ones(snake_case_)) _lowerCAmelCase:Union[str, Any] = eps def __UpperCamelCase ( self : List[str] ,a__ : Any) -> str: """simple docstring""" _lowerCAmelCase:List[Any] = hidden_states.to(torch.floataa).pow(2).mean(-1 ,keepdim=snake_case_) _lowerCAmelCase:Optional[Any] = hidden_states * torch.rsqrt(variance + self.variance_epsilon) # convert into half-precision if necessary if self.weight.dtype in [torch.floataa, torch.bfloataa]: _lowerCAmelCase:Dict = hidden_states.to(self.weight.dtype) return self.weight * hidden_states class a__ ( nn.Module ): def __UpperCamelCase ( self : List[Any] ,a__ : Optional[int]) -> Optional[int]: """simple docstring""" return 0.5 * input * (1.0 + torch.tanh(math.sqrt(2.0 / math.pi) * (input + 0.044715 * torch.pow(snake_case_ ,3.0)))) class a__ ( nn.Module ): def __init__( self : str ,a__ : Any ,a__ : str) -> int: """simple docstring""" super().__init__() _lowerCAmelCase:int = nn.Linear(snake_case_ ,out_features * 2 ,bias=snake_case_) def __UpperCamelCase ( self : Union[str, Any] ,a__ : Optional[Any] ,a__ : Tuple) -> List[Any]: """simple docstring""" _lowerCAmelCase:List[Any] = self.scale_bias(snake_case_) _lowerCAmelCase , _lowerCAmelCase:Optional[int] = torch.chunk(snake_case_ ,2 ,-1) _lowerCAmelCase:List[str] = x * (1 + scale) + shift return x
227
'''simple docstring''' _UpperCAmelCase : Tuple = '''ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/''' def UpperCamelCase ( lowercase_ : bytes ) -> bytes: '''simple docstring''' if not isinstance(lowercase_ , lowercase_ ): lowercase =f'a bytes-like object is required, not \'{data.__class__.__name__}\'' raise TypeError(lowercase_ ) lowercase =''''''.join(bin(lowercase_ )[2:].zfill(8 ) for byte in data ) lowercase =len(lowercase_ ) % 6 != 0 if padding_needed: # The padding that will be added later lowercase =b'''=''' * ((6 - len(lowercase_ ) % 6) // 2) # Append binary_stream with arbitrary binary digits (0's by default) to make its # length a multiple of 6. binary_stream += "0" * (6 - len(lowercase_ ) % 6) else: lowercase =b'''''' # Encode every 6 binary digits to their corresponding Base64 character return ( "".join( B64_CHARSET[int(binary_stream[index : index + 6] , 2 )] for index in range(0 , len(lowercase_ ) , 6 ) ).encode() + padding ) def UpperCamelCase ( lowercase_ : str ) -> bytes: '''simple docstring''' if not isinstance(lowercase_ , lowercase_ ) and not isinstance(lowercase_ , lowercase_ ): lowercase =( '''argument should be a bytes-like object or ASCII string, ''' f'not \'{encoded_data.__class__.__name__}\'' ) raise TypeError(lowercase_ ) # In case encoded_data is a bytes-like object, make sure it contains only # ASCII characters so we convert it to a string object if isinstance(lowercase_ , lowercase_ ): try: lowercase =encoded_data.decode('''utf-8''' ) except UnicodeDecodeError: raise ValueError('''base64 encoded data should only contain ASCII characters''' ) lowercase =encoded_data.count('''=''' ) # Check if the encoded string contains non base64 characters if padding: assert all( char in B64_CHARSET for char in encoded_data[:-padding] ), "Invalid base64 character(s) found." else: assert all( char in B64_CHARSET for char in encoded_data ), "Invalid base64 character(s) found." # Check the padding assert len(lowercase_ ) % 4 == 0 and padding < 3, "Incorrect padding" if padding: # Remove padding if there is one lowercase =encoded_data[:-padding] lowercase =''''''.join( bin(B64_CHARSET.index(lowercase_ ) )[2:].zfill(6 ) for char in encoded_data )[: -padding * 2] else: lowercase =''''''.join( bin(B64_CHARSET.index(lowercase_ ) )[2:].zfill(6 ) for char in encoded_data ) lowercase =[ int(binary_stream[index : index + 8] , 2 ) for index in range(0 , len(lowercase_ ) , 8 ) ] return bytes(lowercase_ ) if __name__ == "__main__": import doctest doctest.testmod()
72
0
import tempfile import unittest import numpy as np from huggingface_hub import HfFolder, delete_repo from requests.exceptions import HTTPError from transformers import BertConfig, is_flax_available from transformers.testing_utils import TOKEN, USER, is_staging_test, require_flax if is_flax_available(): import os from flax.core.frozen_dict import unfreeze from flax.traverse_util import flatten_dict from transformers import FlaxBertModel __magic_name__ : Optional[int] = '''0.12''' # assumed parallelism: 8 @require_flax @is_staging_test class A__ ( unittest.TestCase ): '''simple docstring''' @classmethod def _SCREAMING_SNAKE_CASE ( cls : Optional[int] ): """simple docstring""" UpperCamelCase = TOKEN HfFolder.save_token(snake_case_ ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : Tuple ): """simple docstring""" try: delete_repo(token=cls._token , repo_id='test-model-flax' ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id='valid_org/test-model-flax-org' ) except HTTPError: pass def _SCREAMING_SNAKE_CASE ( self : List[str] ): """simple docstring""" UpperCamelCase = BertConfig( vocab_size=99 , hidden_size=32 , num_hidden_layers=5 , num_attention_heads=4 , intermediate_size=37 ) UpperCamelCase = FlaxBertModel(snake_case_ ) model.push_to_hub('test-model-flax' , use_auth_token=self._token ) UpperCamelCase = FlaxBertModel.from_pretrained(f'{USER}/test-model-flax' ) UpperCamelCase = flatten_dict(unfreeze(model.params ) ) UpperCamelCase = flatten_dict(unfreeze(new_model.params ) ) for key in base_params.keys(): UpperCamelCase = (base_params[key] - new_params[key]).sum().item() self.assertLessEqual(snake_case_ , 1E-3 , msg=f'{key} not identical' ) # Reset repo delete_repo(token=self._token , repo_id='test-model-flax' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: model.save_pretrained(snake_case_ , repo_id='test-model-flax' , push_to_hub=snake_case_ , use_auth_token=self._token ) UpperCamelCase = FlaxBertModel.from_pretrained(f'{USER}/test-model-flax' ) UpperCamelCase = flatten_dict(unfreeze(model.params ) ) UpperCamelCase = flatten_dict(unfreeze(new_model.params ) ) for key in base_params.keys(): UpperCamelCase = (base_params[key] - new_params[key]).sum().item() self.assertLessEqual(snake_case_ , 1E-3 , msg=f'{key} not identical' ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" UpperCamelCase = BertConfig( vocab_size=99 , hidden_size=32 , num_hidden_layers=5 , num_attention_heads=4 , intermediate_size=37 ) UpperCamelCase = FlaxBertModel(snake_case_ ) model.push_to_hub('valid_org/test-model-flax-org' , use_auth_token=self._token ) UpperCamelCase = FlaxBertModel.from_pretrained('valid_org/test-model-flax-org' ) UpperCamelCase = flatten_dict(unfreeze(model.params ) ) UpperCamelCase = flatten_dict(unfreeze(new_model.params ) ) for key in base_params.keys(): UpperCamelCase = (base_params[key] - new_params[key]).sum().item() self.assertLessEqual(snake_case_ , 1E-3 , msg=f'{key} not identical' ) # Reset repo delete_repo(token=self._token , repo_id='valid_org/test-model-flax-org' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: model.save_pretrained( snake_case_ , repo_id='valid_org/test-model-flax-org' , push_to_hub=snake_case_ , use_auth_token=self._token ) UpperCamelCase = FlaxBertModel.from_pretrained('valid_org/test-model-flax-org' ) UpperCamelCase = flatten_dict(unfreeze(model.params ) ) UpperCamelCase = flatten_dict(unfreeze(new_model.params ) ) for key in base_params.keys(): UpperCamelCase = (base_params[key] - new_params[key]).sum().item() self.assertLessEqual(snake_case_ , 1E-3 , msg=f'{key} not identical' ) def lowercase__ ( _UpperCamelCase , _UpperCamelCase) -> Any: """simple docstring""" UpperCamelCase = True UpperCamelCase = flatten_dict(modela.params) UpperCamelCase = flatten_dict(modela.params) for key in flat_params_a.keys(): if np.sum(np.abs(flat_params_a[key] - flat_params_a[key])) > 1e-4: UpperCamelCase = False return models_are_equal @require_flax class A__ ( unittest.TestCase ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" UpperCamelCase = BertConfig.from_pretrained('hf-internal-testing/tiny-bert-flax-only' ) UpperCamelCase = FlaxBertModel(snake_case_ ) UpperCamelCase = 'bert' with tempfile.TemporaryDirectory() as tmp_dir: model.save_pretrained(os.path.join(snake_case_ , snake_case_ ) ) with self.assertRaises(snake_case_ ): UpperCamelCase = FlaxBertModel.from_pretrained(snake_case_ ) UpperCamelCase = FlaxBertModel.from_pretrained(snake_case_ , subfolder=snake_case_ ) self.assertTrue(check_models_equal(snake_case_ , snake_case_ ) ) def _SCREAMING_SNAKE_CASE ( self : Tuple ): """simple docstring""" UpperCamelCase = BertConfig.from_pretrained('hf-internal-testing/tiny-bert-flax-only' ) UpperCamelCase = FlaxBertModel(snake_case_ ) UpperCamelCase = 'bert' with tempfile.TemporaryDirectory() as tmp_dir: model.save_pretrained(os.path.join(snake_case_ , snake_case_ ) , max_shard_size='10KB' ) with self.assertRaises(snake_case_ ): UpperCamelCase = FlaxBertModel.from_pretrained(snake_case_ ) UpperCamelCase = FlaxBertModel.from_pretrained(snake_case_ , subfolder=snake_case_ ) self.assertTrue(check_models_equal(snake_case_ , snake_case_ ) ) def _SCREAMING_SNAKE_CASE ( self : List[str] ): """simple docstring""" UpperCamelCase = 'bert' UpperCamelCase = 'hf-internal-testing/tiny-random-bert-subfolder' with self.assertRaises(snake_case_ ): UpperCamelCase = FlaxBertModel.from_pretrained(snake_case_ ) UpperCamelCase = FlaxBertModel.from_pretrained(snake_case_ , subfolder=snake_case_ ) self.assertIsNotNone(snake_case_ ) def _SCREAMING_SNAKE_CASE ( self : Tuple ): """simple docstring""" UpperCamelCase = 'bert' UpperCamelCase = 'hf-internal-testing/tiny-random-bert-sharded-subfolder' with self.assertRaises(snake_case_ ): UpperCamelCase = FlaxBertModel.from_pretrained(snake_case_ ) UpperCamelCase = FlaxBertModel.from_pretrained(snake_case_ , subfolder=snake_case_ ) self.assertIsNotNone(snake_case_ )
280
'''simple docstring''' import coval # From: git+https://github.com/ns-moosavi/coval.git # noqa: F401 from coval.conll import reader, util from coval.eval import evaluator import datasets _UpperCAmelCase : Union[str, Any] = datasets.logging.get_logger(__name__) _UpperCAmelCase : Optional[Any] = '''\ @InProceedings{moosavi2019minimum, author = { Nafise Sadat Moosavi, Leo Born, Massimo Poesio and Michael Strube}, title = {Using Automatically Extracted Minimum Spans to Disentangle Coreference Evaluation from Boundary Detection}, year = {2019}, booktitle = {Proceedings of the 57th Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers)}, publisher = {Association for Computational Linguistics}, address = {Florence, Italy}, } @inproceedings{10.3115/1072399.1072405, author = {Vilain, Marc and Burger, John and Aberdeen, John and Connolly, Dennis and Hirschman, Lynette}, title = {A Model-Theoretic Coreference Scoring Scheme}, year = {1995}, isbn = {1558604022}, publisher = {Association for Computational Linguistics}, address = {USA}, url = {https://doi.org/10.3115/1072399.1072405}, doi = {10.3115/1072399.1072405}, booktitle = {Proceedings of the 6th Conference on Message Understanding}, pages = {45–52}, numpages = {8}, location = {Columbia, Maryland}, series = {MUC6 ’95} } @INPROCEEDINGS{Bagga98algorithmsfor, author = {Amit Bagga and Breck Baldwin}, title = {Algorithms for Scoring Coreference Chains}, booktitle = {In The First International Conference on Language Resources and Evaluation Workshop on Linguistics Coreference}, year = {1998}, pages = {563--566} } @INPROCEEDINGS{Luo05oncoreference, author = {Xiaoqiang Luo}, title = {On coreference resolution performance metrics}, booktitle = {In Proc. of HLT/EMNLP}, year = {2005}, pages = {25--32}, publisher = {URL} } @inproceedings{moosavi-strube-2016-coreference, title = "Which Coreference Evaluation Metric Do You Trust? A Proposal for a Link-based Entity Aware Metric", author = "Moosavi, Nafise Sadat and Strube, Michael", booktitle = "Proceedings of the 54th Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers)", month = aug, year = "2016", address = "Berlin, Germany", publisher = "Association for Computational Linguistics", url = "https://www.aclweb.org/anthology/P16-1060", doi = "10.18653/v1/P16-1060", pages = "632--642", } ''' _UpperCAmelCase : str = '''\ CoVal is a coreference evaluation tool for the CoNLL and ARRAU datasets which implements of the common evaluation metrics including MUC [Vilain et al, 1995], B-cubed [Bagga and Baldwin, 1998], CEAFe [Luo et al., 2005], LEA [Moosavi and Strube, 2016] and the averaged CoNLL score (the average of the F1 values of MUC, B-cubed and CEAFe) [Denis and Baldridge, 2009a; Pradhan et al., 2011]. This wrapper of CoVal currently only work with CoNLL line format: The CoNLL format has one word per line with all the annotation for this word in column separated by spaces: Column Type Description 1 Document ID This is a variation on the document filename 2 Part number Some files are divided into multiple parts numbered as 000, 001, 002, ... etc. 3 Word number 4 Word itself This is the token as segmented/tokenized in the Treebank. Initially the *_skel file contain the placeholder [WORD] which gets replaced by the actual token from the Treebank which is part of the OntoNotes release. 5 Part-of-Speech 6 Parse bit This is the bracketed structure broken before the first open parenthesis in the parse, and the word/part-of-speech leaf replaced with a *. The full parse can be created by substituting the asterix with the "([pos] [word])" string (or leaf) and concatenating the items in the rows of that column. 7 Predicate lemma The predicate lemma is mentioned for the rows for which we have semantic role information. All other rows are marked with a "-" 8 Predicate Frameset ID This is the PropBank frameset ID of the predicate in Column 7. 9 Word sense This is the word sense of the word in Column 3. 10 Speaker/Author This is the speaker or author name where available. Mostly in Broadcast Conversation and Web Log data. 11 Named Entities These columns identifies the spans representing various named entities. 12:N Predicate Arguments There is one column each of predicate argument structure information for the predicate mentioned in Column 7. N Coreference Coreference chain information encoded in a parenthesis structure. More informations on the format can be found here (section "*_conll File Format"): http://www.conll.cemantix.org/2012/data.html Details on the evaluation on CoNLL can be found here: https://github.com/ns-moosavi/coval/blob/master/conll/README.md CoVal code was written by @ns-moosavi. Some parts are borrowed from https://github.com/clarkkev/deep-coref/blob/master/evaluation.py The test suite is taken from https://github.com/conll/reference-coreference-scorers/ Mention evaluation and the test suite are added by @andreasvc. Parsing CoNLL files is developed by Leo Born. ''' _UpperCAmelCase : Optional[int] = ''' Calculates coreference evaluation metrics. Args: predictions: list of sentences. Each sentence is a list of word predictions to score in the CoNLL format. Each prediction is a word with its annotations as a string made of columns joined with spaces. Only columns 4, 5, 6 and the last column are used (word, POS, Pars and coreference annotation) See the details on the format in the description of the metric. references: list of sentences. Each sentence is a list of word reference to score in the CoNLL format. Each reference is a word with its annotations as a string made of columns joined with spaces. Only columns 4, 5, 6 and the last column are used (word, POS, Pars and coreference annotation) See the details on the format in the description of the metric. keep_singletons: After extracting all mentions of key or system files, mentions whose corresponding coreference chain is of size one, are considered as singletons. The default evaluation mode will include singletons in evaluations if they are included in the key or the system files. By setting \'keep_singletons=False\', all singletons in the key and system files will be excluded from the evaluation. NP_only: Most of the recent coreference resolvers only resolve NP mentions and leave out the resolution of VPs. By setting the \'NP_only\' option, the scorer will only evaluate the resolution of NPs. min_span: By setting \'min_span\', the scorer reports the results based on automatically detected minimum spans. Minimum spans are determined using the MINA algorithm. Returns: \'mentions\': mentions \'muc\': MUC metric [Vilain et al, 1995] \'bcub\': B-cubed [Bagga and Baldwin, 1998] \'ceafe\': CEAFe [Luo et al., 2005] \'lea\': LEA [Moosavi and Strube, 2016] \'conll_score\': averaged CoNLL score (the average of the F1 values of MUC, B-cubed and CEAFe) Examples: >>> coval = datasets.load_metric(\'coval\') >>> words = [\'bc/cctv/00/cctv_0005 0 0 Thank VBP (TOP(S(VP* thank 01 1 Xu_li * (V*) * -\', ... \'bc/cctv/00/cctv_0005 0 1 you PRP (NP*) - - - Xu_li * (ARG1*) (ARG0*) (116)\', ... \'bc/cctv/00/cctv_0005 0 2 everyone NN (NP*) - - - Xu_li * (ARGM-DIS*) * (116)\', ... \'bc/cctv/00/cctv_0005 0 3 for IN (PP* - - - Xu_li * (ARG2* * -\', ... \'bc/cctv/00/cctv_0005 0 4 watching VBG (S(VP*)))) watch 01 1 Xu_li * *) (V*) -\', ... \'bc/cctv/00/cctv_0005 0 5 . . *)) - - - Xu_li * * * -\'] >>> references = [words] >>> predictions = [words] >>> results = coval.compute(predictions=predictions, references=references) >>> print(results) # doctest:+ELLIPSIS {\'mentions/recall\': 1.0,[...] \'conll_score\': 100.0} ''' def UpperCamelCase ( lowercase_ : Optional[Any] , lowercase_ : List[Any] , lowercase_ : Optional[Any]=False , lowercase_ : Optional[Any]=False , lowercase_ : Optional[Any]=True , lowercase_ : Optional[Any]=False , lowercase_ : int="dummy_doc" ) -> str: '''simple docstring''' lowercase ={doc: key_lines} lowercase ={doc: sys_lines} lowercase ={} lowercase =0 lowercase =0 lowercase =0 lowercase =0 lowercase =0 lowercase =0 lowercase , lowercase =reader.get_doc_mentions(lowercase_ , key_doc_lines[doc] , lowercase_ ) key_singletons_num += singletons_num if NP_only or min_span: lowercase =reader.set_annotated_parse_trees(lowercase_ , key_doc_lines[doc] , lowercase_ , lowercase_ ) lowercase , lowercase =reader.get_doc_mentions(lowercase_ , sys_doc_lines[doc] , lowercase_ ) sys_singletons_num += singletons_num if NP_only or min_span: lowercase =reader.set_annotated_parse_trees(lowercase_ , key_doc_lines[doc] , lowercase_ , lowercase_ ) if remove_nested: lowercase , lowercase =reader.remove_nested_coref_mentions(lowercase_ , lowercase_ ) key_nested_coref_num += nested_mentions key_removed_nested_clusters += removed_clusters lowercase , lowercase =reader.remove_nested_coref_mentions(lowercase_ , lowercase_ ) sys_nested_coref_num += nested_mentions sys_removed_nested_clusters += removed_clusters lowercase =reader.get_mention_assignments(lowercase_ , lowercase_ ) lowercase =reader.get_mention_assignments(lowercase_ , lowercase_ ) lowercase =(key_clusters, sys_clusters, key_mention_sys_cluster, sys_mention_key_cluster) if remove_nested: logger.info( '''Number of removed nested coreferring mentions in the key ''' f'annotation: {key_nested_coref_num}; and system annotation: {sys_nested_coref_num}' ) logger.info( '''Number of resulting singleton clusters in the key ''' f'annotation: {key_removed_nested_clusters}; and system annotation: {sys_removed_nested_clusters}' ) if not keep_singletons: logger.info( f'{key_singletons_num:d} and {sys_singletons_num:d} singletons are removed from the key and system ' '''files, respectively''' ) return doc_coref_infos def UpperCamelCase ( lowercase_ : List[Any] , lowercase_ : Union[str, Any] , lowercase_ : List[str] , lowercase_ : Optional[Any] , lowercase_ : List[str] , lowercase_ : Any , lowercase_ : Tuple ) -> Dict: '''simple docstring''' lowercase =get_coref_infos(lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ ) lowercase ={} lowercase =0 lowercase =0 for name, metric in metrics: lowercase , lowercase , lowercase =evaluator.evaluate_documents(lowercase_ , lowercase_ , beta=1 ) if name in ["muc", "bcub", "ceafe"]: conll += fa conll_subparts_num += 1 output_scores.update({f'{name}/recall': recall, f'{name}/precision': precision, f'{name}/f1': fa} ) logger.info( name.ljust(1_0 ) , f'Recall: {recall * 1_0_0:.2f}' , f' Precision: {precision * 1_0_0:.2f}' , f' F1: {fa * 1_0_0:.2f}' , ) if conll_subparts_num == 3: lowercase =(conll / 3) * 1_0_0 logger.info(f'CoNLL score: {conll:.2f}' ) output_scores.update({'''conll_score''': conll} ) return output_scores def UpperCamelCase ( lowercase_ : Any ) -> List[Any]: '''simple docstring''' lowercase =False for line in key_lines: if not line.startswith('''#''' ): if len(line.split() ) > 6: lowercase =line.split()[5] if not parse_col == "-": lowercase =True break else: break return has_gold_parse @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class __magic_name__ ( datasets.Metric ): def _A( self ): return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Sequence(datasets.Value('''string''' ) ), '''references''': datasets.Sequence(datasets.Value('''string''' ) ), } ) , codebase_urls=['''https://github.com/ns-moosavi/coval'''] , reference_urls=[ '''https://github.com/ns-moosavi/coval''', '''https://www.aclweb.org/anthology/P16-1060''', '''http://www.conll.cemantix.org/2012/data.html''', ] , ) def _A( self , snake_case_ , snake_case_ , snake_case_=True , snake_case_=False , snake_case_=False , snake_case_=False ): lowercase =[ ('''mentions''', evaluator.mentions), ('''muc''', evaluator.muc), ('''bcub''', evaluator.b_cubed), ('''ceafe''', evaluator.ceafe), ('''lea''', evaluator.lea), ] if min_span: lowercase =util.check_gold_parse_annotation(snake_case_ ) if not has_gold_parse: raise NotImplementedError('''References should have gold parse annotation to use \'min_span\'.''' ) # util.parse_key_file(key_file) # key_file = key_file + ".parsed" lowercase =evaluate( key_lines=snake_case_ , sys_lines=snake_case_ , metrics=snake_case_ , NP_only=snake_case_ , remove_nested=snake_case_ , keep_singletons=snake_case_ , min_span=snake_case_ , ) return score
72
0
'''simple docstring''' from statistics import mean import numpy as np def a ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ): '''simple docstring''' A_ : Dict = 0 # Number of processes finished A_ : Optional[Any] = 0 # Displays the finished process. # If it is 0, the performance is completed if it is 1, before the performance. A_ : Tuple = [0] * no_of_process # List to include calculation results A_ : Union[str, Any] = [0] * no_of_process # Sort by arrival time. A_ : List[str] = [burst_time[i] for i in np.argsort(lowercase_ )] A_ : List[str] = [process_name[i] for i in np.argsort(lowercase_ )] arrival_time.sort() while no_of_process > finished_process_count: A_ : List[Any] = 0 while finished_process[i] == 1: i += 1 if current_time < arrival_time[i]: A_ : Optional[Any] = arrival_time[i] A_ : Union[str, Any] = 0 # Index showing the location of the process being performed A_ : Optional[int] = 0 # Saves the current response ratio. A_ : int = 0 for i in range(0 , lowercase_ ): if finished_process[i] == 0 and arrival_time[i] <= current_time: A_ : Union[str, Any] = (burst_time[i] + (current_time - arrival_time[i])) / burst_time[ i ] if response_ratio < temp: A_ : Dict = temp A_ : List[str] = i # Calculate the turn around time A_ : Optional[int] = current_time + burst_time[loc] - arrival_time[loc] current_time += burst_time[loc] # Indicates that the process has been performed. A_ : List[str] = 1 # Increase finished_process_count by 1 finished_process_count += 1 return turn_around_time def a ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ): '''simple docstring''' A_ : int = [0] * no_of_process for i in range(0 , lowercase_ ): A_ : List[str] = turn_around_time[i] - burst_time[i] return waiting_time if __name__ == "__main__": lowerCamelCase :str = 5 lowerCamelCase :Optional[Any] = ['''A''', '''B''', '''C''', '''D''', '''E'''] lowerCamelCase :Dict = [1, 2, 3, 4, 5] lowerCamelCase :List[Any] = [1, 2, 3, 4, 5] lowerCamelCase :Optional[Any] = calculate_turn_around_time( process_name, arrival_time, burst_time, no_of_process ) lowerCamelCase :Optional[Any] = calculate_waiting_time( process_name, turn_around_time, burst_time, no_of_process ) print('''Process name \tArrival time \tBurst time \tTurn around time \tWaiting time''') for i in range(0, no_of_process): print( F"{process_name[i]}\t\t{arrival_time[i]}\t\t{burst_time[i]}\t\t" F"{turn_around_time[i]}\t\t\t{waiting_time[i]}" ) print(F"average waiting time : {mean(waiting_time):.5f}") print(F"average turn around time : {mean(turn_around_time):.5f}")
667
'''simple docstring''' def UpperCamelCase ( lowercase_ : int ) -> int: '''simple docstring''' if n == 1 or not isinstance(lowercase_ , lowercase_ ): return 0 elif n == 2: return 1 else: lowercase =[0, 1] for i in range(2 , n + 1 ): sequence.append(sequence[i - 1] + sequence[i - 2] ) return sequence[n] def UpperCamelCase ( lowercase_ : int ) -> int: '''simple docstring''' lowercase =0 lowercase =2 while digits < n: index += 1 lowercase =len(str(fibonacci(lowercase_ ) ) ) return index def UpperCamelCase ( lowercase_ : int = 1_0_0_0 ) -> int: '''simple docstring''' return fibonacci_digits_index(lowercase_ ) if __name__ == "__main__": print(solution(int(str(input()).strip())))
72
0
'''simple docstring''' 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 __SCREAMING_SNAKE_CASE : str = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE : Any = {'''vocab_file''': '''vocab.json''', '''merges_file''': '''merges.txt'''} # See all BART models at https://huggingface.co/models?filter=bart __SCREAMING_SNAKE_CASE : Optional[int] = { '''vocab_file''': { '''facebook/bart-base''': '''https://huggingface.co/facebook/bart-base/resolve/main/vocab.json''', '''facebook/bart-large''': '''https://huggingface.co/facebook/bart-large/resolve/main/vocab.json''', '''facebook/bart-large-mnli''': '''https://huggingface.co/facebook/bart-large-mnli/resolve/main/vocab.json''', '''facebook/bart-large-cnn''': '''https://huggingface.co/facebook/bart-large-cnn/resolve/main/vocab.json''', '''facebook/bart-large-xsum''': '''https://huggingface.co/facebook/bart-large-xsum/resolve/main/vocab.json''', '''yjernite/bart_eli5''': '''https://huggingface.co/yjernite/bart_eli5/resolve/main/vocab.json''', }, '''merges_file''': { '''facebook/bart-base''': '''https://huggingface.co/facebook/bart-base/resolve/main/merges.txt''', '''facebook/bart-large''': '''https://huggingface.co/facebook/bart-large/resolve/main/merges.txt''', '''facebook/bart-large-mnli''': '''https://huggingface.co/facebook/bart-large-mnli/resolve/main/merges.txt''', '''facebook/bart-large-cnn''': '''https://huggingface.co/facebook/bart-large-cnn/resolve/main/merges.txt''', '''facebook/bart-large-xsum''': '''https://huggingface.co/facebook/bart-large-xsum/resolve/main/merges.txt''', '''yjernite/bart_eli5''': '''https://huggingface.co/yjernite/bart_eli5/resolve/main/merges.txt''', }, } __SCREAMING_SNAKE_CASE : Union[str, Any] = { '''facebook/bart-base''': 1024, '''facebook/bart-large''': 1024, '''facebook/bart-large-mnli''': 1024, '''facebook/bart-large-cnn''': 1024, '''facebook/bart-large-xsum''': 1024, '''yjernite/bart_eli5''': 1024, } @lru_cache() def a_ ( ): A_ = ( list(range(ord("!" ) , ord("~" ) + 1 ) ) + list(range(ord("¡" ) , ord("¬" ) + 1 ) ) + list(range(ord("®" ) , ord("ÿ" ) + 1 ) ) ) A_ = bs[:] A_ = 0 for b in range(2**8 ): if b not in bs: bs.append(lowercase_ ) cs.append(2**8 + n ) n += 1 A_ = [chr(lowercase_ ) for n in cs] return dict(zip(lowercase_ , lowercase_ ) ) def a_ ( UpperCamelCase_ ): A_ = set() A_ = word[0] for char in word[1:]: pairs.add((prev_char, char) ) A_ = char return pairs class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): """simple docstring""" _UpperCAmelCase : Union[str, Any] =VOCAB_FILES_NAMES _UpperCAmelCase : Tuple =PRETRAINED_VOCAB_FILES_MAP _UpperCAmelCase : Tuple =PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _UpperCAmelCase : Any =["input_ids", "attention_mask"] def __init__( self : Tuple , lowerCAmelCase : Union[str, Any] , lowerCAmelCase : str , lowerCAmelCase : Union[str, Any]="replace" , lowerCAmelCase : Optional[int]="<s>" , lowerCAmelCase : Optional[int]="</s>" , lowerCAmelCase : Optional[Any]="</s>" , lowerCAmelCase : str="<s>" , lowerCAmelCase : str="<unk>" , lowerCAmelCase : Dict="<pad>" , lowerCAmelCase : Optional[int]="<mask>" , lowerCAmelCase : Any=False , **lowerCAmelCase : List[str] , ): A_ = AddedToken(snake_case_ , lstrip=snake_case_ , rstrip=snake_case_ ) if isinstance(snake_case_ , snake_case_ ) else bos_token A_ = AddedToken(snake_case_ , lstrip=snake_case_ , rstrip=snake_case_ ) if isinstance(snake_case_ , snake_case_ ) else eos_token A_ = AddedToken(snake_case_ , lstrip=snake_case_ , rstrip=snake_case_ ) if isinstance(snake_case_ , snake_case_ ) else sep_token A_ = AddedToken(snake_case_ , lstrip=snake_case_ , rstrip=snake_case_ ) if isinstance(snake_case_ , snake_case_ ) else cls_token A_ = AddedToken(snake_case_ , lstrip=snake_case_ , rstrip=snake_case_ ) if isinstance(snake_case_ , snake_case_ ) else unk_token A_ = AddedToken(snake_case_ , lstrip=snake_case_ , rstrip=snake_case_ ) if isinstance(snake_case_ , snake_case_ ) else pad_token # Mask token behave like a normal word, i.e. include the space before it A_ = AddedToken(snake_case_ , lstrip=snake_case_ , rstrip=snake_case_ ) if isinstance(snake_case_ , snake_case_ ) else mask_token super().__init__( errors=snake_case_ , bos_token=snake_case_ , eos_token=snake_case_ , unk_token=snake_case_ , sep_token=snake_case_ , cls_token=snake_case_ , pad_token=snake_case_ , mask_token=snake_case_ , add_prefix_space=snake_case_ , **snake_case_ , ) with open(snake_case_ , encoding="utf-8" ) as vocab_handle: A_ = json.load(snake_case_ ) A_ = {v: k for k, v in self.encoder.items()} A_ = errors # how to handle errors in decoding A_ = bytes_to_unicode() A_ = {v: k for k, v in self.byte_encoder.items()} with open(snake_case_ , encoding="utf-8" ) as merges_handle: A_ = merges_handle.read().split("\n" )[1:-1] A_ = [tuple(merge.split() ) for merge in bpe_merges] A_ = dict(zip(snake_case_ , range(len(snake_case_ ) ) ) ) A_ = {} A_ = add_prefix_space # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions A_ = re.compile(r"\'s|\'t|\'re|\'ve|\'m|\'ll|\'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+" ) @property def _UpperCAmelCase ( self : Optional[Any] ): return len(self.encoder ) def _UpperCAmelCase ( self : Union[str, Any] ): return dict(self.encoder , **self.added_tokens_encoder ) def _UpperCAmelCase ( self : Dict , lowerCAmelCase : int ): if token in self.cache: return self.cache[token] A_ = tuple(snake_case_ ) A_ = get_pairs(snake_case_ ) if not pairs: return token while True: A_ = min(snake_case_ , key=lambda lowerCAmelCase : self.bpe_ranks.get(snake_case_ , float("inf" ) ) ) if bigram not in self.bpe_ranks: break A_ , A_ = bigram A_ = [] A_ = 0 while i < len(snake_case_ ): try: A_ = word.index(snake_case_ , snake_case_ ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) A_ = j if word[i] == first and i < len(snake_case_ ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 A_ = tuple(snake_case_ ) A_ = new_word if len(snake_case_ ) == 1: break else: A_ = get_pairs(snake_case_ ) A_ = " ".join(snake_case_ ) A_ = word return word def _UpperCAmelCase ( self : Dict , lowerCAmelCase : Optional[int] ): A_ = [] for token in re.findall(self.pat , snake_case_ ): A_ = "".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(snake_case_ ).split(" " ) ) return bpe_tokens def _UpperCAmelCase ( self : str , lowerCAmelCase : Any ): return self.encoder.get(snake_case_ , self.encoder.get(self.unk_token ) ) def _UpperCAmelCase ( self : List[Any] , lowerCAmelCase : Optional[int] ): return self.decoder.get(snake_case_ ) def _UpperCAmelCase ( self : Tuple , lowerCAmelCase : int ): A_ = "".join(snake_case_ ) A_ = bytearray([self.byte_decoder[c] for c in text] ).decode("utf-8" , errors=self.errors ) return text def _UpperCAmelCase ( self : Union[str, Any] , lowerCAmelCase : Union[str, Any] , lowerCAmelCase : Union[str, Any] = None ): if not os.path.isdir(snake_case_ ): logger.error(F"Vocabulary path ({save_directory}) should be a directory" ) return A_ = os.path.join( snake_case_ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) A_ = os.path.join( snake_case_ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"] ) with open(snake_case_ , "w" , encoding="utf-8" ) as f: f.write(json.dumps(self.encoder , indent=2 , sort_keys=snake_case_ , ensure_ascii=snake_case_ ) + "\n" ) A_ = 0 with open(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 lowerCAmelCase : 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!" ) A_ = token_index writer.write(" ".join(snake_case_ ) + "\n" ) index += 1 return vocab_file, merge_file def _UpperCAmelCase ( self : List[str] , lowerCAmelCase : Any , lowerCAmelCase : Union[str, Any] = None ): if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] A_ = [self.cls_token_id] A_ = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def _UpperCAmelCase ( self : Optional[int] , lowerCAmelCase : Dict , lowerCAmelCase : Tuple = None , lowerCAmelCase : int = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=snake_case_ , token_ids_a=snake_case_ , already_has_special_tokens=snake_case_ ) if token_ids_a is None: return [1] + ([0] * len(snake_case_ )) + [1] return [1] + ([0] * len(snake_case_ )) + [1, 1] + ([0] * len(snake_case_ )) + [1] def _UpperCAmelCase ( self : Optional[Any] , lowerCAmelCase : Optional[int] , lowerCAmelCase : Optional[int] = None ): A_ = [self.sep_token_id] A_ = [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 _UpperCAmelCase ( self : Tuple , lowerCAmelCase : Any , lowerCAmelCase : Any=False , **lowerCAmelCase : Tuple ): A_ = kwargs.pop("add_prefix_space" , self.add_prefix_space ) if (is_split_into_words or add_prefix_space) and (len(snake_case_ ) > 0 and not text[0].isspace()): A_ = " " + text return (text, kwargs)
452
'''simple docstring''' from collections import OrderedDict from typing import Any, Mapping, Optional from ... import PreTrainedTokenizer from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig, OnnxConfigWithPast, OnnxSeqaSeqConfigWithPast from ...onnx.utils import compute_effective_axis_dimension from ...utils import TensorType, is_torch_available, logging _UpperCAmelCase : str = logging.get_logger(__name__) _UpperCAmelCase : Any = { '''Helsinki-NLP/opus-mt-en-de''': '''https://huggingface.co/Helsinki-NLP/opus-mt-en-de/resolve/main/config.json''', # See all Marian models at https://huggingface.co/models?filter=marian } class __magic_name__ ( __SCREAMING_SNAKE_CASE ): UpperCamelCase__ = 'marian' UpperCamelCase__ = ['past_key_values'] UpperCamelCase__ = {'num_attention_heads': 'encoder_attention_heads', 'hidden_size': 'd_model'} def __init__( self , snake_case_=5_81_01 , snake_case_=None , snake_case_=10_24 , snake_case_=12 , snake_case_=40_96 , snake_case_=16 , snake_case_=12 , snake_case_=40_96 , snake_case_=16 , snake_case_=0.0 , snake_case_=0.0 , snake_case_=True , snake_case_=True , snake_case_="gelu" , snake_case_=10_24 , snake_case_=0.1 , snake_case_=0.0 , snake_case_=0.0 , snake_case_=0.02 , snake_case_=5_81_00 , snake_case_=False , snake_case_=5_81_00 , snake_case_=0 , snake_case_=0 , snake_case_=True , **snake_case_ , ): lowercase =vocab_size lowercase =decoder_vocab_size or vocab_size lowercase =max_position_embeddings lowercase =d_model lowercase =encoder_ffn_dim lowercase =encoder_layers lowercase =encoder_attention_heads lowercase =decoder_ffn_dim lowercase =decoder_layers lowercase =decoder_attention_heads lowercase =dropout lowercase =attention_dropout lowercase =activation_dropout lowercase =activation_function lowercase =init_std lowercase =encoder_layerdrop lowercase =decoder_layerdrop lowercase =use_cache lowercase =encoder_layers lowercase =scale_embedding # scale factor will be sqrt(d_model) if True lowercase =share_encoder_decoder_embeddings super().__init__( pad_token_id=snake_case_ , eos_token_id=snake_case_ , is_encoder_decoder=snake_case_ , decoder_start_token_id=snake_case_ , forced_eos_token_id=snake_case_ , **snake_case_ , ) class __magic_name__ ( __SCREAMING_SNAKE_CASE ): @property # Copied from transformers.models.bart.configuration_bart.BartOnnxConfig.inputs def _A( self ): if self.task in ["default", "seq2seq-lm"]: lowercase =OrderedDict( [ ('''input_ids''', {0: '''batch''', 1: '''encoder_sequence'''}), ('''attention_mask''', {0: '''batch''', 1: '''encoder_sequence'''}), ] ) if self.use_past: lowercase ={0: '''batch'''} lowercase ={0: '''batch''', 1: '''past_decoder_sequence + sequence'''} else: lowercase ={0: '''batch''', 1: '''decoder_sequence'''} lowercase ={0: '''batch''', 1: '''decoder_sequence'''} if self.use_past: self.fill_with_past_key_values_(snake_case_ , direction='''inputs''' ) elif self.task == "causal-lm": # TODO: figure this case out. lowercase =OrderedDict( [ ('''input_ids''', {0: '''batch''', 1: '''encoder_sequence'''}), ('''attention_mask''', {0: '''batch''', 1: '''encoder_sequence'''}), ] ) if self.use_past: lowercase , lowercase =self.num_layers for i in range(snake_case_ ): lowercase ={0: '''batch''', 2: '''past_sequence + sequence'''} lowercase ={0: '''batch''', 2: '''past_sequence + sequence'''} else: lowercase =OrderedDict( [ ('''input_ids''', {0: '''batch''', 1: '''encoder_sequence'''}), ('''attention_mask''', {0: '''batch''', 1: '''encoder_sequence'''}), ('''decoder_input_ids''', {0: '''batch''', 1: '''decoder_sequence'''}), ('''decoder_attention_mask''', {0: '''batch''', 1: '''decoder_sequence'''}), ] ) return common_inputs @property # Copied from transformers.models.bart.configuration_bart.BartOnnxConfig.outputs def _A( self ): if self.task in ["default", "seq2seq-lm"]: lowercase =super().outputs else: lowercase =super(snake_case_ , self ).outputs if self.use_past: lowercase , lowercase =self.num_layers for i in range(snake_case_ ): lowercase ={0: '''batch''', 2: '''past_sequence + sequence'''} lowercase ={0: '''batch''', 2: '''past_sequence + sequence'''} return common_outputs def _A( self , snake_case_ , snake_case_ = -1 , snake_case_ = -1 , snake_case_ = False , snake_case_ = None , ): lowercase =self._generate_dummy_inputs_for_encoder_and_decoder( snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) # Generate decoder inputs lowercase =seq_length if not self.use_past else 1 lowercase =self._generate_dummy_inputs_for_encoder_and_decoder( snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) lowercase ={f'decoder_{name}': tensor for name, tensor in decoder_inputs.items()} lowercase =dict(**snake_case_ , **snake_case_ ) if self.use_past: if not is_torch_available(): raise ValueError('''Cannot generate dummy past_keys inputs without PyTorch installed.''' ) else: import torch lowercase , lowercase =common_inputs['''input_ids'''].shape lowercase =common_inputs['''decoder_input_ids'''].shape[1] lowercase , lowercase =self.num_attention_heads lowercase =( batch, num_encoder_attention_heads, encoder_seq_length, self._config.hidden_size // num_encoder_attention_heads, ) lowercase =decoder_seq_length + 3 lowercase =( batch, num_decoder_attention_heads, decoder_past_length, self._config.hidden_size // num_decoder_attention_heads, ) lowercase =torch.cat( [common_inputs['''decoder_attention_mask'''], torch.ones(snake_case_ , snake_case_ )] , dim=1 ) lowercase =[] # If the number of encoder and decoder layers are present in the model configuration, both are considered lowercase , lowercase =self.num_layers lowercase =min(snake_case_ , snake_case_ ) lowercase =max(snake_case_ , snake_case_ ) - min_num_layers lowercase ='''encoder''' if num_encoder_layers > num_decoder_layers else '''decoder''' for _ in range(snake_case_ ): common_inputs["past_key_values"].append( ( torch.zeros(snake_case_ ), torch.zeros(snake_case_ ), torch.zeros(snake_case_ ), torch.zeros(snake_case_ ), ) ) # TODO: test this. lowercase =encoder_shape if remaining_side_name == '''encoder''' else decoder_shape for _ in range(snake_case_ , snake_case_ ): common_inputs["past_key_values"].append((torch.zeros(snake_case_ ), torch.zeros(snake_case_ )) ) return common_inputs def _A( self , snake_case_ , snake_case_ = -1 , snake_case_ = -1 , snake_case_ = False , snake_case_ = None , ): lowercase =self._generate_dummy_inputs_for_encoder_and_decoder( snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) if self.use_past: if not is_torch_available(): raise ValueError('''Cannot generate dummy past_keys inputs without PyTorch installed.''' ) else: import torch lowercase , lowercase =common_inputs['''input_ids'''].shape # Not using the same length for past_key_values lowercase =seqlen + 2 lowercase , lowercase =self.num_layers lowercase , lowercase =self.num_attention_heads lowercase =( batch, num_encoder_attention_heads, past_key_values_length, self._config.hidden_size // num_encoder_attention_heads, ) lowercase =common_inputs['''attention_mask'''].dtype lowercase =torch.cat( [common_inputs['''attention_mask'''], torch.ones(snake_case_ , snake_case_ , dtype=snake_case_ )] , dim=1 ) lowercase =[ (torch.zeros(snake_case_ ), torch.zeros(snake_case_ )) for _ in range(snake_case_ ) ] return common_inputs def _A( self , snake_case_ , snake_case_ = -1 , snake_case_ = -1 , snake_case_ = False , snake_case_ = None , ): # Copied from OnnxConfig.generate_dummy_inputs # Did not use super(OnnxConfigWithPast, self).generate_dummy_inputs for code clarity. # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX lowercase =compute_effective_axis_dimension( snake_case_ , fixed_dimension=OnnxConfig.default_fixed_batch , num_token_to_add=0 ) # If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX lowercase =tokenizer.num_special_tokens_to_add(snake_case_ ) lowercase =compute_effective_axis_dimension( snake_case_ , fixed_dimension=OnnxConfig.default_fixed_sequence , num_token_to_add=snake_case_ ) # Generate dummy inputs according to compute batch and sequence lowercase =[''' '''.join([tokenizer.unk_token] ) * seq_length] * batch_size lowercase =dict(tokenizer(snake_case_ , return_tensors=snake_case_ ) ) return common_inputs def _A( self , snake_case_ , snake_case_ = -1 , snake_case_ = -1 , snake_case_ = False , snake_case_ = None , ): if self.task in ["default", "seq2seq-lm"]: lowercase =self._generate_dummy_inputs_for_default_and_seqaseq_lm( snake_case_ , batch_size=snake_case_ , seq_length=snake_case_ , is_pair=snake_case_ , framework=snake_case_ ) else: lowercase =self._generate_dummy_inputs_for_causal_lm( snake_case_ , batch_size=snake_case_ , seq_length=snake_case_ , is_pair=snake_case_ , framework=snake_case_ ) return common_inputs def _A( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ ): if self.task in ["default", "seq2seq-lm"]: lowercase =super()._flatten_past_key_values_(snake_case_ , snake_case_ , snake_case_ , snake_case_ ) else: lowercase =super(snake_case_ , self )._flatten_past_key_values_( snake_case_ , snake_case_ , snake_case_ , snake_case_ ) @property def _A( self ): return 1E-4
72
0
"""simple docstring""" def lowerCAmelCase_ ( SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) -> int: if len(lowercase_ ) != len(lowercase_ ): raise ValueError("The length of profit and weight must be same." ) if max_weight <= 0: raise ValueError("max_weight must greater than zero." ) if any(p < 0 for p in profit ): raise ValueError("Profit can not be negative." ) if any(w < 0 for w in weight ): raise ValueError("Weight can not be negative." ) # List created to store profit gained for the 1kg in case of each weight # respectively. Calculate and append profit/weight for each element. a_ : List[str] = [p / w for p, w in zip(lowercase_, lowercase_ )] # Creating a copy of the list and sorting profit/weight in ascending order a_ : List[str] = sorted(lowercase_ ) # declaring useful variables a_ : Any = len(lowercase_ ) a_ : Union[str, Any] = 0 a_ : List[str] = 0 a_ : Tuple = 0 # loop till the total weight do not reach max limit e.g. 15 kg and till i<length while limit <= max_weight and i < length: # flag value for encountered greatest element in sorted_profit_by_weight a_ : Any = sorted_profit_by_weight[length - i - 1] a_ : Optional[int] = profit_by_weight.index(lowercase_ ) a_ : Any = -1 # check if the weight encountered is less than the total weight # encountered before. if max_weight - limit >= weight[index]: limit += weight[index] # Adding profit gained for the given weight 1 === # weight[index]/weight[index] gain += 1 * profit[index] else: # Since the weight encountered is greater than limit, therefore take the # required number of remaining kgs and calculate profit for it. # weight remaining / weight[index] gain += (max_weight - limit) / weight[index] * profit[index] break i += 1 return gain if __name__ == "__main__": print( """Input profits, weights, and then max_weight (all positive ints) separated by """ """spaces.""" ) SCREAMING_SNAKE_CASE_ = [int(x) for x in input("""Input profits separated by spaces: """).split()] SCREAMING_SNAKE_CASE_ = [int(x) for x in input("""Input weights separated by spaces: """).split()] SCREAMING_SNAKE_CASE_ = int(input("""Max weight allowed: """)) # Function Call calc_profit(profit, weight, max_weight)
237
'''simple docstring''' import importlib.metadata from typing import Union from packaging.version import Version, parse from .constants import STR_OPERATION_TO_FUNC _UpperCAmelCase : Dict = parse(importlib.metadata.version('''torch''')) def UpperCamelCase ( lowercase_ : Union[str, Version] , lowercase_ : str , lowercase_ : str ) -> List[Any]: '''simple docstring''' if operation not in STR_OPERATION_TO_FUNC.keys(): raise ValueError(f'`operation` must be one of {list(STR_OPERATION_TO_FUNC.keys() )}, received {operation}' ) lowercase =STR_OPERATION_TO_FUNC[operation] if isinstance(lowercase_ , lowercase_ ): lowercase =parse(importlib.metadata.version(lowercase_ ) ) return operation(lowercase_ , parse(lowercase_ ) ) def UpperCamelCase ( lowercase_ : str , lowercase_ : str ) -> Union[str, Any]: '''simple docstring''' return compare_versions(lowercase_ , lowercase_ , lowercase_ )
72
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import _LazyModule UpperCamelCase = {'''tokenization_byt5''': ['''ByT5Tokenizer''']} if TYPE_CHECKING: from .tokenization_byta import ByTaTokenizer else: import sys UpperCamelCase = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
104
'''simple docstring''' from __future__ import annotations import time import numpy as np _UpperCAmelCase : int = [8, 5, 9, 7] _UpperCAmelCase : List[str] = [ [2, 0, 1, 1], [0, 1, 2, 1], [4, 0, 0, 3], [0, 2, 1, 0], [1, 0, 3, 0], ] _UpperCAmelCase : Union[str, Any] = [ [3, 2, 1, 4], [0, 2, 5, 2], [5, 1, 0, 5], [1, 5, 3, 0], [3, 0, 3, 3], ] class __magic_name__ : def __init__( self , snake_case_ , snake_case_ , snake_case_ , ): lowercase =claim_vector lowercase =allocated_resources_table lowercase =maximum_claim_table def _A( self ): return [ sum(p_item[i] for p_item in self.__allocated_resources_table ) for i in range(len(self.__allocated_resources_table[0] ) ) ] def _A( self ): return np.array(self.__claim_vector ) - np.array( self.__processes_resource_summation() ) def _A( self ): return [ list(np.array(self.__maximum_claim_table[i] ) - np.array(snake_case_ ) ) for i, allocated_resource in enumerate(self.__allocated_resources_table ) ] def _A( self ): return {self.__need().index(snake_case_ ): i for i in self.__need()} def _A( self , **snake_case_ ): lowercase =self.__need() lowercase =self.__allocated_resources_table lowercase =self.__available_resources() lowercase =self.__need_index_manager() for kw, val in kwargs.items(): if kw and val is True: self.__pretty_data() print('''_''' * 50 + '''\n''' ) while need_list: lowercase =False for each_need in need_list: lowercase =True for index, need in enumerate(snake_case_ ): if need > available_resources[index]: lowercase =False break if execution: lowercase =True # get the original index of the process from ind_ctrl db for original_need_index, need_clone in need_index_manager.items(): if each_need == need_clone: lowercase =original_need_index print(f'Process {process_number + 1} is executing.' ) # remove the process run from stack need_list.remove(snake_case_ ) # update available/freed resources stack lowercase =np.array(snake_case_ ) + np.array( alloc_resources_table[process_number] ) print( '''Updated available resource stack for processes: ''' + ''' '''.join([str(snake_case_ ) for x in available_resources] ) ) break if safe: print('''The process is in a safe state.\n''' ) else: print('''System in unsafe state. Aborting...\n''' ) break def _A( self ): print(''' ''' * 9 + '''Allocated Resource Table''' ) for item in self.__allocated_resources_table: print( f'P{self.__allocated_resources_table.index(snake_case_ ) + 1}' + ''' '''.join(f'{it:>8}' for it in item ) + '''\n''' ) print(''' ''' * 9 + '''System Resource Table''' ) for item in self.__maximum_claim_table: print( f'P{self.__maximum_claim_table.index(snake_case_ ) + 1}' + ''' '''.join(f'{it:>8}' for it in item ) + '''\n''' ) print( '''Current Usage by Active Processes: ''' + ''' '''.join(str(snake_case_ ) for x in self.__claim_vector ) ) print( '''Initial Available Resources: ''' + ''' '''.join(str(snake_case_ ) for x in self.__available_resources() ) ) time.sleep(1 ) if __name__ == "__main__": import doctest doctest.testmod()
72
0
"""simple docstring""" import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging _A = logging.get_logger(__name__) _A = { '''microsoft/unispeech-large-1500h-cv''': ( '''https://huggingface.co/microsoft/unispeech-large-1500h-cv/resolve/main/config.json''' ), # See all UniSpeech models at https://huggingface.co/models?filter=unispeech } class lowerCamelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' SCREAMING_SNAKE_CASE = 'unispeech' def __init__(self , _lowerCamelCase=32 , _lowerCamelCase=768 , _lowerCamelCase=12 , _lowerCamelCase=12 , _lowerCamelCase=3072 , _lowerCamelCase="gelu" , _lowerCamelCase=0.1 , _lowerCamelCase=0.1 , _lowerCamelCase=0.1 , _lowerCamelCase=0.0 , _lowerCamelCase=0.0 , _lowerCamelCase=0.1 , _lowerCamelCase=0.1 , _lowerCamelCase=0.02 , _lowerCamelCase=1e-5 , _lowerCamelCase="group" , _lowerCamelCase="gelu" , _lowerCamelCase=(512, 512, 512, 512, 512, 512, 512) , _lowerCamelCase=(5, 2, 2, 2, 2, 2, 2) , _lowerCamelCase=(10, 3, 3, 3, 3, 2, 2) , _lowerCamelCase=False , _lowerCamelCase=128 , _lowerCamelCase=16 , _lowerCamelCase=False , _lowerCamelCase=True , _lowerCamelCase=0.05 , _lowerCamelCase=10 , _lowerCamelCase=2 , _lowerCamelCase=0.0 , _lowerCamelCase=10 , _lowerCamelCase=0 , _lowerCamelCase=320 , _lowerCamelCase=2 , _lowerCamelCase=0.1 , _lowerCamelCase=100 , _lowerCamelCase=256 , _lowerCamelCase=256 , _lowerCamelCase=0.1 , _lowerCamelCase="mean" , _lowerCamelCase=False , _lowerCamelCase=False , _lowerCamelCase=256 , _lowerCamelCase=80 , _lowerCamelCase=0 , _lowerCamelCase=1 , _lowerCamelCase=2 , _lowerCamelCase=0.5 , **_lowerCamelCase , ): """simple docstring""" super().__init__(**snake_case_ , pad_token_id=snake_case_ , bos_token_id=snake_case_ , eos_token_id=snake_case_ ) UpperCAmelCase__ : List[Any] = hidden_size UpperCAmelCase__ : Union[str, Any] = feat_extract_norm UpperCAmelCase__ : List[str] = feat_extract_activation UpperCAmelCase__ : Dict = list(snake_case_ ) UpperCAmelCase__ : Optional[Any] = list(snake_case_ ) UpperCAmelCase__ : Tuple = list(snake_case_ ) UpperCAmelCase__ : Tuple = conv_bias UpperCAmelCase__ : Optional[Any] = num_conv_pos_embeddings UpperCAmelCase__ : List[Any] = num_conv_pos_embedding_groups UpperCAmelCase__ : Tuple = len(self.conv_dim ) UpperCAmelCase__ : Dict = num_hidden_layers UpperCAmelCase__ : int = intermediate_size UpperCAmelCase__ : str = hidden_act UpperCAmelCase__ : Optional[Any] = num_attention_heads UpperCAmelCase__ : Optional[Any] = hidden_dropout UpperCAmelCase__ : Optional[Any] = attention_dropout UpperCAmelCase__ : Dict = activation_dropout UpperCAmelCase__ : Any = feat_proj_dropout UpperCAmelCase__ : Union[str, Any] = final_dropout UpperCAmelCase__ : Tuple = layerdrop UpperCAmelCase__ : Any = layer_norm_eps UpperCAmelCase__ : int = initializer_range UpperCAmelCase__ : Tuple = num_ctc_classes UpperCAmelCase__ : List[Any] = vocab_size UpperCAmelCase__ : Tuple = do_stable_layer_norm UpperCAmelCase__ : int = use_weighted_layer_sum UpperCAmelCase__ : Optional[Any] = classifier_proj_size if ( (len(self.conv_stride ) != self.num_feat_extract_layers) or (len(self.conv_kernel ) != self.num_feat_extract_layers) or (len(self.conv_dim ) != self.num_feat_extract_layers) ): raise ValueError( """Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` ==""" """ `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) =""" F""" {len(self.conv_dim )}`, `len(config.conv_stride) = {len(self.conv_stride )}`,""" F""" `len(config.conv_kernel) = {len(self.conv_kernel )}`.""" ) # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 UpperCAmelCase__ : Union[str, Any] = apply_spec_augment UpperCAmelCase__ : List[Any] = mask_time_prob UpperCAmelCase__ : int = mask_time_length UpperCAmelCase__ : Optional[int] = mask_time_min_masks UpperCAmelCase__ : List[Any] = mask_feature_prob UpperCAmelCase__ : str = mask_feature_length UpperCAmelCase__ : Union[str, Any] = mask_feature_min_masks # parameters for pretraining with codevector quantized representations UpperCAmelCase__ : Dict = num_codevectors_per_group UpperCAmelCase__ : Tuple = num_codevector_groups UpperCAmelCase__ : Tuple = contrastive_logits_temperature UpperCAmelCase__ : Optional[Any] = feat_quantizer_dropout UpperCAmelCase__ : List[Any] = num_negatives UpperCAmelCase__ : Any = codevector_dim UpperCAmelCase__ : Optional[Any] = proj_codevector_dim UpperCAmelCase__ : List[Any] = diversity_loss_weight # ctc loss UpperCAmelCase__ : Tuple = ctc_loss_reduction UpperCAmelCase__ : str = ctc_zero_infinity # pretraining loss UpperCAmelCase__ : Union[str, Any] = replace_prob @property def _a (self ): """simple docstring""" return functools.reduce(operator.mul , self.conv_stride , 1 )
182
'''simple docstring''' import numpy as np from nltk.translate import meteor_score import datasets from datasets.config import importlib_metadata, version _UpperCAmelCase : Dict = version.parse(importlib_metadata.version('''nltk''')) if NLTK_VERSION >= version.Version('''3.6.4'''): from nltk import word_tokenize _UpperCAmelCase : Dict = '''\ @inproceedings{banarjee2005, title = {{METEOR}: An Automatic Metric for {MT} Evaluation with Improved Correlation with Human Judgments}, author = {Banerjee, Satanjeev and Lavie, Alon}, booktitle = {Proceedings of the {ACL} Workshop on Intrinsic and Extrinsic Evaluation Measures for Machine Translation and/or Summarization}, month = jun, year = {2005}, address = {Ann Arbor, Michigan}, publisher = {Association for Computational Linguistics}, url = {https://www.aclweb.org/anthology/W05-0909}, pages = {65--72}, } ''' _UpperCAmelCase : Union[str, Any] = '''\ METEOR, an automatic metric for machine translation evaluation that is based on a generalized concept of unigram matching between the machine-produced translation and human-produced reference translations. Unigrams can be matched based on their surface forms, stemmed forms, and meanings; furthermore, METEOR can be easily extended to include more advanced matching strategies. Once all generalized unigram matches between the two strings have been found, METEOR computes a score for this matching using a combination of unigram-precision, unigram-recall, and a measure of fragmentation that is designed to directly capture how well-ordered the matched words in the machine translation are in relation to the reference. METEOR gets an R correlation value of 0.347 with human evaluation on the Arabic data and 0.331 on the Chinese data. This is shown to be an improvement on using simply unigram-precision, unigram-recall and their harmonic F1 combination. ''' _UpperCAmelCase : Tuple = ''' Computes METEOR score of translated segments against one or more references. Args: predictions: list of predictions to score. Each prediction should be a string with tokens separated by spaces. references: list of reference for each prediction. Each reference should be a string with tokens separated by spaces. alpha: Parameter for controlling relative weights of precision and recall. default: 0.9 beta: Parameter for controlling shape of penalty as a function of fragmentation. default: 3 gamma: Relative weight assigned to fragmentation penalty. default: 0.5 Returns: \'meteor\': meteor score. Examples: >>> meteor = datasets.load_metric(\'meteor\') >>> predictions = ["It is a guide to action which ensures that the military always obeys the commands of the party"] >>> references = ["It is a guide to action that ensures that the military will forever heed Party commands"] >>> results = meteor.compute(predictions=predictions, references=references) >>> print(round(results["meteor"], 4)) 0.6944 ''' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class __magic_name__ ( datasets.Metric ): def _A( self ): return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Value('''string''' , id='''sequence''' ), '''references''': datasets.Value('''string''' , id='''sequence''' ), } ) , codebase_urls=['''https://github.com/nltk/nltk/blob/develop/nltk/translate/meteor_score.py'''] , reference_urls=[ '''https://www.nltk.org/api/nltk.translate.html#module-nltk.translate.meteor_score''', '''https://en.wikipedia.org/wiki/METEOR''', ] , ) def _A( self , snake_case_ ): import nltk nltk.download('''wordnet''' ) if NLTK_VERSION >= version.Version('''3.6.5''' ): nltk.download('''punkt''' ) if NLTK_VERSION >= version.Version('''3.6.6''' ): nltk.download('''omw-1.4''' ) def _A( self , snake_case_ , snake_case_ , snake_case_=0.9 , snake_case_=3 , snake_case_=0.5 ): if NLTK_VERSION >= version.Version('''3.6.5''' ): lowercase =[ meteor_score.single_meteor_score( word_tokenize(snake_case_ ) , word_tokenize(snake_case_ ) , alpha=snake_case_ , beta=snake_case_ , gamma=snake_case_ ) for ref, pred in zip(snake_case_ , snake_case_ ) ] else: lowercase =[ meteor_score.single_meteor_score(snake_case_ , snake_case_ , alpha=snake_case_ , beta=snake_case_ , gamma=snake_case_ ) for ref, pred in zip(snake_case_ , snake_case_ ) ] return {"meteor": np.mean(snake_case_ )}
72
0
from .glue import glue_convert_examples_to_features, glue_output_modes, glue_processors, glue_tasks_num_labels from .squad import SquadExample, SquadFeatures, SquadVaProcessor, SquadVaProcessor, squad_convert_examples_to_features from .utils import DataProcessor, InputExample, InputFeatures, SingleSentenceClassificationProcessor from .xnli import xnli_output_modes, xnli_processors, xnli_tasks_num_labels
89
'''simple docstring''' import sys _UpperCAmelCase : Dict = ( '''73167176531330624919225119674426574742355349194934''' '''96983520312774506326239578318016984801869478851843''' '''85861560789112949495459501737958331952853208805511''' '''12540698747158523863050715693290963295227443043557''' '''66896648950445244523161731856403098711121722383113''' '''62229893423380308135336276614282806444486645238749''' '''30358907296290491560440772390713810515859307960866''' '''70172427121883998797908792274921901699720888093776''' '''65727333001053367881220235421809751254540594752243''' '''52584907711670556013604839586446706324415722155397''' '''53697817977846174064955149290862569321978468622482''' '''83972241375657056057490261407972968652414535100474''' '''82166370484403199890008895243450658541227588666881''' '''16427171479924442928230863465674813919123162824586''' '''17866458359124566529476545682848912883142607690042''' '''24219022671055626321111109370544217506941658960408''' '''07198403850962455444362981230987879927244284909188''' '''84580156166097919133875499200524063689912560717606''' '''05886116467109405077541002256983155200055935729725''' '''71636269561882670428252483600823257530420752963450''' ) def UpperCamelCase ( lowercase_ : str = N ) -> int: '''simple docstring''' lowercase =-sys.maxsize - 1 for i in range(len(lowercase_ ) - 1_2 ): lowercase =1 for j in range(1_3 ): product *= int(n[i + j] ) if product > largest_product: lowercase =product return largest_product if __name__ == "__main__": print(F"""{solution() = }""")
72
0
from typing import Any, Dict, List, Union from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging, requires_backends from .base import PIPELINE_INIT_ARGS, ChunkPipeline if is_vision_available(): from PIL import Image from ..image_utils import load_image if is_torch_available(): import torch from transformers.modeling_outputs import BaseModelOutput from ..models.auto.modeling_auto import MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING _lowerCamelCase = logging.get_logger(__name__) @add_end_docstrings(__SCREAMING_SNAKE_CASE ) class __A ( __SCREAMING_SNAKE_CASE ): """simple docstring""" def __init__( self , **a__): """simple docstring""" super().__init__(**snake_case_) if self.framework == "tf": raise ValueError(F"""The {self.__class__} is only available in PyTorch.""") requires_backends(self , '''vision''') self.check_model_type(snake_case_) def __call__( self , a__ , a__ = None , **a__ , ): """simple docstring""" if "text_queries" in kwargs: _lowerCamelCase : Optional[Any] = kwargs.pop('''text_queries''') if isinstance(snake_case_ , (str, Image.Image)): _lowerCamelCase : Dict = {'''image''': image, '''candidate_labels''': candidate_labels} else: _lowerCamelCase : Optional[Any] = image _lowerCamelCase : Tuple = super().__call__(snake_case_ , **snake_case_) return results def __snake_case ( self , **a__): """simple docstring""" _lowerCamelCase : Dict = {} if "threshold" in kwargs: _lowerCamelCase : Tuple = kwargs['''threshold'''] if "top_k" in kwargs: _lowerCamelCase : str = kwargs['''top_k'''] return {}, {}, postprocess_params def __snake_case ( self , a__): """simple docstring""" _lowerCamelCase : int = load_image(inputs['''image''']) _lowerCamelCase : Optional[int] = inputs['''candidate_labels'''] if isinstance(snake_case_ , snake_case_): _lowerCamelCase : Optional[int] = candidate_labels.split(''',''') _lowerCamelCase : Union[str, Any] = torch.tensor([[image.height, image.width]] , dtype=torch.intaa) for i, candidate_label in enumerate(snake_case_): _lowerCamelCase : List[str] = self.tokenizer(snake_case_ , return_tensors=self.framework) _lowerCamelCase : Any = self.image_processor(snake_case_ , return_tensors=self.framework) yield { "is_last": i == len(snake_case_) - 1, "target_size": target_size, "candidate_label": candidate_label, **text_inputs, **image_features, } def __snake_case ( self , a__): """simple docstring""" _lowerCamelCase : List[str] = model_inputs.pop('''target_size''') _lowerCamelCase : Tuple = model_inputs.pop('''candidate_label''') _lowerCamelCase : Union[str, Any] = model_inputs.pop('''is_last''') _lowerCamelCase : int = self.model(**snake_case_) _lowerCamelCase : Dict = {'''target_size''': target_size, '''candidate_label''': candidate_label, '''is_last''': is_last, **outputs} return model_outputs def __snake_case ( self , a__ , a__=0.1 , a__=None): """simple docstring""" _lowerCamelCase : List[Any] = [] for model_output in model_outputs: _lowerCamelCase : Dict = model_output['''candidate_label'''] _lowerCamelCase : str = BaseModelOutput(snake_case_) _lowerCamelCase : str = self.image_processor.post_process_object_detection( outputs=snake_case_ , threshold=snake_case_ , target_sizes=model_output['''target_size'''])[0] for index in outputs["scores"].nonzero(): _lowerCamelCase : Dict = outputs['''scores'''][index].item() _lowerCamelCase : Optional[Any] = self._get_bounding_box(outputs['''boxes'''][index][0]) _lowerCamelCase : List[Any] = {'''score''': score, '''label''': label, '''box''': box} results.append(snake_case_) _lowerCamelCase : Optional[Any] = sorted(snake_case_ , key=lambda a__: x["score"] , reverse=snake_case_) if top_k: _lowerCamelCase : int = results[:top_k] return results def __snake_case ( self , a__): """simple docstring""" if self.framework != "pt": raise ValueError('''The ZeroShotObjectDetectionPipeline is only available in PyTorch.''') _lowerCamelCase, _lowerCamelCase, _lowerCamelCase, _lowerCamelCase : Tuple = box.int().tolist() _lowerCamelCase : str = { '''xmin''': xmin, '''ymin''': ymin, '''xmax''': xmax, '''ymax''': ymax, } return bbox
114
'''simple docstring''' import warnings from ...utils import logging from .image_processing_yolos import YolosImageProcessor _UpperCAmelCase : Any = logging.get_logger(__name__) class __magic_name__ ( __SCREAMING_SNAKE_CASE ): def __init__( self , *snake_case_ , **snake_case_ ): warnings.warn( '''The class YolosFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please''' ''' use YolosImageProcessor instead.''' , snake_case_ , ) super().__init__(*snake_case_ , **snake_case_ )
72
0
from collections import OrderedDict from typing import TYPE_CHECKING, Any, Mapping, Optional, Union from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig, OnnxSeqaSeqConfigWithPast from ...utils import logging if TYPE_CHECKING: from ...feature_extraction_utils import FeatureExtractionMixin from ...tokenization_utils_base import PreTrainedTokenizerBase from ...utils import TensorType _UpperCAmelCase = logging.get_logger(__name__) _UpperCAmelCase = { '''openai/whisper-base''': '''https://huggingface.co/openai/whisper-base/resolve/main/config.json''', } # fmt: off _UpperCAmelCase = [ 1, 2, 7, 8, 9, 10, 14, 25, 26, 27, 28, 29, 31, 58, 59, 60, 61, 62, 63, 90, 91, 92, 93, 357, 366, 438, 532, 685, 705, 796, 930, 1058, 1220, 1267, 1279, 1303, 1343, 1377, 1391, 1635, 1782, 1875, 2162, 2361, 2488, 3467, 4008, 4211, 4600, 4808, 5299, 5855, 6329, 7203, 9609, 9959, 10563, 10786, 11420, 11709, 11907, 13163, 13697, 13700, 14808, 15306, 16410, 16791, 17992, 19203, 19510, 20724, 22305, 22935, 27007, 30109, 30420, 33409, 34949, 40283, 40493, 40549, 47282, 49146, 50257, 50359, 50360, 50361 ] _UpperCAmelCase = [ 1, 2, 7, 8, 9, 10, 14, 25, 26, 27, 28, 29, 31, 58, 59, 60, 61, 62, 63, 90, 91, 92, 93, 359, 503, 522, 542, 873, 893, 902, 918, 922, 931, 1350, 1853, 1982, 2460, 2627, 3246, 3253, 3268, 3536, 3846, 3961, 4183, 4667, 6585, 6647, 7273, 9061, 9383, 10428, 10929, 11938, 12033, 12331, 12562, 13793, 14157, 14635, 15265, 15618, 16553, 16604, 18362, 18956, 20075, 21675, 22520, 26130, 26161, 26435, 28279, 29464, 31650, 32302, 32470, 36865, 42863, 47425, 49870, 50254, 50258, 50360, 50361, 50362 ] class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowerCamelCase_ = '''whisper''' lowerCamelCase_ = ['''past_key_values'''] lowerCamelCase_ = {'''num_attention_heads''': '''encoder_attention_heads''', '''hidden_size''': '''d_model'''} def __init__( self , lowercase=5_1_8_6_5 , lowercase=8_0 , lowercase=6 , lowercase=4 , lowercase=6 , lowercase=4 , lowercase=1_5_3_6 , lowercase=1_5_3_6 , lowercase=0.0 , lowercase=0.0 , lowercase=5_0_2_5_7 , lowercase=True , lowercase=True , lowercase="gelu" , lowercase=2_5_6 , lowercase=0.0 , lowercase=0.0 , lowercase=0.0 , lowercase=0.02 , lowercase=False , lowercase=1_5_0_0 , lowercase=4_4_8 , lowercase=5_0_2_5_6 , lowercase=5_0_2_5_6 , lowercase=5_0_2_5_6 , lowercase=None , lowercase=[2_2_0, 5_0_2_5_6] , lowercase=False , lowercase=2_5_6 , lowercase=False , lowercase=0.05 , lowercase=1_0 , lowercase=2 , lowercase=0.0 , lowercase=1_0 , lowercase=0 , lowercase=7 , **lowercase , ): """simple docstring""" A_ : List[Any] = vocab_size A_ : Union[str, Any] = num_mel_bins A_ : Optional[int] = d_model A_ : Any = encoder_layers A_ : List[Any] = encoder_attention_heads A_ : int = decoder_layers A_ : int = decoder_attention_heads A_ : str = decoder_ffn_dim A_ : Union[str, Any] = encoder_ffn_dim A_ : str = dropout A_ : List[Any] = attention_dropout A_ : Optional[int] = activation_dropout A_ : Tuple = activation_function A_ : List[Any] = init_std A_ : Union[str, Any] = encoder_layerdrop A_ : List[str] = decoder_layerdrop A_ : Any = use_cache A_ : List[Any] = encoder_layers A_ : List[Any] = scale_embedding # scale factor will be sqrt(d_model) if True A_ : Union[str, Any] = max_source_positions A_ : Dict = max_target_positions # Audio Classification-specific parameters. Feel free to ignore for other classes. A_ : Dict = classifier_proj_size A_ : List[str] = use_weighted_layer_sum # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 A_ : Dict = apply_spec_augment A_ : Any = mask_time_prob A_ : Dict = mask_time_length A_ : int = mask_time_min_masks A_ : Tuple = mask_feature_prob A_ : Dict = mask_feature_length A_ : str = mask_feature_min_masks A_ : str = median_filter_width super().__init__( pad_token_id=snake_case_ , bos_token_id=snake_case_ , eos_token_id=snake_case_ , is_encoder_decoder=snake_case_ , decoder_start_token_id=snake_case_ , suppress_tokens=snake_case_ , begin_suppress_tokens=snake_case_ , **snake_case_ , ) class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' @property def lowerCAmelCase_ ( self ): """simple docstring""" A_ : Dict = OrderedDict( [ ('input_features', {0: 'batch', 1: 'feature_size', 2: 'encoder_sequence'}), ] ) if self.use_past: A_ : str = {0: 'batch'} else: A_ : Any = {0: 'batch', 1: 'decoder_sequence'} if self.use_past: self.fill_with_past_key_values_(snake_case_ , direction='inputs' ) return common_inputs def lowerCAmelCase_ ( self , lowercase , lowercase = -1 , lowercase = -1 , lowercase = False , lowercase = None , lowercase = 2_2_0_5_0 , lowercase = 5.0 , lowercase = 2_2_0 , ): """simple docstring""" A_ : List[Any] = OrderedDict() A_ : Optional[Any] = OnnxConfig.generate_dummy_inputs( self , preprocessor=preprocessor.feature_extractor , batch_size=snake_case_ , framework=snake_case_ , sampling_rate=snake_case_ , time_duration=snake_case_ , frequency=snake_case_ , ) A_ : int = encoder_inputs['input_features'].shape[2] A_ : str = encoder_sequence_length // 2 if self.use_past else seq_length A_ : str = super().generate_dummy_inputs( preprocessor.tokenizer , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) A_ : Dict = encoder_inputs.pop('input_features' ) A_ : str = decoder_inputs.pop('decoder_input_ids' ) if "past_key_values" in decoder_inputs: A_ : Tuple = decoder_inputs.pop('past_key_values' ) return dummy_inputs @property def lowerCAmelCase_ ( self ): """simple docstring""" return 1E-3
558
'''simple docstring''' import math from typing import Optional import numpy as np from ...configuration_utils import PretrainedConfig from ...utils import logging _UpperCAmelCase : int = logging.get_logger(__name__) _UpperCAmelCase : Optional[Any] = { '''facebook/encodec_24khz''': '''https://huggingface.co/facebook/encodec_24khz/resolve/main/config.json''', '''facebook/encodec_48khz''': '''https://huggingface.co/facebook/encodec_48khz/resolve/main/config.json''', } class __magic_name__ ( __SCREAMING_SNAKE_CASE ): UpperCamelCase__ = 'encodec' def __init__( self , snake_case_=[1.5, 3.0, 6.0, 12.0, 24.0] , snake_case_=2_40_00 , snake_case_=1 , snake_case_=False , snake_case_=None , snake_case_=None , snake_case_=1_28 , snake_case_=32 , snake_case_=1 , snake_case_=[8, 5, 4, 2] , snake_case_="weight_norm" , snake_case_=7 , snake_case_=7 , snake_case_=3 , snake_case_=2 , snake_case_=True , snake_case_="reflect" , snake_case_=2 , snake_case_=2 , snake_case_=1.0 , snake_case_=10_24 , snake_case_=None , snake_case_=True , **snake_case_ , ): lowercase =target_bandwidths lowercase =sampling_rate lowercase =audio_channels lowercase =normalize lowercase =chunk_length_s lowercase =overlap lowercase =hidden_size lowercase =num_filters lowercase =num_residual_layers lowercase =upsampling_ratios lowercase =norm_type lowercase =kernel_size lowercase =last_kernel_size lowercase =residual_kernel_size lowercase =dilation_growth_rate lowercase =use_causal_conv lowercase =pad_mode lowercase =compress lowercase =num_lstm_layers lowercase =trim_right_ratio lowercase =codebook_size lowercase =codebook_dim if codebook_dim is not None else hidden_size lowercase =use_conv_shortcut if self.norm_type not in ["weight_norm", "time_group_norm"]: raise ValueError( f'self.norm_type must be one of `"weight_norm"`, `"time_group_norm"`), got {self.norm_type}' ) super().__init__(**snake_case_ ) @property def _A( self ): if self.chunk_length_s is None: return None else: return int(self.chunk_length_s * self.sampling_rate ) @property def _A( self ): if self.chunk_length_s is None or self.overlap is None: return None else: return max(1 , int((1.0 - self.overlap) * self.chunk_length ) ) @property def _A( self ): lowercase =np.prod(self.upsampling_ratios ) return math.ceil(self.sampling_rate / hop_length ) @property def _A( self ): return int(10_00 * self.target_bandwidths[-1] // (self.frame_rate * 10) )
72
0
'''simple docstring''' from collections import OrderedDict from typing import List, Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging UpperCamelCase_ = logging.get_logger(__name__) UpperCamelCase_ = { '''google/efficientnet-b7''': '''https://huggingface.co/google/efficientnet-b7/resolve/main/config.json''', } class a_ (__SCREAMING_SNAKE_CASE ): __lowerCAmelCase : int = """efficientnet""" def __init__( self , snake_case_ = 3 , snake_case_ = 6_0_0 , snake_case_ = 2.0 , snake_case_ = 3.1 , snake_case_ = 8 , snake_case_ = [3, 3, 5, 3, 5, 5, 3] , snake_case_ = [3_2, 1_6, 2_4, 4_0, 8_0, 1_1_2, 1_9_2] , snake_case_ = [1_6, 2_4, 4_0, 8_0, 1_1_2, 1_9_2, 3_2_0] , snake_case_ = [] , snake_case_ = [1, 2, 2, 2, 1, 2, 1] , snake_case_ = [1, 2, 2, 3, 3, 4, 1] , snake_case_ = [1, 6, 6, 6, 6, 6, 6] , snake_case_ = 0.25 , snake_case_ = "swish" , snake_case_ = 2_5_6_0 , snake_case_ = "mean" , snake_case_ = 0.02 , snake_case_ = 0.001 , snake_case_ = 0.99 , snake_case_ = 0.5 , snake_case_ = 0.2 , **snake_case_ , ): super().__init__(**snake_case_ ) _lowerCAmelCase : Union[str, Any] = num_channels _lowerCAmelCase : Dict = image_size _lowerCAmelCase : Optional[int] = width_coefficient _lowerCAmelCase : Tuple = depth_coefficient _lowerCAmelCase : Union[str, Any] = depth_divisor _lowerCAmelCase : List[str] = kernel_sizes _lowerCAmelCase : Union[str, Any] = in_channels _lowerCAmelCase : str = out_channels _lowerCAmelCase : List[Any] = depthwise_padding _lowerCAmelCase : Optional[int] = strides _lowerCAmelCase : Optional[Any] = num_block_repeats _lowerCAmelCase : int = expand_ratios _lowerCAmelCase : Optional[int] = squeeze_expansion_ratio _lowerCAmelCase : List[Any] = hidden_act _lowerCAmelCase : Tuple = hidden_dim _lowerCAmelCase : Optional[int] = pooling_type _lowerCAmelCase : Any = initializer_range _lowerCAmelCase : Optional[Any] = batch_norm_eps _lowerCAmelCase : Optional[int] = batch_norm_momentum _lowerCAmelCase : Optional[int] = dropout_rate _lowerCAmelCase : List[str] = drop_connect_rate _lowerCAmelCase : Dict = sum(snake_case_ ) * 4 class a_ (__SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Optional[Any] = version.parse("""1.11""" ) @property def __UpperCamelCase ( self ): return OrderedDict( [ ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}), ] ) @property def __UpperCamelCase ( self ): return 1E-5
384
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) _UpperCAmelCase : int = { '''configuration_blip''': [ '''BLIP_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''BlipConfig''', '''BlipTextConfig''', '''BlipVisionConfig''', ], '''processing_blip''': ['''BlipProcessor'''], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCAmelCase : int = ['''BlipImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCAmelCase : Optional[Any] = [ '''BLIP_PRETRAINED_MODEL_ARCHIVE_LIST''', '''BlipModel''', '''BlipPreTrainedModel''', '''BlipForConditionalGeneration''', '''BlipForQuestionAnswering''', '''BlipVisionModel''', '''BlipTextModel''', '''BlipForImageTextRetrieval''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCAmelCase : Dict = [ '''TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFBlipModel''', '''TFBlipPreTrainedModel''', '''TFBlipForConditionalGeneration''', '''TFBlipForQuestionAnswering''', '''TFBlipVisionModel''', '''TFBlipTextModel''', '''TFBlipForImageTextRetrieval''', ] if TYPE_CHECKING: from .configuration_blip import BLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, BlipConfig, BlipTextConfig, BlipVisionConfig from .processing_blip import BlipProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_blip import BlipImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_blip import ( BLIP_PRETRAINED_MODEL_ARCHIVE_LIST, BlipForConditionalGeneration, BlipForImageTextRetrieval, BlipForQuestionAnswering, BlipModel, BlipPreTrainedModel, BlipTextModel, BlipVisionModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_blip import ( TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST, TFBlipForConditionalGeneration, TFBlipForImageTextRetrieval, TFBlipForQuestionAnswering, TFBlipModel, TFBlipPreTrainedModel, TFBlipTextModel, TFBlipVisionModel, ) else: import sys _UpperCAmelCase : str = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
72
0
"""simple docstring""" from typing import Union from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging from .base import PIPELINE_INIT_ARGS, Pipeline if is_vision_available(): from PIL import Image from ..image_utils import load_image if is_torch_available(): from ..models.auto.modeling_auto import MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING UpperCamelCase__ = logging.get_logger(__name__) @add_end_docstrings(__SCREAMING_SNAKE_CASE ) class a__ ( __SCREAMING_SNAKE_CASE ): def __init__( self : Optional[Any] ,*a__ : int ,**a__ : Dict) -> str: """simple docstring""" super().__init__(*snake_case_ ,**snake_case_) self.check_model_type(snake_case_) def __UpperCamelCase ( self : Dict ,a__ : Dict=None ,a__ : Tuple=None ,a__ : Dict=None ,**a__ : Any) -> List[Any]: """simple docstring""" _lowerCAmelCase , _lowerCAmelCase:int = {}, {} if padding is not None: _lowerCAmelCase:Dict = padding if truncation is not None: _lowerCAmelCase:str = truncation if top_k is not None: _lowerCAmelCase:List[str] = top_k return preprocess_params, {}, postprocess_params def __call__( self : str ,a__ : List[Any] ,a__ : Any = None ,**a__ : Tuple) -> str: """simple docstring""" if isinstance(snake_case_ ,(Image.Image, str)) and isinstance(snake_case_ ,snake_case_): _lowerCAmelCase:List[str] = {'''image''': image, '''question''': question} else: _lowerCAmelCase:Any = image _lowerCAmelCase:List[Any] = super().__call__(snake_case_ ,**snake_case_) return results def __UpperCamelCase ( self : Dict ,a__ : str ,a__ : Optional[Any]=False ,a__ : Union[str, Any]=False) -> Union[str, Any]: """simple docstring""" _lowerCAmelCase:List[str] = load_image(inputs['''image''']) _lowerCAmelCase:Tuple = self.tokenizer( inputs['''question'''] ,return_tensors=self.framework ,padding=snake_case_ ,truncation=snake_case_) _lowerCAmelCase:List[Any] = self.image_processor(images=snake_case_ ,return_tensors=self.framework) model_inputs.update(snake_case_) return model_inputs def __UpperCamelCase ( self : Optional[Any] ,a__ : Tuple) -> List[Any]: """simple docstring""" _lowerCAmelCase:Tuple = self.model(**snake_case_) return model_outputs def __UpperCamelCase ( self : List[Any] ,a__ : List[str] ,a__ : Tuple=5) -> Dict: """simple docstring""" if top_k > self.model.config.num_labels: _lowerCAmelCase:int = self.model.config.num_labels if self.framework == "pt": _lowerCAmelCase:Tuple = model_outputs.logits.sigmoid()[0] _lowerCAmelCase , _lowerCAmelCase:int = probs.topk(snake_case_) else: raise ValueError(F'Unsupported framework: {self.framework}') _lowerCAmelCase:Any = scores.tolist() _lowerCAmelCase:List[str] = ids.tolist() return [{"score": score, "answer": self.model.config.idalabel[_id]} for score, _id in zip(snake_case_ ,snake_case_)]
227
'''simple docstring''' from __future__ import annotations from math import pi, sqrt def UpperCamelCase ( lowercase_ : float , lowercase_ : float ) -> tuple: '''simple docstring''' if inductance <= 0: raise ValueError('''Inductance cannot be 0 or negative''' ) elif capacitance <= 0: raise ValueError('''Capacitance cannot be 0 or negative''' ) else: return ( "Resonant frequency", float(1 / (2 * pi * (sqrt(inductance * capacitance ))) ), ) if __name__ == "__main__": import doctest doctest.testmod()
72
0
import argparse import re import numpy as np import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( SamConfig, SamImageProcessor, SamModel, SamProcessor, SamVisionConfig, ) __magic_name__ : List[str] = { '''iou_prediction_head.layers.0''': '''iou_prediction_head.proj_in''', '''iou_prediction_head.layers.1''': '''iou_prediction_head.layers.0''', '''iou_prediction_head.layers.2''': '''iou_prediction_head.proj_out''', '''mask_decoder.output_upscaling.0''': '''mask_decoder.upscale_conv1''', '''mask_decoder.output_upscaling.1''': '''mask_decoder.upscale_layer_norm''', '''mask_decoder.output_upscaling.3''': '''mask_decoder.upscale_conv2''', '''mask_downscaling.0''': '''mask_embed.conv1''', '''mask_downscaling.1''': '''mask_embed.layer_norm1''', '''mask_downscaling.3''': '''mask_embed.conv2''', '''mask_downscaling.4''': '''mask_embed.layer_norm2''', '''mask_downscaling.6''': '''mask_embed.conv3''', '''point_embeddings''': '''point_embed''', '''pe_layer.positional_encoding_gaussian_matrix''': '''shared_embedding.positional_embedding''', '''image_encoder''': '''vision_encoder''', '''neck.0''': '''neck.conv1''', '''neck.1''': '''neck.layer_norm1''', '''neck.2''': '''neck.conv2''', '''neck.3''': '''neck.layer_norm2''', '''patch_embed.proj''': '''patch_embed.projection''', '''.norm''': '''.layer_norm''', '''blocks''': '''layers''', } def lowercase__ ( _UpperCamelCase) -> int: """simple docstring""" UpperCamelCase = {} state_dict.pop('pixel_mean' , lowercase_) state_dict.pop('pixel_std' , lowercase_) UpperCamelCase = r'.*.output_hypernetworks_mlps.(\d+).layers.(\d+).*' for key, value in state_dict.items(): for key_to_modify, new_key in KEYS_TO_MODIFY_MAPPING.items(): if key_to_modify in key: UpperCamelCase = key.replace(lowercase_ , lowercase_) if re.match(lowercase_ , lowercase_): UpperCamelCase = int(re.match(lowercase_ , lowercase_).group(2)) if layer_nb == 0: UpperCamelCase = key.replace('layers.0' , 'proj_in') elif layer_nb == 1: UpperCamelCase = key.replace('layers.1' , 'layers.0') elif layer_nb == 2: UpperCamelCase = key.replace('layers.2' , 'proj_out') UpperCamelCase = value UpperCamelCase = model_state_dict[ 'prompt_encoder.shared_embedding.positional_embedding' ] return model_state_dict def lowercase__ ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase="ybelkada/segment-anything") -> Tuple: """simple docstring""" UpperCamelCase = hf_hub_download(lowercase_ , F'checkpoints/{model_name}.pth') if "sam_vit_b" in model_name: UpperCamelCase = SamConfig() elif "sam_vit_l" in model_name: UpperCamelCase = SamVisionConfig( hidden_size=10_24 , num_hidden_layers=24 , num_attention_heads=16 , global_attn_indexes=[5, 11, 17, 23] , ) UpperCamelCase = SamConfig( vision_config=lowercase_ , ) elif "sam_vit_h" in model_name: UpperCamelCase = SamVisionConfig( hidden_size=12_80 , num_hidden_layers=32 , num_attention_heads=16 , global_attn_indexes=[7, 15, 23, 31] , ) UpperCamelCase = SamConfig( vision_config=lowercase_ , ) UpperCamelCase = torch.load(lowercase_ , map_location='cpu') UpperCamelCase = replace_keys(lowercase_) UpperCamelCase = SamImageProcessor() UpperCamelCase = SamProcessor(image_processor=lowercase_) UpperCamelCase = SamModel(lowercase_) hf_model.load_state_dict(lowercase_) UpperCamelCase = hf_model.to('cuda') UpperCamelCase = 'https://huggingface.co/ybelkada/segment-anything/resolve/main/assets/car.png' UpperCamelCase = Image.open(requests.get(lowercase_ , stream=lowercase_).raw).convert('RGB') UpperCamelCase = [[[4_00, 6_50]]] UpperCamelCase = [[1]] UpperCamelCase = processor(images=np.array(lowercase_) , return_tensors='pt').to('cuda') with torch.no_grad(): UpperCamelCase = hf_model(**lowercase_) UpperCamelCase = output.iou_scores.squeeze() if model_name == "sam_vit_h_4b8939": assert scores[-1].item() == 0.5_7_9_8_9_0_2_5_1_1_5_9_6_6_8 UpperCamelCase = processor( images=np.array(lowercase_) , input_points=lowercase_ , input_labels=lowercase_ , return_tensors='pt').to('cuda') with torch.no_grad(): UpperCamelCase = hf_model(**lowercase_) UpperCamelCase = output.iou_scores.squeeze() assert scores[-1].item() == 0.9_7_1_2_6_0_3_0_9_2_1_9_3_6_0_4 UpperCamelCase = ((75, 2_75, 17_25, 8_50),) UpperCamelCase = processor(images=np.array(lowercase_) , input_boxes=lowercase_ , return_tensors='pt').to('cuda') with torch.no_grad(): UpperCamelCase = hf_model(**lowercase_) UpperCamelCase = output.iou_scores.squeeze() assert scores[-1].item() == 0.8_6_8_6_0_1_5_6_0_5_9_2_6_5_1_4 # Test with 2 points and 1 image. UpperCamelCase = [[[4_00, 6_50], [8_00, 6_50]]] UpperCamelCase = [[1, 1]] UpperCamelCase = processor( images=np.array(lowercase_) , input_points=lowercase_ , input_labels=lowercase_ , return_tensors='pt').to('cuda') with torch.no_grad(): UpperCamelCase = hf_model(**lowercase_) UpperCamelCase = output.iou_scores.squeeze() assert scores[-1].item() == 0.9_9_3_6_0_4_7_7_9_2_4_3_4_6_9_2 if __name__ == "__main__": __magic_name__ : Tuple = argparse.ArgumentParser() __magic_name__ : Optional[Any] = ['''sam_vit_b_01ec64''', '''sam_vit_h_4b8939''', '''sam_vit_l_0b3195'''] parser.add_argument( '''--model_name''', default='''sam_vit_h_4b8939''', choices=choices, type=str, help='''Path to hf config.json of model to convert''', ) parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') parser.add_argument( '''--push_to_hub''', action='''store_true''', help='''Whether to push the model and processor to the hub after converting''', ) parser.add_argument( '''--model_hub_id''', default='''ybelkada/segment-anything''', choices=choices, type=str, help='''Path to hf config.json of model to convert''', ) __magic_name__ : List[str] = parser.parse_args() convert_sam_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub, args.model_hub_id)
280
'''simple docstring''' import inspect import unittest from transformers import DecisionTransformerConfig, 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, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import DecisionTransformerModel from transformers.models.decision_transformer.modeling_decision_transformer import ( DECISION_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, ) class __magic_name__ : def __init__( self , snake_case_ , snake_case_=13 , snake_case_=7 , snake_case_=6 , snake_case_=17 , snake_case_=23 , snake_case_=11 , snake_case_=True , ): lowercase =parent lowercase =batch_size lowercase =seq_length lowercase =act_dim lowercase =state_dim lowercase =hidden_size lowercase =max_length lowercase =is_training def _A( self ): lowercase =floats_tensor((self.batch_size, self.seq_length, self.state_dim) ) lowercase =floats_tensor((self.batch_size, self.seq_length, self.act_dim) ) lowercase =floats_tensor((self.batch_size, self.seq_length, 1) ) lowercase =floats_tensor((self.batch_size, self.seq_length, 1) ) lowercase =ids_tensor((self.batch_size, self.seq_length) , vocab_size=10_00 ) lowercase =random_attention_mask((self.batch_size, self.seq_length) ) lowercase =self.get_config() return ( config, states, actions, rewards, returns_to_go, timesteps, attention_mask, ) def _A( self ): return DecisionTransformerConfig( batch_size=self.batch_size , seq_length=self.seq_length , act_dim=self.act_dim , state_dim=self.state_dim , hidden_size=self.hidden_size , max_length=self.max_length , ) def _A( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , ): lowercase =DecisionTransformerModel(config=snake_case_ ) model.to(snake_case_ ) model.eval() lowercase =model(snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) self.parent.assertEqual(result.state_preds.shape , states.shape ) self.parent.assertEqual(result.action_preds.shape , actions.shape ) self.parent.assertEqual(result.return_preds.shape , returns_to_go.shape ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.seq_length * 3, self.hidden_size) ) # seq length *3 as there are 3 modelities: states, returns and actions def _A( self ): lowercase =self.prepare_config_and_inputs() ( ( lowercase ) , ( lowercase ) , ( lowercase ) , ( lowercase ) , ( lowercase ) , ( lowercase ) , ( lowercase ) , ) =config_and_inputs lowercase ={ '''states''': states, '''actions''': actions, '''rewards''': rewards, '''returns_to_go''': returns_to_go, '''timesteps''': timesteps, '''attention_mask''': attention_mask, } return config, inputs_dict @require_torch class __magic_name__ ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): UpperCamelCase__ = (DecisionTransformerModel,) if is_torch_available() else () UpperCamelCase__ = () UpperCamelCase__ = {'feature-extraction': DecisionTransformerModel} if is_torch_available() else {} # Ignoring of a failing test from GenerationTesterMixin, as the model does not use inputs_ids UpperCamelCase__ = False # Ignoring of a failing tests from ModelTesterMixin, as the model does not implement these features UpperCamelCase__ = False UpperCamelCase__ = False UpperCamelCase__ = False UpperCamelCase__ = False UpperCamelCase__ = False UpperCamelCase__ = False UpperCamelCase__ = False UpperCamelCase__ = False UpperCamelCase__ = False def _A( self ): lowercase =DecisionTransformerModelTester(self ) lowercase =ConfigTester(self , config_class=snake_case_ , hidden_size=37 ) def _A( self ): self.config_tester.run_common_tests() def _A( self ): lowercase =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*snake_case_ ) @slow def _A( self ): for model_name in DECISION_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowercase =DecisionTransformerModel.from_pretrained(snake_case_ ) self.assertIsNotNone(snake_case_ ) def _A( self ): lowercase , lowercase =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowercase =model_class(snake_case_ ) lowercase =inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowercase =[*signature.parameters.keys()] lowercase =[ '''states''', '''actions''', '''rewards''', '''returns_to_go''', '''timesteps''', '''attention_mask''', ] self.assertListEqual(arg_names[: len(snake_case_ )] , snake_case_ ) @require_torch class __magic_name__ ( unittest.TestCase ): @slow def _A( self ): lowercase =2 # number of steps of autoregressive prediction we will perform lowercase =10 # defined by the RL environment, may be normalized lowercase =DecisionTransformerModel.from_pretrained('''edbeeching/decision-transformer-gym-hopper-expert''' ) lowercase =model.to(snake_case_ ) lowercase =model.config torch.manual_seed(0 ) lowercase =torch.randn(1 , 1 , config.state_dim ).to(device=snake_case_ , dtype=torch.floataa ) # env.reset() lowercase =torch.tensor( [[0.24_27_93, -0.28_69_30_74, 0.8_74_26_13], [0.67_81_52_74, -0.08_10_10_85, -0.12_95_21_47]] , device=snake_case_ ) lowercase =torch.tensor(snake_case_ , device=snake_case_ , dtype=torch.floataa ).reshape(1 , 1 , 1 ) lowercase =state lowercase =torch.zeros(1 , 0 , config.act_dim , device=snake_case_ , dtype=torch.floataa ) lowercase =torch.zeros(1 , 0 , device=snake_case_ , dtype=torch.floataa ) lowercase =torch.tensor(0 , device=snake_case_ , dtype=torch.long ).reshape(1 , 1 ) for step in range(snake_case_ ): lowercase =torch.cat([actions, torch.zeros(1 , 1 , config.act_dim , device=snake_case_ )] , dim=1 ) lowercase =torch.cat([rewards, torch.zeros(1 , 1 , device=snake_case_ )] , dim=1 ) lowercase =torch.ones(1 , states.shape[1] ).to(dtype=torch.long , device=states.device ) with torch.no_grad(): lowercase , lowercase , lowercase =model( states=snake_case_ , actions=snake_case_ , rewards=snake_case_ , returns_to_go=snake_case_ , timesteps=snake_case_ , attention_mask=snake_case_ , return_dict=snake_case_ , ) self.assertEqual(action_pred.shape , actions.shape ) self.assertTrue(torch.allclose(action_pred[0, -1] , expected_outputs[step] , atol=1E-4 ) ) lowercase , lowercase , lowercase , lowercase =( # env.step(action) torch.randn(1 , 1 , config.state_dim ).to(device=snake_case_ , dtype=torch.floataa ), 1.0, False, {}, ) lowercase =action_pred[0, -1] lowercase =torch.cat([states, state] , dim=1 ) lowercase =returns_to_go[0, -1] - reward lowercase =torch.cat([returns_to_go, pred_return.reshape(1 , 1 , 1 )] , dim=1 ) lowercase =torch.cat( [timesteps, torch.ones((1, 1) , device=snake_case_ , dtype=torch.long ) * (step + 1)] , dim=1 )
72
0
import colorsys from PIL import Image # type: ignore def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = x SCREAMING_SNAKE_CASE = y for step in range(_UpperCAmelCase): # noqa: B007 SCREAMING_SNAKE_CASE = a * a - b * b + x SCREAMING_SNAKE_CASE = 2 * a * b + y SCREAMING_SNAKE_CASE = a_new # divergence happens for all complex number with an absolute value # greater than 4 if a * a + b * b > 4: break return step / (max_step - 1) def lowerCamelCase__ (_UpperCAmelCase): if distance == 1: return (0, 0, 0) else: return (255, 255, 255) def lowerCamelCase__ (_UpperCAmelCase): if distance == 1: return (0, 0, 0) else: return tuple(round(i * 255) for i in colorsys.hsv_to_rgb(_UpperCAmelCase , 1 , 1)) def lowerCamelCase__ (_UpperCAmelCase = 800 , _UpperCAmelCase = 600 , _UpperCAmelCase = -0.6 , _UpperCAmelCase = 0 , _UpperCAmelCase = 3.2 , _UpperCAmelCase = 50 , _UpperCAmelCase = True , ): SCREAMING_SNAKE_CASE = Image.new('RGB' , (image_width, image_height)) SCREAMING_SNAKE_CASE = img.load() # loop through the image-coordinates for image_x in range(_UpperCAmelCase): for image_y in range(_UpperCAmelCase): # determine the figure-coordinates based on the image-coordinates SCREAMING_SNAKE_CASE = figure_width / image_width * image_height SCREAMING_SNAKE_CASE = figure_center_x + (image_x / image_width - 0.5) * figure_width SCREAMING_SNAKE_CASE = figure_center_y + (image_y / image_height - 0.5) * figure_height SCREAMING_SNAKE_CASE = get_distance(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) # color the corresponding pixel based on the selected coloring-function if use_distance_color_coding: SCREAMING_SNAKE_CASE = get_color_coded_rgb(_UpperCAmelCase) else: SCREAMING_SNAKE_CASE = get_black_and_white_rgb(_UpperCAmelCase) return img if __name__ == "__main__": import doctest doctest.testmod() # colored version, full figure a_ : List[Any] = get_image() # uncomment for colored version, different section, zoomed in # img = get_image(figure_center_x = -0.6, figure_center_y = -0.4, # figure_width = 0.8) # uncomment for black and white version, full figure # img = get_image(use_distance_color_coding = False) # uncomment to save the image # img.save("mandelbrot.png") img.show()
73
import sys import turtle def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): return (pa[0] + pa[0]) / 2, (pa[1] + pa[1]) / 2 def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , ): my_pen.up() my_pen.goto(vertexa[0] , vertexa[1]) my_pen.down() my_pen.goto(vertexa[0] , vertexa[1]) my_pen.goto(vertexa[0] , vertexa[1]) my_pen.goto(vertexa[0] , vertexa[1]) if depth == 0: return triangle(_UpperCAmelCase , get_mid(_UpperCAmelCase , _UpperCAmelCase) , get_mid(_UpperCAmelCase , _UpperCAmelCase) , depth - 1) triangle(_UpperCAmelCase , get_mid(_UpperCAmelCase , _UpperCAmelCase) , get_mid(_UpperCAmelCase , _UpperCAmelCase) , depth - 1) triangle(_UpperCAmelCase , get_mid(_UpperCAmelCase , _UpperCAmelCase) , get_mid(_UpperCAmelCase , _UpperCAmelCase) , depth - 1) if __name__ == "__main__": if len(sys.argv) != 2: raise ValueError( 'Correct format for using this script: ' 'python fractals.py <int:depth_for_fractal>' ) a_ : Any = turtle.Turtle() my_pen.ht() my_pen.speed(5) my_pen.pencolor('red') a_ : str = [(-1_75, -1_25), (0, 1_75), (1_75, -1_25)] # vertices of triangle triangle(vertices[0], vertices[1], vertices[2], int(sys.argv[1]))
73
1
# A Bipartite Graph is a graph whose vertices can be divided into two independent sets, # U and V such that every edge (u, v) either connects a vertex from U to V or a vertex # from V to U. In other words, for every edge (u, v), either u belongs to U and v to V, # or u belongs to V and v to U. We can also say that there is no edge that connects # vertices of same set. def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = [False] * len(_UpperCAmelCase) SCREAMING_SNAKE_CASE = [-1] * len(_UpperCAmelCase) def dfs(_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = c for u in graph[v]: if not visited[u]: dfs(_UpperCAmelCase , 1 - c) for i in range(len(_UpperCAmelCase)): if not visited[i]: dfs(_UpperCAmelCase , 0) for i in range(len(_UpperCAmelCase)): for j in graph[i]: if color[i] == color[j]: return False return True # Adjacency list of graph a_ : int = {0: [1, 3], 1: [0, 2], 2: [1, 3], 3: [0, 2], 4: []} print(check_bipartite_dfs(graph))
73
import math import os from copy import deepcopy import datasets import evaluate import torch import transformers from datasets import load_dataset from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer from accelerate import Accelerator from accelerate.test_utils import RegressionDataset, RegressionModel from accelerate.utils import is_tpu_available, set_seed a_ : Any = 'true' def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase=82 , _UpperCAmelCase=16): set_seed(42) SCREAMING_SNAKE_CASE = RegressionModel() SCREAMING_SNAKE_CASE = deepcopy(_UpperCAmelCase) SCREAMING_SNAKE_CASE = RegressionDataset(length=_UpperCAmelCase) SCREAMING_SNAKE_CASE = DataLoader(_UpperCAmelCase , batch_size=_UpperCAmelCase) model.to(accelerator.device) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = accelerator.prepare(_UpperCAmelCase , _UpperCAmelCase) return model, ddp_model, dataloader def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase=False): SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained('hf-internal-testing/mrpc-bert-base-cased') SCREAMING_SNAKE_CASE = load_dataset('glue' , 'mrpc' , split='validation') def tokenize_function(_UpperCAmelCase): SCREAMING_SNAKE_CASE = tokenizer(examples['sentence1'] , examples['sentence2'] , truncation=_UpperCAmelCase , max_length=_UpperCAmelCase) return outputs with accelerator.main_process_first(): SCREAMING_SNAKE_CASE = dataset.map( _UpperCAmelCase , batched=_UpperCAmelCase , remove_columns=['idx', 'sentence1', 'sentence2'] , ) SCREAMING_SNAKE_CASE = tokenized_datasets.rename_column('label' , 'labels') def collate_fn(_UpperCAmelCase): if use_longest: return tokenizer.pad(_UpperCAmelCase , padding='longest' , return_tensors='pt') return tokenizer.pad(_UpperCAmelCase , padding='max_length' , max_length=128 , return_tensors='pt') return DataLoader(_UpperCAmelCase , shuffle=_UpperCAmelCase , collate_fn=_UpperCAmelCase , batch_size=16) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = Accelerator(dispatch_batches=_UpperCAmelCase , split_batches=_UpperCAmelCase) SCREAMING_SNAKE_CASE = get_dataloader(_UpperCAmelCase , not dispatch_batches) SCREAMING_SNAKE_CASE = AutoModelForSequenceClassification.from_pretrained( 'hf-internal-testing/mrpc-bert-base-cased' , return_dict=_UpperCAmelCase) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = accelerator.prepare(_UpperCAmelCase , _UpperCAmelCase) return {"ddp": [ddp_model, ddp_dataloader, "cuda:0"], "no": [model, dataloader, accelerator.device]}, accelerator def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = [] for batch in dataloader: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = batch.values() with torch.no_grad(): SCREAMING_SNAKE_CASE = model(_UpperCAmelCase) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = accelerator.gather_for_metrics((logit, target)) logits_and_targets.append((logit, target)) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = [], [] for logit, targ in logits_and_targets: logits.append(_UpperCAmelCase) targs.append(_UpperCAmelCase) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = torch.cat(_UpperCAmelCase), torch.cat(_UpperCAmelCase) return logits, targs def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase=82 , _UpperCAmelCase=False , _UpperCAmelCase=False , _UpperCAmelCase=16): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = get_basic_setup(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = generate_predictions(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) assert ( len(_UpperCAmelCase) == num_samples ), F'''Unexpected number of inputs:\n Expected: {num_samples}\n Actual: {len(_UpperCAmelCase)}''' def lowerCamelCase__ (_UpperCAmelCase = False , _UpperCAmelCase = False): SCREAMING_SNAKE_CASE = evaluate.load('glue' , 'mrpc') SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = get_mrpc_setup(_UpperCAmelCase , _UpperCAmelCase) # First do baseline SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = setup['no'] model.to(_UpperCAmelCase) model.eval() for batch in dataloader: batch.to(_UpperCAmelCase) with torch.inference_mode(): SCREAMING_SNAKE_CASE = model(**_UpperCAmelCase) SCREAMING_SNAKE_CASE = outputs.logits.argmax(dim=-1) metric.add_batch(predictions=_UpperCAmelCase , references=batch['labels']) SCREAMING_SNAKE_CASE = metric.compute() # Then do distributed SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = setup['ddp'] model.eval() for batch in dataloader: with torch.inference_mode(): SCREAMING_SNAKE_CASE = model(**_UpperCAmelCase) SCREAMING_SNAKE_CASE = outputs.logits.argmax(dim=-1) SCREAMING_SNAKE_CASE = batch['labels'] SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = accelerator.gather_for_metrics((preds, references)) metric.add_batch(predictions=_UpperCAmelCase , references=_UpperCAmelCase) SCREAMING_SNAKE_CASE = metric.compute() for key in "accuracy f1".split(): assert math.isclose( baseline[key] , distributed[key]), F'''Baseline and Distributed are not the same for key {key}:\n\tBaseline: {baseline[key]}\n\tDistributed: {distributed[key]}\n''' def lowerCamelCase__ (): SCREAMING_SNAKE_CASE = Accelerator(split_batches=_UpperCAmelCase , dispatch_batches=_UpperCAmelCase) if accelerator.is_local_main_process: datasets.utils.logging.set_verbosity_warning() transformers.utils.logging.set_verbosity_warning() else: datasets.utils.logging.set_verbosity_error() transformers.utils.logging.set_verbosity_error() # These are a bit slower so they should only be ran on the GPU or TPU if torch.cuda.is_available() or is_tpu_available(): if accelerator.is_local_main_process: print('**Testing gather_for_metrics**') for split_batches in [True, False]: for dispatch_batches in [True, False]: if accelerator.is_local_main_process: print(F'''With: `split_batches={split_batches}`, `dispatch_batches={dispatch_batches}`''') test_mrpc(_UpperCAmelCase , _UpperCAmelCase) accelerator.state._reset_state() if accelerator.is_local_main_process: print('**Test torch metrics**') for split_batches in [True, False]: for dispatch_batches in [True, False]: SCREAMING_SNAKE_CASE = Accelerator(split_batches=_UpperCAmelCase , dispatch_batches=_UpperCAmelCase) if accelerator.is_local_main_process: print(F'''With: `split_batches={split_batches}`, `dispatch_batches={dispatch_batches}`, length=99''') test_torch_metrics(_UpperCAmelCase , 99) accelerator.state._reset_state() if accelerator.is_local_main_process: print('**Test last batch is not dropped when perfectly divisible**') SCREAMING_SNAKE_CASE = Accelerator() test_torch_metrics(_UpperCAmelCase , 512) accelerator.state._reset_state() def lowerCamelCase__ (_UpperCAmelCase): # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
73
1
def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = len(_UpperCAmelCase) SCREAMING_SNAKE_CASE = [] for i in range(len(_UpperCAmelCase) - pat_len + 1): SCREAMING_SNAKE_CASE = True for j in range(_UpperCAmelCase): if s[i + j] != pattern[j]: SCREAMING_SNAKE_CASE = False break if match_found: position.append(_UpperCAmelCase) return position if __name__ == "__main__": assert naive_pattern_search('ABCDEFG', 'DE') == [3] print(naive_pattern_search('ABAAABCDBBABCDDEBCABC', 'ABC'))
73
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available a_ : List[str] = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : Optional[Any] = ['GPTSw3Tokenizer'] if TYPE_CHECKING: try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_gpt_swa import GPTSwaTokenizer else: import sys a_ : Tuple = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
73
1
import time import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch, torch_device from ..test_modeling_common import ids_tensor if is_torch_available(): import torch from transformers.generation import ( MaxLengthCriteria, MaxNewTokensCriteria, MaxTimeCriteria, StoppingCriteriaList, validate_stopping_criteria, ) @require_torch class _snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ ( self , a) -> str: SCREAMING_SNAKE_CASE = 3 SCREAMING_SNAKE_CASE = 250 SCREAMING_SNAKE_CASE = ids_tensor((batch_size, length) , a) SCREAMING_SNAKE_CASE = torch.ones((batch_size, length) , device=a , dtype=torch.float) / length return input_ids, scores def SCREAMING_SNAKE_CASE__ ( self) -> Any: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self._get_tensors(5) SCREAMING_SNAKE_CASE = StoppingCriteriaList( [ MaxLengthCriteria(max_length=10), MaxTimeCriteria(max_time=0.1), ]) self.assertFalse(criteria(a , a)) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self._get_tensors(9) self.assertFalse(criteria(a , a)) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self._get_tensors(10) self.assertTrue(criteria(a , a)) def SCREAMING_SNAKE_CASE__ ( self) -> int: SCREAMING_SNAKE_CASE = MaxLengthCriteria(max_length=10) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self._get_tensors(5) self.assertFalse(criteria(a , a)) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self._get_tensors(9) self.assertFalse(criteria(a , a)) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self._get_tensors(10) self.assertTrue(criteria(a , a)) def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: SCREAMING_SNAKE_CASE = MaxNewTokensCriteria(start_length=5 , max_new_tokens=5) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self._get_tensors(5) self.assertFalse(criteria(a , a)) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self._get_tensors(9) self.assertFalse(criteria(a , a)) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self._get_tensors(10) self.assertTrue(criteria(a , a)) SCREAMING_SNAKE_CASE = StoppingCriteriaList([criteria]) self.assertEqual(criteria_list.max_length , 10) def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self._get_tensors(5) SCREAMING_SNAKE_CASE = MaxTimeCriteria(max_time=0.1) self.assertFalse(criteria(a , a)) SCREAMING_SNAKE_CASE = MaxTimeCriteria(max_time=0.1 , initial_timestamp=time.time() - 0.2) self.assertTrue(criteria(a , a)) def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: validate_stopping_criteria(StoppingCriteriaList([MaxLengthCriteria(10)]) , 10) with self.assertWarns(a): validate_stopping_criteria(StoppingCriteriaList([MaxLengthCriteria(10)]) , 11) SCREAMING_SNAKE_CASE = validate_stopping_criteria(StoppingCriteriaList() , 11) self.assertEqual(len(a) , 1)
73
import os from tempfile import TemporaryDirectory from unittest import TestCase import pytest from absl.testing import parameterized from datasets import config from datasets.arrow_reader import HF_GCP_BASE_URL from datasets.builder import DatasetBuilder from datasets.dataset_dict import IterableDatasetDict from datasets.iterable_dataset import IterableDataset from datasets.load import dataset_module_factory, import_main_class from datasets.utils.file_utils import cached_path a_ : str = [ {'dataset': 'wikipedia', 'config_name': '20220301.de'}, {'dataset': 'wikipedia', 'config_name': '20220301.en'}, {'dataset': 'wikipedia', 'config_name': '20220301.fr'}, {'dataset': 'wikipedia', 'config_name': '20220301.frr'}, {'dataset': 'wikipedia', 'config_name': '20220301.it'}, {'dataset': 'wikipedia', 'config_name': '20220301.simple'}, {'dataset': 'snli', 'config_name': 'plain_text'}, {'dataset': 'eli5', 'config_name': 'LFQA_reddit'}, {'dataset': 'wiki40b', 'config_name': 'en'}, {'dataset': 'wiki_dpr', 'config_name': 'psgs_w100.nq.compressed'}, {'dataset': 'wiki_dpr', 'config_name': 'psgs_w100.nq.no_index'}, {'dataset': 'wiki_dpr', 'config_name': 'psgs_w100.multiset.no_index'}, {'dataset': 'natural_questions', 'config_name': 'default'}, ] def lowerCamelCase__ (_UpperCAmelCase=True): if with_config: return [ { "testcase_name": d["dataset"] + "/" + d["config_name"], "dataset": d["dataset"], "config_name": d["config_name"], } for d in DATASETS_ON_HF_GCP ] else: return [ {"testcase_name": dataset, "dataset": dataset} for dataset in {d["dataset"] for d in DATASETS_ON_HF_GCP} ] @parameterized.named_parameters(list_datasets_on_hf_gcp_parameters(with_config=A__ ) ) class _snake_case ( A__ ): _lowercase : Optional[Any] = None _lowercase : Optional[Any] = None def SCREAMING_SNAKE_CASE__ ( self , a , a) -> Optional[Any]: with TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE = dataset_module_factory(a , cache_dir=a) SCREAMING_SNAKE_CASE = import_main_class(dataset_module.module_path , dataset=a) SCREAMING_SNAKE_CASE = builder_cls( cache_dir=a , config_name=a , hash=dataset_module.hash , ) SCREAMING_SNAKE_CASE = '/'.join( [ HF_GCP_BASE_URL, builder_instance._relative_data_dir(with_hash=a).replace(os.sep , '/'), config.DATASET_INFO_FILENAME, ]) SCREAMING_SNAKE_CASE = cached_path(a , cache_dir=a) self.assertTrue(os.path.exists(a)) @pytest.mark.integration def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = tmp_path_factory.mktemp('test_hf_gcp') / 'test_wikipedia_simple' SCREAMING_SNAKE_CASE = dataset_module_factory('wikipedia' , cache_dir=_UpperCAmelCase) SCREAMING_SNAKE_CASE = import_main_class(dataset_module.module_path) SCREAMING_SNAKE_CASE = builder_cls( cache_dir=_UpperCAmelCase , config_name='20220301.frr' , hash=dataset_module.hash , ) # use the HF cloud storage, not the original download_and_prepare that uses apache-beam SCREAMING_SNAKE_CASE = None builder_instance.download_and_prepare() SCREAMING_SNAKE_CASE = builder_instance.as_dataset() assert ds @pytest.mark.integration def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = dataset_module_factory('wikipedia' , cache_dir=_UpperCAmelCase) SCREAMING_SNAKE_CASE = import_main_class(dataset_module.module_path , dataset=_UpperCAmelCase) SCREAMING_SNAKE_CASE = builder_cls( cache_dir=_UpperCAmelCase , config_name='20220301.frr' , hash=dataset_module.hash , ) SCREAMING_SNAKE_CASE = builder_instance.as_streaming_dataset() assert ds assert isinstance(_UpperCAmelCase , _UpperCAmelCase) assert "train" in ds assert isinstance(ds['train'] , _UpperCAmelCase) assert next(iter(ds['train']))
73
1
a_ : dict[tuple[int, int, int], int] = {} def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): # if we are absent twice, or late 3 consecutive days, # no further prize strings are possible if late == 3 or absent == 2: return 0 # if we have no days left, and have not failed any other rules, # we have a prize string if days == 0: return 1 # No easy solution, so now we need to do the recursive calculation # First, check if the combination is already in the cache, and # if yes, return the stored value from there since we already # know the number of possible prize strings from this point on SCREAMING_SNAKE_CASE = (days, absent, late) if key in cache: return cache[key] # now we calculate the three possible ways that can unfold from # this point on, depending on our attendance today # 1) if we are late (but not absent), the "absent" counter stays as # it is, but the "late" counter increases by one SCREAMING_SNAKE_CASE = _calculate(days - 1 , _UpperCAmelCase , late + 1) # 2) if we are absent, the "absent" counter increases by 1, and the # "late" counter resets to 0 SCREAMING_SNAKE_CASE = _calculate(days - 1 , absent + 1 , 0) # 3) if we are on time, this resets the "late" counter and keeps the # absent counter SCREAMING_SNAKE_CASE = _calculate(days - 1 , _UpperCAmelCase , 0) SCREAMING_SNAKE_CASE = state_late + state_absent + state_ontime SCREAMING_SNAKE_CASE = prizestrings return prizestrings def lowerCamelCase__ (_UpperCAmelCase = 30): return _calculate(_UpperCAmelCase , absent=0 , late=0) if __name__ == "__main__": print(solution())
73
from __future__ import annotations def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = 2 SCREAMING_SNAKE_CASE = [] while i * i <= n: if n % i: i += 1 else: n //= i factors.append(_UpperCAmelCase) if n > 1: factors.append(_UpperCAmelCase) return factors if __name__ == "__main__": import doctest doctest.testmod()
73
1
import copy from ...configuration_utils import PretrainedConfig from ...utils import logging a_ : Optional[Any] = logging.get_logger(__name__) class _snake_case ( A__ ): _lowercase : int = '''encoder-decoder''' _lowercase : Dict = True def __init__( self , **a) -> List[Any]: super().__init__(**a) assert ( "encoder" in kwargs and "decoder" in kwargs ), "Config has to be initialized with encoder and decoder config" SCREAMING_SNAKE_CASE = kwargs.pop('encoder') SCREAMING_SNAKE_CASE = encoder_config.pop('model_type') SCREAMING_SNAKE_CASE = kwargs.pop('decoder') SCREAMING_SNAKE_CASE = decoder_config.pop('model_type') from ..auto.configuration_auto import AutoConfig SCREAMING_SNAKE_CASE = AutoConfig.for_model(a , **a) SCREAMING_SNAKE_CASE = AutoConfig.for_model(a , **a) SCREAMING_SNAKE_CASE = True @classmethod def SCREAMING_SNAKE_CASE__ ( cls , a , a , **a) -> PretrainedConfig: logger.info('Set `config.is_decoder=True` and `config.add_cross_attention=True` for decoder_config') SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = True return cls(encoder=encoder_config.to_dict() , decoder=decoder_config.to_dict() , **a) def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: SCREAMING_SNAKE_CASE = copy.deepcopy(self.__dict__) SCREAMING_SNAKE_CASE = self.encoder.to_dict() SCREAMING_SNAKE_CASE = self.decoder.to_dict() SCREAMING_SNAKE_CASE = self.__class__.model_type return output
73
import math import os import sys def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = '' try: with open(_UpperCAmelCase , 'rb') as binary_file: SCREAMING_SNAKE_CASE = binary_file.read() for dat in data: SCREAMING_SNAKE_CASE = F'''{dat:08b}''' result += curr_byte return result except OSError: print('File not accessible') sys.exit() def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): lexicon.pop(_UpperCAmelCase) SCREAMING_SNAKE_CASE = last_match_id if math.loga(_UpperCAmelCase).is_integer(): for curr_key in lexicon: SCREAMING_SNAKE_CASE = '0' + lexicon[curr_key] SCREAMING_SNAKE_CASE = bin(_UpperCAmelCase)[2:] def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = {'0': '0', '1': '1'} SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = '', '' SCREAMING_SNAKE_CASE = len(_UpperCAmelCase) for i in range(len(_UpperCAmelCase)): curr_string += data_bits[i] if curr_string not in lexicon: continue SCREAMING_SNAKE_CASE = lexicon[curr_string] result += last_match_id add_key_to_lexicon(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) index += 1 SCREAMING_SNAKE_CASE = '' while curr_string != "" and curr_string not in lexicon: curr_string += "0" if curr_string != "": SCREAMING_SNAKE_CASE = lexicon[curr_string] result += last_match_id return result def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = os.path.getsize(_UpperCAmelCase) SCREAMING_SNAKE_CASE = bin(_UpperCAmelCase)[2:] SCREAMING_SNAKE_CASE = len(_UpperCAmelCase) return "0" * (length_length - 1) + file_length_binary + compressed def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = 8 try: with open(_UpperCAmelCase , 'wb') as opened_file: SCREAMING_SNAKE_CASE = [ to_write[i : i + byte_length] for i in range(0 , len(_UpperCAmelCase) , _UpperCAmelCase) ] 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(_UpperCAmelCase , 2).to_bytes(1 , byteorder='big')) except OSError: print('File not accessible') sys.exit() def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = read_file_binary(_UpperCAmelCase) SCREAMING_SNAKE_CASE = compress_data(_UpperCAmelCase) SCREAMING_SNAKE_CASE = add_file_length(_UpperCAmelCase , _UpperCAmelCase) write_file_binary(_UpperCAmelCase , _UpperCAmelCase) if __name__ == "__main__": compress(sys.argv[1], sys.argv[2])
73
1
import gc import random import tempfile import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMInverseScheduler, DDIMScheduler, DPMSolverMultistepInverseScheduler, DPMSolverMultistepScheduler, StableDiffusionDiffEditPipeline, UNetaDConditionModel, ) from diffusers.utils import load_image, slow from diffusers.utils.testing_utils import enable_full_determinism, floats_tensor, require_torch_gpu, torch_device from ..pipeline_params import TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class _snake_case ( A__ , A__ , unittest.TestCase ): _lowercase : List[Any] = StableDiffusionDiffEditPipeline _lowercase : List[str] = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS - {'''height''', '''width''', '''image'''} | {'''image_latents'''} _lowercase : Optional[int] = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS - {'''image'''} | {'''image_latents'''} _lowercase : List[str] = frozenset( [] ) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess _lowercase : List[str] = frozenset([] ) def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: torch.manual_seed(0) SCREAMING_SNAKE_CASE = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D') , up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D') , cross_attention_dim=32 , attention_head_dim=(2, 4) , use_linear_projection=a , ) SCREAMING_SNAKE_CASE = DDIMScheduler( beta_start=0.0_00_85 , beta_end=0.0_12 , beta_schedule='scaled_linear' , clip_sample=a , set_alpha_to_one=a , ) SCREAMING_SNAKE_CASE = DDIMInverseScheduler( beta_start=0.0_00_85 , beta_end=0.0_12 , beta_schedule='scaled_linear' , clip_sample=a , set_alpha_to_zero=a , ) torch.manual_seed(0) SCREAMING_SNAKE_CASE = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D'] , up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D'] , latent_channels=4 , sample_size=128 , ) torch.manual_seed(0) SCREAMING_SNAKE_CASE = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , hidden_act='gelu' , projection_dim=512 , ) SCREAMING_SNAKE_CASE = CLIPTextModel(a) SCREAMING_SNAKE_CASE = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip') SCREAMING_SNAKE_CASE = { 'unet': unet, 'scheduler': scheduler, 'inverse_scheduler': inverse_scheduler, 'vae': vae, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'safety_checker': None, 'feature_extractor': None, } return components def SCREAMING_SNAKE_CASE__ ( self , a , a=0) -> List[Any]: SCREAMING_SNAKE_CASE = floats_tensor((1, 16, 16) , rng=random.Random(a)).to(a) SCREAMING_SNAKE_CASE = floats_tensor((1, 2, 4, 16, 16) , rng=random.Random(a)).to(a) if str(a).startswith('mps'): SCREAMING_SNAKE_CASE = torch.manual_seed(a) else: SCREAMING_SNAKE_CASE = torch.Generator(device=a).manual_seed(a) SCREAMING_SNAKE_CASE = { 'prompt': 'a dog and a newt', 'mask_image': mask, 'image_latents': latents, 'generator': generator, 'num_inference_steps': 2, 'inpaint_strength': 1.0, 'guidance_scale': 6.0, 'output_type': 'numpy', } return inputs def SCREAMING_SNAKE_CASE__ ( self , a , a=0) -> List[Any]: SCREAMING_SNAKE_CASE = floats_tensor((1, 3, 32, 32) , rng=random.Random(a)).to(a) SCREAMING_SNAKE_CASE = image.cpu().permute(0 , 2 , 3 , 1)[0] SCREAMING_SNAKE_CASE = Image.fromarray(np.uinta(a)).convert('RGB') if str(a).startswith('mps'): SCREAMING_SNAKE_CASE = torch.manual_seed(a) else: SCREAMING_SNAKE_CASE = torch.Generator(device=a).manual_seed(a) SCREAMING_SNAKE_CASE = { 'image': image, 'source_prompt': 'a cat and a frog', 'target_prompt': 'a dog and a newt', 'generator': generator, 'num_inference_steps': 2, 'num_maps_per_mask': 2, 'mask_encode_strength': 1.0, 'guidance_scale': 6.0, 'output_type': 'numpy', } return inputs def SCREAMING_SNAKE_CASE__ ( self , a , a=0) -> Optional[int]: SCREAMING_SNAKE_CASE = floats_tensor((1, 3, 32, 32) , rng=random.Random(a)).to(a) SCREAMING_SNAKE_CASE = image.cpu().permute(0 , 2 , 3 , 1)[0] SCREAMING_SNAKE_CASE = Image.fromarray(np.uinta(a)).convert('RGB') if str(a).startswith('mps'): SCREAMING_SNAKE_CASE = torch.manual_seed(a) else: SCREAMING_SNAKE_CASE = torch.Generator(device=a).manual_seed(a) SCREAMING_SNAKE_CASE = { 'image': image, 'prompt': 'a cat and a frog', 'generator': generator, 'num_inference_steps': 2, 'inpaint_strength': 1.0, 'guidance_scale': 6.0, 'decode_latents': True, 'output_type': 'numpy', } return inputs def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: if not hasattr(self.pipeline_class , '_optional_components'): return SCREAMING_SNAKE_CASE = self.get_dummy_components() SCREAMING_SNAKE_CASE = self.pipeline_class(**a) pipe.to(a) pipe.set_progress_bar_config(disable=a) # set all optional components to None and update pipeline config accordingly for optional_component in pipe._optional_components: setattr(a , a , a) pipe.register_modules(**{optional_component: None for optional_component in pipe._optional_components}) SCREAMING_SNAKE_CASE = self.get_dummy_inputs(a) SCREAMING_SNAKE_CASE = pipe(**a)[0] with tempfile.TemporaryDirectory() as tmpdir: pipe.save_pretrained(a) SCREAMING_SNAKE_CASE = self.pipeline_class.from_pretrained(a) pipe_loaded.to(a) pipe_loaded.set_progress_bar_config(disable=a) for optional_component in pipe._optional_components: self.assertTrue( getattr(a , a) is None , f'''`{optional_component}` did not stay set to None after loading.''' , ) SCREAMING_SNAKE_CASE = self.get_dummy_inputs(a) SCREAMING_SNAKE_CASE = pipe_loaded(**a)[0] SCREAMING_SNAKE_CASE = np.abs(output - output_loaded).max() self.assertLess(a , 1E-4) def SCREAMING_SNAKE_CASE__ ( self) -> str: SCREAMING_SNAKE_CASE = 'cpu' SCREAMING_SNAKE_CASE = self.get_dummy_components() SCREAMING_SNAKE_CASE = self.pipeline_class(**a) pipe.to(a) pipe.set_progress_bar_config(disable=a) SCREAMING_SNAKE_CASE = self.get_dummy_mask_inputs(a) SCREAMING_SNAKE_CASE = pipe.generate_mask(**a) SCREAMING_SNAKE_CASE = mask[0, -3:, -3:] self.assertEqual(mask.shape , (1, 16, 16)) SCREAMING_SNAKE_CASE = np.array([0] * 9) SCREAMING_SNAKE_CASE = np.abs(mask_slice.flatten() - expected_slice).max() self.assertLessEqual(a , 1E-3) self.assertEqual(mask[0, -3, -4] , 0) def SCREAMING_SNAKE_CASE__ ( self) -> str: SCREAMING_SNAKE_CASE = 'cpu' SCREAMING_SNAKE_CASE = self.get_dummy_components() SCREAMING_SNAKE_CASE = self.pipeline_class(**a) pipe.to(a) pipe.set_progress_bar_config(disable=a) SCREAMING_SNAKE_CASE = self.get_dummy_inversion_inputs(a) SCREAMING_SNAKE_CASE = pipe.invert(**a).images SCREAMING_SNAKE_CASE = image[0, -1, -3:, -3:] self.assertEqual(image.shape , (2, 32, 32, 3)) SCREAMING_SNAKE_CASE = np.array( [0.51_50, 0.51_34, 0.50_43, 0.53_76, 0.46_94, 0.5_10_50, 0.50_15, 0.44_07, 0.47_99] , ) SCREAMING_SNAKE_CASE = np.abs(image_slice.flatten() - expected_slice).max() self.assertLessEqual(a , 1E-3) def SCREAMING_SNAKE_CASE__ ( self) -> Dict: super().test_inference_batch_single_identical(expected_max_diff=5E-3) def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: SCREAMING_SNAKE_CASE = 'cpu' SCREAMING_SNAKE_CASE = self.get_dummy_components() SCREAMING_SNAKE_CASE = {'beta_start': 0.0_00_85, 'beta_end': 0.0_12, 'beta_schedule': 'scaled_linear'} SCREAMING_SNAKE_CASE = DPMSolverMultistepScheduler(**a) SCREAMING_SNAKE_CASE = DPMSolverMultistepInverseScheduler(**a) SCREAMING_SNAKE_CASE = self.pipeline_class(**a) pipe.to(a) pipe.set_progress_bar_config(disable=a) SCREAMING_SNAKE_CASE = self.get_dummy_inversion_inputs(a) SCREAMING_SNAKE_CASE = pipe.invert(**a).images SCREAMING_SNAKE_CASE = image[0, -1, -3:, -3:] self.assertEqual(image.shape , (2, 32, 32, 3)) SCREAMING_SNAKE_CASE = np.array( [0.51_50, 0.51_34, 0.50_43, 0.53_76, 0.46_94, 0.5_10_50, 0.50_15, 0.44_07, 0.47_99] , ) SCREAMING_SNAKE_CASE = np.abs(image_slice.flatten() - expected_slice).max() self.assertLessEqual(a , 1E-3) @require_torch_gpu @slow class _snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ ( self) -> Any: super().tearDown() gc.collect() torch.cuda.empty_cache() @classmethod def SCREAMING_SNAKE_CASE__ ( cls) -> List[Any]: SCREAMING_SNAKE_CASE = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/diffedit/fruit.png') SCREAMING_SNAKE_CASE = raw_image.convert('RGB').resize((768, 768)) SCREAMING_SNAKE_CASE = raw_image def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: SCREAMING_SNAKE_CASE = torch.manual_seed(0) SCREAMING_SNAKE_CASE = StableDiffusionDiffEditPipeline.from_pretrained( 'stabilityai/stable-diffusion-2-1' , safety_checker=a , torch_dtype=torch.floataa) SCREAMING_SNAKE_CASE = DDIMScheduler.from_config(pipe.scheduler.config) SCREAMING_SNAKE_CASE = DDIMInverseScheduler.from_config(pipe.scheduler.config) pipe.enable_model_cpu_offload() pipe.set_progress_bar_config(disable=a) SCREAMING_SNAKE_CASE = 'a bowl of fruit' SCREAMING_SNAKE_CASE = 'a bowl of pears' SCREAMING_SNAKE_CASE = pipe.generate_mask( image=self.raw_image , source_prompt=a , target_prompt=a , generator=a , ) SCREAMING_SNAKE_CASE = pipe.invert( prompt=a , image=self.raw_image , inpaint_strength=0.7 , generator=a).latents SCREAMING_SNAKE_CASE = pipe( prompt=a , mask_image=a , image_latents=a , generator=a , negative_prompt=a , inpaint_strength=0.7 , output_type='numpy' , ).images[0] SCREAMING_SNAKE_CASE = ( np.array( load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/diffedit/pears.png').resize((768, 768))) / 255 ) assert np.abs((expected_image - image).max()) < 5E-1 def SCREAMING_SNAKE_CASE__ ( self) -> str: SCREAMING_SNAKE_CASE = torch.manual_seed(0) SCREAMING_SNAKE_CASE = StableDiffusionDiffEditPipeline.from_pretrained( 'stabilityai/stable-diffusion-2-1' , safety_checker=a , torch_dtype=torch.floataa) SCREAMING_SNAKE_CASE = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config) SCREAMING_SNAKE_CASE = DPMSolverMultistepInverseScheduler.from_config(pipe.scheduler.config) pipe.enable_model_cpu_offload() pipe.set_progress_bar_config(disable=a) SCREAMING_SNAKE_CASE = 'a bowl of fruit' SCREAMING_SNAKE_CASE = 'a bowl of pears' SCREAMING_SNAKE_CASE = pipe.generate_mask( image=self.raw_image , source_prompt=a , target_prompt=a , generator=a , ) SCREAMING_SNAKE_CASE = pipe.invert( prompt=a , image=self.raw_image , inpaint_strength=0.7 , generator=a , num_inference_steps=25 , ).latents SCREAMING_SNAKE_CASE = pipe( prompt=a , mask_image=a , image_latents=a , generator=a , negative_prompt=a , inpaint_strength=0.7 , num_inference_steps=25 , output_type='numpy' , ).images[0] SCREAMING_SNAKE_CASE = ( np.array( load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/diffedit/pears.png').resize((768, 768))) / 255 ) assert np.abs((expected_image - image).max()) < 5E-1
73
import warnings from typing import Dict import numpy as np from ..utils import ExplicitEnum, add_end_docstrings, is_tf_available, is_torch_available from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline if is_tf_available(): from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if is_torch_available(): from ..models.auto.modeling_auto import MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING def lowerCamelCase__ (_UpperCAmelCase): return 1.0 / (1.0 + np.exp(-_outputs)) def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = np.max(_outputs , axis=-1 , keepdims=_UpperCAmelCase) SCREAMING_SNAKE_CASE = np.exp(_outputs - maxes) return shifted_exp / shifted_exp.sum(axis=-1 , keepdims=_UpperCAmelCase) class _snake_case ( A__ ): _lowercase : Tuple = '''sigmoid''' _lowercase : List[str] = '''softmax''' _lowercase : Tuple = '''none''' @add_end_docstrings( A__ , R''' return_all_scores (`bool`, *optional*, defaults to `False`): Whether to return all prediction scores or just the one of the predicted class. function_to_apply (`str`, *optional*, defaults to `"default"`): The function to apply to the model outputs in order to retrieve the scores. Accepts four different values: - `"default"`: if the model has a single label, will apply the sigmoid function on the output. If the model has several labels, will apply the softmax function on the output. - `"sigmoid"`: Applies the sigmoid function on the output. - `"softmax"`: Applies the softmax function on the output. - `"none"`: Does not apply any function on the output. ''' , ) class _snake_case ( A__ ): _lowercase : Optional[Any] = False _lowercase : Tuple = ClassificationFunction.NONE def __init__( self , **a) -> Optional[Any]: super().__init__(**a) self.check_model_type( TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if self.framework == 'tf' else MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING) def SCREAMING_SNAKE_CASE__ ( self , a=None , a=None , a="" , **a) -> Tuple: # Using "" as default argument because we're going to use `top_k=None` in user code to declare # "No top_k" SCREAMING_SNAKE_CASE = tokenizer_kwargs SCREAMING_SNAKE_CASE = {} if hasattr(self.model.config , 'return_all_scores') and return_all_scores is None: SCREAMING_SNAKE_CASE = self.model.config.return_all_scores if isinstance(a , a) or top_k is None: SCREAMING_SNAKE_CASE = top_k SCREAMING_SNAKE_CASE = False elif return_all_scores is not None: warnings.warn( '`return_all_scores` is now deprecated, if want a similar functionality use `top_k=None` instead of' ' `return_all_scores=True` or `top_k=1` instead of `return_all_scores=False`.' , a , ) if return_all_scores: SCREAMING_SNAKE_CASE = None else: SCREAMING_SNAKE_CASE = 1 if isinstance(a , a): SCREAMING_SNAKE_CASE = ClassificationFunction[function_to_apply.upper()] if function_to_apply is not None: SCREAMING_SNAKE_CASE = function_to_apply return preprocess_params, {}, postprocess_params def __call__( self , *a , **a) -> Optional[int]: SCREAMING_SNAKE_CASE = super().__call__(*a , **a) # TODO try and retrieve it in a nicer way from _sanitize_parameters. SCREAMING_SNAKE_CASE = 'top_k' not in kwargs if isinstance(args[0] , a) and _legacy: # This pipeline is odd, and return a list when single item is run return [result] else: return result def SCREAMING_SNAKE_CASE__ ( self , a , **a) -> Dict[str, GenericTensor]: SCREAMING_SNAKE_CASE = self.framework if isinstance(a , a): return self.tokenizer(**a , return_tensors=a , **a) elif isinstance(a , a) and len(a) == 1 and isinstance(inputs[0] , a) and len(inputs[0]) == 2: # It used to be valid to use a list of list of list for text pairs, keeping this path for BC return self.tokenizer( text=inputs[0][0] , text_pair=inputs[0][1] , return_tensors=a , **a) elif isinstance(a , a): # This is likely an invalid usage of the pipeline attempting to pass text pairs. raise ValueError( 'The pipeline received invalid inputs, if you are trying to send text pairs, you can try to send a' ' dictionary `{"text": "My text", "text_pair": "My pair"}` in order to send a text pair.') return self.tokenizer(a , return_tensors=a , **a) def SCREAMING_SNAKE_CASE__ ( self , a) -> Optional[Any]: return self.model(**a) def SCREAMING_SNAKE_CASE__ ( self , a , a=None , a=1 , a=True) -> Any: # `_legacy` is used to determine if we're running the naked pipeline and in backward # compatibility mode, or if running the pipeline with `pipeline(..., top_k=1)` we're running # the more natural result containing the list. # Default value before `set_parameters` if function_to_apply is None: if self.model.config.problem_type == "multi_label_classification" or self.model.config.num_labels == 1: SCREAMING_SNAKE_CASE = ClassificationFunction.SIGMOID elif self.model.config.problem_type == "single_label_classification" or self.model.config.num_labels > 1: SCREAMING_SNAKE_CASE = ClassificationFunction.SOFTMAX elif hasattr(self.model.config , 'function_to_apply') and function_to_apply is None: SCREAMING_SNAKE_CASE = self.model.config.function_to_apply else: SCREAMING_SNAKE_CASE = ClassificationFunction.NONE SCREAMING_SNAKE_CASE = model_outputs['logits'][0] SCREAMING_SNAKE_CASE = outputs.numpy() if function_to_apply == ClassificationFunction.SIGMOID: SCREAMING_SNAKE_CASE = sigmoid(a) elif function_to_apply == ClassificationFunction.SOFTMAX: SCREAMING_SNAKE_CASE = softmax(a) elif function_to_apply == ClassificationFunction.NONE: SCREAMING_SNAKE_CASE = outputs else: raise ValueError(f'''Unrecognized `function_to_apply` argument: {function_to_apply}''') if top_k == 1 and _legacy: return {"label": self.model.config.idalabel[scores.argmax().item()], "score": scores.max().item()} SCREAMING_SNAKE_CASE = [ {'label': self.model.config.idalabel[i], 'score': score.item()} for i, score in enumerate(a) ] if not _legacy: dict_scores.sort(key=lambda a: x["score"] , reverse=a) if top_k is not None: SCREAMING_SNAKE_CASE = dict_scores[:top_k] return dict_scores
73
1
import os def lowerCamelCase__ (): SCREAMING_SNAKE_CASE = os.path.join(os.path.dirname(_UpperCAmelCase) , 'num.txt') with open(_UpperCAmelCase) as file_hand: return str(sum(int(_UpperCAmelCase) for line in file_hand))[:10] if __name__ == "__main__": print(solution())
73
import heapq as hq import math from collections.abc import Iterator class _snake_case : def __init__( self , a) -> Optional[Any]: SCREAMING_SNAKE_CASE = str(id_) SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = {} # {vertex:distance} def __lt__( self , a) -> Dict: return self.key < other.key def __repr__( self) -> Optional[Any]: return self.id def SCREAMING_SNAKE_CASE__ ( self , a) -> Optional[Any]: self.neighbors.append(a) def SCREAMING_SNAKE_CASE__ ( self , a , a) -> Tuple: SCREAMING_SNAKE_CASE = weight def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): # add the neighbors: graph[a - 1].add_neighbor(graph[b - 1]) graph[b - 1].add_neighbor(graph[a - 1]) # add the edges: graph[a - 1].add_edge(graph[b - 1] , _UpperCAmelCase) graph[b - 1].add_edge(graph[a - 1] , _UpperCAmelCase) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = [] for u in graph: SCREAMING_SNAKE_CASE = math.inf SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = graph[:] while q: SCREAMING_SNAKE_CASE = min(_UpperCAmelCase) q.remove(_UpperCAmelCase) for v in u.neighbors: if (v in q) and (u.edges[v.id] < v.key): SCREAMING_SNAKE_CASE = u SCREAMING_SNAKE_CASE = u.edges[v.id] for i in range(1 , len(_UpperCAmelCase)): a.append((int(graph[i].id) + 1, int(graph[i].pi.id) + 1)) return a def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): for u in graph: SCREAMING_SNAKE_CASE = math.inf SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = list(_UpperCAmelCase) hq.heapify(_UpperCAmelCase) while h: SCREAMING_SNAKE_CASE = hq.heappop(_UpperCAmelCase) for v in u.neighbors: if (v in h) and (u.edges[v.id] < v.key): SCREAMING_SNAKE_CASE = u SCREAMING_SNAKE_CASE = u.edges[v.id] hq.heapify(_UpperCAmelCase) for i in range(1 , len(_UpperCAmelCase)): yield (int(graph[i].id) + 1, int(graph[i].pi.id) + 1) def lowerCamelCase__ (): pass if __name__ == "__main__": import doctest doctest.testmod()
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 _snake_case ( A__ , unittest.TestCase ): _lowercase : Tuple = FunnelTokenizer _lowercase : Union[str, Any] = FunnelTokenizerFast _lowercase : Dict = True _lowercase : Union[str, Any] = True def SCREAMING_SNAKE_CASE__ ( self) -> Dict: super().setUp() SCREAMING_SNAKE_CASE = [ '<unk>', '<cls>', '<sep>', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing', ',', 'low', 'lowest', ] SCREAMING_SNAKE_CASE = 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 SCREAMING_SNAKE_CASE__ ( self , **a) -> List[str]: return FunnelTokenizer.from_pretrained(self.tmpdirname , **a) def SCREAMING_SNAKE_CASE__ ( self , **a) -> int: return FunnelTokenizerFast.from_pretrained(self.tmpdirname , **a) def SCREAMING_SNAKE_CASE__ ( self , a) -> Optional[Any]: SCREAMING_SNAKE_CASE = 'UNwant\u00E9d,running' SCREAMING_SNAKE_CASE = 'unwanted, running' return input_text, output_text def SCREAMING_SNAKE_CASE__ ( self) -> Any: SCREAMING_SNAKE_CASE = self.tokenizer_class(self.vocab_file) SCREAMING_SNAKE_CASE = tokenizer.tokenize('UNwant\u00E9d,running') self.assertListEqual(a , ['un', '##want', '##ed', ',', 'runn', '##ing']) self.assertListEqual(tokenizer.convert_tokens_to_ids(a) , [7, 4, 5, 10, 8, 9]) def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: SCREAMING_SNAKE_CASE = self.get_tokenizers(do_lower_case=a) for tokenizer in tokenizers: SCREAMING_SNAKE_CASE = tokenizer('UNwant\u00E9d,running') SCREAMING_SNAKE_CASE = len(inputs['input_ids']) - 1 self.assertListEqual(inputs['token_type_ids'] , [2] + [0] * sentence_len) SCREAMING_SNAKE_CASE = tokenizer('UNwant\u00E9d,running' , 'UNwant\u00E9d,running') self.assertListEqual(inputs['token_type_ids'] , [2] + [0] * sentence_len + [1] * sentence_len)
73
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available a_ : Optional[Any] = { 'configuration_mask2former': [ 'MASK2FORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'Mask2FormerConfig', ], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : Union[str, Any] = ['Mask2FormerImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : List[Any] = [ 'MASK2FORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'Mask2FormerForUniversalSegmentation', 'Mask2FormerModel', 'Mask2FormerPreTrainedModel', ] if TYPE_CHECKING: from .configuration_maskaformer import MASK2FORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, MaskaFormerConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_maskaformer import MaskaFormerImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_maskaformer import ( MASK2FORMER_PRETRAINED_MODEL_ARCHIVE_LIST, MaskaFormerForUniversalSegmentation, MaskaFormerModel, MaskaFormerPreTrainedModel, ) else: import sys a_ : str = _LazyModule(__name__, globals()['__file__'], _import_structure)
73
1
def lowerCamelCase__ (_UpperCAmelCase = "The quick brown fox jumps over the lazy dog" , ): SCREAMING_SNAKE_CASE = set() # Replace all the whitespace in our sentence SCREAMING_SNAKE_CASE = input_str.replace(' ' , '') for alpha in input_str: if "a" <= alpha.lower() <= "z": frequency.add(alpha.lower()) return len(_UpperCAmelCase) == 26 def lowerCamelCase__ (_UpperCAmelCase = "The quick brown fox jumps over the lazy dog" , ): SCREAMING_SNAKE_CASE = [False] * 26 for char in input_str: if char.islower(): SCREAMING_SNAKE_CASE = True elif char.isupper(): SCREAMING_SNAKE_CASE = True return all(_UpperCAmelCase) def lowerCamelCase__ (_UpperCAmelCase = "The quick brown fox jumps over the lazy dog" , ): return len({char for char in input_str.lower() if char.isalpha()}) == 26 def lowerCamelCase__ (): from timeit import timeit SCREAMING_SNAKE_CASE = 'from __main__ import is_pangram, is_pangram_faster, is_pangram_fastest' print(timeit('is_pangram()' , setup=_UpperCAmelCase)) print(timeit('is_pangram_faster()' , setup=_UpperCAmelCase)) print(timeit('is_pangram_fastest()' , setup=_UpperCAmelCase)) # 5.348480500048026, 2.6477354579837993, 1.8470395830227062 # 5.036091582966037, 2.644472333951853, 1.8869528750656173 if __name__ == "__main__": import doctest doctest.testmod() benchmark()
73
from ...configuration_utils import PretrainedConfig from ...utils import logging a_ : Dict = logging.get_logger(__name__) a_ : Union[str, Any] = { 'edbeeching/decision-transformer-gym-hopper-medium': ( 'https://huggingface.co/edbeeching/decision-transformer-gym-hopper-medium/resolve/main/config.json' ), # See all DecisionTransformer models at https://huggingface.co/models?filter=decision_transformer } class _snake_case ( A__ ): _lowercase : Optional[Any] = '''decision_transformer''' _lowercase : str = ['''past_key_values'''] _lowercase : Union[str, Any] = { '''max_position_embeddings''': '''n_positions''', '''num_attention_heads''': '''n_head''', '''num_hidden_layers''': '''n_layer''', } def __init__( self , a=17 , a=4 , a=128 , a=4096 , a=True , a=1 , a=1024 , a=3 , a=1 , a=None , a="relu" , a=0.1 , a=0.1 , a=0.1 , a=1E-5 , a=0.02 , a=True , a=True , a=5_0256 , a=5_0256 , a=False , a=False , **a , ) -> List[str]: SCREAMING_SNAKE_CASE = state_dim SCREAMING_SNAKE_CASE = act_dim SCREAMING_SNAKE_CASE = hidden_size SCREAMING_SNAKE_CASE = max_ep_len SCREAMING_SNAKE_CASE = action_tanh SCREAMING_SNAKE_CASE = vocab_size SCREAMING_SNAKE_CASE = n_positions SCREAMING_SNAKE_CASE = n_layer SCREAMING_SNAKE_CASE = n_head SCREAMING_SNAKE_CASE = n_inner SCREAMING_SNAKE_CASE = activation_function SCREAMING_SNAKE_CASE = resid_pdrop SCREAMING_SNAKE_CASE = embd_pdrop SCREAMING_SNAKE_CASE = attn_pdrop SCREAMING_SNAKE_CASE = layer_norm_epsilon SCREAMING_SNAKE_CASE = initializer_range SCREAMING_SNAKE_CASE = scale_attn_weights SCREAMING_SNAKE_CASE = use_cache SCREAMING_SNAKE_CASE = scale_attn_by_inverse_layer_idx SCREAMING_SNAKE_CASE = reorder_and_upcast_attn SCREAMING_SNAKE_CASE = bos_token_id SCREAMING_SNAKE_CASE = eos_token_id super().__init__(bos_token_id=a , eos_token_id=a , **a)
73
1
def lowerCamelCase__ (_UpperCAmelCase): if not numbers: return 0 if not isinstance(_UpperCAmelCase , (list, tuple)) or not all( isinstance(_UpperCAmelCase , _UpperCAmelCase) for number in numbers): raise ValueError('numbers must be an iterable of integers') SCREAMING_SNAKE_CASE = SCREAMING_SNAKE_CASE = SCREAMING_SNAKE_CASE = numbers[0] for i in range(1 , len(_UpperCAmelCase)): # update the maximum and minimum subarray products SCREAMING_SNAKE_CASE = numbers[i] if number < 0: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = min_till_now, max_till_now SCREAMING_SNAKE_CASE = max(_UpperCAmelCase , max_till_now * number) SCREAMING_SNAKE_CASE = min(_UpperCAmelCase , min_till_now * number) # update the maximum product found till now SCREAMING_SNAKE_CASE = max(_UpperCAmelCase , _UpperCAmelCase) return max_prod
73
import argparse import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType ######################################################################## # This is a fully working simple example to use Accelerate # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## a_ : Optional[int] = 16 a_ : Any = 32 def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase = 16): SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained('bert-base-cased') SCREAMING_SNAKE_CASE = load_dataset('glue' , 'mrpc') def tokenize_function(_UpperCAmelCase): # max_length=None => use the model max length (it's actually the default) SCREAMING_SNAKE_CASE = tokenizer(examples['sentence1'] , examples['sentence2'] , truncation=_UpperCAmelCase , max_length=_UpperCAmelCase) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): SCREAMING_SNAKE_CASE = datasets.map( _UpperCAmelCase , batched=_UpperCAmelCase , remove_columns=['idx', 'sentence1', 'sentence2'] , ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library SCREAMING_SNAKE_CASE = tokenized_datasets.rename_column('label' , 'labels') def collate_fn(_UpperCAmelCase): # On TPU it's best to pad everything to the same length or training will be very slow. SCREAMING_SNAKE_CASE = 128 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": SCREAMING_SNAKE_CASE = 16 elif accelerator.mixed_precision != "no": SCREAMING_SNAKE_CASE = 8 else: SCREAMING_SNAKE_CASE = None return tokenizer.pad( _UpperCAmelCase , padding='longest' , max_length=_UpperCAmelCase , pad_to_multiple_of=_UpperCAmelCase , return_tensors='pt' , ) # Instantiate dataloaders. SCREAMING_SNAKE_CASE = DataLoader( tokenized_datasets['train'] , shuffle=_UpperCAmelCase , collate_fn=_UpperCAmelCase , batch_size=_UpperCAmelCase , drop_last=_UpperCAmelCase) SCREAMING_SNAKE_CASE = DataLoader( tokenized_datasets['validation'] , shuffle=_UpperCAmelCase , collate_fn=_UpperCAmelCase , batch_size=_UpperCAmelCase , drop_last=(accelerator.mixed_precision == 'fp8') , ) return train_dataloader, eval_dataloader def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): # Initialize accelerator SCREAMING_SNAKE_CASE = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs SCREAMING_SNAKE_CASE = config['lr'] SCREAMING_SNAKE_CASE = int(config['num_epochs']) SCREAMING_SNAKE_CASE = int(config['seed']) SCREAMING_SNAKE_CASE = int(config['batch_size']) SCREAMING_SNAKE_CASE = evaluate.load('glue' , 'mrpc') # If the batch size is too big we use gradient accumulation SCREAMING_SNAKE_CASE = 1 if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU: SCREAMING_SNAKE_CASE = batch_size // MAX_GPU_BATCH_SIZE SCREAMING_SNAKE_CASE = MAX_GPU_BATCH_SIZE set_seed(_UpperCAmelCase) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = get_dataloaders(_UpperCAmelCase , _UpperCAmelCase) # Instantiate the model (we build the model here so that the seed also control new weights initialization) SCREAMING_SNAKE_CASE = AutoModelForSequenceClassification.from_pretrained('bert-base-cased' , return_dict=_UpperCAmelCase) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). SCREAMING_SNAKE_CASE = model.to(accelerator.device) # Instantiate optimizer SCREAMING_SNAKE_CASE = AdamW(params=model.parameters() , lr=_UpperCAmelCase) # Instantiate scheduler SCREAMING_SNAKE_CASE = get_linear_schedule_with_warmup( optimizer=_UpperCAmelCase , num_warmup_steps=100 , num_training_steps=(len(_UpperCAmelCase) * num_epochs) // gradient_accumulation_steps , ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = accelerator.prepare( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) # Now we train the model for epoch in range(_UpperCAmelCase): model.train() for step, batch in enumerate(_UpperCAmelCase): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device) SCREAMING_SNAKE_CASE = model(**_UpperCAmelCase) SCREAMING_SNAKE_CASE = outputs.loss SCREAMING_SNAKE_CASE = loss / gradient_accumulation_steps accelerator.backward(_UpperCAmelCase) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(_UpperCAmelCase): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device) with torch.no_grad(): SCREAMING_SNAKE_CASE = model(**_UpperCAmelCase) SCREAMING_SNAKE_CASE = outputs.logits.argmax(dim=-1) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = accelerator.gather_for_metrics((predictions, batch['labels'])) metric.add_batch( predictions=_UpperCAmelCase , references=_UpperCAmelCase , ) SCREAMING_SNAKE_CASE = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F'''epoch {epoch}:''' , _UpperCAmelCase) def lowerCamelCase__ (): SCREAMING_SNAKE_CASE = argparse.ArgumentParser(description='Simple example of training script.') parser.add_argument( '--mixed_precision' , type=_UpperCAmelCase , default=_UpperCAmelCase , choices=['no', 'fp16', 'bf16', 'fp8'] , help='Whether to use mixed precision. Choose' 'between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.' 'and an Nvidia Ampere GPU.' , ) parser.add_argument('--cpu' , action='store_true' , help='If passed, will train on the CPU.') SCREAMING_SNAKE_CASE = parser.parse_args() SCREAMING_SNAKE_CASE = {'lr': 2e-5, 'num_epochs': 3, 'seed': 42, 'batch_size': 16} training_function(_UpperCAmelCase , _UpperCAmelCase) if __name__ == "__main__": main()
73
1
import os from distutils.util import strtobool def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): for e in env_keys: SCREAMING_SNAKE_CASE = int(os.environ.get(_UpperCAmelCase , -1)) if val >= 0: return val return default def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase=False): SCREAMING_SNAKE_CASE = os.environ.get(_UpperCAmelCase , str(_UpperCAmelCase)) return strtobool(_UpperCAmelCase) == 1 # As its name indicates `strtobool` actually returns an int... def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase="no"): SCREAMING_SNAKE_CASE = os.environ.get(_UpperCAmelCase , str(_UpperCAmelCase)) return value
73
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available a_ : int = { 'configuration_rag': ['RagConfig'], 'retrieval_rag': ['RagRetriever'], 'tokenization_rag': ['RagTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : List[Any] = [ 'RagModel', 'RagPreTrainedModel', 'RagSequenceForGeneration', 'RagTokenForGeneration', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : Tuple = [ 'TFRagModel', 'TFRagPreTrainedModel', 'TFRagSequenceForGeneration', 'TFRagTokenForGeneration', ] if TYPE_CHECKING: from .configuration_rag import RagConfig from .retrieval_rag import RagRetriever from .tokenization_rag import RagTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_rag import RagModel, RagPreTrainedModel, RagSequenceForGeneration, RagTokenForGeneration try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_rag import ( TFRagModel, TFRagPreTrainedModel, TFRagSequenceForGeneration, TFRagTokenForGeneration, ) else: import sys a_ : Union[str, Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
73
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available a_ : List[str] = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : Optional[Any] = ['GPTSw3Tokenizer'] if TYPE_CHECKING: try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_gpt_swa import GPTSwaTokenizer else: import sys a_ : Tuple = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
73
from __future__ import annotations from numpy import array, cos, cross, floataa, radians, sin from numpy.typing import NDArray def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase = False): if radian_mode: return [magnitude * cos(_UpperCAmelCase), magnitude * sin(_UpperCAmelCase)] return [magnitude * cos(radians(_UpperCAmelCase)), magnitude * sin(radians(_UpperCAmelCase))] def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase = 10**-1): SCREAMING_SNAKE_CASE = cross(_UpperCAmelCase , _UpperCAmelCase) SCREAMING_SNAKE_CASE = sum(_UpperCAmelCase) return abs(_UpperCAmelCase) < eps if __name__ == "__main__": # Test to check if it works a_ : int = array( [ polar_force(718.4, 1_80 - 30), polar_force(879.54, 45), polar_force(1_00, -90), ] ) a_ : NDArray[floataa] = array([[0, 0], [0, 0], [0, 0]]) assert in_static_equilibrium(forces, location) # Problem 1 in image_data/2D_problems.jpg a_ : Dict = array( [ polar_force(30 * 9.81, 15), polar_force(2_15, 1_80 - 45), polar_force(2_64, 90 - 30), ] ) a_ : Any = array([[0, 0], [0, 0], [0, 0]]) assert in_static_equilibrium(forces, location) # Problem in image_data/2D_problems_1.jpg a_ : int = array([[0, -20_00], [0, -12_00], [0, 1_56_00], [0, -1_24_00]]) a_ : Optional[Any] = array([[0, 0], [6, 0], [10, 0], [12, 0]]) assert in_static_equilibrium(forces, location) import doctest doctest.testmod()
73
1
import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch if is_torch_available(): import torch from transformers.generation import DisjunctiveConstraint @require_torch class _snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ ( self) -> Dict: # For consistency across different places the DisjunctiveConstraint is called, # dc.token_ids is a list of integers. It is also initialized only by integers. SCREAMING_SNAKE_CASE = [[1, 2, 4], [1, 2, 3, 4]] SCREAMING_SNAKE_CASE = DisjunctiveConstraint(a) self.assertTrue(isinstance(dc.token_ids , a)) with self.assertRaises(a): DisjunctiveConstraint(torch.LongTensor([[1, 2, 4], [1, 2, 3]])) with self.assertRaises(a): DisjunctiveConstraint([torch.LongTensor([1, 2, 4]), torch.LongTensor([1, 2, 3, 4, 5])]) def SCREAMING_SNAKE_CASE__ ( self) -> int: # We can't have constraints that are complete subsets of another. This leads to a preverse # interpretation of "constraint fulfillment": does generating [1,2,3] fulfill the constraint? # It would mean that it generated [1,2] which fulfills it, but it's in the middle of potentially # fulfilling [1,2,3,4]. If we believe that [1,2,3] does fulfill the constraint, then the algorithm # will necessarily never reach [1,2,3,4], giving users a false sense of control (better to just not allow it). SCREAMING_SNAKE_CASE = [[1, 2], [1, 2, 3, 4]] with self.assertRaises(a): DisjunctiveConstraint(a) # fails here def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: SCREAMING_SNAKE_CASE = [[1, 2, 3], [1, 2, 4]] SCREAMING_SNAKE_CASE = DisjunctiveConstraint(a) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = dc.update(1) SCREAMING_SNAKE_CASE = stepped is True and completed is False and reset is False self.assertTrue(a) self.assertTrue(not dc.completed) self.assertTrue(dc.current_seq == [1]) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = dc.update(2) SCREAMING_SNAKE_CASE = stepped is True and completed is False and reset is False self.assertTrue(a) self.assertTrue(not dc.completed) self.assertTrue(dc.current_seq == [1, 2]) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = dc.update(3) SCREAMING_SNAKE_CASE = stepped is True and completed is True and reset is False self.assertTrue(a) self.assertTrue(dc.completed) # Completed! self.assertTrue(dc.current_seq == [1, 2, 3]) def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: SCREAMING_SNAKE_CASE = [[1, 2, 3], [1, 2, 4, 5], [1, 2, 5]] SCREAMING_SNAKE_CASE = DisjunctiveConstraint(a) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = dc.update(1) self.assertTrue(not dc.completed) self.assertTrue(dc.current_seq == [1]) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = dc.update(2) self.assertTrue(not dc.completed) self.assertTrue(dc.current_seq == [1, 2]) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = dc.update(4) self.assertTrue(not dc.completed) self.assertTrue(dc.current_seq == [1, 2, 4]) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = dc.update(5) self.assertTrue(dc.completed) # Completed! self.assertTrue(dc.current_seq == [1, 2, 4, 5]) dc.reset() SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = dc.update(1) self.assertTrue(not dc.completed) self.assertTrue(dc.remaining() == 3) self.assertTrue(dc.current_seq == [1]) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = dc.update(2) self.assertTrue(not dc.completed) self.assertTrue(dc.remaining() == 2) self.assertTrue(dc.current_seq == [1, 2]) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = dc.update(5) self.assertTrue(dc.completed) # Completed! self.assertTrue(dc.remaining() == 0) self.assertTrue(dc.current_seq == [1, 2, 5])
73
from ...configuration_utils import PretrainedConfig from ...utils import logging a_ : Optional[int] = logging.get_logger(__name__) a_ : int = { 'microsoft/cvt-13': 'https://huggingface.co/microsoft/cvt-13/resolve/main/config.json', # See all Cvt models at https://huggingface.co/models?filter=cvt } class _snake_case ( A__ ): _lowercase : Dict = '''cvt''' def __init__( self , a=3 , a=[7, 3, 3] , a=[4, 2, 2] , a=[2, 1, 1] , a=[64, 192, 384] , a=[1, 3, 6] , a=[1, 2, 10] , a=[4.0, 4.0, 4.0] , a=[0.0, 0.0, 0.0] , a=[0.0, 0.0, 0.0] , a=[0.0, 0.0, 0.1] , a=[True, True, True] , a=[False, False, True] , a=["dw_bn", "dw_bn", "dw_bn"] , a=[3, 3, 3] , a=[1, 1, 1] , a=[2, 2, 2] , a=[1, 1, 1] , a=[1, 1, 1] , a=0.02 , a=1E-12 , **a , ) -> List[Any]: super().__init__(**a) SCREAMING_SNAKE_CASE = num_channels SCREAMING_SNAKE_CASE = patch_sizes SCREAMING_SNAKE_CASE = patch_stride SCREAMING_SNAKE_CASE = patch_padding SCREAMING_SNAKE_CASE = embed_dim SCREAMING_SNAKE_CASE = num_heads SCREAMING_SNAKE_CASE = depth SCREAMING_SNAKE_CASE = mlp_ratio SCREAMING_SNAKE_CASE = attention_drop_rate SCREAMING_SNAKE_CASE = drop_rate SCREAMING_SNAKE_CASE = drop_path_rate SCREAMING_SNAKE_CASE = qkv_bias SCREAMING_SNAKE_CASE = cls_token SCREAMING_SNAKE_CASE = qkv_projection_method SCREAMING_SNAKE_CASE = kernel_qkv SCREAMING_SNAKE_CASE = padding_kv SCREAMING_SNAKE_CASE = stride_kv SCREAMING_SNAKE_CASE = padding_q SCREAMING_SNAKE_CASE = stride_q SCREAMING_SNAKE_CASE = initializer_range SCREAMING_SNAKE_CASE = layer_norm_eps
73
1
import re def lowerCamelCase__ (_UpperCAmelCase): return [char.split() for char in re.split(R'[^ a-z A-Z 0-9 \s]' , str_)] def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = split_input(str_) return "".join( [''.join([char.capitalize() for char in sub_str]) for sub_str in string_split]) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): try: SCREAMING_SNAKE_CASE = split_input(_UpperCAmelCase) if upper: SCREAMING_SNAKE_CASE = ''.join( [ separator.join([char.upper() for char in sub_str]) for sub_str in string_split ]) else: SCREAMING_SNAKE_CASE = ''.join( [ separator.join([char.lower() for char in sub_str]) for sub_str in string_split ]) return res_str except IndexError: return "not valid string" def lowerCamelCase__ (_UpperCAmelCase): return to_simple_case(_UpperCAmelCase) def lowerCamelCase__ (_UpperCAmelCase): try: SCREAMING_SNAKE_CASE = to_simple_case(_UpperCAmelCase) return res_str[0].lower() + res_str[1:] except IndexError: return "not valid string" def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): return to_complex_case(_UpperCAmelCase , _UpperCAmelCase , '_') def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): return to_complex_case(_UpperCAmelCase , _UpperCAmelCase , '-') if __name__ == "__main__": __import__('doctest').testmod()
73
def lowerCamelCase__ (_UpperCAmelCase = 10 , _UpperCAmelCase = 1000 , _UpperCAmelCase = True): assert ( isinstance(_UpperCAmelCase , _UpperCAmelCase) and isinstance(_UpperCAmelCase , _UpperCAmelCase) and isinstance(_UpperCAmelCase , _UpperCAmelCase) ), "Invalid type of value(s) specified to function!" if min_val > max_val: raise ValueError('Invalid value for min_val or max_val (min_value < max_value)') return min_val if option else max_val def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): return int((number_a + number_a) / 2) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): assert ( isinstance(_UpperCAmelCase , _UpperCAmelCase) and isinstance(_UpperCAmelCase , _UpperCAmelCase) and isinstance(_UpperCAmelCase , _UpperCAmelCase) ), 'argument values must be type of "int"' if lower > higher: raise ValueError('argument value for lower and higher must be(lower > higher)') if not lower < to_guess < higher: raise ValueError( 'guess value must be within the range of lower and higher value') def answer(_UpperCAmelCase) -> str: if number > to_guess: return "high" elif number < to_guess: return "low" else: return "same" print('started...') SCREAMING_SNAKE_CASE = lower SCREAMING_SNAKE_CASE = higher SCREAMING_SNAKE_CASE = [] while True: SCREAMING_SNAKE_CASE = get_avg(_UpperCAmelCase , _UpperCAmelCase) last_numbers.append(_UpperCAmelCase) if answer(_UpperCAmelCase) == "low": SCREAMING_SNAKE_CASE = number elif answer(_UpperCAmelCase) == "high": SCREAMING_SNAKE_CASE = number else: break print(F'''guess the number : {last_numbers[-1]}''') print(F'''details : {last_numbers!s}''') def lowerCamelCase__ (): SCREAMING_SNAKE_CASE = int(input('Enter lower value : ').strip()) SCREAMING_SNAKE_CASE = int(input('Enter high value : ').strip()) SCREAMING_SNAKE_CASE = int(input('Enter value to guess : ').strip()) guess_the_number(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) if __name__ == "__main__": main()
73
1
import math import flax.linen as nn import jax.numpy as jnp def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase = 1 , _UpperCAmelCase = 1 , _UpperCAmelCase = 1.0e4 , _UpperCAmelCase = False , _UpperCAmelCase = 1.0 , ): assert timesteps.ndim == 1, "Timesteps should be a 1d-array" assert embedding_dim % 2 == 0, F'''Embedding dimension {embedding_dim} should be even''' SCREAMING_SNAKE_CASE = float(embedding_dim // 2) SCREAMING_SNAKE_CASE = math.log(max_timescale / min_timescale) / (num_timescales - freq_shift) SCREAMING_SNAKE_CASE = min_timescale * jnp.exp(jnp.arange(_UpperCAmelCase , dtype=jnp.floataa) * -log_timescale_increment) SCREAMING_SNAKE_CASE = jnp.expand_dims(_UpperCAmelCase , 1) * jnp.expand_dims(_UpperCAmelCase , 0) # scale embeddings SCREAMING_SNAKE_CASE = scale * emb if flip_sin_to_cos: SCREAMING_SNAKE_CASE = jnp.concatenate([jnp.cos(_UpperCAmelCase), jnp.sin(_UpperCAmelCase)] , axis=1) else: SCREAMING_SNAKE_CASE = jnp.concatenate([jnp.sin(_UpperCAmelCase), jnp.cos(_UpperCAmelCase)] , axis=1) SCREAMING_SNAKE_CASE = jnp.reshape(_UpperCAmelCase , [jnp.shape(_UpperCAmelCase)[0], embedding_dim]) return signal class _snake_case ( nn.Module ): _lowercase : int = 32 _lowercase : jnp.dtype = jnp.floataa @nn.compact def __call__( self , a) -> int: SCREAMING_SNAKE_CASE = nn.Dense(self.time_embed_dim , dtype=self.dtype , name='linear_1')(a) SCREAMING_SNAKE_CASE = nn.silu(a) SCREAMING_SNAKE_CASE = nn.Dense(self.time_embed_dim , dtype=self.dtype , name='linear_2')(a) return temb class _snake_case ( nn.Module ): _lowercase : int = 32 _lowercase : bool = False _lowercase : float = 1 @nn.compact def __call__( self , a) -> str: return get_sinusoidal_embeddings( a , embedding_dim=self.dim , flip_sin_to_cos=self.flip_sin_to_cos , freq_shift=self.freq_shift)
73
import unittest from parameterized import parameterized from transformers import OpenLlamaConfig, is_torch_available, set_seed from transformers.testing_utils import require_torch, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import OpenLlamaForCausalLM, OpenLlamaForSequenceClassification, OpenLlamaModel class _snake_case : def __init__( self , a , a=13 , a=7 , a=True , a=True , a=False , a=True , a=99 , a=32 , a=5 , a=4 , a=37 , a="gelu" , a=0.1 , a=0.1 , a=512 , a=16 , a=2 , a=0.02 , a=3 , a=4 , a=None , ) -> Union[str, Any]: SCREAMING_SNAKE_CASE = parent SCREAMING_SNAKE_CASE = batch_size SCREAMING_SNAKE_CASE = seq_length SCREAMING_SNAKE_CASE = is_training SCREAMING_SNAKE_CASE = use_input_mask SCREAMING_SNAKE_CASE = use_token_type_ids SCREAMING_SNAKE_CASE = use_labels SCREAMING_SNAKE_CASE = vocab_size SCREAMING_SNAKE_CASE = hidden_size SCREAMING_SNAKE_CASE = num_hidden_layers SCREAMING_SNAKE_CASE = num_attention_heads SCREAMING_SNAKE_CASE = intermediate_size SCREAMING_SNAKE_CASE = hidden_act SCREAMING_SNAKE_CASE = hidden_dropout_prob SCREAMING_SNAKE_CASE = attention_probs_dropout_prob SCREAMING_SNAKE_CASE = max_position_embeddings SCREAMING_SNAKE_CASE = type_vocab_size SCREAMING_SNAKE_CASE = type_sequence_label_size SCREAMING_SNAKE_CASE = initializer_range SCREAMING_SNAKE_CASE = num_labels SCREAMING_SNAKE_CASE = num_choices SCREAMING_SNAKE_CASE = scope def SCREAMING_SNAKE_CASE__ ( self) -> Dict: SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size) SCREAMING_SNAKE_CASE = None if self.use_input_mask: SCREAMING_SNAKE_CASE = random_attention_mask([self.batch_size, self.seq_length]) SCREAMING_SNAKE_CASE = None if self.use_token_type_ids: SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size) SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = None if self.use_labels: SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.type_sequence_label_size) SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.num_labels) SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.num_choices) SCREAMING_SNAKE_CASE = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: return OpenLlamaConfig( 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 , is_decoder=a , initializer_range=self.initializer_range , use_stable_embedding=a , ) def SCREAMING_SNAKE_CASE__ ( self , a , a , a , a , a , a , a) -> Any: SCREAMING_SNAKE_CASE = OpenLlamaModel(config=a) model.to(a) model.eval() SCREAMING_SNAKE_CASE = model(a , attention_mask=a) SCREAMING_SNAKE_CASE = model(a) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size)) def SCREAMING_SNAKE_CASE__ ( self , a , a , a , a , a , a , a , a , a , ) -> str: SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = OpenLlamaModel(a) model.to(a) model.eval() SCREAMING_SNAKE_CASE = model( a , attention_mask=a , encoder_hidden_states=a , encoder_attention_mask=a , ) SCREAMING_SNAKE_CASE = model( a , attention_mask=a , encoder_hidden_states=a , ) SCREAMING_SNAKE_CASE = model(a , attention_mask=a) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size)) def SCREAMING_SNAKE_CASE__ ( self , a , a , a , a , a , a , a , a , a , ) -> int: SCREAMING_SNAKE_CASE = OpenLlamaForCausalLM(config=a) model.to(a) model.eval() SCREAMING_SNAKE_CASE = model(a , attention_mask=a , labels=a) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size)) def SCREAMING_SNAKE_CASE__ ( self , a , a , a , a , a , a , a , a , a , ) -> str: SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = OpenLlamaForCausalLM(config=a) model.to(a) model.eval() # first forward pass SCREAMING_SNAKE_CASE = model( a , attention_mask=a , encoder_hidden_states=a , encoder_attention_mask=a , use_cache=a , ) SCREAMING_SNAKE_CASE = outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids SCREAMING_SNAKE_CASE = ids_tensor((self.batch_size, 3) , config.vocab_size) SCREAMING_SNAKE_CASE = ids_tensor((self.batch_size, 3) , vocab_size=2) # append to next input_ids and SCREAMING_SNAKE_CASE = torch.cat([input_ids, next_tokens] , dim=-1) SCREAMING_SNAKE_CASE = torch.cat([input_mask, next_mask] , dim=-1) SCREAMING_SNAKE_CASE = model( a , attention_mask=a , encoder_hidden_states=a , encoder_attention_mask=a , output_hidden_states=a , )['hidden_states'][0] SCREAMING_SNAKE_CASE = model( a , attention_mask=a , encoder_hidden_states=a , encoder_attention_mask=a , past_key_values=a , output_hidden_states=a , )['hidden_states'][0] # select random slice SCREAMING_SNAKE_CASE = ids_tensor((1,) , output_from_past.shape[-1]).item() SCREAMING_SNAKE_CASE = output_from_no_past[:, -3:, random_slice_idx].detach() SCREAMING_SNAKE_CASE = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1]) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(a , a , atol=1E-3)) def SCREAMING_SNAKE_CASE__ ( self) -> str: SCREAMING_SNAKE_CASE = self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ) = config_and_inputs SCREAMING_SNAKE_CASE = {'input_ids': input_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class _snake_case ( A__ , A__ , A__ , unittest.TestCase ): _lowercase : List[Any] = ( (OpenLlamaModel, OpenLlamaForCausalLM, OpenLlamaForSequenceClassification) if is_torch_available() else () ) _lowercase : str = (OpenLlamaForCausalLM,) if is_torch_available() else () _lowercase : List[str] = ( { '''feature-extraction''': OpenLlamaModel, '''text-classification''': OpenLlamaForSequenceClassification, '''text-generation''': OpenLlamaForCausalLM, '''zero-shot''': OpenLlamaForSequenceClassification, } if is_torch_available() else {} ) _lowercase : List[str] = False _lowercase : Optional[int] = False def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: SCREAMING_SNAKE_CASE = OpenLlamaModelTester(self) SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=a , hidden_size=37) def SCREAMING_SNAKE_CASE__ ( self) -> str: self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE__ ( self) -> Any: SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a) def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: SCREAMING_SNAKE_CASE = type self.model_tester.create_and_check_model(*a) def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE = 3 SCREAMING_SNAKE_CASE = input_dict['input_ids'] SCREAMING_SNAKE_CASE = input_ids.ne(1).to(a) SCREAMING_SNAKE_CASE = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size) SCREAMING_SNAKE_CASE = OpenLlamaForSequenceClassification(a) model.to(a) model.eval() SCREAMING_SNAKE_CASE = model(a , attention_mask=a , labels=a) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels)) def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE = 3 SCREAMING_SNAKE_CASE = 'single_label_classification' SCREAMING_SNAKE_CASE = input_dict['input_ids'] SCREAMING_SNAKE_CASE = input_ids.ne(1).to(a) SCREAMING_SNAKE_CASE = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size) SCREAMING_SNAKE_CASE = OpenLlamaForSequenceClassification(a) model.to(a) model.eval() SCREAMING_SNAKE_CASE = model(a , attention_mask=a , labels=a) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels)) def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE = 3 SCREAMING_SNAKE_CASE = 'multi_label_classification' SCREAMING_SNAKE_CASE = input_dict['input_ids'] SCREAMING_SNAKE_CASE = input_ids.ne(1).to(a) SCREAMING_SNAKE_CASE = ids_tensor( [self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size).to(torch.float) SCREAMING_SNAKE_CASE = OpenLlamaForSequenceClassification(a) model.to(a) model.eval() SCREAMING_SNAKE_CASE = model(a , attention_mask=a , labels=a) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels)) @unittest.skip('Open-Llama buffers include complex numbers, which breaks this test') def SCREAMING_SNAKE_CASE__ ( self) -> Any: pass @parameterized.expand([('linear',), ('dynamic',)]) def SCREAMING_SNAKE_CASE__ ( self , a) -> Dict: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE = ids_tensor([1, 10] , config.vocab_size) SCREAMING_SNAKE_CASE = ids_tensor([1, int(config.max_position_embeddings * 1.5)] , config.vocab_size) set_seed(42) # Fixed seed at init time so the two models get the same random weights SCREAMING_SNAKE_CASE = OpenLlamaModel(a) original_model.to(a) original_model.eval() SCREAMING_SNAKE_CASE = original_model(a).last_hidden_state SCREAMING_SNAKE_CASE = original_model(a).last_hidden_state set_seed(42) # Fixed seed at init time so the two models get the same random weights SCREAMING_SNAKE_CASE = {'type': scaling_type, 'factor': 10.0} SCREAMING_SNAKE_CASE = OpenLlamaModel(a) scaled_model.to(a) scaled_model.eval() SCREAMING_SNAKE_CASE = scaled_model(a).last_hidden_state SCREAMING_SNAKE_CASE = scaled_model(a).last_hidden_state # Dynamic scaling does not change the RoPE embeddings until it receives an input longer than the original # maximum sequence length, so the outputs for the short input should match. if scaling_type == "dynamic": self.assertTrue(torch.allclose(a , a , atol=1E-5)) else: self.assertFalse(torch.allclose(a , a , atol=1E-5)) # The output should be different for long inputs self.assertFalse(torch.allclose(a , a , atol=1E-5))
73
1
import os import posixpath import uuid from dataclasses import dataclass from typing import TYPE_CHECKING, Iterable, List, Optional, Tuple, Union import numpy as np import pyarrow as pa import datasets from datasets.arrow_writer import ArrowWriter, ParquetWriter from datasets.config import MAX_SHARD_SIZE from datasets.filesystems import ( is_remote_filesystem, rename, ) from datasets.iterable_dataset import _BaseExamplesIterable from datasets.utils.py_utils import convert_file_size_to_int a_ : int = datasets.utils.logging.get_logger(__name__) if TYPE_CHECKING: import pyspark @dataclass class _snake_case ( datasets.BuilderConfig ): _lowercase : Optional[datasets.Features] = None def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , ): import pyspark def generate_fn(): SCREAMING_SNAKE_CASE = df.select('*' , pyspark.sql.functions.spark_partition_id().alias('part_id')) for partition_id in partition_order: SCREAMING_SNAKE_CASE = df_with_partition_id.select('*').where(F'''part_id = {partition_id}''').drop('part_id') SCREAMING_SNAKE_CASE = partition_df.collect() SCREAMING_SNAKE_CASE = 0 for row in rows: yield F'''{partition_id}_{row_id}''', row.asDict() row_id += 1 return generate_fn class _snake_case ( _BaseExamplesIterable ): def __init__( self , a , a=None , ) -> Tuple: SCREAMING_SNAKE_CASE = df SCREAMING_SNAKE_CASE = partition_order or range(self.df.rdd.getNumPartitions()) SCREAMING_SNAKE_CASE = _generate_iterable_examples(self.df , self.partition_order) def __iter__( self) -> Dict: yield from self.generate_examples_fn() def SCREAMING_SNAKE_CASE__ ( self , a) -> "SparkExamplesIterable": SCREAMING_SNAKE_CASE = list(range(self.df.rdd.getNumPartitions())) generator.shuffle(a) return SparkExamplesIterable(self.df , partition_order=a) def SCREAMING_SNAKE_CASE__ ( self , a , a) -> "SparkExamplesIterable": SCREAMING_SNAKE_CASE = self.split_shard_indices_by_worker(a , a) return SparkExamplesIterable(self.df , partition_order=a) @property def SCREAMING_SNAKE_CASE__ ( self) -> int: return len(self.partition_order) class _snake_case ( datasets.DatasetBuilder ): _lowercase : List[Any] = SparkConfig def __init__( self , a , a = None , a = None , **a , ) -> List[Any]: import pyspark SCREAMING_SNAKE_CASE = pyspark.sql.SparkSession.builder.getOrCreate() SCREAMING_SNAKE_CASE = df SCREAMING_SNAKE_CASE = working_dir super().__init__( cache_dir=a , config_name=str(self.df.semanticHash()) , **a , ) def SCREAMING_SNAKE_CASE__ ( self) -> Any: # Returns the path of the created file. def create_cache_and_write_probe(a): # makedirs with exist_ok will recursively create the directory. It will not throw an error if directories # already exist. os.makedirs(self._cache_dir , exist_ok=a) SCREAMING_SNAKE_CASE = os.path.join(self._cache_dir , 'fs_test' + uuid.uuida().hex) # Opening the file in append mode will create a new file unless it already exists, in which case it will not # change the file contents. open(a , 'a') return [probe_file] if self._spark.conf.get('spark.master' , '').startswith('local'): return # If the cluster is multi-node, make sure that the user provided a cache_dir and that it is on an NFS # accessible to the driver. # TODO: Stream batches to the driver using ArrowCollectSerializer instead of throwing an error. if self._cache_dir: SCREAMING_SNAKE_CASE = ( self._spark.sparkContext.parallelize(range(1) , 1).mapPartitions(a).collect() ) if os.path.isfile(probe[0]): return raise ValueError( 'When using Dataset.from_spark on a multi-node cluster, the driver and all workers should be able to access cache_dir') def SCREAMING_SNAKE_CASE__ ( self) -> Dict: return datasets.DatasetInfo(features=self.config.features) def SCREAMING_SNAKE_CASE__ ( self , a) -> Optional[int]: return [datasets.SplitGenerator(name=datasets.Split.TRAIN)] def SCREAMING_SNAKE_CASE__ ( self , a) -> Union[str, Any]: import pyspark def get_arrow_batch_size(a): for batch in it: yield pa.RecordBatch.from_pydict({'batch_bytes': [batch.nbytes]}) SCREAMING_SNAKE_CASE = self.df.count() SCREAMING_SNAKE_CASE = df_num_rows if df_num_rows <= 100 else 100 # Approximate the size of each row (in Arrow format) by averaging over a max-100-row sample. SCREAMING_SNAKE_CASE = ( self.df.limit(a) .repartition(1) .mapInArrow(a , 'batch_bytes: long') .agg(pyspark.sql.functions.sum('batch_bytes').alias('sample_bytes')) .collect()[0] .sample_bytes / sample_num_rows ) SCREAMING_SNAKE_CASE = approx_bytes_per_row * df_num_rows if approx_total_size > max_shard_size: # Make sure there is at least one row per partition. SCREAMING_SNAKE_CASE = min(a , int(approx_total_size / max_shard_size)) SCREAMING_SNAKE_CASE = self.df.repartition(a) def SCREAMING_SNAKE_CASE__ ( self , a , a , a , ) -> Iterable[Tuple[int, bool, Union[int, tuple]]]: import pyspark SCREAMING_SNAKE_CASE = ParquetWriter if file_format == 'parquet' else ArrowWriter SCREAMING_SNAKE_CASE = os.path.join(self._working_dir , os.path.basename(a)) if self._working_dir else fpath SCREAMING_SNAKE_CASE = file_format == 'parquet' # Define these so that we don't reference self in write_arrow, which will result in a pickling error due to # pickling the SparkContext. SCREAMING_SNAKE_CASE = self.config.features SCREAMING_SNAKE_CASE = self._writer_batch_size SCREAMING_SNAKE_CASE = self._fs.storage_options def write_arrow(a): # Within the same SparkContext, no two task attempts will share the same attempt ID. SCREAMING_SNAKE_CASE = pyspark.TaskContext().taskAttemptId() SCREAMING_SNAKE_CASE = next(a , a) if first_batch is None: # Some partitions might not receive any data. return pa.RecordBatch.from_arrays( [[task_id], [0], [0]] , names=['task_id', 'num_examples', 'num_bytes'] , ) SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = writer_class( features=a , path=working_fpath.replace('SSSSS' , f'''{shard_id:05d}''').replace('TTTTT' , f'''{task_id:05d}''') , writer_batch_size=a , storage_options=a , embed_local_files=a , ) SCREAMING_SNAKE_CASE = pa.Table.from_batches([first_batch]) writer.write_table(a) for batch in it: if max_shard_size is not None and writer._num_bytes >= max_shard_size: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = writer.finalize() writer.close() yield pa.RecordBatch.from_arrays( [[task_id], [num_examples], [num_bytes]] , names=['task_id', 'num_examples', 'num_bytes'] , ) shard_id += 1 SCREAMING_SNAKE_CASE = writer_class( features=writer._features , path=working_fpath.replace('SSSSS' , f'''{shard_id:05d}''').replace('TTTTT' , f'''{task_id:05d}''') , writer_batch_size=a , storage_options=a , embed_local_files=a , ) SCREAMING_SNAKE_CASE = pa.Table.from_batches([batch]) writer.write_table(a) if writer._num_bytes > 0: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = writer.finalize() writer.close() yield pa.RecordBatch.from_arrays( [[task_id], [num_examples], [num_bytes]] , names=['task_id', 'num_examples', 'num_bytes'] , ) if working_fpath != fpath: for file in os.listdir(os.path.dirname(a)): SCREAMING_SNAKE_CASE = os.path.join(os.path.dirname(a) , os.path.basename(a)) shutil.move(a , a) SCREAMING_SNAKE_CASE = ( self.df.mapInArrow(a , 'task_id: long, num_examples: long, num_bytes: long') .groupBy('task_id') .agg( pyspark.sql.functions.sum('num_examples').alias('total_num_examples') , pyspark.sql.functions.sum('num_bytes').alias('total_num_bytes') , pyspark.sql.functions.count('num_bytes').alias('num_shards') , pyspark.sql.functions.collect_list('num_examples').alias('shard_lengths') , ) .collect() ) for row in stats: yield row.task_id, (row.total_num_examples, row.total_num_bytes, row.num_shards, row.shard_lengths) def SCREAMING_SNAKE_CASE__ ( self , a , a = "arrow" , a = None , a = None , **a , ) -> List[str]: self._validate_cache_dir() SCREAMING_SNAKE_CASE = convert_file_size_to_int(max_shard_size or MAX_SHARD_SIZE) self._repartition_df_if_needed(a) SCREAMING_SNAKE_CASE = not is_remote_filesystem(self._fs) SCREAMING_SNAKE_CASE = os.path.join if is_local else posixpath.join SCREAMING_SNAKE_CASE = '-TTTTT-SSSSS-of-NNNNN' SCREAMING_SNAKE_CASE = f'''{self.name}-{split_generator.name}{SUFFIX}.{file_format}''' SCREAMING_SNAKE_CASE = path_join(self._output_dir , a) SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = [] for task_id, content in self._prepare_split_single(a , a , a): ( ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ) = content if num_bytes > 0: total_num_examples += num_examples total_num_bytes += num_bytes total_shards += num_shards task_id_and_num_shards.append((task_id, num_shards)) all_shard_lengths.extend(a) SCREAMING_SNAKE_CASE = total_num_examples SCREAMING_SNAKE_CASE = total_num_bytes # should rename everything at the end logger.debug(f'''Renaming {total_shards} shards.''') if total_shards > 1: SCREAMING_SNAKE_CASE = all_shard_lengths # Define fs outside of _rename_shard so that we don't reference self in the function, which will result in a # pickling error due to pickling the SparkContext. SCREAMING_SNAKE_CASE = self._fs # use the -SSSSS-of-NNNNN pattern def _rename_shard( a , a , a , ): rename( a , fpath.replace('SSSSS' , f'''{shard_id:05d}''').replace('TTTTT' , f'''{task_id:05d}''') , fpath.replace('TTTTT-SSSSS' , f'''{global_shard_id:05d}''').replace('NNNNN' , f'''{total_shards:05d}''') , ) SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = 0 for i in range(len(a)): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = task_id_and_num_shards[i] for shard_id in range(a): args.append([task_id, shard_id, global_shard_id]) global_shard_id += 1 self._spark.sparkContext.parallelize(a , len(a)).map(lambda a: _rename_shard(*a)).collect() else: # don't use any pattern SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = task_id_and_num_shards[0][0] self._rename( fpath.replace('SSSSS' , f'''{shard_id:05d}''').replace('TTTTT' , f'''{task_id:05d}''') , fpath.replace(a , '') , ) def SCREAMING_SNAKE_CASE__ ( self , a , ) -> SparkExamplesIterable: return SparkExamplesIterable(self.df)
73
from __future__ import annotations a_ : str = [] def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): for i in range(len(_UpperCAmelCase)): if board[row][i] == 1: return False for i in range(len(_UpperCAmelCase)): if board[i][column] == 1: return False for i, j in zip(range(_UpperCAmelCase , -1 , -1) , range(_UpperCAmelCase , -1 , -1)): if board[i][j] == 1: return False for i, j in zip(range(_UpperCAmelCase , -1 , -1) , range(_UpperCAmelCase , len(_UpperCAmelCase))): if board[i][j] == 1: return False return True def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): if row >= len(_UpperCAmelCase): solution.append(_UpperCAmelCase) printboard(_UpperCAmelCase) print() return True for i in range(len(_UpperCAmelCase)): if is_safe(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = 1 solve(_UpperCAmelCase , row + 1) SCREAMING_SNAKE_CASE = 0 return False def lowerCamelCase__ (_UpperCAmelCase): for i in range(len(_UpperCAmelCase)): for j in range(len(_UpperCAmelCase)): if board[i][j] == 1: print('Q' , end=' ') else: print('.' , end=' ') print() # n=int(input("The no. of queens")) a_ : Tuple = 8 a_ : int = [[0 for i in range(n)] for j in range(n)] solve(board, 0) print('The total no. of solutions are :', len(solution))
73
1
import os import re from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging a_ : str = logging.get_logger(__name__) a_ : Union[str, Any] = { 'vocab_file': 'vocab.txt', 'merges_file': 'bpe.codes', } a_ : List[str] = { 'vocab_file': { 'vinai/phobert-base': 'https://huggingface.co/vinai/phobert-base/resolve/main/vocab.txt', 'vinai/phobert-large': 'https://huggingface.co/vinai/phobert-large/resolve/main/vocab.txt', }, 'merges_file': { 'vinai/phobert-base': 'https://huggingface.co/vinai/phobert-base/resolve/main/bpe.codes', 'vinai/phobert-large': 'https://huggingface.co/vinai/phobert-large/resolve/main/bpe.codes', }, } a_ : Tuple = { 'vinai/phobert-base': 2_56, 'vinai/phobert-large': 2_56, } def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = set() SCREAMING_SNAKE_CASE = word[0] for char in word[1:]: pairs.add((prev_char, char)) SCREAMING_SNAKE_CASE = char SCREAMING_SNAKE_CASE = set(_UpperCAmelCase) return pairs class _snake_case ( A__ ): _lowercase : Optional[Any] = VOCAB_FILES_NAMES _lowercase : Tuple = PRETRAINED_VOCAB_FILES_MAP _lowercase : Union[str, Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self , a , a , a="<s>" , a="</s>" , a="</s>" , a="<s>" , a="<unk>" , a="<pad>" , a="<mask>" , **a , ) -> Dict: super().__init__( bos_token=a , eos_token=a , unk_token=a , sep_token=a , cls_token=a , pad_token=a , mask_token=a , **a , ) SCREAMING_SNAKE_CASE = vocab_file SCREAMING_SNAKE_CASE = merges_file SCREAMING_SNAKE_CASE = {} SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = 1 SCREAMING_SNAKE_CASE = 2 SCREAMING_SNAKE_CASE = 3 self.add_from_file(a) SCREAMING_SNAKE_CASE = {v: k for k, v in self.encoder.items()} with open(a , encoding='utf-8') as merges_handle: SCREAMING_SNAKE_CASE = merges_handle.read().split('\n')[:-1] SCREAMING_SNAKE_CASE = [tuple(merge.split()[:-1]) for merge in merges] SCREAMING_SNAKE_CASE = dict(zip(a , range(len(a)))) SCREAMING_SNAKE_CASE = {} def SCREAMING_SNAKE_CASE__ ( self , a , a = None) -> List[int]: if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] SCREAMING_SNAKE_CASE = [self.cls_token_id] SCREAMING_SNAKE_CASE = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def SCREAMING_SNAKE_CASE__ ( self , a , a = None , a = False) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=a , token_ids_a=a , already_has_special_tokens=a) if token_ids_a is None: return [1] + ([0] * len(a)) + [1] return [1] + ([0] * len(a)) + [1, 1] + ([0] * len(a)) + [1] def SCREAMING_SNAKE_CASE__ ( self , a , a = None) -> List[int]: SCREAMING_SNAKE_CASE = [self.sep_token_id] SCREAMING_SNAKE_CASE = [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] @property def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: return len(self.encoder) def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: return dict(self.encoder , **self.added_tokens_encoder) def SCREAMING_SNAKE_CASE__ ( self , a) -> Dict: if token in self.cache: return self.cache[token] SCREAMING_SNAKE_CASE = tuple(a) SCREAMING_SNAKE_CASE = tuple(list(word[:-1]) + [word[-1] + '</w>']) SCREAMING_SNAKE_CASE = get_pairs(a) if not pairs: return token while True: SCREAMING_SNAKE_CASE = min(a , key=lambda a: self.bpe_ranks.get(a , float('inf'))) if bigram not in self.bpe_ranks: break SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = bigram SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = 0 while i < len(a): try: SCREAMING_SNAKE_CASE = word.index(a , a) except ValueError: new_word.extend(word[i:]) break else: new_word.extend(word[i:j]) SCREAMING_SNAKE_CASE = j if word[i] == first and i < len(a) - 1 and word[i + 1] == second: new_word.append(first + second) i += 2 else: new_word.append(word[i]) i += 1 SCREAMING_SNAKE_CASE = tuple(a) SCREAMING_SNAKE_CASE = new_word if len(a) == 1: break else: SCREAMING_SNAKE_CASE = get_pairs(a) SCREAMING_SNAKE_CASE = '@@ '.join(a) SCREAMING_SNAKE_CASE = word[:-4] SCREAMING_SNAKE_CASE = word return word def SCREAMING_SNAKE_CASE__ ( self , a) -> Tuple: SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = re.findall(R'\S+\n?' , a) for token in words: split_tokens.extend(list(self.bpe(a).split(' '))) return split_tokens def SCREAMING_SNAKE_CASE__ ( self , a) -> Any: return self.encoder.get(a , self.encoder.get(self.unk_token)) def SCREAMING_SNAKE_CASE__ ( self , a) -> List[str]: return self.decoder.get(a , self.unk_token) def SCREAMING_SNAKE_CASE__ ( self , a) -> Tuple: SCREAMING_SNAKE_CASE = ' '.join(a).replace('@@ ' , '').strip() return out_string def SCREAMING_SNAKE_CASE__ ( self , a , a = None) -> Tuple[str]: if not os.path.isdir(a): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''') return SCREAMING_SNAKE_CASE = os.path.join( a , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file']) SCREAMING_SNAKE_CASE = os.path.join( a , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['merges_file']) if os.path.abspath(self.vocab_file) != os.path.abspath(a): copyfile(self.vocab_file , a) if os.path.abspath(self.merges_file) != os.path.abspath(a): copyfile(self.merges_file , a) return out_vocab_file, out_merge_file def SCREAMING_SNAKE_CASE__ ( self , a) -> Optional[Any]: if isinstance(a , a): try: with open(a , 'r' , encoding='utf-8') as fd: self.add_from_file(a) except FileNotFoundError as fnfe: raise fnfe except UnicodeError: raise Exception(f'''Incorrect encoding detected in {f}, please rebuild the dataset''') return SCREAMING_SNAKE_CASE = f.readlines() for lineTmp in lines: SCREAMING_SNAKE_CASE = lineTmp.strip() SCREAMING_SNAKE_CASE = line.rfind(' ') if idx == -1: raise ValueError('Incorrect dictionary format, expected \'<token> <cnt>\'') SCREAMING_SNAKE_CASE = line[:idx] SCREAMING_SNAKE_CASE = len(self.encoder)
73
import gc import random import tempfile import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMInverseScheduler, DDIMScheduler, DPMSolverMultistepInverseScheduler, DPMSolverMultistepScheduler, StableDiffusionDiffEditPipeline, UNetaDConditionModel, ) from diffusers.utils import load_image, slow from diffusers.utils.testing_utils import enable_full_determinism, floats_tensor, require_torch_gpu, torch_device from ..pipeline_params import TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class _snake_case ( A__ , A__ , unittest.TestCase ): _lowercase : List[Any] = StableDiffusionDiffEditPipeline _lowercase : List[str] = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS - {'''height''', '''width''', '''image'''} | {'''image_latents'''} _lowercase : Optional[int] = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS - {'''image'''} | {'''image_latents'''} _lowercase : List[str] = frozenset( [] ) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess _lowercase : List[str] = frozenset([] ) def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: torch.manual_seed(0) SCREAMING_SNAKE_CASE = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D') , up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D') , cross_attention_dim=32 , attention_head_dim=(2, 4) , use_linear_projection=a , ) SCREAMING_SNAKE_CASE = DDIMScheduler( beta_start=0.0_00_85 , beta_end=0.0_12 , beta_schedule='scaled_linear' , clip_sample=a , set_alpha_to_one=a , ) SCREAMING_SNAKE_CASE = DDIMInverseScheduler( beta_start=0.0_00_85 , beta_end=0.0_12 , beta_schedule='scaled_linear' , clip_sample=a , set_alpha_to_zero=a , ) torch.manual_seed(0) SCREAMING_SNAKE_CASE = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D'] , up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D'] , latent_channels=4 , sample_size=128 , ) torch.manual_seed(0) SCREAMING_SNAKE_CASE = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , hidden_act='gelu' , projection_dim=512 , ) SCREAMING_SNAKE_CASE = CLIPTextModel(a) SCREAMING_SNAKE_CASE = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip') SCREAMING_SNAKE_CASE = { 'unet': unet, 'scheduler': scheduler, 'inverse_scheduler': inverse_scheduler, 'vae': vae, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'safety_checker': None, 'feature_extractor': None, } return components def SCREAMING_SNAKE_CASE__ ( self , a , a=0) -> List[Any]: SCREAMING_SNAKE_CASE = floats_tensor((1, 16, 16) , rng=random.Random(a)).to(a) SCREAMING_SNAKE_CASE = floats_tensor((1, 2, 4, 16, 16) , rng=random.Random(a)).to(a) if str(a).startswith('mps'): SCREAMING_SNAKE_CASE = torch.manual_seed(a) else: SCREAMING_SNAKE_CASE = torch.Generator(device=a).manual_seed(a) SCREAMING_SNAKE_CASE = { 'prompt': 'a dog and a newt', 'mask_image': mask, 'image_latents': latents, 'generator': generator, 'num_inference_steps': 2, 'inpaint_strength': 1.0, 'guidance_scale': 6.0, 'output_type': 'numpy', } return inputs def SCREAMING_SNAKE_CASE__ ( self , a , a=0) -> List[Any]: SCREAMING_SNAKE_CASE = floats_tensor((1, 3, 32, 32) , rng=random.Random(a)).to(a) SCREAMING_SNAKE_CASE = image.cpu().permute(0 , 2 , 3 , 1)[0] SCREAMING_SNAKE_CASE = Image.fromarray(np.uinta(a)).convert('RGB') if str(a).startswith('mps'): SCREAMING_SNAKE_CASE = torch.manual_seed(a) else: SCREAMING_SNAKE_CASE = torch.Generator(device=a).manual_seed(a) SCREAMING_SNAKE_CASE = { 'image': image, 'source_prompt': 'a cat and a frog', 'target_prompt': 'a dog and a newt', 'generator': generator, 'num_inference_steps': 2, 'num_maps_per_mask': 2, 'mask_encode_strength': 1.0, 'guidance_scale': 6.0, 'output_type': 'numpy', } return inputs def SCREAMING_SNAKE_CASE__ ( self , a , a=0) -> Optional[int]: SCREAMING_SNAKE_CASE = floats_tensor((1, 3, 32, 32) , rng=random.Random(a)).to(a) SCREAMING_SNAKE_CASE = image.cpu().permute(0 , 2 , 3 , 1)[0] SCREAMING_SNAKE_CASE = Image.fromarray(np.uinta(a)).convert('RGB') if str(a).startswith('mps'): SCREAMING_SNAKE_CASE = torch.manual_seed(a) else: SCREAMING_SNAKE_CASE = torch.Generator(device=a).manual_seed(a) SCREAMING_SNAKE_CASE = { 'image': image, 'prompt': 'a cat and a frog', 'generator': generator, 'num_inference_steps': 2, 'inpaint_strength': 1.0, 'guidance_scale': 6.0, 'decode_latents': True, 'output_type': 'numpy', } return inputs def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: if not hasattr(self.pipeline_class , '_optional_components'): return SCREAMING_SNAKE_CASE = self.get_dummy_components() SCREAMING_SNAKE_CASE = self.pipeline_class(**a) pipe.to(a) pipe.set_progress_bar_config(disable=a) # set all optional components to None and update pipeline config accordingly for optional_component in pipe._optional_components: setattr(a , a , a) pipe.register_modules(**{optional_component: None for optional_component in pipe._optional_components}) SCREAMING_SNAKE_CASE = self.get_dummy_inputs(a) SCREAMING_SNAKE_CASE = pipe(**a)[0] with tempfile.TemporaryDirectory() as tmpdir: pipe.save_pretrained(a) SCREAMING_SNAKE_CASE = self.pipeline_class.from_pretrained(a) pipe_loaded.to(a) pipe_loaded.set_progress_bar_config(disable=a) for optional_component in pipe._optional_components: self.assertTrue( getattr(a , a) is None , f'''`{optional_component}` did not stay set to None after loading.''' , ) SCREAMING_SNAKE_CASE = self.get_dummy_inputs(a) SCREAMING_SNAKE_CASE = pipe_loaded(**a)[0] SCREAMING_SNAKE_CASE = np.abs(output - output_loaded).max() self.assertLess(a , 1E-4) def SCREAMING_SNAKE_CASE__ ( self) -> str: SCREAMING_SNAKE_CASE = 'cpu' SCREAMING_SNAKE_CASE = self.get_dummy_components() SCREAMING_SNAKE_CASE = self.pipeline_class(**a) pipe.to(a) pipe.set_progress_bar_config(disable=a) SCREAMING_SNAKE_CASE = self.get_dummy_mask_inputs(a) SCREAMING_SNAKE_CASE = pipe.generate_mask(**a) SCREAMING_SNAKE_CASE = mask[0, -3:, -3:] self.assertEqual(mask.shape , (1, 16, 16)) SCREAMING_SNAKE_CASE = np.array([0] * 9) SCREAMING_SNAKE_CASE = np.abs(mask_slice.flatten() - expected_slice).max() self.assertLessEqual(a , 1E-3) self.assertEqual(mask[0, -3, -4] , 0) def SCREAMING_SNAKE_CASE__ ( self) -> str: SCREAMING_SNAKE_CASE = 'cpu' SCREAMING_SNAKE_CASE = self.get_dummy_components() SCREAMING_SNAKE_CASE = self.pipeline_class(**a) pipe.to(a) pipe.set_progress_bar_config(disable=a) SCREAMING_SNAKE_CASE = self.get_dummy_inversion_inputs(a) SCREAMING_SNAKE_CASE = pipe.invert(**a).images SCREAMING_SNAKE_CASE = image[0, -1, -3:, -3:] self.assertEqual(image.shape , (2, 32, 32, 3)) SCREAMING_SNAKE_CASE = np.array( [0.51_50, 0.51_34, 0.50_43, 0.53_76, 0.46_94, 0.5_10_50, 0.50_15, 0.44_07, 0.47_99] , ) SCREAMING_SNAKE_CASE = np.abs(image_slice.flatten() - expected_slice).max() self.assertLessEqual(a , 1E-3) def SCREAMING_SNAKE_CASE__ ( self) -> Dict: super().test_inference_batch_single_identical(expected_max_diff=5E-3) def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: SCREAMING_SNAKE_CASE = 'cpu' SCREAMING_SNAKE_CASE = self.get_dummy_components() SCREAMING_SNAKE_CASE = {'beta_start': 0.0_00_85, 'beta_end': 0.0_12, 'beta_schedule': 'scaled_linear'} SCREAMING_SNAKE_CASE = DPMSolverMultistepScheduler(**a) SCREAMING_SNAKE_CASE = DPMSolverMultistepInverseScheduler(**a) SCREAMING_SNAKE_CASE = self.pipeline_class(**a) pipe.to(a) pipe.set_progress_bar_config(disable=a) SCREAMING_SNAKE_CASE = self.get_dummy_inversion_inputs(a) SCREAMING_SNAKE_CASE = pipe.invert(**a).images SCREAMING_SNAKE_CASE = image[0, -1, -3:, -3:] self.assertEqual(image.shape , (2, 32, 32, 3)) SCREAMING_SNAKE_CASE = np.array( [0.51_50, 0.51_34, 0.50_43, 0.53_76, 0.46_94, 0.5_10_50, 0.50_15, 0.44_07, 0.47_99] , ) SCREAMING_SNAKE_CASE = np.abs(image_slice.flatten() - expected_slice).max() self.assertLessEqual(a , 1E-3) @require_torch_gpu @slow class _snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ ( self) -> Any: super().tearDown() gc.collect() torch.cuda.empty_cache() @classmethod def SCREAMING_SNAKE_CASE__ ( cls) -> List[Any]: SCREAMING_SNAKE_CASE = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/diffedit/fruit.png') SCREAMING_SNAKE_CASE = raw_image.convert('RGB').resize((768, 768)) SCREAMING_SNAKE_CASE = raw_image def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: SCREAMING_SNAKE_CASE = torch.manual_seed(0) SCREAMING_SNAKE_CASE = StableDiffusionDiffEditPipeline.from_pretrained( 'stabilityai/stable-diffusion-2-1' , safety_checker=a , torch_dtype=torch.floataa) SCREAMING_SNAKE_CASE = DDIMScheduler.from_config(pipe.scheduler.config) SCREAMING_SNAKE_CASE = DDIMInverseScheduler.from_config(pipe.scheduler.config) pipe.enable_model_cpu_offload() pipe.set_progress_bar_config(disable=a) SCREAMING_SNAKE_CASE = 'a bowl of fruit' SCREAMING_SNAKE_CASE = 'a bowl of pears' SCREAMING_SNAKE_CASE = pipe.generate_mask( image=self.raw_image , source_prompt=a , target_prompt=a , generator=a , ) SCREAMING_SNAKE_CASE = pipe.invert( prompt=a , image=self.raw_image , inpaint_strength=0.7 , generator=a).latents SCREAMING_SNAKE_CASE = pipe( prompt=a , mask_image=a , image_latents=a , generator=a , negative_prompt=a , inpaint_strength=0.7 , output_type='numpy' , ).images[0] SCREAMING_SNAKE_CASE = ( np.array( load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/diffedit/pears.png').resize((768, 768))) / 255 ) assert np.abs((expected_image - image).max()) < 5E-1 def SCREAMING_SNAKE_CASE__ ( self) -> str: SCREAMING_SNAKE_CASE = torch.manual_seed(0) SCREAMING_SNAKE_CASE = StableDiffusionDiffEditPipeline.from_pretrained( 'stabilityai/stable-diffusion-2-1' , safety_checker=a , torch_dtype=torch.floataa) SCREAMING_SNAKE_CASE = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config) SCREAMING_SNAKE_CASE = DPMSolverMultistepInverseScheduler.from_config(pipe.scheduler.config) pipe.enable_model_cpu_offload() pipe.set_progress_bar_config(disable=a) SCREAMING_SNAKE_CASE = 'a bowl of fruit' SCREAMING_SNAKE_CASE = 'a bowl of pears' SCREAMING_SNAKE_CASE = pipe.generate_mask( image=self.raw_image , source_prompt=a , target_prompt=a , generator=a , ) SCREAMING_SNAKE_CASE = pipe.invert( prompt=a , image=self.raw_image , inpaint_strength=0.7 , generator=a , num_inference_steps=25 , ).latents SCREAMING_SNAKE_CASE = pipe( prompt=a , mask_image=a , image_latents=a , generator=a , negative_prompt=a , inpaint_strength=0.7 , num_inference_steps=25 , output_type='numpy' , ).images[0] SCREAMING_SNAKE_CASE = ( np.array( load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/diffedit/pears.png').resize((768, 768))) / 255 ) assert np.abs((expected_image - image).max()) < 5E-1
73
1
from typing import Optional, Tuple import jax import jax.numpy as jnp from flax import linen as nn from flax.core.frozen_dict import FrozenDict from transformers import CLIPConfig, FlaxPreTrainedModel from transformers.models.clip.modeling_flax_clip import FlaxCLIPVisionModule def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase=1e-12): SCREAMING_SNAKE_CASE = jnp.divide(emb_a.T , jnp.clip(jnp.linalg.norm(_UpperCAmelCase , axis=1) , a_min=_UpperCAmelCase)).T SCREAMING_SNAKE_CASE = jnp.divide(emb_a.T , jnp.clip(jnp.linalg.norm(_UpperCAmelCase , axis=1) , a_min=_UpperCAmelCase)).T return jnp.matmul(_UpperCAmelCase , norm_emb_a.T) class _snake_case ( nn.Module ): _lowercase : CLIPConfig _lowercase : jnp.dtype = jnp.floataa def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: SCREAMING_SNAKE_CASE = FlaxCLIPVisionModule(self.config.vision_config) SCREAMING_SNAKE_CASE = nn.Dense(self.config.projection_dim , use_bias=a , dtype=self.dtype) SCREAMING_SNAKE_CASE = self.param('concept_embeds' , jax.nn.initializers.ones , (17, self.config.projection_dim)) SCREAMING_SNAKE_CASE = self.param( 'special_care_embeds' , jax.nn.initializers.ones , (3, self.config.projection_dim)) SCREAMING_SNAKE_CASE = self.param('concept_embeds_weights' , jax.nn.initializers.ones , (17,)) SCREAMING_SNAKE_CASE = self.param('special_care_embeds_weights' , jax.nn.initializers.ones , (3,)) def __call__( self , a) -> Tuple: SCREAMING_SNAKE_CASE = self.vision_model(a)[1] SCREAMING_SNAKE_CASE = self.visual_projection(a) SCREAMING_SNAKE_CASE = jax_cosine_distance(a , self.special_care_embeds) SCREAMING_SNAKE_CASE = jax_cosine_distance(a , self.concept_embeds) # increase this value to create a stronger `nfsw` filter # at the cost of increasing the possibility of filtering benign image inputs SCREAMING_SNAKE_CASE = 0.0 SCREAMING_SNAKE_CASE = special_cos_dist - self.special_care_embeds_weights[None, :] + adjustment SCREAMING_SNAKE_CASE = jnp.round(a , 3) SCREAMING_SNAKE_CASE = jnp.any(special_scores > 0 , axis=1 , keepdims=a) # Use a lower threshold if an image has any special care concept SCREAMING_SNAKE_CASE = is_special_care * 0.01 SCREAMING_SNAKE_CASE = cos_dist - self.concept_embeds_weights[None, :] + special_adjustment SCREAMING_SNAKE_CASE = jnp.round(a , 3) SCREAMING_SNAKE_CASE = jnp.any(concept_scores > 0 , axis=1) return has_nsfw_concepts class _snake_case ( A__ ): _lowercase : Optional[Any] = CLIPConfig _lowercase : Optional[Any] = '''clip_input''' _lowercase : Dict = FlaxStableDiffusionSafetyCheckerModule def __init__( self , a , a = None , a = 0 , a = jnp.floataa , a = True , **a , ) -> Dict: if input_shape is None: SCREAMING_SNAKE_CASE = (1, 224, 224, 3) SCREAMING_SNAKE_CASE = self.module_class(config=a , dtype=a , **a) super().__init__(a , a , input_shape=a , seed=a , dtype=a , _do_init=_do_init) def SCREAMING_SNAKE_CASE__ ( self , a , a , a = None) -> FrozenDict: # init input tensor SCREAMING_SNAKE_CASE = jax.random.normal(a , a) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = jax.random.split(a) SCREAMING_SNAKE_CASE = {'params': params_rng, 'dropout': dropout_rng} SCREAMING_SNAKE_CASE = self.module.init(a , a)['params'] return random_params def __call__( self , a , a = None , ) -> Optional[int]: SCREAMING_SNAKE_CASE = jnp.transpose(a , (0, 2, 3, 1)) return self.module.apply( {'params': params or self.params} , jnp.array(a , dtype=jnp.floataa) , rngs={} , )
73
import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging a_ : List[str] = logging.get_logger(__name__) a_ : Any = { 'microsoft/unispeech-large-1500h-cv': ( 'https://huggingface.co/microsoft/unispeech-large-1500h-cv/resolve/main/config.json' ), # See all UniSpeech models at https://huggingface.co/models?filter=unispeech } class _snake_case ( A__ ): _lowercase : Optional[int] = '''unispeech''' def __init__( self , a=32 , a=768 , a=12 , a=12 , a=3072 , a="gelu" , a=0.1 , a=0.1 , a=0.1 , a=0.0 , a=0.0 , a=0.1 , a=0.1 , a=0.02 , a=1E-5 , a="group" , a="gelu" , a=(512, 512, 512, 512, 512, 512, 512) , a=(5, 2, 2, 2, 2, 2, 2) , a=(10, 3, 3, 3, 3, 2, 2) , a=False , a=128 , a=16 , a=False , a=True , a=0.05 , a=10 , a=2 , a=0.0 , a=10 , a=0 , a=320 , a=2 , a=0.1 , a=100 , a=256 , a=256 , a=0.1 , a="mean" , a=False , a=False , a=256 , a=80 , a=0 , a=1 , a=2 , a=0.5 , **a , ) -> Optional[int]: super().__init__(**a , pad_token_id=a , bos_token_id=a , eos_token_id=a) SCREAMING_SNAKE_CASE = hidden_size SCREAMING_SNAKE_CASE = feat_extract_norm SCREAMING_SNAKE_CASE = feat_extract_activation SCREAMING_SNAKE_CASE = list(a) SCREAMING_SNAKE_CASE = list(a) SCREAMING_SNAKE_CASE = list(a) SCREAMING_SNAKE_CASE = conv_bias SCREAMING_SNAKE_CASE = num_conv_pos_embeddings SCREAMING_SNAKE_CASE = num_conv_pos_embedding_groups SCREAMING_SNAKE_CASE = len(self.conv_dim) SCREAMING_SNAKE_CASE = num_hidden_layers SCREAMING_SNAKE_CASE = intermediate_size SCREAMING_SNAKE_CASE = hidden_act SCREAMING_SNAKE_CASE = num_attention_heads SCREAMING_SNAKE_CASE = hidden_dropout SCREAMING_SNAKE_CASE = attention_dropout SCREAMING_SNAKE_CASE = activation_dropout SCREAMING_SNAKE_CASE = feat_proj_dropout SCREAMING_SNAKE_CASE = final_dropout SCREAMING_SNAKE_CASE = layerdrop SCREAMING_SNAKE_CASE = layer_norm_eps SCREAMING_SNAKE_CASE = initializer_range SCREAMING_SNAKE_CASE = num_ctc_classes SCREAMING_SNAKE_CASE = vocab_size SCREAMING_SNAKE_CASE = do_stable_layer_norm SCREAMING_SNAKE_CASE = use_weighted_layer_sum SCREAMING_SNAKE_CASE = classifier_proj_size if ( (len(self.conv_stride) != self.num_feat_extract_layers) or (len(self.conv_kernel) != self.num_feat_extract_layers) or (len(self.conv_dim) != self.num_feat_extract_layers) ): raise ValueError( 'Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` ==' ' `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) =' f''' {len(self.conv_dim)}`, `len(config.conv_stride) = {len(self.conv_stride)}`,''' f''' `len(config.conv_kernel) = {len(self.conv_kernel)}`.''') # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 SCREAMING_SNAKE_CASE = apply_spec_augment SCREAMING_SNAKE_CASE = mask_time_prob SCREAMING_SNAKE_CASE = mask_time_length SCREAMING_SNAKE_CASE = mask_time_min_masks SCREAMING_SNAKE_CASE = mask_feature_prob SCREAMING_SNAKE_CASE = mask_feature_length SCREAMING_SNAKE_CASE = mask_feature_min_masks # parameters for pretraining with codevector quantized representations SCREAMING_SNAKE_CASE = num_codevectors_per_group SCREAMING_SNAKE_CASE = num_codevector_groups SCREAMING_SNAKE_CASE = contrastive_logits_temperature SCREAMING_SNAKE_CASE = feat_quantizer_dropout SCREAMING_SNAKE_CASE = num_negatives SCREAMING_SNAKE_CASE = codevector_dim SCREAMING_SNAKE_CASE = proj_codevector_dim SCREAMING_SNAKE_CASE = diversity_loss_weight # ctc loss SCREAMING_SNAKE_CASE = ctc_loss_reduction SCREAMING_SNAKE_CASE = ctc_zero_infinity # pretraining loss SCREAMING_SNAKE_CASE = replace_prob @property def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: return functools.reduce(operator.mul , self.conv_stride , 1)
73
1
from dataclasses import dataclass from typing import List, Optional, Union import numpy as np import PIL from PIL import Image from ...utils import ( BaseOutput, OptionalDependencyNotAvailable, is_flax_available, is_k_diffusion_available, is_k_diffusion_version, is_onnx_available, is_torch_available, is_transformers_available, is_transformers_version, ) @dataclass class _snake_case ( A__ ): _lowercase : Union[List[PIL.Image.Image], np.ndarray] _lowercase : Optional[List[bool]] try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import * # noqa F403 else: from .pipeline_cycle_diffusion import CycleDiffusionPipeline from .pipeline_stable_diffusion import StableDiffusionPipeline from .pipeline_stable_diffusion_attend_and_excite import StableDiffusionAttendAndExcitePipeline from .pipeline_stable_diffusion_imgaimg import StableDiffusionImgaImgPipeline from .pipeline_stable_diffusion_inpaint import StableDiffusionInpaintPipeline from .pipeline_stable_diffusion_inpaint_legacy import StableDiffusionInpaintPipelineLegacy from .pipeline_stable_diffusion_instruct_pixapix import StableDiffusionInstructPixaPixPipeline from .pipeline_stable_diffusion_latent_upscale import StableDiffusionLatentUpscalePipeline from .pipeline_stable_diffusion_ldmad import StableDiffusionLDMaDPipeline from .pipeline_stable_diffusion_model_editing import StableDiffusionModelEditingPipeline from .pipeline_stable_diffusion_panorama import StableDiffusionPanoramaPipeline from .pipeline_stable_diffusion_paradigms import StableDiffusionParadigmsPipeline from .pipeline_stable_diffusion_sag import StableDiffusionSAGPipeline from .pipeline_stable_diffusion_upscale import StableDiffusionUpscalePipeline from .pipeline_stable_unclip import StableUnCLIPPipeline from .pipeline_stable_unclip_imgaimg import StableUnCLIPImgaImgPipeline from .safety_checker import StableDiffusionSafetyChecker from .stable_unclip_image_normalizer import StableUnCLIPImageNormalizer try: if not (is_transformers_available() and is_torch_available() and is_transformers_version('>=', '4.25.0')): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import StableDiffusionImageVariationPipeline else: from .pipeline_stable_diffusion_image_variation import StableDiffusionImageVariationPipeline try: if not (is_transformers_available() and is_torch_available() and is_transformers_version('>=', '4.26.0')): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import ( StableDiffusionDepthaImgPipeline, StableDiffusionDiffEditPipeline, StableDiffusionPixaPixZeroPipeline, ) else: from .pipeline_stable_diffusion_depthaimg import StableDiffusionDepthaImgPipeline from .pipeline_stable_diffusion_diffedit import StableDiffusionDiffEditPipeline from .pipeline_stable_diffusion_pixapix_zero import StableDiffusionPixaPixZeroPipeline try: if not ( is_torch_available() and is_transformers_available() and is_k_diffusion_available() and is_k_diffusion_version('>=', '0.0.12') ): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_and_k_diffusion_objects import * # noqa F403 else: from .pipeline_stable_diffusion_k_diffusion import StableDiffusionKDiffusionPipeline try: if not (is_transformers_available() and is_onnx_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_onnx_objects import * # noqa F403 else: from .pipeline_onnx_stable_diffusion import OnnxStableDiffusionPipeline, StableDiffusionOnnxPipeline from .pipeline_onnx_stable_diffusion_imgaimg import OnnxStableDiffusionImgaImgPipeline from .pipeline_onnx_stable_diffusion_inpaint import OnnxStableDiffusionInpaintPipeline from .pipeline_onnx_stable_diffusion_inpaint_legacy import OnnxStableDiffusionInpaintPipelineLegacy from .pipeline_onnx_stable_diffusion_upscale import OnnxStableDiffusionUpscalePipeline if is_transformers_available() and is_flax_available(): import flax @flax.struct.dataclass class _snake_case ( A__ ): _lowercase : np.ndarray _lowercase : List[bool] from ...schedulers.scheduling_pndm_flax import PNDMSchedulerState from .pipeline_flax_stable_diffusion import FlaxStableDiffusionPipeline from .pipeline_flax_stable_diffusion_imgaimg import FlaxStableDiffusionImgaImgPipeline from .pipeline_flax_stable_diffusion_inpaint import FlaxStableDiffusionInpaintPipeline from .safety_checker_flax import FlaxStableDiffusionSafetyChecker
73
import argparse import collections import json import os import re import string import sys import numpy as np a_ : Optional[Any] = re.compile(R'\b(a|an|the)\b', re.UNICODE) a_ : List[str] = None def lowerCamelCase__ (): SCREAMING_SNAKE_CASE = argparse.ArgumentParser('Official evaluation script for SQuAD version 2.0.') parser.add_argument('data_file' , metavar='data.json' , help='Input data JSON file.') parser.add_argument('pred_file' , metavar='pred.json' , help='Model predictions.') parser.add_argument( '--out-file' , '-o' , metavar='eval.json' , help='Write accuracy metrics to file (default is stdout).') parser.add_argument( '--na-prob-file' , '-n' , metavar='na_prob.json' , help='Model estimates of probability of no answer.') parser.add_argument( '--na-prob-thresh' , '-t' , type=_UpperCAmelCase , default=1.0 , help='Predict "" if no-answer probability exceeds this (default = 1.0).' , ) parser.add_argument( '--out-image-dir' , '-p' , metavar='out_images' , default=_UpperCAmelCase , help='Save precision-recall curves to directory.') parser.add_argument('--verbose' , '-v' , action='store_true') if len(sys.argv) == 1: parser.print_help() sys.exit(1) return parser.parse_args() def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = {} for article in dataset: for p in article["paragraphs"]: for qa in p["qas"]: SCREAMING_SNAKE_CASE = bool(qa['answers']['text']) return qid_to_has_ans def lowerCamelCase__ (_UpperCAmelCase): def remove_articles(_UpperCAmelCase): return ARTICLES_REGEX.sub(' ' , _UpperCAmelCase) def white_space_fix(_UpperCAmelCase): return " ".join(text.split()) def remove_punc(_UpperCAmelCase): SCREAMING_SNAKE_CASE = set(string.punctuation) return "".join(ch for ch in text if ch not in exclude) def lower(_UpperCAmelCase): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(_UpperCAmelCase)))) def lowerCamelCase__ (_UpperCAmelCase): if not s: return [] return normalize_answer(_UpperCAmelCase).split() def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): return int(normalize_answer(_UpperCAmelCase) == normalize_answer(_UpperCAmelCase)) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = get_tokens(_UpperCAmelCase) SCREAMING_SNAKE_CASE = get_tokens(_UpperCAmelCase) SCREAMING_SNAKE_CASE = collections.Counter(_UpperCAmelCase) & collections.Counter(_UpperCAmelCase) SCREAMING_SNAKE_CASE = sum(common.values()) if len(_UpperCAmelCase) == 0 or len(_UpperCAmelCase) == 0: # If either is no-answer, then F1 is 1 if they agree, 0 otherwise return int(gold_toks == pred_toks) if num_same == 0: return 0 SCREAMING_SNAKE_CASE = 1.0 * num_same / len(_UpperCAmelCase) SCREAMING_SNAKE_CASE = 1.0 * num_same / len(_UpperCAmelCase) SCREAMING_SNAKE_CASE = (2 * precision * recall) / (precision + recall) return fa def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = {} SCREAMING_SNAKE_CASE = {} for article in dataset: for p in article["paragraphs"]: for qa in p["qas"]: SCREAMING_SNAKE_CASE = qa['id'] SCREAMING_SNAKE_CASE = [t for t in qa['answers']['text'] if normalize_answer(_UpperCAmelCase)] if not gold_answers: # For unanswerable questions, only correct answer is empty string SCREAMING_SNAKE_CASE = [''] if qid not in preds: print(F'''Missing prediction for {qid}''') continue SCREAMING_SNAKE_CASE = preds[qid] # Take max over all gold answers SCREAMING_SNAKE_CASE = max(compute_exact(_UpperCAmelCase , _UpperCAmelCase) for a in gold_answers) SCREAMING_SNAKE_CASE = max(compute_fa(_UpperCAmelCase , _UpperCAmelCase) for a in gold_answers) return exact_scores, fa_scores def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = {} for qid, s in scores.items(): SCREAMING_SNAKE_CASE = na_probs[qid] > na_prob_thresh if pred_na: SCREAMING_SNAKE_CASE = float(not qid_to_has_ans[qid]) else: SCREAMING_SNAKE_CASE = s return new_scores def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase=None): if not qid_list: SCREAMING_SNAKE_CASE = len(_UpperCAmelCase) return collections.OrderedDict( [ ('exact', 1_00.0 * sum(exact_scores.values()) / total), ('f1', 1_00.0 * sum(fa_scores.values()) / total), ('total', total), ]) else: SCREAMING_SNAKE_CASE = len(_UpperCAmelCase) return collections.OrderedDict( [ ('exact', 1_00.0 * sum(exact_scores[k] for k in qid_list) / total), ('f1', 1_00.0 * sum(fa_scores[k] for k in qid_list) / total), ('total', total), ]) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): for k in new_eval: SCREAMING_SNAKE_CASE = new_eval[k] def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): plt.step(_UpperCAmelCase , _UpperCAmelCase , color='b' , alpha=0.2 , where='post') plt.fill_between(_UpperCAmelCase , _UpperCAmelCase , step='post' , alpha=0.2 , color='b') plt.xlabel('Recall') plt.ylabel('Precision') plt.xlim([0.0, 1.05]) plt.ylim([0.0, 1.05]) plt.title(_UpperCAmelCase) plt.savefig(_UpperCAmelCase) plt.clf() def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase=None , _UpperCAmelCase=None): SCREAMING_SNAKE_CASE = sorted(_UpperCAmelCase , key=lambda _UpperCAmelCase: na_probs[k]) SCREAMING_SNAKE_CASE = 0.0 SCREAMING_SNAKE_CASE = 1.0 SCREAMING_SNAKE_CASE = 0.0 SCREAMING_SNAKE_CASE = [1.0] SCREAMING_SNAKE_CASE = [0.0] SCREAMING_SNAKE_CASE = 0.0 for i, qid in enumerate(_UpperCAmelCase): if qid_to_has_ans[qid]: true_pos += scores[qid] SCREAMING_SNAKE_CASE = true_pos / float(i + 1) SCREAMING_SNAKE_CASE = true_pos / float(_UpperCAmelCase) if i == len(_UpperCAmelCase) - 1 or na_probs[qid] != na_probs[qid_list[i + 1]]: # i.e., if we can put a threshold after this point avg_prec += cur_p * (cur_r - recalls[-1]) precisions.append(_UpperCAmelCase) recalls.append(_UpperCAmelCase) if out_image: plot_pr_curve(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) return {"ap": 1_00.0 * avg_prec} def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): if out_image_dir and not os.path.exists(_UpperCAmelCase): os.makedirs(_UpperCAmelCase) SCREAMING_SNAKE_CASE = sum(1 for v in qid_to_has_ans.values() if v) if num_true_pos == 0: return SCREAMING_SNAKE_CASE = make_precision_recall_eval( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , out_image=os.path.join(_UpperCAmelCase , 'pr_exact.png') , title='Precision-Recall curve for Exact Match score' , ) SCREAMING_SNAKE_CASE = make_precision_recall_eval( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , out_image=os.path.join(_UpperCAmelCase , 'pr_f1.png') , title='Precision-Recall curve for F1 score' , ) SCREAMING_SNAKE_CASE = {k: float(_UpperCAmelCase) for k, v in qid_to_has_ans.items()} SCREAMING_SNAKE_CASE = make_precision_recall_eval( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , out_image=os.path.join(_UpperCAmelCase , 'pr_oracle.png') , title='Oracle Precision-Recall curve (binary task of HasAns vs. NoAns)' , ) merge_eval(_UpperCAmelCase , _UpperCAmelCase , 'pr_exact') merge_eval(_UpperCAmelCase , _UpperCAmelCase , 'pr_f1') merge_eval(_UpperCAmelCase , _UpperCAmelCase , 'pr_oracle') def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): if not qid_list: return SCREAMING_SNAKE_CASE = [na_probs[k] for k in qid_list] SCREAMING_SNAKE_CASE = np.ones_like(_UpperCAmelCase) / float(len(_UpperCAmelCase)) plt.hist(_UpperCAmelCase , weights=_UpperCAmelCase , bins=20 , range=(0.0, 1.0)) plt.xlabel('Model probability of no-answer') plt.ylabel('Proportion of dataset') plt.title(F'''Histogram of no-answer probability: {name}''') plt.savefig(os.path.join(_UpperCAmelCase , F'''na_prob_hist_{name}.png''')) plt.clf() def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = sum(1 for k in qid_to_has_ans if not qid_to_has_ans[k]) SCREAMING_SNAKE_CASE = num_no_ans SCREAMING_SNAKE_CASE = cur_score SCREAMING_SNAKE_CASE = 0.0 SCREAMING_SNAKE_CASE = sorted(_UpperCAmelCase , key=lambda _UpperCAmelCase: na_probs[k]) for i, qid in enumerate(_UpperCAmelCase): if qid not in scores: continue if qid_to_has_ans[qid]: SCREAMING_SNAKE_CASE = scores[qid] else: if preds[qid]: SCREAMING_SNAKE_CASE = -1 else: SCREAMING_SNAKE_CASE = 0 cur_score += diff if cur_score > best_score: SCREAMING_SNAKE_CASE = cur_score SCREAMING_SNAKE_CASE = na_probs[qid] return 1_00.0 * best_score / len(_UpperCAmelCase), best_thresh def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = find_best_thresh(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = find_best_thresh(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) SCREAMING_SNAKE_CASE = best_exact SCREAMING_SNAKE_CASE = exact_thresh SCREAMING_SNAKE_CASE = best_fa SCREAMING_SNAKE_CASE = fa_thresh def lowerCamelCase__ (): with open(OPTS.data_file) as f: SCREAMING_SNAKE_CASE = json.load(_UpperCAmelCase) SCREAMING_SNAKE_CASE = dataset_json['data'] with open(OPTS.pred_file) as f: SCREAMING_SNAKE_CASE = json.load(_UpperCAmelCase) if OPTS.na_prob_file: with open(OPTS.na_prob_file) as f: SCREAMING_SNAKE_CASE = json.load(_UpperCAmelCase) else: SCREAMING_SNAKE_CASE = {k: 0.0 for k in preds} SCREAMING_SNAKE_CASE = make_qid_to_has_ans(_UpperCAmelCase) # maps qid to True/False SCREAMING_SNAKE_CASE = [k for k, v in qid_to_has_ans.items() if v] SCREAMING_SNAKE_CASE = [k for k, v in qid_to_has_ans.items() if not v] SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = get_raw_scores(_UpperCAmelCase , _UpperCAmelCase) SCREAMING_SNAKE_CASE = apply_no_ans_threshold(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , OPTS.na_prob_thresh) SCREAMING_SNAKE_CASE = apply_no_ans_threshold(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , OPTS.na_prob_thresh) SCREAMING_SNAKE_CASE = make_eval_dict(_UpperCAmelCase , _UpperCAmelCase) if has_ans_qids: SCREAMING_SNAKE_CASE = make_eval_dict(_UpperCAmelCase , _UpperCAmelCase , qid_list=_UpperCAmelCase) merge_eval(_UpperCAmelCase , _UpperCAmelCase , 'HasAns') if no_ans_qids: SCREAMING_SNAKE_CASE = make_eval_dict(_UpperCAmelCase , _UpperCAmelCase , qid_list=_UpperCAmelCase) merge_eval(_UpperCAmelCase , _UpperCAmelCase , 'NoAns') if OPTS.na_prob_file: find_all_best_thresh(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) if OPTS.na_prob_file and OPTS.out_image_dir: run_precision_recall_analysis(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , OPTS.out_image_dir) histogram_na_prob(_UpperCAmelCase , _UpperCAmelCase , OPTS.out_image_dir , 'hasAns') histogram_na_prob(_UpperCAmelCase , _UpperCAmelCase , OPTS.out_image_dir , 'noAns') if OPTS.out_file: with open(OPTS.out_file , 'w') as f: json.dump(_UpperCAmelCase , _UpperCAmelCase) else: print(json.dumps(_UpperCAmelCase , indent=2)) if __name__ == "__main__": a_ : Any = parse_args() if OPTS.out_image_dir: import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt main()
73
1
from typing import List, Optional import numpy as np from ...processing_utils import ProcessorMixin from ...utils import to_numpy class _snake_case ( A__ ): _lowercase : Tuple = '''EncodecFeatureExtractor''' _lowercase : Union[str, Any] = ('''T5Tokenizer''', '''T5TokenizerFast''') def __init__( self , a , a) -> Optional[Any]: super().__init__(a , a) SCREAMING_SNAKE_CASE = self.feature_extractor SCREAMING_SNAKE_CASE = False def SCREAMING_SNAKE_CASE__ ( self , a=None , a=None , a=True) -> List[str]: return self.tokenizer.get_decoder_prompt_ids(task=a , language=a , no_timestamps=a) def __call__( self , *a , **a) -> Dict: # For backward compatibility if self._in_target_context_manager: return self.current_processor(*a , **a) SCREAMING_SNAKE_CASE = kwargs.pop('audio' , a) SCREAMING_SNAKE_CASE = kwargs.pop('sampling_rate' , a) SCREAMING_SNAKE_CASE = kwargs.pop('text' , a) if len(a) > 0: SCREAMING_SNAKE_CASE = args[0] SCREAMING_SNAKE_CASE = args[1:] if audio is None and text is None: raise ValueError('You need to specify either an `audio` or `text` input to process.') if text is not None: SCREAMING_SNAKE_CASE = self.tokenizer(a , **a) if audio is not None: SCREAMING_SNAKE_CASE = self.feature_extractor(a , *a , sampling_rate=a , **a) if audio is None: return inputs elif text is None: return audio_inputs else: SCREAMING_SNAKE_CASE = audio_inputs['input_values'] if "padding_mask" in audio_inputs: SCREAMING_SNAKE_CASE = audio_inputs['padding_mask'] return inputs def SCREAMING_SNAKE_CASE__ ( self , *a , **a) -> List[str]: SCREAMING_SNAKE_CASE = kwargs.pop('audio' , a) SCREAMING_SNAKE_CASE = kwargs.pop('padding_mask' , a) if len(a) > 0: SCREAMING_SNAKE_CASE = args[0] SCREAMING_SNAKE_CASE = args[1:] if audio_values is not None: return self._decode_audio(a , padding_mask=a) else: return self.tokenizer.batch_decode(*a , **a) def SCREAMING_SNAKE_CASE__ ( self , *a , **a) -> Optional[Any]: return self.tokenizer.decode(*a , **a) def SCREAMING_SNAKE_CASE__ ( self , a , a = None) -> List[np.ndarray]: SCREAMING_SNAKE_CASE = to_numpy(a) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = audio_values.shape if padding_mask is None: return list(a) SCREAMING_SNAKE_CASE = to_numpy(a) # match the sequence length of the padding mask to the generated audio arrays by padding with the **non-padding** # token (so that the generated audio values are **not** treated as padded tokens) SCREAMING_SNAKE_CASE = seq_len - padding_mask.shape[-1] SCREAMING_SNAKE_CASE = 1 - self.feature_extractor.padding_value SCREAMING_SNAKE_CASE = np.pad(a , ((0, 0), (0, difference)) , 'constant' , constant_values=a) SCREAMING_SNAKE_CASE = audio_values.tolist() for i in range(a): SCREAMING_SNAKE_CASE = np.asarray(audio_values[i])[ padding_mask[i][None, :] != self.feature_extractor.padding_value ] SCREAMING_SNAKE_CASE = sliced_audio.reshape(a , -1) return audio_values
73
import warnings from ...utils import logging from .image_processing_glpn import GLPNImageProcessor a_ : Dict = logging.get_logger(__name__) class _snake_case ( A__ ): def __init__( self , *a , **a) -> None: warnings.warn( 'The class GLPNFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please' ' use GLPNImageProcessor instead.' , a , ) super().__init__(*a , **a)
73
1
import itertools import os from collections import Counter, defaultdict from concurrent.futures import ThreadPoolExecutor, as_completed import numpy as np import datasets from .execute import check_correctness a_ : Optional[Any] = '\\n@misc{chen2021evaluating,\n title={Evaluating Large Language Models Trained on Code},\n author={Mark Chen and Jerry Tworek and Heewoo Jun and Qiming Yuan \\nand Henrique Ponde de Oliveira Pinto and Jared Kaplan and Harri Edwards \\nand Yuri Burda and Nicholas Joseph and Greg Brockman and Alex Ray \\nand Raul Puri and Gretchen Krueger and Michael Petrov and Heidy Khlaaf \\nand Girish Sastry and Pamela Mishkin and Brooke Chan and Scott Gray \\nand Nick Ryder and Mikhail Pavlov and Alethea Power and Lukasz Kaiser \\nand Mohammad Bavarian and Clemens Winter and Philippe Tillet \\nand Felipe Petroski Such and Dave Cummings and Matthias Plappert \\nand Fotios Chantzis and Elizabeth Barnes and Ariel Herbert-Voss \\nand William Hebgen Guss and Alex Nichol and Alex Paino and Nikolas Tezak \\nand Jie Tang and Igor Babuschkin and Suchir Balaji and Shantanu Jain \\nand William Saunders and Christopher Hesse and Andrew N. Carr \\nand Jan Leike and Josh Achiam and Vedant Misra and Evan Morikawa \\nand Alec Radford and Matthew Knight and Miles Brundage and Mira Murati \\nand Katie Mayer and Peter Welinder and Bob McGrew and Dario Amodei \\nand Sam McCandlish and Ilya Sutskever and Wojciech Zaremba},\n year={2021},\n eprint={2107.03374},\n archivePrefix={arXiv},\n primaryClass={cs.LG}\n}\n' a_ : List[str] = '\\nThis metric implements the evaluation harness for the HumanEval problem solving dataset\ndescribed in the paper "Evaluating Large Language Models Trained on Code"\n(https://arxiv.org/abs/2107.03374).\n' a_ : Any = '\nCalculates how good are predictions given some references, using certain scores\nArgs:\n predictions: list of candidates to evaluate. Each candidates should be a list\n of strings with several code candidates to solve the problem.\n references: a list with a test for each prediction. Each test should evaluate the\n correctness of a code candidate.\n k: number of code candidates to consider in the evaluation (Default: [1, 10, 100])\n num_workers: number of workers used to evaluate the canidate programs (Default: 4).\n timeout:\nReturns:\n pass_at_k: dict with pass rates for each k\n results: dict with granular results of each unittest\nExamples:\n >>> code_eval = datasets.load_metric("code_eval")\n >>> test_cases = ["assert add(2,3)==5"]\n >>> candidates = [["def add(a,b): return a*b", "def add(a, b): return a+b"]]\n >>> pass_at_k, results = code_eval.compute(references=test_cases, predictions=candidates, k=[1, 2])\n >>> print(pass_at_k)\n {\'pass@1\': 0.5, \'pass@2\': 1.0}\n' a_ : int = '\n################################################################################\n !!!WARNING!!!\n################################################################################\nThe "code_eval" metric executes untrusted model-generated code in Python.\nAlthough it is highly unlikely that model-generated code will do something\novertly malicious in response to this test suite, model-generated code may act\ndestructively due to a lack of model capability or alignment.\nUsers are strongly encouraged to sandbox this evaluation suite so that it\ndoes not perform destructive actions on their host or network. For more\ninformation on how OpenAI sandboxes its code, see the paper "Evaluating Large\nLanguage Models Trained on Code" (https://arxiv.org/abs/2107.03374).\n\nOnce you have read this disclaimer and taken appropriate precautions,\nset the environment variable HF_ALLOW_CODE_EVAL="1". Within Python you can to this\nwith:\n\n>>> import os\n>>> os.environ["HF_ALLOW_CODE_EVAL"] = "1"\n\n################################################################################\\n' a_ : List[Any] = 'The MIT License\n\nCopyright (c) OpenAI (https://openai.com)\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the "Software"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class _snake_case ( datasets.Metric ): def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: return datasets.MetricInfo( # This is the description that will appear on the metrics page. description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { 'predictions': datasets.Sequence(datasets.Value('string')), 'references': datasets.Value('string'), }) , homepage='https://github.com/openai/human-eval' , codebase_urls=['https://github.com/openai/human-eval'] , reference_urls=['https://github.com/openai/human-eval'] , license=_LICENSE , ) def SCREAMING_SNAKE_CASE__ ( self , a , a , a=[1, 10, 100] , a=4 , a=3.0) -> str: if os.getenv('HF_ALLOW_CODE_EVAL' , 0) != "1": raise ValueError(_WARNING) if os.name == "nt": raise NotImplementedError('This metric is currently not supported on Windows.') with ThreadPoolExecutor(max_workers=a) as executor: SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = Counter() SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = defaultdict(a) for task_id, (candidates, test_case) in enumerate(zip(a , a)): for candidate in candidates: SCREAMING_SNAKE_CASE = candidate + '\n' + test_case SCREAMING_SNAKE_CASE = (test_program, timeout, task_id, completion_id[task_id]) SCREAMING_SNAKE_CASE = executor.submit(a , *a) futures.append(a) completion_id[task_id] += 1 n_samples += 1 for future in as_completed(a): SCREAMING_SNAKE_CASE = future.result() results[result["task_id"]].append((result['completion_id'], result)) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = [], [] for result in results.values(): result.sort() SCREAMING_SNAKE_CASE = [r[1]['passed'] for r in result] total.append(len(a)) correct.append(sum(a)) SCREAMING_SNAKE_CASE = np.array(a) SCREAMING_SNAKE_CASE = np.array(a) SCREAMING_SNAKE_CASE = k SCREAMING_SNAKE_CASE = {f'''pass@{k}''': estimate_pass_at_k(a , a , a).mean() for k in ks if (total >= k).all()} return pass_at_k, results def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): def estimator(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) -> float: if n - c < k: return 1.0 return 1.0 - np.prod(1.0 - k / np.arange(n - c + 1 , n + 1)) if isinstance(_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = itertools.repeat(_UpperCAmelCase , len(_UpperCAmelCase)) else: assert len(_UpperCAmelCase) == len(_UpperCAmelCase) SCREAMING_SNAKE_CASE = iter(_UpperCAmelCase) return np.array([estimator(int(_UpperCAmelCase) , int(_UpperCAmelCase) , _UpperCAmelCase) for n, c in zip(_UpperCAmelCase , _UpperCAmelCase)])
73
import unittest from transformers import load_tool from .test_tools_common import ToolTesterMixin class _snake_case ( unittest.TestCase , A__ ): def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: SCREAMING_SNAKE_CASE = load_tool('text-classification') self.tool.setup() SCREAMING_SNAKE_CASE = load_tool('text-classification' , remote=a) def SCREAMING_SNAKE_CASE__ ( self) -> str: SCREAMING_SNAKE_CASE = self.tool('That\'s quite cool' , ['positive', 'negative']) self.assertEqual(a , 'positive') def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: SCREAMING_SNAKE_CASE = self.remote_tool('That\'s quite cool' , ['positive', 'negative']) self.assertEqual(a , 'positive') def SCREAMING_SNAKE_CASE__ ( self) -> int: SCREAMING_SNAKE_CASE = self.tool(text='That\'s quite cool' , labels=['positive', 'negative']) self.assertEqual(a , 'positive') def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: SCREAMING_SNAKE_CASE = self.remote_tool(text='That\'s quite cool' , labels=['positive', 'negative']) self.assertEqual(a , 'positive')
73
1
from ...configuration_utils import PretrainedConfig from ...utils import logging a_ : str = logging.get_logger(__name__) a_ : Any = { 'unc-nlp/lxmert-base-uncased': 'https://huggingface.co/unc-nlp/lxmert-base-uncased/resolve/main/config.json', } class _snake_case ( A__ ): _lowercase : List[Any] = '''lxmert''' _lowercase : Any = {} def __init__( self , a=3_0522 , a=768 , a=12 , a=9500 , a=1600 , a=400 , a=3072 , a="gelu" , a=0.1 , a=0.1 , a=512 , a=2 , a=0.02 , a=1E-12 , a=9 , a=5 , a=5 , a=2048 , a=4 , a=6.67 , a=True , a=True , a=True , a=True , a=True , a=True , a=True , **a , ) -> Optional[int]: SCREAMING_SNAKE_CASE = vocab_size SCREAMING_SNAKE_CASE = hidden_size SCREAMING_SNAKE_CASE = num_attention_heads SCREAMING_SNAKE_CASE = hidden_act SCREAMING_SNAKE_CASE = intermediate_size SCREAMING_SNAKE_CASE = hidden_dropout_prob SCREAMING_SNAKE_CASE = attention_probs_dropout_prob SCREAMING_SNAKE_CASE = max_position_embeddings SCREAMING_SNAKE_CASE = type_vocab_size SCREAMING_SNAKE_CASE = initializer_range SCREAMING_SNAKE_CASE = layer_norm_eps SCREAMING_SNAKE_CASE = num_qa_labels SCREAMING_SNAKE_CASE = num_object_labels SCREAMING_SNAKE_CASE = num_attr_labels SCREAMING_SNAKE_CASE = l_layers SCREAMING_SNAKE_CASE = x_layers SCREAMING_SNAKE_CASE = r_layers SCREAMING_SNAKE_CASE = visual_feat_dim SCREAMING_SNAKE_CASE = visual_pos_dim SCREAMING_SNAKE_CASE = visual_loss_normalizer SCREAMING_SNAKE_CASE = task_matched SCREAMING_SNAKE_CASE = task_mask_lm SCREAMING_SNAKE_CASE = task_obj_predict SCREAMING_SNAKE_CASE = task_qa SCREAMING_SNAKE_CASE = visual_obj_loss SCREAMING_SNAKE_CASE = visual_attr_loss SCREAMING_SNAKE_CASE = visual_feat_loss SCREAMING_SNAKE_CASE = {'vision': r_layers, 'cross_encoder': x_layers, 'language': l_layers} super().__init__(**a)
73
import sys import turtle def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): return (pa[0] + pa[0]) / 2, (pa[1] + pa[1]) / 2 def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , ): my_pen.up() my_pen.goto(vertexa[0] , vertexa[1]) my_pen.down() my_pen.goto(vertexa[0] , vertexa[1]) my_pen.goto(vertexa[0] , vertexa[1]) my_pen.goto(vertexa[0] , vertexa[1]) if depth == 0: return triangle(_UpperCAmelCase , get_mid(_UpperCAmelCase , _UpperCAmelCase) , get_mid(_UpperCAmelCase , _UpperCAmelCase) , depth - 1) triangle(_UpperCAmelCase , get_mid(_UpperCAmelCase , _UpperCAmelCase) , get_mid(_UpperCAmelCase , _UpperCAmelCase) , depth - 1) triangle(_UpperCAmelCase , get_mid(_UpperCAmelCase , _UpperCAmelCase) , get_mid(_UpperCAmelCase , _UpperCAmelCase) , depth - 1) if __name__ == "__main__": if len(sys.argv) != 2: raise ValueError( 'Correct format for using this script: ' 'python fractals.py <int:depth_for_fractal>' ) a_ : Any = turtle.Turtle() my_pen.ht() my_pen.speed(5) my_pen.pencolor('red') a_ : str = [(-1_75, -1_25), (0, 1_75), (1_75, -1_25)] # vertices of triangle triangle(vertices[0], vertices[1], vertices[2], int(sys.argv[1]))
73
1
import argparse import logging import os import sys import numpy as np import onnxruntime import torch from bart_onnx.generation_onnx import BARTBeamSearchGenerator from bart_onnx.reduce_onnx_size import remove_dup_initializers import transformers from transformers import BartForConditionalGeneration, BartTokenizer logging.basicConfig( format='%(asctime)s | %(levelname)s | %(name)s | [%(filename)s:%(lineno)d] %(message)s', datefmt='%Y-%m-%d %H:%M:%S', level=os.environ.get('LOGLEVEL', 'INFO').upper(), stream=sys.stdout, ) a_ : List[Any] = logging.getLogger(__name__) a_ : Tuple = {'facebook/bart-base': BartForConditionalGeneration} a_ : Dict = {'facebook/bart-base': BartTokenizer} def lowerCamelCase__ (): SCREAMING_SNAKE_CASE = argparse.ArgumentParser(description='Export Bart model + Beam Search to ONNX graph.') parser.add_argument( '--validation_file' , type=_UpperCAmelCase , default=_UpperCAmelCase , help='A csv or a json file containing the validation data.') parser.add_argument( '--max_length' , type=_UpperCAmelCase , default=5 , help='The maximum total input sequence length after tokenization.' , ) parser.add_argument( '--num_beams' , type=_UpperCAmelCase , default=_UpperCAmelCase , help=( 'Number of beams to use for evaluation. This argument will be ' 'passed to ``model.generate``, which is used during ``evaluate`` and ``predict``.' ) , ) parser.add_argument( '--model_name_or_path' , type=_UpperCAmelCase , help='Path to pretrained model or model identifier from huggingface.co/models.' , required=_UpperCAmelCase , ) parser.add_argument( '--config_name' , type=_UpperCAmelCase , default=_UpperCAmelCase , help='Pretrained config name or path if not the same as model_name' , ) parser.add_argument( '--device' , type=_UpperCAmelCase , default='cpu' , help='Device where the model will be run' , ) parser.add_argument('--output_file_path' , type=_UpperCAmelCase , default=_UpperCAmelCase , help='Where to store the final ONNX file.') SCREAMING_SNAKE_CASE = parser.parse_args() return args def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase="cpu"): SCREAMING_SNAKE_CASE = model_dict[model_name].from_pretrained(_UpperCAmelCase).to(_UpperCAmelCase) SCREAMING_SNAKE_CASE = tokenizer_dict[model_name].from_pretrained(_UpperCAmelCase) if model_name in ["facebook/bart-base"]: SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = 0 return huggingface_model, tokenizer def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): model.eval() SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = torch.jit.script(BARTBeamSearchGenerator(_UpperCAmelCase)) with torch.no_grad(): SCREAMING_SNAKE_CASE = 'My friends are cool but they eat too many carbs.' SCREAMING_SNAKE_CASE = tokenizer([ARTICLE_TO_SUMMARIZE] , max_length=1024 , return_tensors='pt').to(model.device) SCREAMING_SNAKE_CASE = model.generate( inputs['input_ids'] , attention_mask=inputs['attention_mask'] , num_beams=_UpperCAmelCase , max_length=_UpperCAmelCase , early_stopping=_UpperCAmelCase , decoder_start_token_id=model.config.decoder_start_token_id , ) torch.onnx.export( _UpperCAmelCase , ( inputs['input_ids'], inputs['attention_mask'], num_beams, max_length, model.config.decoder_start_token_id, ) , _UpperCAmelCase , opset_version=14 , input_names=['input_ids', 'attention_mask', 'num_beams', 'max_length', 'decoder_start_token_id'] , output_names=['output_ids'] , dynamic_axes={ 'input_ids': {0: 'batch', 1: 'seq'}, 'output_ids': {0: 'batch', 1: 'seq_out'}, } , example_outputs=_UpperCAmelCase , ) logger.info('Model exported to {}'.format(_UpperCAmelCase)) SCREAMING_SNAKE_CASE = remove_dup_initializers(os.path.abspath(_UpperCAmelCase)) logger.info('Deduplicated and optimized model written to {}'.format(_UpperCAmelCase)) SCREAMING_SNAKE_CASE = onnxruntime.InferenceSession(_UpperCAmelCase) SCREAMING_SNAKE_CASE = ort_sess.run( _UpperCAmelCase , { 'input_ids': inputs['input_ids'].cpu().numpy(), 'attention_mask': inputs['attention_mask'].cpu().numpy(), 'num_beams': np.array(_UpperCAmelCase), 'max_length': np.array(_UpperCAmelCase), 'decoder_start_token_id': np.array(model.config.decoder_start_token_id), } , ) np.testing.assert_allclose(summary_ids.cpu().numpy() , ort_out[0] , rtol=1e-3 , atol=1e-3) logger.info('Model outputs from torch and ONNX Runtime are similar.') logger.info('Success.') def lowerCamelCase__ (): SCREAMING_SNAKE_CASE = parse_args() SCREAMING_SNAKE_CASE = 5 SCREAMING_SNAKE_CASE = 4 # Make one log on every process with the configuration for debugging. logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s - %(message)s' , datefmt='%m/%d/%Y %H:%M:%S' , level=logging.INFO , ) logger.setLevel(logging.INFO) transformers.utils.logging.set_verbosity_error() SCREAMING_SNAKE_CASE = torch.device(args.device) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = load_model_tokenizer(args.model_name_or_path , _UpperCAmelCase) if model.config.decoder_start_token_id is None: raise ValueError('Make sure that `config.decoder_start_token_id` is correctly defined') model.to(_UpperCAmelCase) if args.max_length: SCREAMING_SNAKE_CASE = args.max_length if args.num_beams: SCREAMING_SNAKE_CASE = args.num_beams if args.output_file_path: SCREAMING_SNAKE_CASE = args.output_file_path else: SCREAMING_SNAKE_CASE = 'BART.onnx' logger.info('Exporting model to ONNX') export_and_validate_model(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) if __name__ == "__main__": main()
73
import math import os from copy import deepcopy import datasets import evaluate import torch import transformers from datasets import load_dataset from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer from accelerate import Accelerator from accelerate.test_utils import RegressionDataset, RegressionModel from accelerate.utils import is_tpu_available, set_seed a_ : Any = 'true' def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase=82 , _UpperCAmelCase=16): set_seed(42) SCREAMING_SNAKE_CASE = RegressionModel() SCREAMING_SNAKE_CASE = deepcopy(_UpperCAmelCase) SCREAMING_SNAKE_CASE = RegressionDataset(length=_UpperCAmelCase) SCREAMING_SNAKE_CASE = DataLoader(_UpperCAmelCase , batch_size=_UpperCAmelCase) model.to(accelerator.device) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = accelerator.prepare(_UpperCAmelCase , _UpperCAmelCase) return model, ddp_model, dataloader def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase=False): SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained('hf-internal-testing/mrpc-bert-base-cased') SCREAMING_SNAKE_CASE = load_dataset('glue' , 'mrpc' , split='validation') def tokenize_function(_UpperCAmelCase): SCREAMING_SNAKE_CASE = tokenizer(examples['sentence1'] , examples['sentence2'] , truncation=_UpperCAmelCase , max_length=_UpperCAmelCase) return outputs with accelerator.main_process_first(): SCREAMING_SNAKE_CASE = dataset.map( _UpperCAmelCase , batched=_UpperCAmelCase , remove_columns=['idx', 'sentence1', 'sentence2'] , ) SCREAMING_SNAKE_CASE = tokenized_datasets.rename_column('label' , 'labels') def collate_fn(_UpperCAmelCase): if use_longest: return tokenizer.pad(_UpperCAmelCase , padding='longest' , return_tensors='pt') return tokenizer.pad(_UpperCAmelCase , padding='max_length' , max_length=128 , return_tensors='pt') return DataLoader(_UpperCAmelCase , shuffle=_UpperCAmelCase , collate_fn=_UpperCAmelCase , batch_size=16) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = Accelerator(dispatch_batches=_UpperCAmelCase , split_batches=_UpperCAmelCase) SCREAMING_SNAKE_CASE = get_dataloader(_UpperCAmelCase , not dispatch_batches) SCREAMING_SNAKE_CASE = AutoModelForSequenceClassification.from_pretrained( 'hf-internal-testing/mrpc-bert-base-cased' , return_dict=_UpperCAmelCase) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = accelerator.prepare(_UpperCAmelCase , _UpperCAmelCase) return {"ddp": [ddp_model, ddp_dataloader, "cuda:0"], "no": [model, dataloader, accelerator.device]}, accelerator def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = [] for batch in dataloader: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = batch.values() with torch.no_grad(): SCREAMING_SNAKE_CASE = model(_UpperCAmelCase) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = accelerator.gather_for_metrics((logit, target)) logits_and_targets.append((logit, target)) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = [], [] for logit, targ in logits_and_targets: logits.append(_UpperCAmelCase) targs.append(_UpperCAmelCase) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = torch.cat(_UpperCAmelCase), torch.cat(_UpperCAmelCase) return logits, targs def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase=82 , _UpperCAmelCase=False , _UpperCAmelCase=False , _UpperCAmelCase=16): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = get_basic_setup(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = generate_predictions(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) assert ( len(_UpperCAmelCase) == num_samples ), F'''Unexpected number of inputs:\n Expected: {num_samples}\n Actual: {len(_UpperCAmelCase)}''' def lowerCamelCase__ (_UpperCAmelCase = False , _UpperCAmelCase = False): SCREAMING_SNAKE_CASE = evaluate.load('glue' , 'mrpc') SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = get_mrpc_setup(_UpperCAmelCase , _UpperCAmelCase) # First do baseline SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = setup['no'] model.to(_UpperCAmelCase) model.eval() for batch in dataloader: batch.to(_UpperCAmelCase) with torch.inference_mode(): SCREAMING_SNAKE_CASE = model(**_UpperCAmelCase) SCREAMING_SNAKE_CASE = outputs.logits.argmax(dim=-1) metric.add_batch(predictions=_UpperCAmelCase , references=batch['labels']) SCREAMING_SNAKE_CASE = metric.compute() # Then do distributed SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = setup['ddp'] model.eval() for batch in dataloader: with torch.inference_mode(): SCREAMING_SNAKE_CASE = model(**_UpperCAmelCase) SCREAMING_SNAKE_CASE = outputs.logits.argmax(dim=-1) SCREAMING_SNAKE_CASE = batch['labels'] SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = accelerator.gather_for_metrics((preds, references)) metric.add_batch(predictions=_UpperCAmelCase , references=_UpperCAmelCase) SCREAMING_SNAKE_CASE = metric.compute() for key in "accuracy f1".split(): assert math.isclose( baseline[key] , distributed[key]), F'''Baseline and Distributed are not the same for key {key}:\n\tBaseline: {baseline[key]}\n\tDistributed: {distributed[key]}\n''' def lowerCamelCase__ (): SCREAMING_SNAKE_CASE = Accelerator(split_batches=_UpperCAmelCase , dispatch_batches=_UpperCAmelCase) if accelerator.is_local_main_process: datasets.utils.logging.set_verbosity_warning() transformers.utils.logging.set_verbosity_warning() else: datasets.utils.logging.set_verbosity_error() transformers.utils.logging.set_verbosity_error() # These are a bit slower so they should only be ran on the GPU or TPU if torch.cuda.is_available() or is_tpu_available(): if accelerator.is_local_main_process: print('**Testing gather_for_metrics**') for split_batches in [True, False]: for dispatch_batches in [True, False]: if accelerator.is_local_main_process: print(F'''With: `split_batches={split_batches}`, `dispatch_batches={dispatch_batches}`''') test_mrpc(_UpperCAmelCase , _UpperCAmelCase) accelerator.state._reset_state() if accelerator.is_local_main_process: print('**Test torch metrics**') for split_batches in [True, False]: for dispatch_batches in [True, False]: SCREAMING_SNAKE_CASE = Accelerator(split_batches=_UpperCAmelCase , dispatch_batches=_UpperCAmelCase) if accelerator.is_local_main_process: print(F'''With: `split_batches={split_batches}`, `dispatch_batches={dispatch_batches}`, length=99''') test_torch_metrics(_UpperCAmelCase , 99) accelerator.state._reset_state() if accelerator.is_local_main_process: print('**Test last batch is not dropped when perfectly divisible**') SCREAMING_SNAKE_CASE = Accelerator() test_torch_metrics(_UpperCAmelCase , 512) accelerator.state._reset_state() def lowerCamelCase__ (_UpperCAmelCase): # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
73
1
# NOTE: This file is deprecated and will be removed in a future version. # It only exists so that temporarely `from diffusers.pipelines import DiffusionPipeline` works from ...utils import deprecate from ..controlnet.multicontrolnet import MultiControlNetModel # noqa: F401 from ..controlnet.pipeline_controlnet import StableDiffusionControlNetPipeline # noqa: F401 deprecate( 'stable diffusion controlnet', '0.22.0', 'Importing `StableDiffusionControlNetPipeline` or `MultiControlNetModel` from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_controlnet is deprecated. Please import `from diffusers import StableDiffusionControlNetPipeline` instead.', standard_warn=False, stacklevel=3, )
73
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available a_ : List[str] = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : Optional[Any] = ['GPTSw3Tokenizer'] if TYPE_CHECKING: try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_gpt_swa import GPTSwaTokenizer else: import sys a_ : Tuple = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
73
1
import argparse import dataclasses import json import logging import os import shutil from typing import List, Optional import datasets from accelerate import Accelerator from datasets import load_dataset from finetuning import finetune from tqdm.auto import tqdm import transformers from transformers import AutoConfig, set_seed from transformers.trainer_utils import IntervalStrategy a_ : Dict = logging.getLogger(__name__) a_ : Tuple = 'pytorch_model.bin' @dataclasses.dataclass class _snake_case : _lowercase : str = dataclasses.field( metadata={'''help''': '''Path to pretrained model or model identifier from huggingface.co/models.'''} ) _lowercase : Optional[str] = dataclasses.field( default=A__ , metadata={'''help''': '''Where do you want to store the pretrained models downloaded from huggingface.co.'''} , ) @dataclasses.dataclass class _snake_case : _lowercase : str = dataclasses.field(metadata={'''help''': '''A csv or a json file containing the training data.'''} ) _lowercase : str = dataclasses.field(metadata={'''help''': '''A csv or a json file containing the data to predict on.'''} ) _lowercase : Optional[str] = dataclasses.field( default=A__ , metadata={'''help''': '''A csv or a json file containing the validation data.'''} ) _lowercase : Optional[str] = dataclasses.field( default=A__ , metadata={'''help''': '''The name of the task to train on.'''} , ) _lowercase : Optional[List[str]] = dataclasses.field( default=A__ , metadata={'''help''': '''The list of labels for the task.'''} ) @dataclasses.dataclass class _snake_case : _lowercase : str = dataclasses.field( metadata={'''help''': '''The output directory where the model predictions and checkpoints will be written.'''} ) _lowercase : Optional[str] = dataclasses.field( default='''accuracy''' , metadata={'''help''': '''The evaluation metric used for the task.'''} ) _lowercase : Optional[str] = dataclasses.field( default='''no''' , metadata={ '''help''': '''The evaluation strategy to adopt during training. Possible values are: ["no", "step", "epoch]''' } , ) _lowercase : Optional[int] = dataclasses.field( default=10 , metadata={'''help''': '''Number of evaluation calls with no improvement after which training will be stopped.'''} , ) _lowercase : Optional[float] = dataclasses.field( default=0.0 , metadata={ '''help''': '''How much the specified evaluation metric must improve to satisfy early stopping conditions.''' } , ) _lowercase : Optional[bool] = dataclasses.field( default=A__ , metadata={'''help''': '''Whether to filter the pseudo-labeled data based on the confidence score.'''} , ) _lowercase : Optional[bool] = dataclasses.field( default=A__ , metadata={'''help''': '''Whether to filter the pseudo-labeled data based on the validation performance.'''} , ) _lowercase : Optional[bool] = dataclasses.field( default=A__ , metadata={'''help''': '''Whether to fine-tune on labeled data after pseudo training.'''} , ) _lowercase : Optional[float] = dataclasses.field( default=0.0 , metadata={'''help''': '''Confidence threshold for pseudo-labeled data filtering.'''} , ) _lowercase : Optional[int] = dataclasses.field( default=1_00 , metadata={'''help''': '''Number of evaluation calls with no improvement after which training will be stopped.'''} , ) _lowercase : Optional[int] = dataclasses.field( default=A__ , metadata={'''help''': '''Random seed for initialization.'''} , ) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = datasets.concatenate_datasets([infer_input, infer_output] , axis=1) if args.do_filter_by_confidence: SCREAMING_SNAKE_CASE = dataset.filter(lambda _UpperCAmelCase: example["probability"] > args.confidence_threshold) if args.do_filter_by_val_performance: assert eval_result >= 0.0 and eval_result <= 1.0 SCREAMING_SNAKE_CASE = int(eval_result * len(_UpperCAmelCase)) print(_UpperCAmelCase) SCREAMING_SNAKE_CASE = dataset.sort('probability' , reverse=_UpperCAmelCase) SCREAMING_SNAKE_CASE = dataset.select(range(_UpperCAmelCase)) SCREAMING_SNAKE_CASE = dataset.remove_columns(['label', 'probability']) SCREAMING_SNAKE_CASE = dataset.rename_column('prediction' , 'label') SCREAMING_SNAKE_CASE = dataset.map(lambda _UpperCAmelCase: {"label": idalabel[example["label"]]}) SCREAMING_SNAKE_CASE = dataset.shuffle(seed=args.seed) SCREAMING_SNAKE_CASE = os.path.join(_UpperCAmelCase , F'''train_pseudo.{args.data_file_extension}''') if args.data_file_extension == "csv": dataset.to_csv(_UpperCAmelCase , index=_UpperCAmelCase) else: dataset.to_json(_UpperCAmelCase) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , **_UpperCAmelCase): SCREAMING_SNAKE_CASE = Accelerator() # Make one log on every process with the configuration for debugging. logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s - %(message)s' , datefmt='%m/%d/%Y %H:%M:%S' , level=logging.INFO , ) logger.info(accelerator.state) # Setup logging, we only want one process per machine to log things on the # screen. accelerator.is_local_main_process is only True for one process per # machine. logger.setLevel(logging.INFO if accelerator.is_local_main_process else logging.ERROR) if accelerator.is_local_main_process: datasets.utils.logging.set_verbosity_warning() transformers.utils.logging.set_verbosity_info() else: datasets.utils.logging.set_verbosity_error() transformers.utils.logging.set_verbosity_error() SCREAMING_SNAKE_CASE = STModelArguments(model_name_or_path=_UpperCAmelCase) SCREAMING_SNAKE_CASE = STDataArguments(train_file=_UpperCAmelCase , infer_file=_UpperCAmelCase) SCREAMING_SNAKE_CASE = STTrainingArguments(output_dir=_UpperCAmelCase) SCREAMING_SNAKE_CASE = argparse.Namespace() for arg_class in (model_args, data_args, training_args): for key, value in vars(_UpperCAmelCase).items(): setattr(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) for key, value in kwargs.items(): if hasattr(_UpperCAmelCase , _UpperCAmelCase): setattr(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) # Sanity checks SCREAMING_SNAKE_CASE = {} SCREAMING_SNAKE_CASE = None # You need to provide the training data and the data to predict on assert args.train_file is not None assert args.infer_file is not None SCREAMING_SNAKE_CASE = args.train_file SCREAMING_SNAKE_CASE = args.infer_file if args.evaluation_strategy != IntervalStrategy.NO.value: assert args.eval_file is not None SCREAMING_SNAKE_CASE = args.eval_file for key in data_files: SCREAMING_SNAKE_CASE = data_files[key].split('.')[-1] assert extension in ["csv", "json"], F'''`{key}_file` should be a csv or a json file.''' if args.data_file_extension is None: SCREAMING_SNAKE_CASE = extension else: assert extension == args.data_file_extension, F'''`{key}_file` should be a {args.data_file_extension} file`.''' assert ( args.eval_metric in datasets.list_metrics() ), F'''{args.eval_metric} not in the list of supported metrics {datasets.list_metrics()}.''' # If passed along, set the training seed now. if args.seed is not None: set_seed(args.seed) logger.info('Creating the initial data directory for self-training...') SCREAMING_SNAKE_CASE = F'''{args.output_dir}/self-train_iter-{{}}'''.format SCREAMING_SNAKE_CASE = data_dir_format(0) if accelerator.is_main_process: if args.output_dir is not None: os.makedirs(args.output_dir , exist_ok=_UpperCAmelCase) os.makedirs(_UpperCAmelCase , exist_ok=_UpperCAmelCase) accelerator.wait_for_everyone() SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = False # Show the progress bar SCREAMING_SNAKE_CASE = tqdm(range(args.max_selftrain_iterations) , disable=not accelerator.is_local_main_process) # Self-train for iteration in range(0 , int(args.max_selftrain_iterations)): SCREAMING_SNAKE_CASE = data_dir_format(_UpperCAmelCase) assert os.path.exists(_UpperCAmelCase) # Stage 1: initial fine-tuning for iteration = 0 or pseudo-training for # iteration > 0 SCREAMING_SNAKE_CASE = os.path.join(_UpperCAmelCase , 'stage-1') SCREAMING_SNAKE_CASE = { 'accelerator': accelerator, 'model_name_or_path': args.model_name_or_path, 'cache_dir': args.cache_dir, 'do_train': True, 'train_file': data_files['train'] if iteration == 0 else data_files['train_pseudo'], 'do_eval': True if args.eval_file is not None else False, 'eval_file': data_files['eval'], 'do_predict': True, 'infer_file': data_files['infer'], 'task_name': args.task_name, 'label_list': args.label_list, 'output_dir': current_output_dir, 'eval_metric': args.eval_metric, 'evaluation_strategy': args.evaluation_strategy, 'early_stopping_patience': args.early_stopping_patience, 'early_stopping_threshold': args.early_stopping_threshold, 'seed': args.seed, } # Add additional training arguments for key, value in kwargs.items(): if key not in arguments_dict and not hasattr(_UpperCAmelCase , _UpperCAmelCase): arguments_dict.update({key: value}) SCREAMING_SNAKE_CASE = os.path.join(_UpperCAmelCase , 'best-checkpoint' , _UpperCAmelCase) if os.path.exists(_UpperCAmelCase): logger.info( 'Found existing model checkpoint at %s. Skipping self-training: iteration: %d, stage: 1.' , _UpperCAmelCase , _UpperCAmelCase , ) else: logger.info('***** Running self-training: iteration: %d, stage: 1 *****' , _UpperCAmelCase) finetune(**_UpperCAmelCase) accelerator.wait_for_everyone() assert os.path.exists(_UpperCAmelCase) logger.info('Self-training job completed: iteration: %d, stage: 1.' , _UpperCAmelCase) if iteration > 0 and args.finetune_on_labeled_data: # Stage 2 (optional): fine-tuning on the original labeled data SCREAMING_SNAKE_CASE = os.path.join(_UpperCAmelCase , 'best-checkpoint') SCREAMING_SNAKE_CASE = os.path.join(_UpperCAmelCase , 'stage-2') # Update arguments_dict SCREAMING_SNAKE_CASE = model_path SCREAMING_SNAKE_CASE = data_files['train'] SCREAMING_SNAKE_CASE = current_output_dir SCREAMING_SNAKE_CASE = os.path.join(_UpperCAmelCase , 'best-checkpoint' , _UpperCAmelCase) if os.path.exists(_UpperCAmelCase): logger.info( 'Found existing model checkpoint at %s. Skipping self-training: iteration: %d, stage: 2.' , _UpperCAmelCase , _UpperCAmelCase , ) else: logger.info('***** Running self-training: iteration: %d, stage: 2 *****' , _UpperCAmelCase) finetune(**_UpperCAmelCase) accelerator.wait_for_everyone() assert os.path.exists(_UpperCAmelCase) logger.info('Self-training job completed: iteration: %d, stage: 2.' , _UpperCAmelCase) SCREAMING_SNAKE_CASE = iteration SCREAMING_SNAKE_CASE = data_dir_format(iteration + 1) SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained(os.path.join(_UpperCAmelCase , 'best-checkpoint')) SCREAMING_SNAKE_CASE = config.idalabel SCREAMING_SNAKE_CASE = os.path.join(_UpperCAmelCase , 'eval_results_best-checkpoint.json') SCREAMING_SNAKE_CASE = os.path.join(_UpperCAmelCase , 'test_results_best-checkpoint.json') assert os.path.exists(_UpperCAmelCase) with open(_UpperCAmelCase , 'r') as f: SCREAMING_SNAKE_CASE = float(json.load(_UpperCAmelCase)[args.eval_metric]) SCREAMING_SNAKE_CASE = os.path.join(_UpperCAmelCase , 'infer_output_best-checkpoint.csv') assert os.path.exists(_UpperCAmelCase) # Loading the dataset from local csv or json files. SCREAMING_SNAKE_CASE = load_dataset(args.data_file_extension , data_files={'data': data_files['infer']})['data'] SCREAMING_SNAKE_CASE = load_dataset('csv' , data_files={'data': infer_output_file})['data'] if accelerator.is_main_process: os.makedirs(_UpperCAmelCase , exist_ok=_UpperCAmelCase) shutil.copy(_UpperCAmelCase , os.path.join(_UpperCAmelCase , F'''eval_results_iter-{iteration}.json''')) if os.path.exists(_UpperCAmelCase): shutil.copy(_UpperCAmelCase , os.path.join(_UpperCAmelCase , F'''test_results_iter-{iteration}.json''')) create_pseudo_labeled_data(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) accelerator.wait_for_everyone() SCREAMING_SNAKE_CASE = os.path.join(_UpperCAmelCase , F'''train_pseudo.{args.data_file_extension}''') if args.evaluation_strategy != IntervalStrategy.NO.value: SCREAMING_SNAKE_CASE = eval_result if best_iteration is None: SCREAMING_SNAKE_CASE = new_iteration SCREAMING_SNAKE_CASE = new_eval_result else: if new_eval_result - best_eval_result > args.early_stopping_threshold: SCREAMING_SNAKE_CASE = new_iteration SCREAMING_SNAKE_CASE = new_eval_result SCREAMING_SNAKE_CASE = 0 else: if new_eval_result == best_eval_result: SCREAMING_SNAKE_CASE = new_iteration SCREAMING_SNAKE_CASE = new_eval_result early_stopping_patience_counter += 1 if early_stopping_patience_counter >= args.early_stopping_patience: SCREAMING_SNAKE_CASE = True progress_bar.update(1) if should_training_stop: break if best_iteration is not None: # Save the best iteration logger.info('Best iteration: %d' , _UpperCAmelCase) logger.info('Best evaluation result: %s = %f' , args.eval_metric , _UpperCAmelCase) accelerator.wait_for_everyone() if accelerator.is_main_process: shutil.copy( os.path.join(_UpperCAmelCase , F'''eval_results_iter-{iteration}.json''') , os.path.join(_UpperCAmelCase , 'eval_results_best-iteration.json') , ) else: # Assume that the last iteration is the best logger.info('Best iteration: %d' , args.max_selftrain_iterations - 1) logger.info('Best evaluation result: %s = %f' , args.eval_metric , _UpperCAmelCase) accelerator.wait_for_everyone() if accelerator.is_main_process: shutil.copy( os.path.join(_UpperCAmelCase , F'''eval_results_iter-{args.max_selftrain_iterations - 1}.json''') , os.path.join(_UpperCAmelCase , 'eval_results_best-iteration.json') , )
73
import os from tempfile import TemporaryDirectory from unittest import TestCase import pytest from absl.testing import parameterized from datasets import config from datasets.arrow_reader import HF_GCP_BASE_URL from datasets.builder import DatasetBuilder from datasets.dataset_dict import IterableDatasetDict from datasets.iterable_dataset import IterableDataset from datasets.load import dataset_module_factory, import_main_class from datasets.utils.file_utils import cached_path a_ : str = [ {'dataset': 'wikipedia', 'config_name': '20220301.de'}, {'dataset': 'wikipedia', 'config_name': '20220301.en'}, {'dataset': 'wikipedia', 'config_name': '20220301.fr'}, {'dataset': 'wikipedia', 'config_name': '20220301.frr'}, {'dataset': 'wikipedia', 'config_name': '20220301.it'}, {'dataset': 'wikipedia', 'config_name': '20220301.simple'}, {'dataset': 'snli', 'config_name': 'plain_text'}, {'dataset': 'eli5', 'config_name': 'LFQA_reddit'}, {'dataset': 'wiki40b', 'config_name': 'en'}, {'dataset': 'wiki_dpr', 'config_name': 'psgs_w100.nq.compressed'}, {'dataset': 'wiki_dpr', 'config_name': 'psgs_w100.nq.no_index'}, {'dataset': 'wiki_dpr', 'config_name': 'psgs_w100.multiset.no_index'}, {'dataset': 'natural_questions', 'config_name': 'default'}, ] def lowerCamelCase__ (_UpperCAmelCase=True): if with_config: return [ { "testcase_name": d["dataset"] + "/" + d["config_name"], "dataset": d["dataset"], "config_name": d["config_name"], } for d in DATASETS_ON_HF_GCP ] else: return [ {"testcase_name": dataset, "dataset": dataset} for dataset in {d["dataset"] for d in DATASETS_ON_HF_GCP} ] @parameterized.named_parameters(list_datasets_on_hf_gcp_parameters(with_config=A__ ) ) class _snake_case ( A__ ): _lowercase : Optional[Any] = None _lowercase : Optional[Any] = None def SCREAMING_SNAKE_CASE__ ( self , a , a) -> Optional[Any]: with TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE = dataset_module_factory(a , cache_dir=a) SCREAMING_SNAKE_CASE = import_main_class(dataset_module.module_path , dataset=a) SCREAMING_SNAKE_CASE = builder_cls( cache_dir=a , config_name=a , hash=dataset_module.hash , ) SCREAMING_SNAKE_CASE = '/'.join( [ HF_GCP_BASE_URL, builder_instance._relative_data_dir(with_hash=a).replace(os.sep , '/'), config.DATASET_INFO_FILENAME, ]) SCREAMING_SNAKE_CASE = cached_path(a , cache_dir=a) self.assertTrue(os.path.exists(a)) @pytest.mark.integration def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = tmp_path_factory.mktemp('test_hf_gcp') / 'test_wikipedia_simple' SCREAMING_SNAKE_CASE = dataset_module_factory('wikipedia' , cache_dir=_UpperCAmelCase) SCREAMING_SNAKE_CASE = import_main_class(dataset_module.module_path) SCREAMING_SNAKE_CASE = builder_cls( cache_dir=_UpperCAmelCase , config_name='20220301.frr' , hash=dataset_module.hash , ) # use the HF cloud storage, not the original download_and_prepare that uses apache-beam SCREAMING_SNAKE_CASE = None builder_instance.download_and_prepare() SCREAMING_SNAKE_CASE = builder_instance.as_dataset() assert ds @pytest.mark.integration def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = dataset_module_factory('wikipedia' , cache_dir=_UpperCAmelCase) SCREAMING_SNAKE_CASE = import_main_class(dataset_module.module_path , dataset=_UpperCAmelCase) SCREAMING_SNAKE_CASE = builder_cls( cache_dir=_UpperCAmelCase , config_name='20220301.frr' , hash=dataset_module.hash , ) SCREAMING_SNAKE_CASE = builder_instance.as_streaming_dataset() assert ds assert isinstance(_UpperCAmelCase , _UpperCAmelCase) assert "train" in ds assert isinstance(ds['train'] , _UpperCAmelCase) assert next(iter(ds['train']))
73
1
from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class _snake_case ( A__ ): _lowercase : List[str] = '''ClapFeatureExtractor''' _lowercase : str = ('''RobertaTokenizer''', '''RobertaTokenizerFast''') def __init__( self , a , a) -> Optional[int]: super().__init__(a , a) def __call__( self , a=None , a=None , a=None , **a) -> int: SCREAMING_SNAKE_CASE = kwargs.pop('sampling_rate' , a) if text is None and audios is None: raise ValueError('You have to specify either text or audios. Both cannot be none.') if text is not None: SCREAMING_SNAKE_CASE = self.tokenizer(a , return_tensors=a , **a) if audios is not None: SCREAMING_SNAKE_CASE = self.feature_extractor( a , sampling_rate=a , return_tensors=a , **a) if text is not None and audios is not None: SCREAMING_SNAKE_CASE = audio_features.input_features return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**a) , tensor_type=a) def SCREAMING_SNAKE_CASE__ ( self , *a , **a) -> List[str]: return self.tokenizer.batch_decode(*a , **a) def SCREAMING_SNAKE_CASE__ ( self , *a , **a) -> Union[str, Any]: return self.tokenizer.decode(*a , **a) @property def SCREAMING_SNAKE_CASE__ ( self) -> str: SCREAMING_SNAKE_CASE = self.tokenizer.model_input_names SCREAMING_SNAKE_CASE = self.feature_extractor.model_input_names return list(dict.fromkeys(tokenizer_input_names + feature_extractor_input_names))
73
from __future__ import annotations def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = 2 SCREAMING_SNAKE_CASE = [] while i * i <= n: if n % i: i += 1 else: n //= i factors.append(_UpperCAmelCase) if n > 1: factors.append(_UpperCAmelCase) return factors if __name__ == "__main__": import doctest doctest.testmod()
73
1
def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): global f # a global dp table for knapsack if f[i][j] < 0: if j < wt[i - 1]: SCREAMING_SNAKE_CASE = mf_knapsack(i - 1 , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) else: SCREAMING_SNAKE_CASE = max( mf_knapsack(i - 1 , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) , mf_knapsack(i - 1 , _UpperCAmelCase , _UpperCAmelCase , j - wt[i - 1]) + val[i - 1] , ) SCREAMING_SNAKE_CASE = val return f[i][j] def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = [[0] * (w + 1) for _ in range(n + 1)] for i in range(1 , n + 1): for w_ in range(1 , w + 1): if wt[i - 1] <= w_: SCREAMING_SNAKE_CASE = max(val[i - 1] + dp[i - 1][w_ - wt[i - 1]] , dp[i - 1][w_]) else: SCREAMING_SNAKE_CASE = dp[i - 1][w_] return dp[n][w_], dp def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): if not (isinstance(_UpperCAmelCase , (list, tuple)) and isinstance(_UpperCAmelCase , (list, tuple))): raise ValueError( 'Both the weights and values vectors must be either lists or tuples') SCREAMING_SNAKE_CASE = len(_UpperCAmelCase) if num_items != len(_UpperCAmelCase): SCREAMING_SNAKE_CASE = ( 'The number of weights must be the same as the number of values.\n' F'''But got {num_items} weights and {len(_UpperCAmelCase)} values''' ) raise ValueError(_UpperCAmelCase) for i in range(_UpperCAmelCase): if not isinstance(wt[i] , _UpperCAmelCase): SCREAMING_SNAKE_CASE = ( 'All weights must be integers but got weight of ' F'''type {type(wt[i])} at index {i}''' ) raise TypeError(_UpperCAmelCase) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = knapsack(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) SCREAMING_SNAKE_CASE = set() _construct_solution(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) return optimal_val, example_optional_set def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): # for the current item i at a maximum weight j to be part of an optimal subset, # the optimal value at (i, j) must be greater than the optimal value at (i-1, j). # where i - 1 means considering only the previous items at the given maximum weight if i > 0 and j > 0: if dp[i - 1][j] == dp[i][j]: _construct_solution(_UpperCAmelCase , _UpperCAmelCase , i - 1 , _UpperCAmelCase , _UpperCAmelCase) else: optimal_set.add(_UpperCAmelCase) _construct_solution(_UpperCAmelCase , _UpperCAmelCase , i - 1 , j - wt[i - 1] , _UpperCAmelCase) if __name__ == "__main__": a_ : int = [3, 2, 4, 4] a_ : Union[str, Any] = [4, 3, 2, 3] a_ : Tuple = 4 a_ : Optional[int] = 6 a_ : Dict = [[0] * (w + 1)] + [[0] + [-1] * (w + 1) for _ in range(n + 1)] a_ , a_ : str = knapsack(w, wt, val, n) print(optimal_solution) print(mf_knapsack(n, wt, val, w)) # switched the n and w # testing the dynamic programming problem with example # the optimal subset for the above example are items 3 and 4 a_ , a_ : Union[str, Any] = knapsack_with_example_solution(w, wt, val) assert optimal_solution == 8 assert optimal_subset == {3, 4} print('optimal_value = ', optimal_solution) print('An optimal subset corresponding to the optimal value', optimal_subset)
73
import math import os import sys def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = '' try: with open(_UpperCAmelCase , 'rb') as binary_file: SCREAMING_SNAKE_CASE = binary_file.read() for dat in data: SCREAMING_SNAKE_CASE = F'''{dat:08b}''' result += curr_byte return result except OSError: print('File not accessible') sys.exit() def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): lexicon.pop(_UpperCAmelCase) SCREAMING_SNAKE_CASE = last_match_id if math.loga(_UpperCAmelCase).is_integer(): for curr_key in lexicon: SCREAMING_SNAKE_CASE = '0' + lexicon[curr_key] SCREAMING_SNAKE_CASE = bin(_UpperCAmelCase)[2:] def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = {'0': '0', '1': '1'} SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = '', '' SCREAMING_SNAKE_CASE = len(_UpperCAmelCase) for i in range(len(_UpperCAmelCase)): curr_string += data_bits[i] if curr_string not in lexicon: continue SCREAMING_SNAKE_CASE = lexicon[curr_string] result += last_match_id add_key_to_lexicon(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) index += 1 SCREAMING_SNAKE_CASE = '' while curr_string != "" and curr_string not in lexicon: curr_string += "0" if curr_string != "": SCREAMING_SNAKE_CASE = lexicon[curr_string] result += last_match_id return result def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = os.path.getsize(_UpperCAmelCase) SCREAMING_SNAKE_CASE = bin(_UpperCAmelCase)[2:] SCREAMING_SNAKE_CASE = len(_UpperCAmelCase) return "0" * (length_length - 1) + file_length_binary + compressed def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = 8 try: with open(_UpperCAmelCase , 'wb') as opened_file: SCREAMING_SNAKE_CASE = [ to_write[i : i + byte_length] for i in range(0 , len(_UpperCAmelCase) , _UpperCAmelCase) ] 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(_UpperCAmelCase , 2).to_bytes(1 , byteorder='big')) except OSError: print('File not accessible') sys.exit() def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = read_file_binary(_UpperCAmelCase) SCREAMING_SNAKE_CASE = compress_data(_UpperCAmelCase) SCREAMING_SNAKE_CASE = add_file_length(_UpperCAmelCase , _UpperCAmelCase) write_file_binary(_UpperCAmelCase , _UpperCAmelCase) if __name__ == "__main__": compress(sys.argv[1], sys.argv[2])
73
1
# limitations under the License. # NOTE: This file is deprecated and will be removed in a future version. # It only exists so that temporarely `from diffusers.pipelines import DiffusionPipeline` works from .pipelines import DiffusionPipeline, ImagePipelineOutput # noqa: F401 from .utils import deprecate deprecate( 'pipelines_utils', '0.22.0', 'Importing `DiffusionPipeline` or `ImagePipelineOutput` from diffusers.pipeline_utils is deprecated. Please import from diffusers.pipelines.pipeline_utils instead.', standard_warn=False, stacklevel=3, )
73
import warnings from typing import Dict import numpy as np from ..utils import ExplicitEnum, add_end_docstrings, is_tf_available, is_torch_available from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline if is_tf_available(): from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if is_torch_available(): from ..models.auto.modeling_auto import MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING def lowerCamelCase__ (_UpperCAmelCase): return 1.0 / (1.0 + np.exp(-_outputs)) def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = np.max(_outputs , axis=-1 , keepdims=_UpperCAmelCase) SCREAMING_SNAKE_CASE = np.exp(_outputs - maxes) return shifted_exp / shifted_exp.sum(axis=-1 , keepdims=_UpperCAmelCase) class _snake_case ( A__ ): _lowercase : Tuple = '''sigmoid''' _lowercase : List[str] = '''softmax''' _lowercase : Tuple = '''none''' @add_end_docstrings( A__ , R''' return_all_scores (`bool`, *optional*, defaults to `False`): Whether to return all prediction scores or just the one of the predicted class. function_to_apply (`str`, *optional*, defaults to `"default"`): The function to apply to the model outputs in order to retrieve the scores. Accepts four different values: - `"default"`: if the model has a single label, will apply the sigmoid function on the output. If the model has several labels, will apply the softmax function on the output. - `"sigmoid"`: Applies the sigmoid function on the output. - `"softmax"`: Applies the softmax function on the output. - `"none"`: Does not apply any function on the output. ''' , ) class _snake_case ( A__ ): _lowercase : Optional[Any] = False _lowercase : Tuple = ClassificationFunction.NONE def __init__( self , **a) -> Optional[Any]: super().__init__(**a) self.check_model_type( TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if self.framework == 'tf' else MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING) def SCREAMING_SNAKE_CASE__ ( self , a=None , a=None , a="" , **a) -> Tuple: # Using "" as default argument because we're going to use `top_k=None` in user code to declare # "No top_k" SCREAMING_SNAKE_CASE = tokenizer_kwargs SCREAMING_SNAKE_CASE = {} if hasattr(self.model.config , 'return_all_scores') and return_all_scores is None: SCREAMING_SNAKE_CASE = self.model.config.return_all_scores if isinstance(a , a) or top_k is None: SCREAMING_SNAKE_CASE = top_k SCREAMING_SNAKE_CASE = False elif return_all_scores is not None: warnings.warn( '`return_all_scores` is now deprecated, if want a similar functionality use `top_k=None` instead of' ' `return_all_scores=True` or `top_k=1` instead of `return_all_scores=False`.' , a , ) if return_all_scores: SCREAMING_SNAKE_CASE = None else: SCREAMING_SNAKE_CASE = 1 if isinstance(a , a): SCREAMING_SNAKE_CASE = ClassificationFunction[function_to_apply.upper()] if function_to_apply is not None: SCREAMING_SNAKE_CASE = function_to_apply return preprocess_params, {}, postprocess_params def __call__( self , *a , **a) -> Optional[int]: SCREAMING_SNAKE_CASE = super().__call__(*a , **a) # TODO try and retrieve it in a nicer way from _sanitize_parameters. SCREAMING_SNAKE_CASE = 'top_k' not in kwargs if isinstance(args[0] , a) and _legacy: # This pipeline is odd, and return a list when single item is run return [result] else: return result def SCREAMING_SNAKE_CASE__ ( self , a , **a) -> Dict[str, GenericTensor]: SCREAMING_SNAKE_CASE = self.framework if isinstance(a , a): return self.tokenizer(**a , return_tensors=a , **a) elif isinstance(a , a) and len(a) == 1 and isinstance(inputs[0] , a) and len(inputs[0]) == 2: # It used to be valid to use a list of list of list for text pairs, keeping this path for BC return self.tokenizer( text=inputs[0][0] , text_pair=inputs[0][1] , return_tensors=a , **a) elif isinstance(a , a): # This is likely an invalid usage of the pipeline attempting to pass text pairs. raise ValueError( 'The pipeline received invalid inputs, if you are trying to send text pairs, you can try to send a' ' dictionary `{"text": "My text", "text_pair": "My pair"}` in order to send a text pair.') return self.tokenizer(a , return_tensors=a , **a) def SCREAMING_SNAKE_CASE__ ( self , a) -> Optional[Any]: return self.model(**a) def SCREAMING_SNAKE_CASE__ ( self , a , a=None , a=1 , a=True) -> Any: # `_legacy` is used to determine if we're running the naked pipeline and in backward # compatibility mode, or if running the pipeline with `pipeline(..., top_k=1)` we're running # the more natural result containing the list. # Default value before `set_parameters` if function_to_apply is None: if self.model.config.problem_type == "multi_label_classification" or self.model.config.num_labels == 1: SCREAMING_SNAKE_CASE = ClassificationFunction.SIGMOID elif self.model.config.problem_type == "single_label_classification" or self.model.config.num_labels > 1: SCREAMING_SNAKE_CASE = ClassificationFunction.SOFTMAX elif hasattr(self.model.config , 'function_to_apply') and function_to_apply is None: SCREAMING_SNAKE_CASE = self.model.config.function_to_apply else: SCREAMING_SNAKE_CASE = ClassificationFunction.NONE SCREAMING_SNAKE_CASE = model_outputs['logits'][0] SCREAMING_SNAKE_CASE = outputs.numpy() if function_to_apply == ClassificationFunction.SIGMOID: SCREAMING_SNAKE_CASE = sigmoid(a) elif function_to_apply == ClassificationFunction.SOFTMAX: SCREAMING_SNAKE_CASE = softmax(a) elif function_to_apply == ClassificationFunction.NONE: SCREAMING_SNAKE_CASE = outputs else: raise ValueError(f'''Unrecognized `function_to_apply` argument: {function_to_apply}''') if top_k == 1 and _legacy: return {"label": self.model.config.idalabel[scores.argmax().item()], "score": scores.max().item()} SCREAMING_SNAKE_CASE = [ {'label': self.model.config.idalabel[i], 'score': score.item()} for i, score in enumerate(a) ] if not _legacy: dict_scores.sort(key=lambda a: x["score"] , reverse=a) if top_k is not None: SCREAMING_SNAKE_CASE = dict_scores[:top_k] return dict_scores
73
1
import numpy as np import torch from torch.nn import CrossEntropyLoss from transformers import AutoModelForCausalLM, AutoTokenizer import datasets from datasets import logging a_ : int = '\\n\n' a_ : Tuple = '\nPerplexity (PPL) is one of the most common metrics for evaluating language models.\nIt is defined as the exponentiated average negative log-likelihood of a sequence.\n\nFor more information, see https://huggingface.co/docs/transformers/perplexity\n' a_ : List[Any] = '\nArgs:\n model_id (str): model used for calculating Perplexity\n NOTE: Perplexity can only be calculated for causal language models.\n This includes models such as gpt2, causal variations of bert,\n causal versions of t5, and more (the full list can be found\n in the AutoModelForCausalLM documentation here:\n https://huggingface.co/docs/transformers/master/en/model_doc/auto#transformers.AutoModelForCausalLM )\n\n input_texts (list of str): input text, each separate text snippet\n is one list entry.\n batch_size (int): the batch size to run texts through the model. Defaults to 16.\n add_start_token (bool): whether to add the start token to the texts,\n so the perplexity can include the probability of the first word. Defaults to True.\n device (str): device to run on, defaults to \'cuda\' when available\nReturns:\n perplexity: dictionary containing the perplexity scores for the texts\n in the input list, as well as the mean perplexity. If one of the input texts is\n longer than the max input length of the model, then it is truncated to the\n max length for the perplexity computation.\nExamples:\n Example 1:\n >>> perplexity = datasets.load_metric("perplexity")\n >>> input_texts = ["lorem ipsum", "Happy Birthday!", "Bienvenue"]\n >>> results = perplexity.compute(model_id=\'gpt2\',\n ... add_start_token=False,\n ... input_texts=input_texts) # doctest:+ELLIPSIS\n >>> print(list(results.keys()))\n [\'perplexities\', \'mean_perplexity\']\n >>> print(round(results["mean_perplexity"], 2))\n 78.22\n >>> print(round(results["perplexities"][0], 2))\n 11.11\n\n Example 2:\n >>> perplexity = datasets.load_metric("perplexity")\n >>> input_texts = datasets.load_dataset("wikitext",\n ... "wikitext-2-raw-v1",\n ... split="test")["text"][:50] # doctest:+ELLIPSIS\n [...]\n >>> input_texts = [s for s in input_texts if s!=\'\']\n >>> results = perplexity.compute(model_id=\'gpt2\',\n ... input_texts=input_texts) # doctest:+ELLIPSIS\n >>> print(list(results.keys()))\n [\'perplexities\', \'mean_perplexity\']\n >>> print(round(results["mean_perplexity"], 2))\n 60.35\n >>> print(round(results["perplexities"][0], 2))\n 81.12\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class _snake_case ( datasets.Metric ): def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { 'input_texts': datasets.Value('string'), }) , reference_urls=['https://huggingface.co/docs/transformers/perplexity'] , ) def SCREAMING_SNAKE_CASE__ ( self , a , a , a = 16 , a = True , a=None) -> List[Any]: if device is not None: assert device in ["gpu", "cpu", "cuda"], "device should be either gpu or cpu." if device == "gpu": SCREAMING_SNAKE_CASE = 'cuda' else: SCREAMING_SNAKE_CASE = 'cuda' if torch.cuda.is_available() else 'cpu' SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained(a) SCREAMING_SNAKE_CASE = model.to(a) SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained(a) # if batch_size > 1 (which generally leads to padding being required), and # if there is not an already assigned pad_token, assign an existing # special token to also be the padding token if tokenizer.pad_token is None and batch_size > 1: SCREAMING_SNAKE_CASE = list(tokenizer.special_tokens_map_extended.values()) # check that the model already has at least one special token defined assert ( len(a) > 0 ), "If batch_size > 1, model must have at least one special token to use for padding. Please use a different model or set batch_size=1." # assign one of the special tokens to also be the pad token tokenizer.add_special_tokens({'pad_token': existing_special_tokens[0]}) if add_start_token: # leave room for <BOS> token to be added: assert ( tokenizer.bos_token is not None ), "Input model must already have a BOS token if using add_start_token=True. Please use a different model, or set add_start_token=False" SCREAMING_SNAKE_CASE = model.config.max_length - 1 else: SCREAMING_SNAKE_CASE = model.config.max_length SCREAMING_SNAKE_CASE = tokenizer( a , add_special_tokens=a , padding=a , truncation=a , max_length=a , return_tensors='pt' , return_attention_mask=a , ).to(a) SCREAMING_SNAKE_CASE = encodings['input_ids'] SCREAMING_SNAKE_CASE = encodings['attention_mask'] # check that each input is long enough: if add_start_token: assert torch.all(torch.ge(attn_masks.sum(1) , 1)), "Each input text must be at least one token long." else: assert torch.all( torch.ge(attn_masks.sum(1) , 2)), "When add_start_token=False, each input text must be at least two tokens long. Run with add_start_token=True if inputting strings of only one token, and remove all empty input strings." SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = CrossEntropyLoss(reduction='none') for start_index in logging.tqdm(range(0 , len(a) , a)): SCREAMING_SNAKE_CASE = min(start_index + batch_size , len(a)) SCREAMING_SNAKE_CASE = encoded_texts[start_index:end_index] SCREAMING_SNAKE_CASE = attn_masks[start_index:end_index] if add_start_token: SCREAMING_SNAKE_CASE = torch.tensor([[tokenizer.bos_token_id]] * encoded_batch.size(dim=0)).to(a) SCREAMING_SNAKE_CASE = torch.cat([bos_tokens_tensor, encoded_batch] , dim=1) SCREAMING_SNAKE_CASE = torch.cat( [torch.ones(bos_tokens_tensor.size() , dtype=torch.intaa).to(a), attn_mask] , dim=1) SCREAMING_SNAKE_CASE = encoded_batch with torch.no_grad(): SCREAMING_SNAKE_CASE = model(a , attention_mask=a).logits SCREAMING_SNAKE_CASE = out_logits[..., :-1, :].contiguous() SCREAMING_SNAKE_CASE = labels[..., 1:].contiguous() SCREAMING_SNAKE_CASE = attn_mask[..., 1:].contiguous() SCREAMING_SNAKE_CASE = torch.expa( (loss_fct(shift_logits.transpose(1 , 2) , a) * shift_attention_mask_batch).sum(1) / shift_attention_mask_batch.sum(1)) ppls += perplexity_batch.tolist() return {"perplexities": ppls, "mean_perplexity": np.mean(a)}
73
import heapq as hq import math from collections.abc import Iterator class _snake_case : def __init__( self , a) -> Optional[Any]: SCREAMING_SNAKE_CASE = str(id_) SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = {} # {vertex:distance} def __lt__( self , a) -> Dict: return self.key < other.key def __repr__( self) -> Optional[Any]: return self.id def SCREAMING_SNAKE_CASE__ ( self , a) -> Optional[Any]: self.neighbors.append(a) def SCREAMING_SNAKE_CASE__ ( self , a , a) -> Tuple: SCREAMING_SNAKE_CASE = weight def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): # add the neighbors: graph[a - 1].add_neighbor(graph[b - 1]) graph[b - 1].add_neighbor(graph[a - 1]) # add the edges: graph[a - 1].add_edge(graph[b - 1] , _UpperCAmelCase) graph[b - 1].add_edge(graph[a - 1] , _UpperCAmelCase) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = [] for u in graph: SCREAMING_SNAKE_CASE = math.inf SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = graph[:] while q: SCREAMING_SNAKE_CASE = min(_UpperCAmelCase) q.remove(_UpperCAmelCase) for v in u.neighbors: if (v in q) and (u.edges[v.id] < v.key): SCREAMING_SNAKE_CASE = u SCREAMING_SNAKE_CASE = u.edges[v.id] for i in range(1 , len(_UpperCAmelCase)): a.append((int(graph[i].id) + 1, int(graph[i].pi.id) + 1)) return a def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): for u in graph: SCREAMING_SNAKE_CASE = math.inf SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = list(_UpperCAmelCase) hq.heapify(_UpperCAmelCase) while h: SCREAMING_SNAKE_CASE = hq.heappop(_UpperCAmelCase) for v in u.neighbors: if (v in h) and (u.edges[v.id] < v.key): SCREAMING_SNAKE_CASE = u SCREAMING_SNAKE_CASE = u.edges[v.id] hq.heapify(_UpperCAmelCase) for i in range(1 , len(_UpperCAmelCase)): yield (int(graph[i].id) + 1, int(graph[i].pi.id) + 1) def lowerCamelCase__ (): pass if __name__ == "__main__": import doctest doctest.testmod()
73
1
import inspect import tempfile import unittest from huggingface_hub import hf_hub_download from transformers import is_torch_available from transformers.testing_utils import is_flaky, require_torch, 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 a_ : Dict = 1E-4 if is_torch_available(): import torch from transformers import AutoformerConfig, AutoformerForPrediction, AutoformerModel from transformers.models.autoformer.modeling_autoformer import AutoformerDecoder, AutoformerEncoder @require_torch class _snake_case : def __init__( self , a , a=16 , a=13 , a=7 , a=14 , a=10 , a=19 , a=5 , a=4 , a=True , a=16 , a=2 , a=4 , a=4 , a="gelu" , a=0.1 , a=0.1 , a=[1, 2, 3, 4, 5] , a=25 , a=5 , ) -> Optional[int]: SCREAMING_SNAKE_CASE = d_model SCREAMING_SNAKE_CASE = parent SCREAMING_SNAKE_CASE = batch_size SCREAMING_SNAKE_CASE = prediction_length SCREAMING_SNAKE_CASE = context_length SCREAMING_SNAKE_CASE = cardinality SCREAMING_SNAKE_CASE = num_time_features SCREAMING_SNAKE_CASE = lags_sequence SCREAMING_SNAKE_CASE = embedding_dimension SCREAMING_SNAKE_CASE = is_training SCREAMING_SNAKE_CASE = hidden_size SCREAMING_SNAKE_CASE = num_hidden_layers SCREAMING_SNAKE_CASE = num_attention_heads SCREAMING_SNAKE_CASE = intermediate_size SCREAMING_SNAKE_CASE = hidden_act SCREAMING_SNAKE_CASE = hidden_dropout_prob SCREAMING_SNAKE_CASE = attention_probs_dropout_prob SCREAMING_SNAKE_CASE = context_length SCREAMING_SNAKE_CASE = prediction_length + label_length SCREAMING_SNAKE_CASE = label_length SCREAMING_SNAKE_CASE = moving_average SCREAMING_SNAKE_CASE = autocorrelation_factor def SCREAMING_SNAKE_CASE__ ( self) -> Dict: return AutoformerConfig( d_model=self.d_model , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , prediction_length=self.prediction_length , context_length=self.context_length , label_length=self.label_length , lags_sequence=self.lags_sequence , num_time_features=self.num_time_features , num_static_categorical_features=1 , cardinality=[self.cardinality] , embedding_dimension=[self.embedding_dimension] , moving_average=self.moving_average , ) def SCREAMING_SNAKE_CASE__ ( self , a) -> Dict: SCREAMING_SNAKE_CASE = config.context_length + max(config.lags_sequence) SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, 1] , config.cardinality[0]) SCREAMING_SNAKE_CASE = floats_tensor([self.batch_size, _past_length, config.num_time_features]) SCREAMING_SNAKE_CASE = floats_tensor([self.batch_size, _past_length]) SCREAMING_SNAKE_CASE = floats_tensor([self.batch_size, _past_length]) > 0.5 # decoder inputs SCREAMING_SNAKE_CASE = floats_tensor([self.batch_size, config.prediction_length, config.num_time_features]) SCREAMING_SNAKE_CASE = floats_tensor([self.batch_size, config.prediction_length]) SCREAMING_SNAKE_CASE = { 'past_values': past_values, 'static_categorical_features': static_categorical_features, 'past_time_features': past_time_features, 'past_observed_mask': past_observed_mask, 'future_time_features': future_time_features, 'future_values': future_values, } return inputs_dict def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: SCREAMING_SNAKE_CASE = self.get_config() SCREAMING_SNAKE_CASE = self.prepare_autoformer_inputs_dict(a) return config, inputs_dict def SCREAMING_SNAKE_CASE__ ( self) -> int: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.prepare_config_and_inputs() return config, inputs_dict def SCREAMING_SNAKE_CASE__ ( self , a , a) -> Tuple: SCREAMING_SNAKE_CASE = AutoformerModel(config=a).to(a).eval() SCREAMING_SNAKE_CASE = model(**a) SCREAMING_SNAKE_CASE = outputs.encoder_last_hidden_state SCREAMING_SNAKE_CASE = outputs.last_hidden_state with tempfile.TemporaryDirectory() as tmpdirname: SCREAMING_SNAKE_CASE = model.get_encoder() encoder.save_pretrained(a) SCREAMING_SNAKE_CASE = AutoformerEncoder.from_pretrained(a).to(a) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = model.create_network_inputs(**a) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = model.decomposition_layer(transformer_inputs[:, : config.context_length, ...]) SCREAMING_SNAKE_CASE = torch.cat( (transformer_inputs[:, : config.context_length, ...], feature[:, : config.context_length, ...]) , dim=-1 , ) SCREAMING_SNAKE_CASE = encoder(inputs_embeds=a)[0] self.parent.assertTrue((encoder_last_hidden_state_a - encoder_last_hidden_state).abs().max().item() < 1E-3) SCREAMING_SNAKE_CASE = ( torch.mean(transformer_inputs[:, : config.context_length, ...] , dim=1) .unsqueeze(1) .repeat(1 , config.prediction_length , 1) ) SCREAMING_SNAKE_CASE = torch.zeros( [transformer_inputs.shape[0], config.prediction_length, transformer_inputs.shape[2]] , device=enc_input.device , ) SCREAMING_SNAKE_CASE = torch.cat( ( torch.cat((seasonal_input[:, -config.label_length :, ...], zeros) , dim=1), feature[:, config.context_length - config.label_length :, ...], ) , dim=-1 , ) SCREAMING_SNAKE_CASE = torch.cat( ( torch.cat((trend_input[:, -config.label_length :, ...], mean) , dim=1), feature[:, config.context_length - config.label_length :, ...], ) , dim=-1 , ) with tempfile.TemporaryDirectory() as tmpdirname: SCREAMING_SNAKE_CASE = model.get_decoder() decoder.save_pretrained(a) SCREAMING_SNAKE_CASE = AutoformerDecoder.from_pretrained(a).to(a) SCREAMING_SNAKE_CASE = decoder( trend=a , inputs_embeds=a , encoder_hidden_states=a , )[0] self.parent.assertTrue((last_hidden_state_a - last_hidden_state).abs().max().item() < 1E-3) @require_torch class _snake_case ( A__ , A__ , unittest.TestCase ): _lowercase : List[Any] = (AutoformerModel, AutoformerForPrediction) if is_torch_available() else () _lowercase : Any = (AutoformerForPrediction,) if is_torch_available() else () _lowercase : Optional[Any] = {'''feature-extraction''': AutoformerModel} if is_torch_available() else {} _lowercase : Union[str, Any] = False _lowercase : str = False _lowercase : List[Any] = False _lowercase : List[str] = False _lowercase : Optional[Any] = False _lowercase : Optional[Any] = False def SCREAMING_SNAKE_CASE__ ( self) -> Any: SCREAMING_SNAKE_CASE = AutoformerModelTester(self) SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=a , has_text_modality=a) def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE = model_class(a) with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(a) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = model_class.from_pretrained(a , output_loading_info=a) self.assertEqual(info['missing_keys'] , []) def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_encoder_decoder_model_standalone(*a) @unittest.skip(reason='Model has no tokens embeddings') def SCREAMING_SNAKE_CASE__ ( self) -> int: pass def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: SCREAMING_SNAKE_CASE = inspect.signature(getattr(a , 'forward')) # The main input is the name of the argument after `self` SCREAMING_SNAKE_CASE = list(model_signature.parameters.keys())[1] self.assertEqual(AutoformerModel.main_input_name , a) def SCREAMING_SNAKE_CASE__ ( self) -> Dict: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE = model_class(a) SCREAMING_SNAKE_CASE = inspect.signature(model.forward) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE = [ 'past_values', 'past_time_features', 'past_observed_mask', 'static_categorical_features', 'static_real_features', 'future_values', 'future_time_features', ] if model.__class__.__name__ in ["AutoformerForPrediction"]: expected_arg_names.append('future_observed_mask') expected_arg_names.extend( [ 'decoder_attention_mask', 'head_mask', 'decoder_head_mask', 'cross_attn_head_mask', 'encoder_outputs', 'past_key_values', 'output_hidden_states', 'output_attentions', 'use_cache', 'return_dict', ]) self.assertListEqual(arg_names[: len(a)] , a) def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = getattr(self.model_tester , 'seq_length' , a) SCREAMING_SNAKE_CASE = getattr(self.model_tester , 'decoder_seq_length' , a) SCREAMING_SNAKE_CASE = getattr(self.model_tester , 'encoder_seq_length' , a) SCREAMING_SNAKE_CASE = getattr(self.model_tester , 'd_model' , a) SCREAMING_SNAKE_CASE = getattr(self.model_tester , 'num_attention_heads' , a) SCREAMING_SNAKE_CASE = d_model // num_attention_heads for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = False SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = model_class(a) model.to(a) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE = model(**self._prepare_for_class(a , a)) SCREAMING_SNAKE_CASE = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions self.assertEqual(len(a) , self.model_tester.num_hidden_layers) # check that output_attentions also work using config del inputs_dict["output_attentions"] SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = model_class(a) model.to(a) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE = model(**self._prepare_for_class(a , a)) SCREAMING_SNAKE_CASE = outputs.encoder_attentions self.assertEqual(len(a) , self.model_tester.num_hidden_layers) self.assertListEqual( list(attentions[0].shape[-3:]) , [self.model_tester.num_attention_heads, encoder_seq_length, dim] , ) SCREAMING_SNAKE_CASE = len(a) SCREAMING_SNAKE_CASE = 7 if "last_hidden_state" in outputs: correct_outlen += 1 if "trend" in outputs: correct_outlen += 1 if "past_key_values" in outputs: correct_outlen += 1 # past_key_values have been returned if "loss" in outputs: correct_outlen += 1 if "params" in outputs: correct_outlen += 1 self.assertEqual(a , a) # decoder attentions SCREAMING_SNAKE_CASE = outputs.decoder_attentions self.assertIsInstance(a , (list, tuple)) self.assertEqual(len(a) , self.model_tester.num_hidden_layers) self.assertListEqual( list(decoder_attentions[0].shape[-3:]) , [self.model_tester.num_attention_heads, decoder_seq_length, dim] , ) # cross attentions SCREAMING_SNAKE_CASE = outputs.cross_attentions self.assertIsInstance(a , (list, tuple)) self.assertEqual(len(a) , self.model_tester.num_hidden_layers) self.assertListEqual( list(cross_attentions[0].shape[-3:]) , [self.model_tester.num_attention_heads, decoder_seq_length, dim] , ) # Check attention is always last and order is fine SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = model_class(a) model.to(a) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE = model(**self._prepare_for_class(a , a)) self.assertEqual(out_len + 2 , len(a)) SCREAMING_SNAKE_CASE = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions self.assertEqual(len(a) , self.model_tester.num_hidden_layers) self.assertListEqual( list(self_attentions[0].shape[-3:]) , [self.model_tester.num_attention_heads, encoder_seq_length, dim] , ) @is_flaky() def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: super().test_retain_grad_hidden_states_attentions() def lowerCamelCase__ (_UpperCAmelCase="train-batch.pt"): SCREAMING_SNAKE_CASE = hf_hub_download(repo_id='hf-internal-testing/tourism-monthly-batch' , filename=_UpperCAmelCase , repo_type='dataset') SCREAMING_SNAKE_CASE = torch.load(_UpperCAmelCase , map_location=_UpperCAmelCase) return batch @require_torch @slow class _snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: SCREAMING_SNAKE_CASE = AutoformerModel.from_pretrained('huggingface/autoformer-tourism-monthly').to(a) SCREAMING_SNAKE_CASE = prepare_batch() with torch.no_grad(): SCREAMING_SNAKE_CASE = model( past_values=batch['past_values'] , past_time_features=batch['past_time_features'] , past_observed_mask=batch['past_observed_mask'] , static_categorical_features=batch['static_categorical_features'] , future_values=batch['future_values'] , future_time_features=batch['future_time_features'] , )[0] SCREAMING_SNAKE_CASE = torch.Size( (64, model.config.prediction_length + model.config.label_length, model.config.feature_size)) self.assertEqual(output.shape , a) SCREAMING_SNAKE_CASE = torch.tensor( [[0.35_93, -1.33_98, 0.63_30], [0.22_79, 1.53_96, -0.17_92], [0.04_50, 1.32_25, -0.23_35]] , device=a) self.assertTrue(torch.allclose(output[0, :3, :3] , a , atol=a)) def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: SCREAMING_SNAKE_CASE = AutoformerForPrediction.from_pretrained('huggingface/autoformer-tourism-monthly').to(a) SCREAMING_SNAKE_CASE = prepare_batch('val-batch.pt') with torch.no_grad(): SCREAMING_SNAKE_CASE = model( past_values=batch['past_values'] , past_time_features=batch['past_time_features'] , past_observed_mask=batch['past_observed_mask'] , static_categorical_features=batch['static_categorical_features'] , ).encoder_last_hidden_state SCREAMING_SNAKE_CASE = torch.Size((64, model.config.context_length, model.config.d_model)) self.assertEqual(output.shape , a) SCREAMING_SNAKE_CASE = torch.tensor( [[-0.07_34, -0.90_36, 0.83_58], [4.71_86, 2.41_13, 1.95_81], [1.79_53, 2.35_58, 1.29_70]] , device=a) self.assertTrue(torch.allclose(output[0, :3, :3] , a , atol=a)) def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: SCREAMING_SNAKE_CASE = AutoformerForPrediction.from_pretrained('huggingface/autoformer-tourism-monthly').to(a) SCREAMING_SNAKE_CASE = prepare_batch('val-batch.pt') with torch.no_grad(): SCREAMING_SNAKE_CASE = model.generate( static_categorical_features=batch['static_categorical_features'] , past_time_features=batch['past_time_features'] , past_values=batch['past_values'] , future_time_features=batch['future_time_features'] , past_observed_mask=batch['past_observed_mask'] , ) SCREAMING_SNAKE_CASE = torch.Size((64, model.config.num_parallel_samples, model.config.prediction_length)) self.assertEqual(outputs.sequences.shape , a) SCREAMING_SNAKE_CASE = torch.tensor([31_30.67_63, 40_56.52_93, 70_53.07_86] , device=a) SCREAMING_SNAKE_CASE = outputs.sequences.mean(dim=1) self.assertTrue(torch.allclose(mean_prediction[0, -3:] , a , rtol=1E-1))
73
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available a_ : Optional[Any] = { 'configuration_mask2former': [ 'MASK2FORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'Mask2FormerConfig', ], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : Union[str, Any] = ['Mask2FormerImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : List[Any] = [ 'MASK2FORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'Mask2FormerForUniversalSegmentation', 'Mask2FormerModel', 'Mask2FormerPreTrainedModel', ] if TYPE_CHECKING: from .configuration_maskaformer import MASK2FORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, MaskaFormerConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_maskaformer import MaskaFormerImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_maskaformer import ( MASK2FORMER_PRETRAINED_MODEL_ARCHIVE_LIST, MaskaFormerForUniversalSegmentation, MaskaFormerModel, MaskaFormerPreTrainedModel, ) else: import sys a_ : str = _LazyModule(__name__, globals()['__file__'], _import_structure)
73
1
import pickle import numpy as np from matplotlib import pyplot as plt class _snake_case : def __init__( self , a , a , a , a , a , a=0.2 , a=0.2) -> List[Any]: SCREAMING_SNAKE_CASE = bp_numa SCREAMING_SNAKE_CASE = bp_numa SCREAMING_SNAKE_CASE = bp_numa SCREAMING_SNAKE_CASE = conva_get[:2] SCREAMING_SNAKE_CASE = conva_get[2] SCREAMING_SNAKE_CASE = size_pa SCREAMING_SNAKE_CASE = rate_w SCREAMING_SNAKE_CASE = rate_t SCREAMING_SNAKE_CASE = [ np.mat(-1 * np.random.rand(self.conva[0] , self.conva[0]) + 0.5) for i in range(self.conva[1]) ] SCREAMING_SNAKE_CASE = np.mat(-1 * np.random.rand(self.num_bpa , self.num_bpa) + 0.5) SCREAMING_SNAKE_CASE = np.mat(-1 * np.random.rand(self.num_bpa , self.num_bpa) + 0.5) SCREAMING_SNAKE_CASE = -2 * np.random.rand(self.conva[1]) + 1 SCREAMING_SNAKE_CASE = -2 * np.random.rand(self.num_bpa) + 1 SCREAMING_SNAKE_CASE = -2 * np.random.rand(self.num_bpa) + 1 def SCREAMING_SNAKE_CASE__ ( self , a) -> int: # save model dict with pickle SCREAMING_SNAKE_CASE = { 'num_bp1': self.num_bpa, 'num_bp2': self.num_bpa, 'num_bp3': self.num_bpa, 'conv1': self.conva, 'step_conv1': self.step_conva, 'size_pooling1': self.size_poolinga, 'rate_weight': self.rate_weight, 'rate_thre': self.rate_thre, 'w_conv1': self.w_conva, 'wkj': self.wkj, 'vji': self.vji, 'thre_conv1': self.thre_conva, 'thre_bp2': self.thre_bpa, 'thre_bp3': self.thre_bpa, } with open(a , 'wb') as f: pickle.dump(a , a) print(f'''Model saved: {save_path}''') @classmethod def SCREAMING_SNAKE_CASE__ ( cls , a) -> Optional[Any]: # read saved model with open(a , 'rb') as f: SCREAMING_SNAKE_CASE = pickle.load(a) # noqa: S301 SCREAMING_SNAKE_CASE = model_dic.get('conv1') conv_get.append(model_dic.get('step_conv1')) SCREAMING_SNAKE_CASE = model_dic.get('size_pooling1') SCREAMING_SNAKE_CASE = model_dic.get('num_bp1') SCREAMING_SNAKE_CASE = model_dic.get('num_bp2') SCREAMING_SNAKE_CASE = model_dic.get('num_bp3') SCREAMING_SNAKE_CASE = model_dic.get('rate_weight') SCREAMING_SNAKE_CASE = model_dic.get('rate_thre') # create model instance SCREAMING_SNAKE_CASE = CNN(a , a , a , a , a , a , a) # modify model parameter SCREAMING_SNAKE_CASE = model_dic.get('w_conv1') SCREAMING_SNAKE_CASE = model_dic.get('wkj') SCREAMING_SNAKE_CASE = model_dic.get('vji') SCREAMING_SNAKE_CASE = model_dic.get('thre_conv1') SCREAMING_SNAKE_CASE = model_dic.get('thre_bp2') SCREAMING_SNAKE_CASE = model_dic.get('thre_bp3') return conv_ins def SCREAMING_SNAKE_CASE__ ( self , a) -> Optional[int]: return 1 / (1 + np.exp(-1 * x)) def SCREAMING_SNAKE_CASE__ ( self , a) -> List[str]: return round(a , 3) def SCREAMING_SNAKE_CASE__ ( self , a , a , a , a , a) -> str: # convolution process SCREAMING_SNAKE_CASE = convs[0] SCREAMING_SNAKE_CASE = convs[1] SCREAMING_SNAKE_CASE = np.shape(a)[0] # get the data slice of original image data, data_focus SCREAMING_SNAKE_CASE = [] for i_focus in range(0 , size_data - size_conv + 1 , a): for j_focus in range(0 , size_data - size_conv + 1 , a): SCREAMING_SNAKE_CASE = data[ i_focus : i_focus + size_conv, j_focus : j_focus + size_conv ] data_focus.append(a) # calculate the feature map of every single kernel, and saved as list of matrix SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = int((size_data - size_conv) / conv_step + 1) for i_map in range(a): SCREAMING_SNAKE_CASE = [] for i_focus in range(len(a)): SCREAMING_SNAKE_CASE = ( np.sum(np.multiply(data_focus[i_focus] , w_convs[i_map])) - thre_convs[i_map] ) featuremap.append(self.sig(a)) SCREAMING_SNAKE_CASE = np.asmatrix(a).reshape( a , a) data_featuremap.append(a) # expanding the data slice to One dimenssion SCREAMING_SNAKE_CASE = [] for each_focus in data_focus: focusa_list.extend(self.Expand_Mat(a)) SCREAMING_SNAKE_CASE = np.asarray(a) return focus_list, data_featuremap def SCREAMING_SNAKE_CASE__ ( self , a , a , a="average_pool") -> Any: # pooling process SCREAMING_SNAKE_CASE = len(featuremaps[0]) SCREAMING_SNAKE_CASE = int(size_map / size_pooling) SCREAMING_SNAKE_CASE = [] for i_map in range(len(a)): SCREAMING_SNAKE_CASE = featuremaps[i_map] SCREAMING_SNAKE_CASE = [] for i_focus in range(0 , a , a): for j_focus in range(0 , a , a): SCREAMING_SNAKE_CASE = feature_map[ i_focus : i_focus + size_pooling, j_focus : j_focus + size_pooling, ] if pooling_type == "average_pool": # average pooling map_pooled.append(np.average(a)) elif pooling_type == "max_pooling": # max pooling map_pooled.append(np.max(a)) SCREAMING_SNAKE_CASE = np.asmatrix(a).reshape(a , a) featuremap_pooled.append(a) return featuremap_pooled def SCREAMING_SNAKE_CASE__ ( self , a) -> List[str]: # expanding three dimension data to one dimension list SCREAMING_SNAKE_CASE = [] for i in range(len(a)): SCREAMING_SNAKE_CASE = np.shape(data[i]) SCREAMING_SNAKE_CASE = data[i].reshape(1 , shapes[0] * shapes[1]) SCREAMING_SNAKE_CASE = data_listed.getA().tolist()[0] data_expanded.extend(a) SCREAMING_SNAKE_CASE = np.asarray(a) return data_expanded def SCREAMING_SNAKE_CASE__ ( self , a) -> Optional[int]: # expanding matrix to one dimension list SCREAMING_SNAKE_CASE = np.asarray(a) SCREAMING_SNAKE_CASE = np.shape(a) SCREAMING_SNAKE_CASE = data_mat.reshape(1 , shapes[0] * shapes[1]) return data_expanded def SCREAMING_SNAKE_CASE__ ( self , a , a , a , a , a) -> Optional[Any]: SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = 0 for i_map in range(a): SCREAMING_SNAKE_CASE = np.ones((size_map, size_map)) for i in range(0 , a , a): for j in range(0 , a , a): SCREAMING_SNAKE_CASE = pd_pool[ i_pool ] SCREAMING_SNAKE_CASE = i_pool + 1 SCREAMING_SNAKE_CASE = np.multiply( a , np.multiply(out_map[i_map] , (1 - out_map[i_map]))) pd_all.append(a) return pd_all def SCREAMING_SNAKE_CASE__ ( self , a , a , a , a , a , a=bool) -> Any: # model traning print('----------------------Start Training-------------------------') print((' - - Shape: Train_Data ', np.shape(a))) print((' - - Shape: Teach_Data ', np.shape(a))) SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = 1_0000 while rp < n_repeat and mse >= error_accuracy: SCREAMING_SNAKE_CASE = 0 print(f'''-------------Learning Time {rp}--------------''') for p in range(len(a)): # print('------------Learning Image: %d--------------'%p) SCREAMING_SNAKE_CASE = np.asmatrix(datas_train[p]) SCREAMING_SNAKE_CASE = np.asarray(datas_teach[p]) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.convolute( a , self.conva , self.w_conva , self.thre_conva , conv_step=self.step_conva , ) SCREAMING_SNAKE_CASE = self.pooling(a , self.size_poolinga) SCREAMING_SNAKE_CASE = np.shape(a) SCREAMING_SNAKE_CASE = self._expand(a) SCREAMING_SNAKE_CASE = data_bp_input SCREAMING_SNAKE_CASE = np.dot(a , self.vji.T) - self.thre_bpa SCREAMING_SNAKE_CASE = self.sig(a) SCREAMING_SNAKE_CASE = np.dot(a , self.wkj.T) - self.thre_bpa SCREAMING_SNAKE_CASE = self.sig(a) # --------------Model Leaning ------------------------ # calculate error and gradient--------------- SCREAMING_SNAKE_CASE = np.multiply( (data_teach - bp_outa) , np.multiply(a , (1 - bp_outa))) SCREAMING_SNAKE_CASE = np.multiply( np.dot(a , self.wkj) , np.multiply(a , (1 - bp_outa))) SCREAMING_SNAKE_CASE = np.dot(a , self.vji) SCREAMING_SNAKE_CASE = pd_i_all / (self.size_poolinga * self.size_poolinga) SCREAMING_SNAKE_CASE = pd_conva_pooled.T.getA().tolist() SCREAMING_SNAKE_CASE = self._calculate_gradient_from_pool( a , a , shape_featuremapa[0] , shape_featuremapa[1] , self.size_poolinga , ) # weight and threshold learning process--------- # convolution layer for k_conv in range(self.conva[1]): SCREAMING_SNAKE_CASE = self._expand_mat(pd_conva_all[k_conv]) SCREAMING_SNAKE_CASE = self.rate_weight * np.dot(a , a) SCREAMING_SNAKE_CASE = self.w_conva[k_conv] + delta_w.reshape( (self.conva[0], self.conva[0])) SCREAMING_SNAKE_CASE = ( self.thre_conva[k_conv] - np.sum(pd_conva_all[k_conv]) * self.rate_thre ) # all connected layer SCREAMING_SNAKE_CASE = self.wkj + pd_k_all.T * bp_outa * self.rate_weight SCREAMING_SNAKE_CASE = self.vji + pd_j_all.T * bp_outa * self.rate_weight SCREAMING_SNAKE_CASE = self.thre_bpa - pd_k_all * self.rate_thre SCREAMING_SNAKE_CASE = self.thre_bpa - pd_j_all * self.rate_thre # calculate the sum error of all single image SCREAMING_SNAKE_CASE = np.sum(abs(data_teach - bp_outa)) error_count += errors # print(' ----Teach ',data_teach) # print(' ----BP_output ',bp_out3) SCREAMING_SNAKE_CASE = rp + 1 SCREAMING_SNAKE_CASE = error_count / patterns all_mse.append(a) def draw_error(): SCREAMING_SNAKE_CASE = [error_accuracy for i in range(int(n_repeat * 1.2))] plt.plot(a , '+-') plt.plot(a , 'r--') plt.xlabel('Learning Times') plt.ylabel('All_mse') plt.grid(a , alpha=0.5) plt.show() print('------------------Training Complished---------------------') print((' - - Training epoch: ', rp, f''' - - Mse: {mse:.6f}''')) if draw_e: draw_error() return mse def SCREAMING_SNAKE_CASE__ ( self , a) -> int: # model predict SCREAMING_SNAKE_CASE = [] print('-------------------Start Testing-------------------------') print((' - - Shape: Test_Data ', np.shape(a))) for p in range(len(a)): SCREAMING_SNAKE_CASE = np.asmatrix(datas_test[p]) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.convolute( a , self.conva , self.w_conva , self.thre_conva , conv_step=self.step_conva , ) SCREAMING_SNAKE_CASE = self.pooling(a , self.size_poolinga) SCREAMING_SNAKE_CASE = self._expand(a) SCREAMING_SNAKE_CASE = data_bp_input SCREAMING_SNAKE_CASE = bp_outa * self.vji.T - self.thre_bpa SCREAMING_SNAKE_CASE = self.sig(a) SCREAMING_SNAKE_CASE = bp_outa * self.wkj.T - self.thre_bpa SCREAMING_SNAKE_CASE = self.sig(a) produce_out.extend(bp_outa.getA().tolist()) SCREAMING_SNAKE_CASE = [list(map(self.do_round , a)) for each in produce_out] return np.asarray(a) def SCREAMING_SNAKE_CASE__ ( self , a) -> Any: # return the data of image after convoluting process so we can check it out SCREAMING_SNAKE_CASE = np.asmatrix(a) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.convolute( a , self.conva , self.w_conva , self.thre_conva , conv_step=self.step_conva , ) SCREAMING_SNAKE_CASE = self.pooling(a , self.size_poolinga) return data_conveda, data_pooleda if __name__ == "__main__": pass
73
from ...configuration_utils import PretrainedConfig from ...utils import logging a_ : Dict = logging.get_logger(__name__) a_ : Union[str, Any] = { 'edbeeching/decision-transformer-gym-hopper-medium': ( 'https://huggingface.co/edbeeching/decision-transformer-gym-hopper-medium/resolve/main/config.json' ), # See all DecisionTransformer models at https://huggingface.co/models?filter=decision_transformer } class _snake_case ( A__ ): _lowercase : Optional[Any] = '''decision_transformer''' _lowercase : str = ['''past_key_values'''] _lowercase : Union[str, Any] = { '''max_position_embeddings''': '''n_positions''', '''num_attention_heads''': '''n_head''', '''num_hidden_layers''': '''n_layer''', } def __init__( self , a=17 , a=4 , a=128 , a=4096 , a=True , a=1 , a=1024 , a=3 , a=1 , a=None , a="relu" , a=0.1 , a=0.1 , a=0.1 , a=1E-5 , a=0.02 , a=True , a=True , a=5_0256 , a=5_0256 , a=False , a=False , **a , ) -> List[str]: SCREAMING_SNAKE_CASE = state_dim SCREAMING_SNAKE_CASE = act_dim SCREAMING_SNAKE_CASE = hidden_size SCREAMING_SNAKE_CASE = max_ep_len SCREAMING_SNAKE_CASE = action_tanh SCREAMING_SNAKE_CASE = vocab_size SCREAMING_SNAKE_CASE = n_positions SCREAMING_SNAKE_CASE = n_layer SCREAMING_SNAKE_CASE = n_head SCREAMING_SNAKE_CASE = n_inner SCREAMING_SNAKE_CASE = activation_function SCREAMING_SNAKE_CASE = resid_pdrop SCREAMING_SNAKE_CASE = embd_pdrop SCREAMING_SNAKE_CASE = attn_pdrop SCREAMING_SNAKE_CASE = layer_norm_epsilon SCREAMING_SNAKE_CASE = initializer_range SCREAMING_SNAKE_CASE = scale_attn_weights SCREAMING_SNAKE_CASE = use_cache SCREAMING_SNAKE_CASE = scale_attn_by_inverse_layer_idx SCREAMING_SNAKE_CASE = reorder_and_upcast_attn SCREAMING_SNAKE_CASE = bos_token_id SCREAMING_SNAKE_CASE = eos_token_id super().__init__(bos_token_id=a , eos_token_id=a , **a)
73
1
def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): if n == 0: return 1 elif n % 2 == 1: return (binary_exponentiation(_UpperCAmelCase , n - 1 , _UpperCAmelCase) * a) % mod else: SCREAMING_SNAKE_CASE = binary_exponentiation(_UpperCAmelCase , n / 2 , _UpperCAmelCase) return (b * b) % mod # a prime number a_ : str = 7_01 a_ : Union[str, Any] = 10_00_00_00_00 a_ : List[str] = 10 # using binary exponentiation function, O(log(p)): print((a / b) % p == (a * binary_exponentiation(b, p - 2, p)) % p) print((a / b) % p == (a * b ** (p - 2)) % p)
73
import argparse import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType ######################################################################## # This is a fully working simple example to use Accelerate # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## a_ : Optional[int] = 16 a_ : Any = 32 def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase = 16): SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained('bert-base-cased') SCREAMING_SNAKE_CASE = load_dataset('glue' , 'mrpc') def tokenize_function(_UpperCAmelCase): # max_length=None => use the model max length (it's actually the default) SCREAMING_SNAKE_CASE = tokenizer(examples['sentence1'] , examples['sentence2'] , truncation=_UpperCAmelCase , max_length=_UpperCAmelCase) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): SCREAMING_SNAKE_CASE = datasets.map( _UpperCAmelCase , batched=_UpperCAmelCase , remove_columns=['idx', 'sentence1', 'sentence2'] , ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library SCREAMING_SNAKE_CASE = tokenized_datasets.rename_column('label' , 'labels') def collate_fn(_UpperCAmelCase): # On TPU it's best to pad everything to the same length or training will be very slow. SCREAMING_SNAKE_CASE = 128 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": SCREAMING_SNAKE_CASE = 16 elif accelerator.mixed_precision != "no": SCREAMING_SNAKE_CASE = 8 else: SCREAMING_SNAKE_CASE = None return tokenizer.pad( _UpperCAmelCase , padding='longest' , max_length=_UpperCAmelCase , pad_to_multiple_of=_UpperCAmelCase , return_tensors='pt' , ) # Instantiate dataloaders. SCREAMING_SNAKE_CASE = DataLoader( tokenized_datasets['train'] , shuffle=_UpperCAmelCase , collate_fn=_UpperCAmelCase , batch_size=_UpperCAmelCase , drop_last=_UpperCAmelCase) SCREAMING_SNAKE_CASE = DataLoader( tokenized_datasets['validation'] , shuffle=_UpperCAmelCase , collate_fn=_UpperCAmelCase , batch_size=_UpperCAmelCase , drop_last=(accelerator.mixed_precision == 'fp8') , ) return train_dataloader, eval_dataloader def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): # Initialize accelerator SCREAMING_SNAKE_CASE = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs SCREAMING_SNAKE_CASE = config['lr'] SCREAMING_SNAKE_CASE = int(config['num_epochs']) SCREAMING_SNAKE_CASE = int(config['seed']) SCREAMING_SNAKE_CASE = int(config['batch_size']) SCREAMING_SNAKE_CASE = evaluate.load('glue' , 'mrpc') # If the batch size is too big we use gradient accumulation SCREAMING_SNAKE_CASE = 1 if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU: SCREAMING_SNAKE_CASE = batch_size // MAX_GPU_BATCH_SIZE SCREAMING_SNAKE_CASE = MAX_GPU_BATCH_SIZE set_seed(_UpperCAmelCase) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = get_dataloaders(_UpperCAmelCase , _UpperCAmelCase) # Instantiate the model (we build the model here so that the seed also control new weights initialization) SCREAMING_SNAKE_CASE = AutoModelForSequenceClassification.from_pretrained('bert-base-cased' , return_dict=_UpperCAmelCase) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). SCREAMING_SNAKE_CASE = model.to(accelerator.device) # Instantiate optimizer SCREAMING_SNAKE_CASE = AdamW(params=model.parameters() , lr=_UpperCAmelCase) # Instantiate scheduler SCREAMING_SNAKE_CASE = get_linear_schedule_with_warmup( optimizer=_UpperCAmelCase , num_warmup_steps=100 , num_training_steps=(len(_UpperCAmelCase) * num_epochs) // gradient_accumulation_steps , ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = accelerator.prepare( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) # Now we train the model for epoch in range(_UpperCAmelCase): model.train() for step, batch in enumerate(_UpperCAmelCase): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device) SCREAMING_SNAKE_CASE = model(**_UpperCAmelCase) SCREAMING_SNAKE_CASE = outputs.loss SCREAMING_SNAKE_CASE = loss / gradient_accumulation_steps accelerator.backward(_UpperCAmelCase) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(_UpperCAmelCase): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device) with torch.no_grad(): SCREAMING_SNAKE_CASE = model(**_UpperCAmelCase) SCREAMING_SNAKE_CASE = outputs.logits.argmax(dim=-1) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = accelerator.gather_for_metrics((predictions, batch['labels'])) metric.add_batch( predictions=_UpperCAmelCase , references=_UpperCAmelCase , ) SCREAMING_SNAKE_CASE = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F'''epoch {epoch}:''' , _UpperCAmelCase) def lowerCamelCase__ (): SCREAMING_SNAKE_CASE = argparse.ArgumentParser(description='Simple example of training script.') parser.add_argument( '--mixed_precision' , type=_UpperCAmelCase , default=_UpperCAmelCase , choices=['no', 'fp16', 'bf16', 'fp8'] , help='Whether to use mixed precision. Choose' 'between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.' 'and an Nvidia Ampere GPU.' , ) parser.add_argument('--cpu' , action='store_true' , help='If passed, will train on the CPU.') SCREAMING_SNAKE_CASE = parser.parse_args() SCREAMING_SNAKE_CASE = {'lr': 2e-5, 'num_epochs': 3, 'seed': 42, 'batch_size': 16} training_function(_UpperCAmelCase , _UpperCAmelCase) if __name__ == "__main__": main()
73
1
import os import sys from contextlib import contextmanager # Windows only if os.name == "nt": import ctypes import msvcrt # noqa class _snake_case ( ctypes.Structure ): # _fields is a specific attr expected by ctypes _lowercase : Tuple = [('''size''', ctypes.c_int), ('''visible''', ctypes.c_byte)] def lowerCamelCase__ (): if os.name == "nt": SCREAMING_SNAKE_CASE = CursorInfo() SCREAMING_SNAKE_CASE = ctypes.windll.kernelaa.GetStdHandle(-11) ctypes.windll.kernelaa.GetConsoleCursorInfo(_UpperCAmelCase , ctypes.byref(_UpperCAmelCase)) SCREAMING_SNAKE_CASE = False ctypes.windll.kernelaa.SetConsoleCursorInfo(_UpperCAmelCase , ctypes.byref(_UpperCAmelCase)) elif os.name == "posix": sys.stdout.write('\033[?25l') sys.stdout.flush() def lowerCamelCase__ (): if os.name == "nt": SCREAMING_SNAKE_CASE = CursorInfo() SCREAMING_SNAKE_CASE = ctypes.windll.kernelaa.GetStdHandle(-11) ctypes.windll.kernelaa.GetConsoleCursorInfo(_UpperCAmelCase , ctypes.byref(_UpperCAmelCase)) SCREAMING_SNAKE_CASE = True ctypes.windll.kernelaa.SetConsoleCursorInfo(_UpperCAmelCase , ctypes.byref(_UpperCAmelCase)) elif os.name == "posix": sys.stdout.write('\033[?25h') sys.stdout.flush() @contextmanager def lowerCamelCase__ (): try: hide_cursor() yield finally: show_cursor()
73
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available a_ : int = { 'configuration_rag': ['RagConfig'], 'retrieval_rag': ['RagRetriever'], 'tokenization_rag': ['RagTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : List[Any] = [ 'RagModel', 'RagPreTrainedModel', 'RagSequenceForGeneration', 'RagTokenForGeneration', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : Tuple = [ 'TFRagModel', 'TFRagPreTrainedModel', 'TFRagSequenceForGeneration', 'TFRagTokenForGeneration', ] if TYPE_CHECKING: from .configuration_rag import RagConfig from .retrieval_rag import RagRetriever from .tokenization_rag import RagTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_rag import RagModel, RagPreTrainedModel, RagSequenceForGeneration, RagTokenForGeneration try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_rag import ( TFRagModel, TFRagPreTrainedModel, TFRagSequenceForGeneration, TFRagTokenForGeneration, ) else: import sys a_ : Union[str, Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
73
1
from abc import ABC, abstractmethod from typing import Optional, Union from .. import Dataset, DatasetDict, Features, IterableDataset, IterableDatasetDict, NamedSplit from ..utils.typing import NestedDataStructureLike, PathLike class _snake_case ( A__ ): def __init__( self , a = None , a = None , a = None , a = None , a = False , a = False , a = None , **a , ) -> List[str]: SCREAMING_SNAKE_CASE = path_or_paths SCREAMING_SNAKE_CASE = split if split or isinstance(a , a) else 'train' SCREAMING_SNAKE_CASE = features SCREAMING_SNAKE_CASE = cache_dir SCREAMING_SNAKE_CASE = keep_in_memory SCREAMING_SNAKE_CASE = streaming SCREAMING_SNAKE_CASE = num_proc SCREAMING_SNAKE_CASE = kwargs @abstractmethod def SCREAMING_SNAKE_CASE__ ( self) -> Union[Dataset, DatasetDict, IterableDataset, IterableDatasetDict]: pass class _snake_case ( A__ ): def __init__( self , a = None , a = None , a = False , a = False , a = None , **a , ) -> Union[str, Any]: SCREAMING_SNAKE_CASE = features SCREAMING_SNAKE_CASE = cache_dir SCREAMING_SNAKE_CASE = keep_in_memory SCREAMING_SNAKE_CASE = streaming SCREAMING_SNAKE_CASE = num_proc SCREAMING_SNAKE_CASE = kwargs @abstractmethod def SCREAMING_SNAKE_CASE__ ( self) -> Union[Dataset, IterableDataset]: pass
73
from __future__ import annotations from numpy import array, cos, cross, floataa, radians, sin from numpy.typing import NDArray def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase = False): if radian_mode: return [magnitude * cos(_UpperCAmelCase), magnitude * sin(_UpperCAmelCase)] return [magnitude * cos(radians(_UpperCAmelCase)), magnitude * sin(radians(_UpperCAmelCase))] def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase = 10**-1): SCREAMING_SNAKE_CASE = cross(_UpperCAmelCase , _UpperCAmelCase) SCREAMING_SNAKE_CASE = sum(_UpperCAmelCase) return abs(_UpperCAmelCase) < eps if __name__ == "__main__": # Test to check if it works a_ : int = array( [ polar_force(718.4, 1_80 - 30), polar_force(879.54, 45), polar_force(1_00, -90), ] ) a_ : NDArray[floataa] = array([[0, 0], [0, 0], [0, 0]]) assert in_static_equilibrium(forces, location) # Problem 1 in image_data/2D_problems.jpg a_ : Dict = array( [ polar_force(30 * 9.81, 15), polar_force(2_15, 1_80 - 45), polar_force(2_64, 90 - 30), ] ) a_ : Any = array([[0, 0], [0, 0], [0, 0]]) assert in_static_equilibrium(forces, location) # Problem in image_data/2D_problems_1.jpg a_ : int = array([[0, -20_00], [0, -12_00], [0, 1_56_00], [0, -1_24_00]]) a_ : Optional[Any] = array([[0, 0], [6, 0], [10, 0], [12, 0]]) assert in_static_equilibrium(forces, location) import doctest doctest.testmod()
73
1
import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging a_ : Tuple = logging.get_logger(__name__) a_ : Any = { 'BridgeTower/bridgetower-base': 'https://huggingface.co/BridgeTower/bridgetower-base/blob/main/config.json', 'BridgeTower/bridgetower-base-itm-mlm': ( 'https://huggingface.co/BridgeTower/bridgetower-base-itm-mlm/blob/main/config.json' ), } class _snake_case ( A__ ): _lowercase : Optional[Any] = '''bridgetower_vision_model''' def __init__( self , a=768 , a=12 , a=3 , a=16 , a=288 , a=1 , a=1E-05 , a=False , a=True , a=False , **a , ) -> Optional[int]: super().__init__(**a) SCREAMING_SNAKE_CASE = hidden_size SCREAMING_SNAKE_CASE = num_hidden_layers SCREAMING_SNAKE_CASE = num_channels SCREAMING_SNAKE_CASE = patch_size SCREAMING_SNAKE_CASE = image_size SCREAMING_SNAKE_CASE = initializer_factor SCREAMING_SNAKE_CASE = layer_norm_eps SCREAMING_SNAKE_CASE = stop_gradient SCREAMING_SNAKE_CASE = share_layernorm SCREAMING_SNAKE_CASE = remove_last_layer @classmethod def SCREAMING_SNAKE_CASE__ ( cls , a , **a) -> "PretrainedConfig": SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = cls.get_config_dict(a , **a) if config_dict.get('model_type') == "bridgetower": SCREAMING_SNAKE_CASE = config_dict['text_config'] if "model_type" in config_dict and hasattr(cls , 'model_type') and config_dict["model_type"] != cls.model_type: logger.warning( f'''You are using a model of type {config_dict['model_type']} to instantiate a model of type ''' f'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.''') return cls.from_dict(a , **a) class _snake_case ( A__ ): _lowercase : List[Any] = '''bridgetower_text_model''' def __init__( self , a=5_0265 , a=768 , a=12 , a=12 , a=1 , a=3072 , a="gelu" , a=0.1 , a=0.1 , a=514 , a=1 , a=1E-05 , a=1 , a=0 , a=2 , a="absolute" , a=True , **a , ) -> List[Any]: super().__init__(**a) SCREAMING_SNAKE_CASE = vocab_size SCREAMING_SNAKE_CASE = hidden_size SCREAMING_SNAKE_CASE = num_hidden_layers SCREAMING_SNAKE_CASE = num_attention_heads SCREAMING_SNAKE_CASE = hidden_act SCREAMING_SNAKE_CASE = initializer_factor SCREAMING_SNAKE_CASE = intermediate_size SCREAMING_SNAKE_CASE = hidden_dropout_prob SCREAMING_SNAKE_CASE = attention_probs_dropout_prob SCREAMING_SNAKE_CASE = max_position_embeddings SCREAMING_SNAKE_CASE = type_vocab_size SCREAMING_SNAKE_CASE = layer_norm_eps SCREAMING_SNAKE_CASE = position_embedding_type SCREAMING_SNAKE_CASE = use_cache SCREAMING_SNAKE_CASE = pad_token_id SCREAMING_SNAKE_CASE = bos_token_id SCREAMING_SNAKE_CASE = eos_token_id @classmethod def SCREAMING_SNAKE_CASE__ ( cls , a , **a) -> "PretrainedConfig": SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = cls.get_config_dict(a , **a) if config_dict.get('model_type') == "bridgetower": SCREAMING_SNAKE_CASE = config_dict['text_config'] if "model_type" in config_dict and hasattr(cls , 'model_type') and config_dict["model_type"] != cls.model_type: logger.warning( f'''You are using a model of type {config_dict['model_type']} to instantiate a model of type ''' f'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.''') return cls.from_dict(a , **a) class _snake_case ( A__ ): _lowercase : List[Any] = '''bridgetower''' def __init__( self , a=True , a="gelu" , a=768 , a=1 , a=1E-05 , a=False , a="add" , a=12 , a=6 , a=False , a=False , a=None , a=None , **a , ) -> Dict: # TODO: remove this once the Hub files are updated. SCREAMING_SNAKE_CASE = kwargs.pop('text_config_dict' , a) SCREAMING_SNAKE_CASE = kwargs.pop('vision_config_dict' , a) super().__init__(**a) SCREAMING_SNAKE_CASE = share_cross_modal_transformer_layers SCREAMING_SNAKE_CASE = hidden_act SCREAMING_SNAKE_CASE = hidden_size SCREAMING_SNAKE_CASE = initializer_factor SCREAMING_SNAKE_CASE = layer_norm_eps SCREAMING_SNAKE_CASE = share_link_tower_layers SCREAMING_SNAKE_CASE = link_tower_type SCREAMING_SNAKE_CASE = num_attention_heads SCREAMING_SNAKE_CASE = num_hidden_layers SCREAMING_SNAKE_CASE = tie_word_embeddings SCREAMING_SNAKE_CASE = init_layernorm_from_vision_encoder if text_config is None: SCREAMING_SNAKE_CASE = {} logger.info('`text_config` is `None`. Initializing the `BridgeTowerTextConfig` with default values.') if vision_config is None: SCREAMING_SNAKE_CASE = {} logger.info('`vision_config` is `None`. Initializing the `BridgeTowerVisionConfig` with default values.') SCREAMING_SNAKE_CASE = BridgeTowerTextConfig(**a) SCREAMING_SNAKE_CASE = BridgeTowerVisionConfig(**a) @classmethod def SCREAMING_SNAKE_CASE__ ( cls , a , a , **a) -> List[str]: return cls(text_config=text_config.to_dict() , vision_config=vision_config.to_dict() , **a) def SCREAMING_SNAKE_CASE__ ( self) -> str: SCREAMING_SNAKE_CASE = copy.deepcopy(self.__dict__) SCREAMING_SNAKE_CASE = self.text_config.to_dict() SCREAMING_SNAKE_CASE = self.vision_config.to_dict() SCREAMING_SNAKE_CASE = self.__class__.model_type return output
73
from ...configuration_utils import PretrainedConfig from ...utils import logging a_ : Optional[int] = logging.get_logger(__name__) a_ : int = { 'microsoft/cvt-13': 'https://huggingface.co/microsoft/cvt-13/resolve/main/config.json', # See all Cvt models at https://huggingface.co/models?filter=cvt } class _snake_case ( A__ ): _lowercase : Dict = '''cvt''' def __init__( self , a=3 , a=[7, 3, 3] , a=[4, 2, 2] , a=[2, 1, 1] , a=[64, 192, 384] , a=[1, 3, 6] , a=[1, 2, 10] , a=[4.0, 4.0, 4.0] , a=[0.0, 0.0, 0.0] , a=[0.0, 0.0, 0.0] , a=[0.0, 0.0, 0.1] , a=[True, True, True] , a=[False, False, True] , a=["dw_bn", "dw_bn", "dw_bn"] , a=[3, 3, 3] , a=[1, 1, 1] , a=[2, 2, 2] , a=[1, 1, 1] , a=[1, 1, 1] , a=0.02 , a=1E-12 , **a , ) -> List[Any]: super().__init__(**a) SCREAMING_SNAKE_CASE = num_channels SCREAMING_SNAKE_CASE = patch_sizes SCREAMING_SNAKE_CASE = patch_stride SCREAMING_SNAKE_CASE = patch_padding SCREAMING_SNAKE_CASE = embed_dim SCREAMING_SNAKE_CASE = num_heads SCREAMING_SNAKE_CASE = depth SCREAMING_SNAKE_CASE = mlp_ratio SCREAMING_SNAKE_CASE = attention_drop_rate SCREAMING_SNAKE_CASE = drop_rate SCREAMING_SNAKE_CASE = drop_path_rate SCREAMING_SNAKE_CASE = qkv_bias SCREAMING_SNAKE_CASE = cls_token SCREAMING_SNAKE_CASE = qkv_projection_method SCREAMING_SNAKE_CASE = kernel_qkv SCREAMING_SNAKE_CASE = padding_kv SCREAMING_SNAKE_CASE = stride_kv SCREAMING_SNAKE_CASE = padding_q SCREAMING_SNAKE_CASE = stride_q SCREAMING_SNAKE_CASE = initializer_range SCREAMING_SNAKE_CASE = layer_norm_eps
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_ : Dict = {'configuration_mra': ['MRA_PRETRAINED_CONFIG_ARCHIVE_MAP', 'MraConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : Dict = [ '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_ : List[str] = _LazyModule(__name__, globals()['__file__'], _import_structure)
73
def lowerCamelCase__ (_UpperCAmelCase = 10 , _UpperCAmelCase = 1000 , _UpperCAmelCase = True): assert ( isinstance(_UpperCAmelCase , _UpperCAmelCase) and isinstance(_UpperCAmelCase , _UpperCAmelCase) and isinstance(_UpperCAmelCase , _UpperCAmelCase) ), "Invalid type of value(s) specified to function!" if min_val > max_val: raise ValueError('Invalid value for min_val or max_val (min_value < max_value)') return min_val if option else max_val def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): return int((number_a + number_a) / 2) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): assert ( isinstance(_UpperCAmelCase , _UpperCAmelCase) and isinstance(_UpperCAmelCase , _UpperCAmelCase) and isinstance(_UpperCAmelCase , _UpperCAmelCase) ), 'argument values must be type of "int"' if lower > higher: raise ValueError('argument value for lower and higher must be(lower > higher)') if not lower < to_guess < higher: raise ValueError( 'guess value must be within the range of lower and higher value') def answer(_UpperCAmelCase) -> str: if number > to_guess: return "high" elif number < to_guess: return "low" else: return "same" print('started...') SCREAMING_SNAKE_CASE = lower SCREAMING_SNAKE_CASE = higher SCREAMING_SNAKE_CASE = [] while True: SCREAMING_SNAKE_CASE = get_avg(_UpperCAmelCase , _UpperCAmelCase) last_numbers.append(_UpperCAmelCase) if answer(_UpperCAmelCase) == "low": SCREAMING_SNAKE_CASE = number elif answer(_UpperCAmelCase) == "high": SCREAMING_SNAKE_CASE = number else: break print(F'''guess the number : {last_numbers[-1]}''') print(F'''details : {last_numbers!s}''') def lowerCamelCase__ (): SCREAMING_SNAKE_CASE = int(input('Enter lower value : ').strip()) SCREAMING_SNAKE_CASE = int(input('Enter high value : ').strip()) SCREAMING_SNAKE_CASE = int(input('Enter value to guess : ').strip()) guess_the_number(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) if __name__ == "__main__": main()
73
1
import json import os import shutil import warnings from argparse import ArgumentParser, Namespace from pathlib import Path from typing import List from ..utils import logging from . import BaseTransformersCLICommand try: from cookiecutter.main import cookiecutter a_ : Any = True except ImportError: a_ : Optional[Any] = False a_ : Optional[int] = logging.get_logger(__name__) # pylint: disable=invalid-name def lowerCamelCase__ (_UpperCAmelCase): return AddNewModelCommand(args.testing , args.testing_file , path=args.path) class _snake_case ( A__ ): @staticmethod def SCREAMING_SNAKE_CASE__ ( a) -> int: SCREAMING_SNAKE_CASE = parser.add_parser('add-new-model') add_new_model_parser.add_argument('--testing' , action='store_true' , help='If in testing mode.') add_new_model_parser.add_argument('--testing_file' , type=a , help='Configuration file on which to run.') add_new_model_parser.add_argument( '--path' , type=a , help='Path to cookiecutter. Should only be used for testing purposes.') add_new_model_parser.set_defaults(func=a) def __init__( self , a , a , a=None , *a) -> Union[str, Any]: SCREAMING_SNAKE_CASE = testing SCREAMING_SNAKE_CASE = testing_file SCREAMING_SNAKE_CASE = path def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: warnings.warn( 'The command `transformers-cli add-new-model` is deprecated and will be removed in v5 of Transformers. ' 'It is not actively maintained anymore, so might give a result that won\'t pass all tests and quality ' 'checks, you should use `transformers-cli add-new-model-like` instead.') if not _has_cookiecutter: raise ImportError( 'Model creation dependencies are required to use the `add_new_model` command. Install them by running ' 'the following at the root of your `transformers` clone:\n\n\t$ pip install -e .[modelcreation]\n') # Ensure that there is no other `cookiecutter-template-xxx` directory in the current working directory SCREAMING_SNAKE_CASE = [directory for directory in os.listdir() if 'cookiecutter-template-' == directory[:22]] if len(a) > 0: raise ValueError( 'Several directories starting with `cookiecutter-template-` in current working directory. ' 'Please clean your directory by removing all folders starting with `cookiecutter-template-` or ' 'change your working directory.') SCREAMING_SNAKE_CASE = ( Path(a).parent.parent.parent.parent if self._path is None else Path(self._path).parent.parent ) SCREAMING_SNAKE_CASE = path_to_transformer_root / 'templates' / 'adding_a_new_model' # Execute cookiecutter if not self._testing: cookiecutter(str(a)) else: with open(self._testing_file , 'r') as configuration_file: SCREAMING_SNAKE_CASE = json.load(a) cookiecutter( str(path_to_cookiecutter if self._path is None else self._path) , no_input=a , extra_context=a , ) SCREAMING_SNAKE_CASE = [directory for directory in os.listdir() if 'cookiecutter-template-' in directory[:22]][0] # Retrieve configuration with open(directory + '/configuration.json' , 'r') as configuration_file: SCREAMING_SNAKE_CASE = json.load(a) SCREAMING_SNAKE_CASE = configuration['lowercase_modelname'] SCREAMING_SNAKE_CASE = configuration['generate_tensorflow_pytorch_and_flax'] os.remove(f'''{directory}/configuration.json''') SCREAMING_SNAKE_CASE = 'PyTorch' in generate_tensorflow_pytorch_and_flax SCREAMING_SNAKE_CASE = 'TensorFlow' in generate_tensorflow_pytorch_and_flax SCREAMING_SNAKE_CASE = 'Flax' in generate_tensorflow_pytorch_and_flax SCREAMING_SNAKE_CASE = f'''{path_to_transformer_root}/src/transformers/models/{lowercase_model_name}''' os.makedirs(a , exist_ok=a) os.makedirs(f'''{path_to_transformer_root}/tests/models/{lowercase_model_name}''' , exist_ok=a) # Tests require submodules as they have parent imports with open(f'''{path_to_transformer_root}/tests/models/{lowercase_model_name}/__init__.py''' , 'w'): pass shutil.move( f'''{directory}/__init__.py''' , f'''{model_dir}/__init__.py''' , ) shutil.move( f'''{directory}/configuration_{lowercase_model_name}.py''' , f'''{model_dir}/configuration_{lowercase_model_name}.py''' , ) def remove_copy_lines(a): with open(a , 'r') as f: SCREAMING_SNAKE_CASE = f.readlines() with open(a , 'w') as f: for line in lines: if "# Copied from transformers." not in line: f.write(a) if output_pytorch: if not self._testing: remove_copy_lines(f'''{directory}/modeling_{lowercase_model_name}.py''') shutil.move( f'''{directory}/modeling_{lowercase_model_name}.py''' , f'''{model_dir}/modeling_{lowercase_model_name}.py''' , ) shutil.move( f'''{directory}/test_modeling_{lowercase_model_name}.py''' , f'''{path_to_transformer_root}/tests/models/{lowercase_model_name}/test_modeling_{lowercase_model_name}.py''' , ) else: os.remove(f'''{directory}/modeling_{lowercase_model_name}.py''') os.remove(f'''{directory}/test_modeling_{lowercase_model_name}.py''') if output_tensorflow: if not self._testing: remove_copy_lines(f'''{directory}/modeling_tf_{lowercase_model_name}.py''') shutil.move( f'''{directory}/modeling_tf_{lowercase_model_name}.py''' , f'''{model_dir}/modeling_tf_{lowercase_model_name}.py''' , ) shutil.move( f'''{directory}/test_modeling_tf_{lowercase_model_name}.py''' , f'''{path_to_transformer_root}/tests/models/{lowercase_model_name}/test_modeling_tf_{lowercase_model_name}.py''' , ) else: os.remove(f'''{directory}/modeling_tf_{lowercase_model_name}.py''') os.remove(f'''{directory}/test_modeling_tf_{lowercase_model_name}.py''') if output_flax: if not self._testing: remove_copy_lines(f'''{directory}/modeling_flax_{lowercase_model_name}.py''') shutil.move( f'''{directory}/modeling_flax_{lowercase_model_name}.py''' , f'''{model_dir}/modeling_flax_{lowercase_model_name}.py''' , ) shutil.move( f'''{directory}/test_modeling_flax_{lowercase_model_name}.py''' , f'''{path_to_transformer_root}/tests/models/{lowercase_model_name}/test_modeling_flax_{lowercase_model_name}.py''' , ) else: os.remove(f'''{directory}/modeling_flax_{lowercase_model_name}.py''') os.remove(f'''{directory}/test_modeling_flax_{lowercase_model_name}.py''') shutil.move( f'''{directory}/{lowercase_model_name}.md''' , f'''{path_to_transformer_root}/docs/source/en/model_doc/{lowercase_model_name}.md''' , ) shutil.move( f'''{directory}/tokenization_{lowercase_model_name}.py''' , f'''{model_dir}/tokenization_{lowercase_model_name}.py''' , ) shutil.move( f'''{directory}/tokenization_fast_{lowercase_model_name}.py''' , f'''{model_dir}/tokenization_{lowercase_model_name}_fast.py''' , ) from os import fdopen, remove from shutil import copymode, move from tempfile import mkstemp def replace(a , a , a): # Create temp file SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = mkstemp() SCREAMING_SNAKE_CASE = False with fdopen(a , 'w') as new_file: with open(a) as old_file: for line in old_file: new_file.write(a) if line_to_copy_below in line: SCREAMING_SNAKE_CASE = True for line_to_copy in lines_to_copy: new_file.write(a) if not line_found: raise ValueError(f'''Line {line_to_copy_below} was not found in file.''') # Copy the file permissions from the old file to the new file copymode(a , a) # Remove original file remove(a) # Move new file move(a , a) def skip_units(a): return ( ("generating PyTorch" in line and not output_pytorch) or ("generating TensorFlow" in line and not output_tensorflow) or ("generating Flax" in line and not output_flax) ) def replace_in_files(a): with open(a) as datafile: SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = False SCREAMING_SNAKE_CASE = False for line in datafile: if "# To replace in: " in line and "##" not in line: SCREAMING_SNAKE_CASE = line.split('"')[1] SCREAMING_SNAKE_CASE = skip_units(a) elif "# Below: " in line and "##" not in line: SCREAMING_SNAKE_CASE = line.split('"')[1] SCREAMING_SNAKE_CASE = skip_units(a) elif "# End." in line and "##" not in line: if not skip_file and not skip_snippet: replace(a , a , a) SCREAMING_SNAKE_CASE = [] elif "# Replace with" in line and "##" not in line: SCREAMING_SNAKE_CASE = [] elif "##" not in line: lines_to_copy.append(a) remove(a) replace_in_files(f'''{directory}/to_replace_{lowercase_model_name}.py''') os.rmdir(a)
73
import unittest from parameterized import parameterized from transformers import OpenLlamaConfig, is_torch_available, set_seed from transformers.testing_utils import require_torch, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import OpenLlamaForCausalLM, OpenLlamaForSequenceClassification, OpenLlamaModel class _snake_case : def __init__( self , a , a=13 , a=7 , a=True , a=True , a=False , a=True , a=99 , a=32 , a=5 , a=4 , a=37 , a="gelu" , a=0.1 , a=0.1 , a=512 , a=16 , a=2 , a=0.02 , a=3 , a=4 , a=None , ) -> Union[str, Any]: SCREAMING_SNAKE_CASE = parent SCREAMING_SNAKE_CASE = batch_size SCREAMING_SNAKE_CASE = seq_length SCREAMING_SNAKE_CASE = is_training SCREAMING_SNAKE_CASE = use_input_mask SCREAMING_SNAKE_CASE = use_token_type_ids SCREAMING_SNAKE_CASE = use_labels SCREAMING_SNAKE_CASE = vocab_size SCREAMING_SNAKE_CASE = hidden_size SCREAMING_SNAKE_CASE = num_hidden_layers SCREAMING_SNAKE_CASE = num_attention_heads SCREAMING_SNAKE_CASE = intermediate_size SCREAMING_SNAKE_CASE = hidden_act SCREAMING_SNAKE_CASE = hidden_dropout_prob SCREAMING_SNAKE_CASE = attention_probs_dropout_prob SCREAMING_SNAKE_CASE = max_position_embeddings SCREAMING_SNAKE_CASE = type_vocab_size SCREAMING_SNAKE_CASE = type_sequence_label_size SCREAMING_SNAKE_CASE = initializer_range SCREAMING_SNAKE_CASE = num_labels SCREAMING_SNAKE_CASE = num_choices SCREAMING_SNAKE_CASE = scope def SCREAMING_SNAKE_CASE__ ( self) -> Dict: SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size) SCREAMING_SNAKE_CASE = None if self.use_input_mask: SCREAMING_SNAKE_CASE = random_attention_mask([self.batch_size, self.seq_length]) SCREAMING_SNAKE_CASE = None if self.use_token_type_ids: SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size) SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = None if self.use_labels: SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.type_sequence_label_size) SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.num_labels) SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.num_choices) SCREAMING_SNAKE_CASE = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: return OpenLlamaConfig( 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 , is_decoder=a , initializer_range=self.initializer_range , use_stable_embedding=a , ) def SCREAMING_SNAKE_CASE__ ( self , a , a , a , a , a , a , a) -> Any: SCREAMING_SNAKE_CASE = OpenLlamaModel(config=a) model.to(a) model.eval() SCREAMING_SNAKE_CASE = model(a , attention_mask=a) SCREAMING_SNAKE_CASE = model(a) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size)) def SCREAMING_SNAKE_CASE__ ( self , a , a , a , a , a , a , a , a , a , ) -> str: SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = OpenLlamaModel(a) model.to(a) model.eval() SCREAMING_SNAKE_CASE = model( a , attention_mask=a , encoder_hidden_states=a , encoder_attention_mask=a , ) SCREAMING_SNAKE_CASE = model( a , attention_mask=a , encoder_hidden_states=a , ) SCREAMING_SNAKE_CASE = model(a , attention_mask=a) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size)) def SCREAMING_SNAKE_CASE__ ( self , a , a , a , a , a , a , a , a , a , ) -> int: SCREAMING_SNAKE_CASE = OpenLlamaForCausalLM(config=a) model.to(a) model.eval() SCREAMING_SNAKE_CASE = model(a , attention_mask=a , labels=a) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size)) def SCREAMING_SNAKE_CASE__ ( self , a , a , a , a , a , a , a , a , a , ) -> str: SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = OpenLlamaForCausalLM(config=a) model.to(a) model.eval() # first forward pass SCREAMING_SNAKE_CASE = model( a , attention_mask=a , encoder_hidden_states=a , encoder_attention_mask=a , use_cache=a , ) SCREAMING_SNAKE_CASE = outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids SCREAMING_SNAKE_CASE = ids_tensor((self.batch_size, 3) , config.vocab_size) SCREAMING_SNAKE_CASE = ids_tensor((self.batch_size, 3) , vocab_size=2) # append to next input_ids and SCREAMING_SNAKE_CASE = torch.cat([input_ids, next_tokens] , dim=-1) SCREAMING_SNAKE_CASE = torch.cat([input_mask, next_mask] , dim=-1) SCREAMING_SNAKE_CASE = model( a , attention_mask=a , encoder_hidden_states=a , encoder_attention_mask=a , output_hidden_states=a , )['hidden_states'][0] SCREAMING_SNAKE_CASE = model( a , attention_mask=a , encoder_hidden_states=a , encoder_attention_mask=a , past_key_values=a , output_hidden_states=a , )['hidden_states'][0] # select random slice SCREAMING_SNAKE_CASE = ids_tensor((1,) , output_from_past.shape[-1]).item() SCREAMING_SNAKE_CASE = output_from_no_past[:, -3:, random_slice_idx].detach() SCREAMING_SNAKE_CASE = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1]) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(a , a , atol=1E-3)) def SCREAMING_SNAKE_CASE__ ( self) -> str: SCREAMING_SNAKE_CASE = self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ) = config_and_inputs SCREAMING_SNAKE_CASE = {'input_ids': input_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class _snake_case ( A__ , A__ , A__ , unittest.TestCase ): _lowercase : List[Any] = ( (OpenLlamaModel, OpenLlamaForCausalLM, OpenLlamaForSequenceClassification) if is_torch_available() else () ) _lowercase : str = (OpenLlamaForCausalLM,) if is_torch_available() else () _lowercase : List[str] = ( { '''feature-extraction''': OpenLlamaModel, '''text-classification''': OpenLlamaForSequenceClassification, '''text-generation''': OpenLlamaForCausalLM, '''zero-shot''': OpenLlamaForSequenceClassification, } if is_torch_available() else {} ) _lowercase : List[str] = False _lowercase : Optional[int] = False def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: SCREAMING_SNAKE_CASE = OpenLlamaModelTester(self) SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=a , hidden_size=37) def SCREAMING_SNAKE_CASE__ ( self) -> str: self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE__ ( self) -> Any: SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a) def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: SCREAMING_SNAKE_CASE = type self.model_tester.create_and_check_model(*a) def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE = 3 SCREAMING_SNAKE_CASE = input_dict['input_ids'] SCREAMING_SNAKE_CASE = input_ids.ne(1).to(a) SCREAMING_SNAKE_CASE = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size) SCREAMING_SNAKE_CASE = OpenLlamaForSequenceClassification(a) model.to(a) model.eval() SCREAMING_SNAKE_CASE = model(a , attention_mask=a , labels=a) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels)) def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE = 3 SCREAMING_SNAKE_CASE = 'single_label_classification' SCREAMING_SNAKE_CASE = input_dict['input_ids'] SCREAMING_SNAKE_CASE = input_ids.ne(1).to(a) SCREAMING_SNAKE_CASE = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size) SCREAMING_SNAKE_CASE = OpenLlamaForSequenceClassification(a) model.to(a) model.eval() SCREAMING_SNAKE_CASE = model(a , attention_mask=a , labels=a) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels)) def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE = 3 SCREAMING_SNAKE_CASE = 'multi_label_classification' SCREAMING_SNAKE_CASE = input_dict['input_ids'] SCREAMING_SNAKE_CASE = input_ids.ne(1).to(a) SCREAMING_SNAKE_CASE = ids_tensor( [self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size).to(torch.float) SCREAMING_SNAKE_CASE = OpenLlamaForSequenceClassification(a) model.to(a) model.eval() SCREAMING_SNAKE_CASE = model(a , attention_mask=a , labels=a) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels)) @unittest.skip('Open-Llama buffers include complex numbers, which breaks this test') def SCREAMING_SNAKE_CASE__ ( self) -> Any: pass @parameterized.expand([('linear',), ('dynamic',)]) def SCREAMING_SNAKE_CASE__ ( self , a) -> Dict: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE = ids_tensor([1, 10] , config.vocab_size) SCREAMING_SNAKE_CASE = ids_tensor([1, int(config.max_position_embeddings * 1.5)] , config.vocab_size) set_seed(42) # Fixed seed at init time so the two models get the same random weights SCREAMING_SNAKE_CASE = OpenLlamaModel(a) original_model.to(a) original_model.eval() SCREAMING_SNAKE_CASE = original_model(a).last_hidden_state SCREAMING_SNAKE_CASE = original_model(a).last_hidden_state set_seed(42) # Fixed seed at init time so the two models get the same random weights SCREAMING_SNAKE_CASE = {'type': scaling_type, 'factor': 10.0} SCREAMING_SNAKE_CASE = OpenLlamaModel(a) scaled_model.to(a) scaled_model.eval() SCREAMING_SNAKE_CASE = scaled_model(a).last_hidden_state SCREAMING_SNAKE_CASE = scaled_model(a).last_hidden_state # Dynamic scaling does not change the RoPE embeddings until it receives an input longer than the original # maximum sequence length, so the outputs for the short input should match. if scaling_type == "dynamic": self.assertTrue(torch.allclose(a , a , atol=1E-5)) else: self.assertFalse(torch.allclose(a , a , atol=1E-5)) # The output should be different for long inputs self.assertFalse(torch.allclose(a , a , atol=1E-5))
73
1
import os import re import shutil from argparse import ArgumentParser, Namespace from datasets.commands import BaseDatasetsCLICommand from datasets.utils.logging import get_logger a_ : Union[str, Any] = '<<<<<<< This should probably be modified because it mentions: ' a_ : int = '=======\n>>>>>>>\n' a_ : Tuple = [ 'TextEncoderConfig', 'ByteTextEncoder', 'SubwordTextEncoder', 'encoder_config', 'maybe_build_from_corpus', 'manual_dir', ] a_ : Optional[int] = [ # (pattern, replacement) # Order is important here for some replacements (R'tfds\.core', R'datasets'), (R'tf\.io\.gfile\.GFile', R'open'), (R'tf\.([\w\d]+)', R'datasets.Value(\'\1\')'), (R'tfds\.features\.Text\(\)', R'datasets.Value(\'string\')'), (R'tfds\.features\.Text\(', R'datasets.Value(\'string\'),'), (R'features\s*=\s*tfds.features.FeaturesDict\(', R'features=datasets.Features('), (R'tfds\.features\.FeaturesDict\(', R'dict('), (R'The TensorFlow Datasets Authors', R'The TensorFlow Datasets Authors and the HuggingFace Datasets Authors'), (R'tfds\.', R'datasets.'), (R'dl_manager\.manual_dir', R'self.config.data_dir'), (R'self\.builder_config', R'self.config'), ] def lowerCamelCase__ (_UpperCAmelCase): return ConvertCommand(args.tfds_path , args.datasets_directory) class _snake_case ( A__ ): @staticmethod def SCREAMING_SNAKE_CASE__ ( a) -> Union[str, Any]: SCREAMING_SNAKE_CASE = parser.add_parser( 'convert' , help='Convert a TensorFlow Datasets dataset to a HuggingFace Datasets dataset.' , ) train_parser.add_argument( '--tfds_path' , type=a , required=a , help='Path to a TensorFlow Datasets folder to convert or a single tfds file to convert.' , ) train_parser.add_argument( '--datasets_directory' , type=a , required=a , help='Path to the HuggingFace Datasets folder.') train_parser.set_defaults(func=a) def __init__( self , a , a , *a) -> Union[str, Any]: SCREAMING_SNAKE_CASE = get_logger('datasets-cli/converting') SCREAMING_SNAKE_CASE = tfds_path SCREAMING_SNAKE_CASE = datasets_directory def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: if os.path.isdir(self._tfds_path): SCREAMING_SNAKE_CASE = os.path.abspath(self._tfds_path) elif os.path.isfile(self._tfds_path): SCREAMING_SNAKE_CASE = os.path.dirname(self._tfds_path) else: raise ValueError('--tfds_path is neither a directory nor a file. Please check path.') SCREAMING_SNAKE_CASE = os.path.abspath(self._datasets_directory) self._logger.info(f'''Converting datasets from {abs_tfds_path} to {abs_datasets_path}''') SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = {} if os.path.isdir(self._tfds_path): SCREAMING_SNAKE_CASE = os.listdir(a) else: SCREAMING_SNAKE_CASE = [os.path.basename(self._tfds_path)] for f_name in file_names: self._logger.info(f'''Looking at file {f_name}''') SCREAMING_SNAKE_CASE = os.path.join(a , a) SCREAMING_SNAKE_CASE = os.path.join(a , a) if not os.path.isfile(a) or "__init__" in f_name or "_test" in f_name or ".py" not in f_name: self._logger.info('Skipping file') continue with open(a , encoding='utf-8') as f: SCREAMING_SNAKE_CASE = f.readlines() SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = False SCREAMING_SNAKE_CASE = False SCREAMING_SNAKE_CASE = [] for line in lines: SCREAMING_SNAKE_CASE = line # Convert imports if "import tensorflow.compat.v2 as tf" in out_line: continue elif "@tfds.core" in out_line: continue elif "builder=self" in out_line: continue elif "import tensorflow_datasets.public_api as tfds" in out_line: SCREAMING_SNAKE_CASE = 'import datasets\n' elif "import tensorflow" in out_line: # order is important here SCREAMING_SNAKE_CASE = '' continue elif "from absl import logging" in out_line: SCREAMING_SNAKE_CASE = 'from datasets import logging\n' elif "getLogger" in out_line: SCREAMING_SNAKE_CASE = out_line.replace('getLogger' , 'get_logger') elif any(expression in out_line for expression in TO_HIGHLIGHT): SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = list(filter(lambda a: e in out_line , a)) out_lines.append(HIGHLIGHT_MESSAGE_PRE + str(a) + '\n') out_lines.append(a) out_lines.append(a) continue else: for pattern, replacement in TO_CONVERT: SCREAMING_SNAKE_CASE = re.sub(a , a , a) # Take care of saving utilities (to later move them together with main script) if "tensorflow_datasets" in out_line: SCREAMING_SNAKE_CASE = re.match(R'from\stensorflow_datasets.*import\s([^\.\r\n]+)' , a) tfds_imports.extend(imp.strip() for imp in match.group(1).split(',')) SCREAMING_SNAKE_CASE = 'from . import ' + match.group(1) # Check we have not forget anything if "tf." in out_line or "tfds." in out_line or "tensorflow_datasets" in out_line: raise ValueError(f'''Error converting {out_line.strip()}''') if "GeneratorBasedBuilder" in out_line or "BeamBasedBuilder" in out_line: SCREAMING_SNAKE_CASE = True out_lines.append(a) if is_builder or "wmt" in f_name: # We create a new directory for each dataset SCREAMING_SNAKE_CASE = f_name.replace('.py' , '') SCREAMING_SNAKE_CASE = os.path.join(a , a) SCREAMING_SNAKE_CASE = os.path.join(a , a) os.makedirs(a , exist_ok=a) self._logger.info(f'''Adding directory {output_dir}''') imports_to_builder_map.update({imp: output_dir for imp in tfds_imports}) else: # Utilities will be moved at the end utils_files.append(a) if needs_manual_update: with_manual_update.append(a) with open(a , 'w' , encoding='utf-8') as f: f.writelines(a) self._logger.info(f'''Converted in {output_file}''') for utils_file in utils_files: try: SCREAMING_SNAKE_CASE = os.path.basename(a) SCREAMING_SNAKE_CASE = imports_to_builder_map[f_name.replace('.py' , '')] self._logger.info(f'''Moving {dest_folder} to {utils_file}''') shutil.copy(a , a) except KeyError: self._logger.error(f'''Cannot find destination folder for {utils_file}. Please copy manually.''') if with_manual_update: for file_path in with_manual_update: self._logger.warning( f'''You need to manually update file {file_path} to remove configurations using \'TextEncoderConfig\'.''')
73
from __future__ import annotations a_ : str = [] def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): for i in range(len(_UpperCAmelCase)): if board[row][i] == 1: return False for i in range(len(_UpperCAmelCase)): if board[i][column] == 1: return False for i, j in zip(range(_UpperCAmelCase , -1 , -1) , range(_UpperCAmelCase , -1 , -1)): if board[i][j] == 1: return False for i, j in zip(range(_UpperCAmelCase , -1 , -1) , range(_UpperCAmelCase , len(_UpperCAmelCase))): if board[i][j] == 1: return False return True def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): if row >= len(_UpperCAmelCase): solution.append(_UpperCAmelCase) printboard(_UpperCAmelCase) print() return True for i in range(len(_UpperCAmelCase)): if is_safe(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = 1 solve(_UpperCAmelCase , row + 1) SCREAMING_SNAKE_CASE = 0 return False def lowerCamelCase__ (_UpperCAmelCase): for i in range(len(_UpperCAmelCase)): for j in range(len(_UpperCAmelCase)): if board[i][j] == 1: print('Q' , end=' ') else: print('.' , end=' ') print() # n=int(input("The no. of queens")) a_ : Tuple = 8 a_ : int = [[0 for i in range(n)] for j in range(n)] solve(board, 0) print('The total no. of solutions are :', len(solution))
73
1
import contextlib import importlib import io import unittest import transformers # Try to import everything from transformers to ensure every object can be loaded. from transformers import * # noqa F406 from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, require_flax, require_tf, require_torch from transformers.utils import ContextManagers, find_labels, is_flax_available, is_tf_available, is_torch_available if is_torch_available(): from transformers import BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification if is_tf_available(): from transformers import TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification if is_flax_available(): from transformers import FlaxBertForPreTraining, FlaxBertForQuestionAnswering, FlaxBertForSequenceClassification a_ : Tuple = DUMMY_UNKNOWN_IDENTIFIER # An actual model hosted on huggingface.co a_ : Union[str, Any] = 'main' # Default branch name a_ : List[str] = 'f2c752cfc5c0ab6f4bdec59acea69eefbee381c2' # One particular commit (not the top of `main`) a_ : Optional[int] = 'aaaaaaa' # This commit does not exist, so we should 404. a_ : Dict = 'd9e9f15bc825e4b2c9249e9578f884bbcb5e3684' # Sha-1 of config.json on the top of `main`, for checking purposes a_ : int = '4b243c475af8d0a7754e87d7d096c92e5199ec2fe168a2ee7998e3b8e9bcb1d3' @contextlib.contextmanager def lowerCamelCase__ (): print('Welcome!') yield print('Bye!') @contextlib.contextmanager def lowerCamelCase__ (): print('Bonjour!') yield print('Au revoir!') class _snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ ( self) -> Any: # If the spec is missing, importlib would not be able to import the module dynamically. assert transformers.__spec__ is not None assert importlib.util.find_spec('transformers') is not None class _snake_case ( unittest.TestCase ): @unittest.mock.patch('sys.stdout' , new_callable=io.StringIO) def SCREAMING_SNAKE_CASE__ ( self , a) -> List[str]: with ContextManagers([]): print('Transformers are awesome!') # The print statement adds a new line at the end of the output self.assertEqual(mock_stdout.getvalue() , 'Transformers are awesome!\n') @unittest.mock.patch('sys.stdout' , new_callable=io.StringIO) def SCREAMING_SNAKE_CASE__ ( self , a) -> List[str]: with ContextManagers([context_en()]): print('Transformers are awesome!') # The output should be wrapped with an English welcome and goodbye self.assertEqual(mock_stdout.getvalue() , 'Welcome!\nTransformers are awesome!\nBye!\n') @unittest.mock.patch('sys.stdout' , new_callable=io.StringIO) def SCREAMING_SNAKE_CASE__ ( self , a) -> Optional[int]: with ContextManagers([context_fr(), context_en()]): print('Transformers are awesome!') # The output should be wrapped with an English and French welcome and goodbye self.assertEqual(mock_stdout.getvalue() , 'Bonjour!\nWelcome!\nTransformers are awesome!\nBye!\nAu revoir!\n') @require_torch def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: self.assertEqual(find_labels(a) , ['labels']) self.assertEqual(find_labels(a) , ['labels', 'next_sentence_label']) self.assertEqual(find_labels(a) , ['start_positions', 'end_positions']) class _snake_case ( A__ ): pass self.assertEqual(find_labels(a) , ['labels']) @require_tf def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: self.assertEqual(find_labels(a) , ['labels']) self.assertEqual(find_labels(a) , ['labels', 'next_sentence_label']) self.assertEqual(find_labels(a) , ['start_positions', 'end_positions']) class _snake_case ( A__ ): pass self.assertEqual(find_labels(a) , ['labels']) @require_flax def SCREAMING_SNAKE_CASE__ ( self) -> str: # Flax models don't have labels self.assertEqual(find_labels(a) , []) self.assertEqual(find_labels(a) , []) self.assertEqual(find_labels(a) , []) class _snake_case ( A__ ): pass self.assertEqual(find_labels(a) , [])
73
import gc import random import tempfile import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMInverseScheduler, DDIMScheduler, DPMSolverMultistepInverseScheduler, DPMSolverMultistepScheduler, StableDiffusionDiffEditPipeline, UNetaDConditionModel, ) from diffusers.utils import load_image, slow from diffusers.utils.testing_utils import enable_full_determinism, floats_tensor, require_torch_gpu, torch_device from ..pipeline_params import TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class _snake_case ( A__ , A__ , unittest.TestCase ): _lowercase : List[Any] = StableDiffusionDiffEditPipeline _lowercase : List[str] = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS - {'''height''', '''width''', '''image'''} | {'''image_latents'''} _lowercase : Optional[int] = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS - {'''image'''} | {'''image_latents'''} _lowercase : List[str] = frozenset( [] ) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess _lowercase : List[str] = frozenset([] ) def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: torch.manual_seed(0) SCREAMING_SNAKE_CASE = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D') , up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D') , cross_attention_dim=32 , attention_head_dim=(2, 4) , use_linear_projection=a , ) SCREAMING_SNAKE_CASE = DDIMScheduler( beta_start=0.0_00_85 , beta_end=0.0_12 , beta_schedule='scaled_linear' , clip_sample=a , set_alpha_to_one=a , ) SCREAMING_SNAKE_CASE = DDIMInverseScheduler( beta_start=0.0_00_85 , beta_end=0.0_12 , beta_schedule='scaled_linear' , clip_sample=a , set_alpha_to_zero=a , ) torch.manual_seed(0) SCREAMING_SNAKE_CASE = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D'] , up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D'] , latent_channels=4 , sample_size=128 , ) torch.manual_seed(0) SCREAMING_SNAKE_CASE = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , hidden_act='gelu' , projection_dim=512 , ) SCREAMING_SNAKE_CASE = CLIPTextModel(a) SCREAMING_SNAKE_CASE = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip') SCREAMING_SNAKE_CASE = { 'unet': unet, 'scheduler': scheduler, 'inverse_scheduler': inverse_scheduler, 'vae': vae, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'safety_checker': None, 'feature_extractor': None, } return components def SCREAMING_SNAKE_CASE__ ( self , a , a=0) -> List[Any]: SCREAMING_SNAKE_CASE = floats_tensor((1, 16, 16) , rng=random.Random(a)).to(a) SCREAMING_SNAKE_CASE = floats_tensor((1, 2, 4, 16, 16) , rng=random.Random(a)).to(a) if str(a).startswith('mps'): SCREAMING_SNAKE_CASE = torch.manual_seed(a) else: SCREAMING_SNAKE_CASE = torch.Generator(device=a).manual_seed(a) SCREAMING_SNAKE_CASE = { 'prompt': 'a dog and a newt', 'mask_image': mask, 'image_latents': latents, 'generator': generator, 'num_inference_steps': 2, 'inpaint_strength': 1.0, 'guidance_scale': 6.0, 'output_type': 'numpy', } return inputs def SCREAMING_SNAKE_CASE__ ( self , a , a=0) -> List[Any]: SCREAMING_SNAKE_CASE = floats_tensor((1, 3, 32, 32) , rng=random.Random(a)).to(a) SCREAMING_SNAKE_CASE = image.cpu().permute(0 , 2 , 3 , 1)[0] SCREAMING_SNAKE_CASE = Image.fromarray(np.uinta(a)).convert('RGB') if str(a).startswith('mps'): SCREAMING_SNAKE_CASE = torch.manual_seed(a) else: SCREAMING_SNAKE_CASE = torch.Generator(device=a).manual_seed(a) SCREAMING_SNAKE_CASE = { 'image': image, 'source_prompt': 'a cat and a frog', 'target_prompt': 'a dog and a newt', 'generator': generator, 'num_inference_steps': 2, 'num_maps_per_mask': 2, 'mask_encode_strength': 1.0, 'guidance_scale': 6.0, 'output_type': 'numpy', } return inputs def SCREAMING_SNAKE_CASE__ ( self , a , a=0) -> Optional[int]: SCREAMING_SNAKE_CASE = floats_tensor((1, 3, 32, 32) , rng=random.Random(a)).to(a) SCREAMING_SNAKE_CASE = image.cpu().permute(0 , 2 , 3 , 1)[0] SCREAMING_SNAKE_CASE = Image.fromarray(np.uinta(a)).convert('RGB') if str(a).startswith('mps'): SCREAMING_SNAKE_CASE = torch.manual_seed(a) else: SCREAMING_SNAKE_CASE = torch.Generator(device=a).manual_seed(a) SCREAMING_SNAKE_CASE = { 'image': image, 'prompt': 'a cat and a frog', 'generator': generator, 'num_inference_steps': 2, 'inpaint_strength': 1.0, 'guidance_scale': 6.0, 'decode_latents': True, 'output_type': 'numpy', } return inputs def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: if not hasattr(self.pipeline_class , '_optional_components'): return SCREAMING_SNAKE_CASE = self.get_dummy_components() SCREAMING_SNAKE_CASE = self.pipeline_class(**a) pipe.to(a) pipe.set_progress_bar_config(disable=a) # set all optional components to None and update pipeline config accordingly for optional_component in pipe._optional_components: setattr(a , a , a) pipe.register_modules(**{optional_component: None for optional_component in pipe._optional_components}) SCREAMING_SNAKE_CASE = self.get_dummy_inputs(a) SCREAMING_SNAKE_CASE = pipe(**a)[0] with tempfile.TemporaryDirectory() as tmpdir: pipe.save_pretrained(a) SCREAMING_SNAKE_CASE = self.pipeline_class.from_pretrained(a) pipe_loaded.to(a) pipe_loaded.set_progress_bar_config(disable=a) for optional_component in pipe._optional_components: self.assertTrue( getattr(a , a) is None , f'''`{optional_component}` did not stay set to None after loading.''' , ) SCREAMING_SNAKE_CASE = self.get_dummy_inputs(a) SCREAMING_SNAKE_CASE = pipe_loaded(**a)[0] SCREAMING_SNAKE_CASE = np.abs(output - output_loaded).max() self.assertLess(a , 1E-4) def SCREAMING_SNAKE_CASE__ ( self) -> str: SCREAMING_SNAKE_CASE = 'cpu' SCREAMING_SNAKE_CASE = self.get_dummy_components() SCREAMING_SNAKE_CASE = self.pipeline_class(**a) pipe.to(a) pipe.set_progress_bar_config(disable=a) SCREAMING_SNAKE_CASE = self.get_dummy_mask_inputs(a) SCREAMING_SNAKE_CASE = pipe.generate_mask(**a) SCREAMING_SNAKE_CASE = mask[0, -3:, -3:] self.assertEqual(mask.shape , (1, 16, 16)) SCREAMING_SNAKE_CASE = np.array([0] * 9) SCREAMING_SNAKE_CASE = np.abs(mask_slice.flatten() - expected_slice).max() self.assertLessEqual(a , 1E-3) self.assertEqual(mask[0, -3, -4] , 0) def SCREAMING_SNAKE_CASE__ ( self) -> str: SCREAMING_SNAKE_CASE = 'cpu' SCREAMING_SNAKE_CASE = self.get_dummy_components() SCREAMING_SNAKE_CASE = self.pipeline_class(**a) pipe.to(a) pipe.set_progress_bar_config(disable=a) SCREAMING_SNAKE_CASE = self.get_dummy_inversion_inputs(a) SCREAMING_SNAKE_CASE = pipe.invert(**a).images SCREAMING_SNAKE_CASE = image[0, -1, -3:, -3:] self.assertEqual(image.shape , (2, 32, 32, 3)) SCREAMING_SNAKE_CASE = np.array( [0.51_50, 0.51_34, 0.50_43, 0.53_76, 0.46_94, 0.5_10_50, 0.50_15, 0.44_07, 0.47_99] , ) SCREAMING_SNAKE_CASE = np.abs(image_slice.flatten() - expected_slice).max() self.assertLessEqual(a , 1E-3) def SCREAMING_SNAKE_CASE__ ( self) -> Dict: super().test_inference_batch_single_identical(expected_max_diff=5E-3) def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: SCREAMING_SNAKE_CASE = 'cpu' SCREAMING_SNAKE_CASE = self.get_dummy_components() SCREAMING_SNAKE_CASE = {'beta_start': 0.0_00_85, 'beta_end': 0.0_12, 'beta_schedule': 'scaled_linear'} SCREAMING_SNAKE_CASE = DPMSolverMultistepScheduler(**a) SCREAMING_SNAKE_CASE = DPMSolverMultistepInverseScheduler(**a) SCREAMING_SNAKE_CASE = self.pipeline_class(**a) pipe.to(a) pipe.set_progress_bar_config(disable=a) SCREAMING_SNAKE_CASE = self.get_dummy_inversion_inputs(a) SCREAMING_SNAKE_CASE = pipe.invert(**a).images SCREAMING_SNAKE_CASE = image[0, -1, -3:, -3:] self.assertEqual(image.shape , (2, 32, 32, 3)) SCREAMING_SNAKE_CASE = np.array( [0.51_50, 0.51_34, 0.50_43, 0.53_76, 0.46_94, 0.5_10_50, 0.50_15, 0.44_07, 0.47_99] , ) SCREAMING_SNAKE_CASE = np.abs(image_slice.flatten() - expected_slice).max() self.assertLessEqual(a , 1E-3) @require_torch_gpu @slow class _snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ ( self) -> Any: super().tearDown() gc.collect() torch.cuda.empty_cache() @classmethod def SCREAMING_SNAKE_CASE__ ( cls) -> List[Any]: SCREAMING_SNAKE_CASE = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/diffedit/fruit.png') SCREAMING_SNAKE_CASE = raw_image.convert('RGB').resize((768, 768)) SCREAMING_SNAKE_CASE = raw_image def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: SCREAMING_SNAKE_CASE = torch.manual_seed(0) SCREAMING_SNAKE_CASE = StableDiffusionDiffEditPipeline.from_pretrained( 'stabilityai/stable-diffusion-2-1' , safety_checker=a , torch_dtype=torch.floataa) SCREAMING_SNAKE_CASE = DDIMScheduler.from_config(pipe.scheduler.config) SCREAMING_SNAKE_CASE = DDIMInverseScheduler.from_config(pipe.scheduler.config) pipe.enable_model_cpu_offload() pipe.set_progress_bar_config(disable=a) SCREAMING_SNAKE_CASE = 'a bowl of fruit' SCREAMING_SNAKE_CASE = 'a bowl of pears' SCREAMING_SNAKE_CASE = pipe.generate_mask( image=self.raw_image , source_prompt=a , target_prompt=a , generator=a , ) SCREAMING_SNAKE_CASE = pipe.invert( prompt=a , image=self.raw_image , inpaint_strength=0.7 , generator=a).latents SCREAMING_SNAKE_CASE = pipe( prompt=a , mask_image=a , image_latents=a , generator=a , negative_prompt=a , inpaint_strength=0.7 , output_type='numpy' , ).images[0] SCREAMING_SNAKE_CASE = ( np.array( load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/diffedit/pears.png').resize((768, 768))) / 255 ) assert np.abs((expected_image - image).max()) < 5E-1 def SCREAMING_SNAKE_CASE__ ( self) -> str: SCREAMING_SNAKE_CASE = torch.manual_seed(0) SCREAMING_SNAKE_CASE = StableDiffusionDiffEditPipeline.from_pretrained( 'stabilityai/stable-diffusion-2-1' , safety_checker=a , torch_dtype=torch.floataa) SCREAMING_SNAKE_CASE = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config) SCREAMING_SNAKE_CASE = DPMSolverMultistepInverseScheduler.from_config(pipe.scheduler.config) pipe.enable_model_cpu_offload() pipe.set_progress_bar_config(disable=a) SCREAMING_SNAKE_CASE = 'a bowl of fruit' SCREAMING_SNAKE_CASE = 'a bowl of pears' SCREAMING_SNAKE_CASE = pipe.generate_mask( image=self.raw_image , source_prompt=a , target_prompt=a , generator=a , ) SCREAMING_SNAKE_CASE = pipe.invert( prompt=a , image=self.raw_image , inpaint_strength=0.7 , generator=a , num_inference_steps=25 , ).latents SCREAMING_SNAKE_CASE = pipe( prompt=a , mask_image=a , image_latents=a , generator=a , negative_prompt=a , inpaint_strength=0.7 , num_inference_steps=25 , output_type='numpy' , ).images[0] SCREAMING_SNAKE_CASE = ( np.array( load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/diffedit/pears.png').resize((768, 768))) / 255 ) assert np.abs((expected_image - image).max()) < 5E-1
73
1
from __future__ import annotations def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = 2 SCREAMING_SNAKE_CASE = [] while i * i <= n: if n % i: i += 1 else: n //= i factors.append(_UpperCAmelCase) if n > 1: factors.append(_UpperCAmelCase) return factors if __name__ == "__main__": import doctest doctest.testmod()
73
import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging a_ : List[str] = logging.get_logger(__name__) a_ : Any = { 'microsoft/unispeech-large-1500h-cv': ( 'https://huggingface.co/microsoft/unispeech-large-1500h-cv/resolve/main/config.json' ), # See all UniSpeech models at https://huggingface.co/models?filter=unispeech } class _snake_case ( A__ ): _lowercase : Optional[int] = '''unispeech''' def __init__( self , a=32 , a=768 , a=12 , a=12 , a=3072 , a="gelu" , a=0.1 , a=0.1 , a=0.1 , a=0.0 , a=0.0 , a=0.1 , a=0.1 , a=0.02 , a=1E-5 , a="group" , a="gelu" , a=(512, 512, 512, 512, 512, 512, 512) , a=(5, 2, 2, 2, 2, 2, 2) , a=(10, 3, 3, 3, 3, 2, 2) , a=False , a=128 , a=16 , a=False , a=True , a=0.05 , a=10 , a=2 , a=0.0 , a=10 , a=0 , a=320 , a=2 , a=0.1 , a=100 , a=256 , a=256 , a=0.1 , a="mean" , a=False , a=False , a=256 , a=80 , a=0 , a=1 , a=2 , a=0.5 , **a , ) -> Optional[int]: super().__init__(**a , pad_token_id=a , bos_token_id=a , eos_token_id=a) SCREAMING_SNAKE_CASE = hidden_size SCREAMING_SNAKE_CASE = feat_extract_norm SCREAMING_SNAKE_CASE = feat_extract_activation SCREAMING_SNAKE_CASE = list(a) SCREAMING_SNAKE_CASE = list(a) SCREAMING_SNAKE_CASE = list(a) SCREAMING_SNAKE_CASE = conv_bias SCREAMING_SNAKE_CASE = num_conv_pos_embeddings SCREAMING_SNAKE_CASE = num_conv_pos_embedding_groups SCREAMING_SNAKE_CASE = len(self.conv_dim) SCREAMING_SNAKE_CASE = num_hidden_layers SCREAMING_SNAKE_CASE = intermediate_size SCREAMING_SNAKE_CASE = hidden_act SCREAMING_SNAKE_CASE = num_attention_heads SCREAMING_SNAKE_CASE = hidden_dropout SCREAMING_SNAKE_CASE = attention_dropout SCREAMING_SNAKE_CASE = activation_dropout SCREAMING_SNAKE_CASE = feat_proj_dropout SCREAMING_SNAKE_CASE = final_dropout SCREAMING_SNAKE_CASE = layerdrop SCREAMING_SNAKE_CASE = layer_norm_eps SCREAMING_SNAKE_CASE = initializer_range SCREAMING_SNAKE_CASE = num_ctc_classes SCREAMING_SNAKE_CASE = vocab_size SCREAMING_SNAKE_CASE = do_stable_layer_norm SCREAMING_SNAKE_CASE = use_weighted_layer_sum SCREAMING_SNAKE_CASE = classifier_proj_size if ( (len(self.conv_stride) != self.num_feat_extract_layers) or (len(self.conv_kernel) != self.num_feat_extract_layers) or (len(self.conv_dim) != self.num_feat_extract_layers) ): raise ValueError( 'Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` ==' ' `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) =' f''' {len(self.conv_dim)}`, `len(config.conv_stride) = {len(self.conv_stride)}`,''' f''' `len(config.conv_kernel) = {len(self.conv_kernel)}`.''') # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 SCREAMING_SNAKE_CASE = apply_spec_augment SCREAMING_SNAKE_CASE = mask_time_prob SCREAMING_SNAKE_CASE = mask_time_length SCREAMING_SNAKE_CASE = mask_time_min_masks SCREAMING_SNAKE_CASE = mask_feature_prob SCREAMING_SNAKE_CASE = mask_feature_length SCREAMING_SNAKE_CASE = mask_feature_min_masks # parameters for pretraining with codevector quantized representations SCREAMING_SNAKE_CASE = num_codevectors_per_group SCREAMING_SNAKE_CASE = num_codevector_groups SCREAMING_SNAKE_CASE = contrastive_logits_temperature SCREAMING_SNAKE_CASE = feat_quantizer_dropout SCREAMING_SNAKE_CASE = num_negatives SCREAMING_SNAKE_CASE = codevector_dim SCREAMING_SNAKE_CASE = proj_codevector_dim SCREAMING_SNAKE_CASE = diversity_loss_weight # ctc loss SCREAMING_SNAKE_CASE = ctc_loss_reduction SCREAMING_SNAKE_CASE = ctc_zero_infinity # pretraining loss SCREAMING_SNAKE_CASE = replace_prob @property def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: return functools.reduce(operator.mul , self.conv_stride , 1)
73
1
import json import pathlib import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import DeformableDetrImageProcessor class _snake_case ( unittest.TestCase ): def __init__( self , a , a=7 , a=3 , a=30 , a=400 , a=True , a=None , a=True , a=[0.5, 0.5, 0.5] , a=[0.5, 0.5, 0.5] , a=True , a=1 / 255 , a=True , ) -> Dict: # by setting size["longest_edge"] > max_resolution we're effectively not testing this :p SCREAMING_SNAKE_CASE = size if size is not None else {'shortest_edge': 18, 'longest_edge': 1333} SCREAMING_SNAKE_CASE = parent SCREAMING_SNAKE_CASE = batch_size SCREAMING_SNAKE_CASE = num_channels SCREAMING_SNAKE_CASE = min_resolution SCREAMING_SNAKE_CASE = max_resolution SCREAMING_SNAKE_CASE = do_resize SCREAMING_SNAKE_CASE = size SCREAMING_SNAKE_CASE = do_normalize SCREAMING_SNAKE_CASE = image_mean SCREAMING_SNAKE_CASE = image_std SCREAMING_SNAKE_CASE = do_rescale SCREAMING_SNAKE_CASE = rescale_factor SCREAMING_SNAKE_CASE = do_pad def SCREAMING_SNAKE_CASE__ ( self) -> Dict: return { "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_pad": self.do_pad, } def SCREAMING_SNAKE_CASE__ ( self , a , a=False) -> List[Any]: if not batched: SCREAMING_SNAKE_CASE = image_inputs[0] if isinstance(a , Image.Image): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = image.size else: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = image.shape[1], image.shape[2] if w < h: SCREAMING_SNAKE_CASE = int(self.size['shortest_edge'] * h / w) SCREAMING_SNAKE_CASE = self.size['shortest_edge'] elif w > h: SCREAMING_SNAKE_CASE = self.size['shortest_edge'] SCREAMING_SNAKE_CASE = int(self.size['shortest_edge'] * w / h) else: SCREAMING_SNAKE_CASE = self.size['shortest_edge'] SCREAMING_SNAKE_CASE = self.size['shortest_edge'] else: SCREAMING_SNAKE_CASE = [] for image in image_inputs: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.get_expected_values([image]) expected_values.append((expected_height, expected_width)) SCREAMING_SNAKE_CASE = max(a , key=lambda a: item[0])[0] SCREAMING_SNAKE_CASE = max(a , key=lambda a: item[1])[1] return expected_height, expected_width @require_torch @require_vision class _snake_case ( A__ , unittest.TestCase ): _lowercase : int = DeformableDetrImageProcessor if is_vision_available() else None def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: SCREAMING_SNAKE_CASE = DeformableDetrImageProcessingTester(self) @property def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: return self.image_processor_tester.prepare_image_processor_dict() def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: SCREAMING_SNAKE_CASE = self.image_processing_class(**self.image_processor_dict) self.assertTrue(hasattr(a , 'image_mean')) self.assertTrue(hasattr(a , 'image_std')) self.assertTrue(hasattr(a , 'do_normalize')) self.assertTrue(hasattr(a , 'do_resize')) self.assertTrue(hasattr(a , 'do_rescale')) self.assertTrue(hasattr(a , 'do_pad')) self.assertTrue(hasattr(a , 'size')) def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: SCREAMING_SNAKE_CASE = self.image_processing_class.from_dict(self.image_processor_dict) self.assertEqual(image_processor.size , {'shortest_edge': 18, 'longest_edge': 1333}) self.assertEqual(image_processor.do_pad , a) SCREAMING_SNAKE_CASE = self.image_processing_class.from_dict( self.image_processor_dict , size=42 , max_size=84 , pad_and_return_pixel_mask=a) self.assertEqual(image_processor.size , {'shortest_edge': 42, 'longest_edge': 84}) self.assertEqual(image_processor.do_pad , a) def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: pass def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: # Initialize image_processing SCREAMING_SNAKE_CASE = self.image_processing_class(**self.image_processor_dict) # create random PIL images SCREAMING_SNAKE_CASE = prepare_image_inputs(self.image_processor_tester , equal_resolution=a) for image in image_inputs: self.assertIsInstance(a , Image.Image) # Test not batched input SCREAMING_SNAKE_CASE = image_processing(image_inputs[0] , return_tensors='pt').pixel_values SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.image_processor_tester.get_expected_values(a) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.image_processor_tester.get_expected_values(a , batched=a) SCREAMING_SNAKE_CASE = image_processing(a , return_tensors='pt').pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def SCREAMING_SNAKE_CASE__ ( self) -> Any: # Initialize image_processing SCREAMING_SNAKE_CASE = self.image_processing_class(**self.image_processor_dict) # create random numpy tensors SCREAMING_SNAKE_CASE = prepare_image_inputs(self.image_processor_tester , equal_resolution=a , numpify=a) for image in image_inputs: self.assertIsInstance(a , np.ndarray) # Test not batched input SCREAMING_SNAKE_CASE = image_processing(image_inputs[0] , return_tensors='pt').pixel_values SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.image_processor_tester.get_expected_values(a) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched SCREAMING_SNAKE_CASE = image_processing(a , return_tensors='pt').pixel_values SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.image_processor_tester.get_expected_values(a , batched=a) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: # Initialize image_processing SCREAMING_SNAKE_CASE = self.image_processing_class(**self.image_processor_dict) # create random PyTorch tensors SCREAMING_SNAKE_CASE = prepare_image_inputs(self.image_processor_tester , equal_resolution=a , torchify=a) for image in image_inputs: self.assertIsInstance(a , torch.Tensor) # Test not batched input SCREAMING_SNAKE_CASE = image_processing(image_inputs[0] , return_tensors='pt').pixel_values SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.image_processor_tester.get_expected_values(a) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched SCREAMING_SNAKE_CASE = image_processing(a , return_tensors='pt').pixel_values SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.image_processor_tester.get_expected_values(a , batched=a) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) @slow def SCREAMING_SNAKE_CASE__ ( self) -> Any: # prepare image and target SCREAMING_SNAKE_CASE = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png') with open('./tests/fixtures/tests_samples/COCO/coco_annotations.txt' , 'r') as f: SCREAMING_SNAKE_CASE = json.loads(f.read()) SCREAMING_SNAKE_CASE = {'image_id': 3_9769, 'annotations': target} # encode them SCREAMING_SNAKE_CASE = DeformableDetrImageProcessor() SCREAMING_SNAKE_CASE = image_processing(images=a , annotations=a , return_tensors='pt') # verify pixel values SCREAMING_SNAKE_CASE = torch.Size([1, 3, 800, 1066]) self.assertEqual(encoding['pixel_values'].shape , a) SCREAMING_SNAKE_CASE = torch.tensor([0.27_96, 0.31_38, 0.34_81]) self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3] , a , atol=1E-4)) # verify area SCREAMING_SNAKE_CASE = torch.tensor([58_87.96_00, 1_12_50.20_61, 48_93_53.84_38, 83_71_22.75_00, 14_79_67.51_56, 16_57_32.34_38]) self.assertTrue(torch.allclose(encoding['labels'][0]['area'] , a)) # verify boxes SCREAMING_SNAKE_CASE = torch.Size([6, 4]) self.assertEqual(encoding['labels'][0]['boxes'].shape , a) SCREAMING_SNAKE_CASE = torch.tensor([0.55_03, 0.27_65, 0.06_04, 0.22_15]) self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0] , a , atol=1E-3)) # verify image_id SCREAMING_SNAKE_CASE = torch.tensor([3_9769]) self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] , a)) # verify is_crowd SCREAMING_SNAKE_CASE = torch.tensor([0, 0, 0, 0, 0, 0]) self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] , a)) # verify class_labels SCREAMING_SNAKE_CASE = torch.tensor([75, 75, 63, 65, 17, 17]) self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] , a)) # verify orig_size SCREAMING_SNAKE_CASE = torch.tensor([480, 640]) self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] , a)) # verify size SCREAMING_SNAKE_CASE = torch.tensor([800, 1066]) self.assertTrue(torch.allclose(encoding['labels'][0]['size'] , a)) @slow def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: # prepare image, target and masks_path SCREAMING_SNAKE_CASE = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png') with open('./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt' , 'r') as f: SCREAMING_SNAKE_CASE = json.loads(f.read()) SCREAMING_SNAKE_CASE = {'file_name': '000000039769.png', 'image_id': 3_9769, 'segments_info': target} SCREAMING_SNAKE_CASE = pathlib.Path('./tests/fixtures/tests_samples/COCO/coco_panoptic') # encode them SCREAMING_SNAKE_CASE = DeformableDetrImageProcessor(format='coco_panoptic') SCREAMING_SNAKE_CASE = image_processing(images=a , annotations=a , masks_path=a , return_tensors='pt') # verify pixel values SCREAMING_SNAKE_CASE = torch.Size([1, 3, 800, 1066]) self.assertEqual(encoding['pixel_values'].shape , a) SCREAMING_SNAKE_CASE = torch.tensor([0.27_96, 0.31_38, 0.34_81]) self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3] , a , atol=1E-4)) # verify area SCREAMING_SNAKE_CASE = torch.tensor([14_79_79.68_75, 16_55_27.04_69, 48_46_38.59_38, 1_12_92.93_75, 58_79.65_62, 76_34.11_47]) self.assertTrue(torch.allclose(encoding['labels'][0]['area'] , a)) # verify boxes SCREAMING_SNAKE_CASE = torch.Size([6, 4]) self.assertEqual(encoding['labels'][0]['boxes'].shape , a) SCREAMING_SNAKE_CASE = torch.tensor([0.26_25, 0.54_37, 0.46_88, 0.86_25]) self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0] , a , atol=1E-3)) # verify image_id SCREAMING_SNAKE_CASE = torch.tensor([3_9769]) self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] , a)) # verify is_crowd SCREAMING_SNAKE_CASE = torch.tensor([0, 0, 0, 0, 0, 0]) self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] , a)) # verify class_labels SCREAMING_SNAKE_CASE = torch.tensor([17, 17, 63, 75, 75, 93]) self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] , a)) # verify masks SCREAMING_SNAKE_CASE = 82_2873 self.assertEqual(encoding['labels'][0]['masks'].sum().item() , a) # verify orig_size SCREAMING_SNAKE_CASE = torch.tensor([480, 640]) self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] , a)) # verify size SCREAMING_SNAKE_CASE = torch.tensor([800, 1066]) self.assertTrue(torch.allclose(encoding['labels'][0]['size'] , a))
73
import argparse import collections import json import os import re import string import sys import numpy as np a_ : Optional[Any] = re.compile(R'\b(a|an|the)\b', re.UNICODE) a_ : List[str] = None def lowerCamelCase__ (): SCREAMING_SNAKE_CASE = argparse.ArgumentParser('Official evaluation script for SQuAD version 2.0.') parser.add_argument('data_file' , metavar='data.json' , help='Input data JSON file.') parser.add_argument('pred_file' , metavar='pred.json' , help='Model predictions.') parser.add_argument( '--out-file' , '-o' , metavar='eval.json' , help='Write accuracy metrics to file (default is stdout).') parser.add_argument( '--na-prob-file' , '-n' , metavar='na_prob.json' , help='Model estimates of probability of no answer.') parser.add_argument( '--na-prob-thresh' , '-t' , type=_UpperCAmelCase , default=1.0 , help='Predict "" if no-answer probability exceeds this (default = 1.0).' , ) parser.add_argument( '--out-image-dir' , '-p' , metavar='out_images' , default=_UpperCAmelCase , help='Save precision-recall curves to directory.') parser.add_argument('--verbose' , '-v' , action='store_true') if len(sys.argv) == 1: parser.print_help() sys.exit(1) return parser.parse_args() def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = {} for article in dataset: for p in article["paragraphs"]: for qa in p["qas"]: SCREAMING_SNAKE_CASE = bool(qa['answers']['text']) return qid_to_has_ans def lowerCamelCase__ (_UpperCAmelCase): def remove_articles(_UpperCAmelCase): return ARTICLES_REGEX.sub(' ' , _UpperCAmelCase) def white_space_fix(_UpperCAmelCase): return " ".join(text.split()) def remove_punc(_UpperCAmelCase): SCREAMING_SNAKE_CASE = set(string.punctuation) return "".join(ch for ch in text if ch not in exclude) def lower(_UpperCAmelCase): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(_UpperCAmelCase)))) def lowerCamelCase__ (_UpperCAmelCase): if not s: return [] return normalize_answer(_UpperCAmelCase).split() def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): return int(normalize_answer(_UpperCAmelCase) == normalize_answer(_UpperCAmelCase)) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = get_tokens(_UpperCAmelCase) SCREAMING_SNAKE_CASE = get_tokens(_UpperCAmelCase) SCREAMING_SNAKE_CASE = collections.Counter(_UpperCAmelCase) & collections.Counter(_UpperCAmelCase) SCREAMING_SNAKE_CASE = sum(common.values()) if len(_UpperCAmelCase) == 0 or len(_UpperCAmelCase) == 0: # If either is no-answer, then F1 is 1 if they agree, 0 otherwise return int(gold_toks == pred_toks) if num_same == 0: return 0 SCREAMING_SNAKE_CASE = 1.0 * num_same / len(_UpperCAmelCase) SCREAMING_SNAKE_CASE = 1.0 * num_same / len(_UpperCAmelCase) SCREAMING_SNAKE_CASE = (2 * precision * recall) / (precision + recall) return fa def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = {} SCREAMING_SNAKE_CASE = {} for article in dataset: for p in article["paragraphs"]: for qa in p["qas"]: SCREAMING_SNAKE_CASE = qa['id'] SCREAMING_SNAKE_CASE = [t for t in qa['answers']['text'] if normalize_answer(_UpperCAmelCase)] if not gold_answers: # For unanswerable questions, only correct answer is empty string SCREAMING_SNAKE_CASE = [''] if qid not in preds: print(F'''Missing prediction for {qid}''') continue SCREAMING_SNAKE_CASE = preds[qid] # Take max over all gold answers SCREAMING_SNAKE_CASE = max(compute_exact(_UpperCAmelCase , _UpperCAmelCase) for a in gold_answers) SCREAMING_SNAKE_CASE = max(compute_fa(_UpperCAmelCase , _UpperCAmelCase) for a in gold_answers) return exact_scores, fa_scores def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = {} for qid, s in scores.items(): SCREAMING_SNAKE_CASE = na_probs[qid] > na_prob_thresh if pred_na: SCREAMING_SNAKE_CASE = float(not qid_to_has_ans[qid]) else: SCREAMING_SNAKE_CASE = s return new_scores def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase=None): if not qid_list: SCREAMING_SNAKE_CASE = len(_UpperCAmelCase) return collections.OrderedDict( [ ('exact', 1_00.0 * sum(exact_scores.values()) / total), ('f1', 1_00.0 * sum(fa_scores.values()) / total), ('total', total), ]) else: SCREAMING_SNAKE_CASE = len(_UpperCAmelCase) return collections.OrderedDict( [ ('exact', 1_00.0 * sum(exact_scores[k] for k in qid_list) / total), ('f1', 1_00.0 * sum(fa_scores[k] for k in qid_list) / total), ('total', total), ]) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): for k in new_eval: SCREAMING_SNAKE_CASE = new_eval[k] def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): plt.step(_UpperCAmelCase , _UpperCAmelCase , color='b' , alpha=0.2 , where='post') plt.fill_between(_UpperCAmelCase , _UpperCAmelCase , step='post' , alpha=0.2 , color='b') plt.xlabel('Recall') plt.ylabel('Precision') plt.xlim([0.0, 1.05]) plt.ylim([0.0, 1.05]) plt.title(_UpperCAmelCase) plt.savefig(_UpperCAmelCase) plt.clf() def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase=None , _UpperCAmelCase=None): SCREAMING_SNAKE_CASE = sorted(_UpperCAmelCase , key=lambda _UpperCAmelCase: na_probs[k]) SCREAMING_SNAKE_CASE = 0.0 SCREAMING_SNAKE_CASE = 1.0 SCREAMING_SNAKE_CASE = 0.0 SCREAMING_SNAKE_CASE = [1.0] SCREAMING_SNAKE_CASE = [0.0] SCREAMING_SNAKE_CASE = 0.0 for i, qid in enumerate(_UpperCAmelCase): if qid_to_has_ans[qid]: true_pos += scores[qid] SCREAMING_SNAKE_CASE = true_pos / float(i + 1) SCREAMING_SNAKE_CASE = true_pos / float(_UpperCAmelCase) if i == len(_UpperCAmelCase) - 1 or na_probs[qid] != na_probs[qid_list[i + 1]]: # i.e., if we can put a threshold after this point avg_prec += cur_p * (cur_r - recalls[-1]) precisions.append(_UpperCAmelCase) recalls.append(_UpperCAmelCase) if out_image: plot_pr_curve(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) return {"ap": 1_00.0 * avg_prec} def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): if out_image_dir and not os.path.exists(_UpperCAmelCase): os.makedirs(_UpperCAmelCase) SCREAMING_SNAKE_CASE = sum(1 for v in qid_to_has_ans.values() if v) if num_true_pos == 0: return SCREAMING_SNAKE_CASE = make_precision_recall_eval( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , out_image=os.path.join(_UpperCAmelCase , 'pr_exact.png') , title='Precision-Recall curve for Exact Match score' , ) SCREAMING_SNAKE_CASE = make_precision_recall_eval( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , out_image=os.path.join(_UpperCAmelCase , 'pr_f1.png') , title='Precision-Recall curve for F1 score' , ) SCREAMING_SNAKE_CASE = {k: float(_UpperCAmelCase) for k, v in qid_to_has_ans.items()} SCREAMING_SNAKE_CASE = make_precision_recall_eval( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , out_image=os.path.join(_UpperCAmelCase , 'pr_oracle.png') , title='Oracle Precision-Recall curve (binary task of HasAns vs. NoAns)' , ) merge_eval(_UpperCAmelCase , _UpperCAmelCase , 'pr_exact') merge_eval(_UpperCAmelCase , _UpperCAmelCase , 'pr_f1') merge_eval(_UpperCAmelCase , _UpperCAmelCase , 'pr_oracle') def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): if not qid_list: return SCREAMING_SNAKE_CASE = [na_probs[k] for k in qid_list] SCREAMING_SNAKE_CASE = np.ones_like(_UpperCAmelCase) / float(len(_UpperCAmelCase)) plt.hist(_UpperCAmelCase , weights=_UpperCAmelCase , bins=20 , range=(0.0, 1.0)) plt.xlabel('Model probability of no-answer') plt.ylabel('Proportion of dataset') plt.title(F'''Histogram of no-answer probability: {name}''') plt.savefig(os.path.join(_UpperCAmelCase , F'''na_prob_hist_{name}.png''')) plt.clf() def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = sum(1 for k in qid_to_has_ans if not qid_to_has_ans[k]) SCREAMING_SNAKE_CASE = num_no_ans SCREAMING_SNAKE_CASE = cur_score SCREAMING_SNAKE_CASE = 0.0 SCREAMING_SNAKE_CASE = sorted(_UpperCAmelCase , key=lambda _UpperCAmelCase: na_probs[k]) for i, qid in enumerate(_UpperCAmelCase): if qid not in scores: continue if qid_to_has_ans[qid]: SCREAMING_SNAKE_CASE = scores[qid] else: if preds[qid]: SCREAMING_SNAKE_CASE = -1 else: SCREAMING_SNAKE_CASE = 0 cur_score += diff if cur_score > best_score: SCREAMING_SNAKE_CASE = cur_score SCREAMING_SNAKE_CASE = na_probs[qid] return 1_00.0 * best_score / len(_UpperCAmelCase), best_thresh def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = find_best_thresh(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = find_best_thresh(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) SCREAMING_SNAKE_CASE = best_exact SCREAMING_SNAKE_CASE = exact_thresh SCREAMING_SNAKE_CASE = best_fa SCREAMING_SNAKE_CASE = fa_thresh def lowerCamelCase__ (): with open(OPTS.data_file) as f: SCREAMING_SNAKE_CASE = json.load(_UpperCAmelCase) SCREAMING_SNAKE_CASE = dataset_json['data'] with open(OPTS.pred_file) as f: SCREAMING_SNAKE_CASE = json.load(_UpperCAmelCase) if OPTS.na_prob_file: with open(OPTS.na_prob_file) as f: SCREAMING_SNAKE_CASE = json.load(_UpperCAmelCase) else: SCREAMING_SNAKE_CASE = {k: 0.0 for k in preds} SCREAMING_SNAKE_CASE = make_qid_to_has_ans(_UpperCAmelCase) # maps qid to True/False SCREAMING_SNAKE_CASE = [k for k, v in qid_to_has_ans.items() if v] SCREAMING_SNAKE_CASE = [k for k, v in qid_to_has_ans.items() if not v] SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = get_raw_scores(_UpperCAmelCase , _UpperCAmelCase) SCREAMING_SNAKE_CASE = apply_no_ans_threshold(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , OPTS.na_prob_thresh) SCREAMING_SNAKE_CASE = apply_no_ans_threshold(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , OPTS.na_prob_thresh) SCREAMING_SNAKE_CASE = make_eval_dict(_UpperCAmelCase , _UpperCAmelCase) if has_ans_qids: SCREAMING_SNAKE_CASE = make_eval_dict(_UpperCAmelCase , _UpperCAmelCase , qid_list=_UpperCAmelCase) merge_eval(_UpperCAmelCase , _UpperCAmelCase , 'HasAns') if no_ans_qids: SCREAMING_SNAKE_CASE = make_eval_dict(_UpperCAmelCase , _UpperCAmelCase , qid_list=_UpperCAmelCase) merge_eval(_UpperCAmelCase , _UpperCAmelCase , 'NoAns') if OPTS.na_prob_file: find_all_best_thresh(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) if OPTS.na_prob_file and OPTS.out_image_dir: run_precision_recall_analysis(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , OPTS.out_image_dir) histogram_na_prob(_UpperCAmelCase , _UpperCAmelCase , OPTS.out_image_dir , 'hasAns') histogram_na_prob(_UpperCAmelCase , _UpperCAmelCase , OPTS.out_image_dir , 'noAns') if OPTS.out_file: with open(OPTS.out_file , 'w') as f: json.dump(_UpperCAmelCase , _UpperCAmelCase) else: print(json.dumps(_UpperCAmelCase , indent=2)) if __name__ == "__main__": a_ : Any = parse_args() if OPTS.out_image_dir: import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt main()
73
1
def lowerCamelCase__ (): return [ a * b * (1000 - a - b) for a in range(1 , 999) for b in range(_UpperCAmelCase , 999) if (a * a + b * b == (1000 - a - b) ** 2) ][0] if __name__ == "__main__": print(f"""{solution() = }""")
73
import warnings from ...utils import logging from .image_processing_glpn import GLPNImageProcessor a_ : Dict = logging.get_logger(__name__) class _snake_case ( A__ ): def __init__( self , *a , **a) -> None: warnings.warn( 'The class GLPNFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please' ' use GLPNImageProcessor instead.' , a , ) super().__init__(*a , **a)
73
1
import asyncio import os import re import sys import tempfile import unittest from contextlib import contextmanager from copy import deepcopy from distutils.util import strtobool from enum import Enum from importlib.util import find_spec from pathlib import Path from unittest.mock import patch import pyarrow as pa import pytest import requests from packaging import version from datasets import config if config.PY_VERSION < version.parse('3.8'): import importlib_metadata else: import importlib.metadata as importlib_metadata def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase=False): try: SCREAMING_SNAKE_CASE = os.environ[key] except KeyError: # KEY isn't set, default to `default`. SCREAMING_SNAKE_CASE = default else: # KEY is set, convert it to True or False. try: SCREAMING_SNAKE_CASE = strtobool(_UpperCAmelCase) except ValueError: # More values are supported, but let's keep the message simple. raise ValueError(F'''If set, {key} must be yes or no.''') return _value a_ : Optional[Any] = parse_flag_from_env('RUN_SLOW', default=False) a_ : int = parse_flag_from_env('RUN_REMOTE', default=False) a_ : List[str] = parse_flag_from_env('RUN_LOCAL', default=True) a_ : Dict = parse_flag_from_env('RUN_PACKAGED', default=True) # Compression a_ : Tuple = pytest.mark.skipif(not config.LZ4_AVAILABLE, reason='test requires lz4') a_ : Dict = pytest.mark.skipif(not config.PY7ZR_AVAILABLE, reason='test requires py7zr') a_ : Optional[int] = pytest.mark.skipif(not config.ZSTANDARD_AVAILABLE, reason='test requires zstandard') # Audio a_ : List[Any] = pytest.mark.skipif( # On Windows and OS X, soundfile installs sndfile find_spec('soundfile') is None or version.parse(importlib_metadata.version('soundfile')) < version.parse('0.12.0'), reason='test requires sndfile>=0.12.1: \'pip install \"soundfile>=0.12.1\"\'; ', ) # Beam a_ : int = pytest.mark.skipif( not config.BEAM_AVAILABLE or config.DILL_VERSION >= version.parse('0.3.2'), reason='test requires apache-beam and a compatible dill version', ) # Dill-cloudpickle compatibility a_ : Dict = pytest.mark.skipif( config.DILL_VERSION <= version.parse('0.3.2'), reason='test requires dill>0.3.2 for cloudpickle compatibility', ) # Windows a_ : Optional[int] = pytest.mark.skipif( sys.platform == 'win32', reason='test should not be run on Windows', ) def lowerCamelCase__ (_UpperCAmelCase): try: import faiss # noqa except ImportError: SCREAMING_SNAKE_CASE = unittest.skip('test requires faiss')(_UpperCAmelCase) return test_case def lowerCamelCase__ (_UpperCAmelCase): try: import regex # noqa except ImportError: SCREAMING_SNAKE_CASE = unittest.skip('test requires regex')(_UpperCAmelCase) return test_case def lowerCamelCase__ (_UpperCAmelCase): try: import elasticsearch # noqa except ImportError: SCREAMING_SNAKE_CASE = unittest.skip('test requires elasticsearch')(_UpperCAmelCase) return test_case def lowerCamelCase__ (_UpperCAmelCase): try: import sqlalchemy # noqa except ImportError: SCREAMING_SNAKE_CASE = unittest.skip('test requires sqlalchemy')(_UpperCAmelCase) return test_case def lowerCamelCase__ (_UpperCAmelCase): if not config.TORCH_AVAILABLE: SCREAMING_SNAKE_CASE = unittest.skip('test requires PyTorch')(_UpperCAmelCase) return test_case def lowerCamelCase__ (_UpperCAmelCase): if not config.TF_AVAILABLE: SCREAMING_SNAKE_CASE = unittest.skip('test requires TensorFlow')(_UpperCAmelCase) return test_case def lowerCamelCase__ (_UpperCAmelCase): if not config.JAX_AVAILABLE: SCREAMING_SNAKE_CASE = unittest.skip('test requires JAX')(_UpperCAmelCase) return test_case def lowerCamelCase__ (_UpperCAmelCase): if not config.PIL_AVAILABLE: SCREAMING_SNAKE_CASE = unittest.skip('test requires Pillow')(_UpperCAmelCase) return test_case def lowerCamelCase__ (_UpperCAmelCase): try: import transformers # noqa F401 except ImportError: return unittest.skip('test requires transformers')(_UpperCAmelCase) else: return test_case def lowerCamelCase__ (_UpperCAmelCase): try: import tiktoken # noqa F401 except ImportError: return unittest.skip('test requires tiktoken')(_UpperCAmelCase) else: return test_case def lowerCamelCase__ (_UpperCAmelCase): try: import spacy # noqa F401 except ImportError: return unittest.skip('test requires spacy')(_UpperCAmelCase) else: return test_case def lowerCamelCase__ (_UpperCAmelCase): def _require_spacy_model(_UpperCAmelCase): try: import spacy # noqa F401 spacy.load(_UpperCAmelCase) except ImportError: return unittest.skip('test requires spacy')(_UpperCAmelCase) except OSError: return unittest.skip('test requires spacy model \'{}\''.format(_UpperCAmelCase))(_UpperCAmelCase) else: return test_case return _require_spacy_model def lowerCamelCase__ (_UpperCAmelCase): try: import pyspark # noqa F401 except ImportError: return unittest.skip('test requires pyspark')(_UpperCAmelCase) else: return test_case def lowerCamelCase__ (_UpperCAmelCase): try: import joblibspark # noqa F401 except ImportError: return unittest.skip('test requires joblibspark')(_UpperCAmelCase) else: return test_case def lowerCamelCase__ (_UpperCAmelCase): if not _run_slow_tests or _run_slow_tests == 0: SCREAMING_SNAKE_CASE = unittest.skip('test is slow')(_UpperCAmelCase) return test_case def lowerCamelCase__ (_UpperCAmelCase): if not _run_local_tests or _run_local_tests == 0: SCREAMING_SNAKE_CASE = unittest.skip('test is local')(_UpperCAmelCase) return test_case def lowerCamelCase__ (_UpperCAmelCase): if not _run_packaged_tests or _run_packaged_tests == 0: SCREAMING_SNAKE_CASE = unittest.skip('test is packaged')(_UpperCAmelCase) return test_case def lowerCamelCase__ (_UpperCAmelCase): if not _run_remote_tests or _run_remote_tests == 0: SCREAMING_SNAKE_CASE = unittest.skip('test requires remote')(_UpperCAmelCase) return test_case def lowerCamelCase__ (*_UpperCAmelCase): def decorate(cls): for name, fn in cls.__dict__.items(): if callable(_UpperCAmelCase) and name.startswith('test'): for decorator in decorators: SCREAMING_SNAKE_CASE = decorator(_UpperCAmelCase) setattr(cls , _UpperCAmelCase , _UpperCAmelCase) return cls return decorate class _snake_case ( A__ ): pass class _snake_case ( A__ ): _lowercase : Optional[Any] = 0 _lowercase : Optional[Any] = 1 _lowercase : Optional[int] = 2 @contextmanager def lowerCamelCase__ (_UpperCAmelCase=OfflineSimulationMode.CONNECTION_FAILS , _UpperCAmelCase=1e-16): SCREAMING_SNAKE_CASE = requests.Session().request def timeout_request(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , **_UpperCAmelCase): # Change the url to an invalid url so that the connection hangs SCREAMING_SNAKE_CASE = 'https://10.255.255.1' if kwargs.get('timeout') is None: raise RequestWouldHangIndefinitelyError( F'''Tried a call to {url} in offline mode with no timeout set. Please set a timeout.''') SCREAMING_SNAKE_CASE = timeout try: return online_request(_UpperCAmelCase , _UpperCAmelCase , **_UpperCAmelCase) except Exception as e: # The following changes in the error are just here to make the offline timeout error prettier SCREAMING_SNAKE_CASE = url SCREAMING_SNAKE_CASE = e.args[0] SCREAMING_SNAKE_CASE = (max_retry_error.args[0].replace('10.255.255.1' , F'''OfflineMock[{url}]'''),) SCREAMING_SNAKE_CASE = (max_retry_error,) raise def raise_connection_error(_UpperCAmelCase , _UpperCAmelCase , **_UpperCAmelCase): raise requests.ConnectionError('Offline mode is enabled.' , request=_UpperCAmelCase) if mode is OfflineSimulationMode.CONNECTION_FAILS: with patch('requests.Session.send' , _UpperCAmelCase): yield elif mode is OfflineSimulationMode.CONNECTION_TIMES_OUT: # inspired from https://stackoverflow.com/a/904609 with patch('requests.Session.request' , _UpperCAmelCase): yield elif mode is OfflineSimulationMode.HF_DATASETS_OFFLINE_SET_TO_1: with patch('datasets.config.HF_DATASETS_OFFLINE' , _UpperCAmelCase): yield else: raise ValueError('Please use a value from the OfflineSimulationMode enum.') @contextmanager def lowerCamelCase__ (*_UpperCAmelCase , **_UpperCAmelCase): SCREAMING_SNAKE_CASE = str(Path().resolve()) with tempfile.TemporaryDirectory(*_UpperCAmelCase , **_UpperCAmelCase) as tmp_dir: try: os.chdir(_UpperCAmelCase) yield finally: os.chdir(_UpperCAmelCase) @contextmanager def lowerCamelCase__ (): import gc gc.collect() SCREAMING_SNAKE_CASE = pa.total_allocated_bytes() yield assert pa.total_allocated_bytes() - previous_allocated_memory > 0, "Arrow memory didn't increase." @contextmanager def lowerCamelCase__ (): import gc gc.collect() SCREAMING_SNAKE_CASE = pa.total_allocated_bytes() yield assert pa.total_allocated_bytes() - previous_allocated_memory <= 0, "Arrow memory wasn't expected to increase." def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): return deepcopy(_UpperCAmelCase).integers(0 , 100 , 10).tolist() == deepcopy(_UpperCAmelCase).integers(0 , 100 , 10).tolist() def lowerCamelCase__ (_UpperCAmelCase): import decorator from requests.exceptions import HTTPError def _wrapper(_UpperCAmelCase , *_UpperCAmelCase , **_UpperCAmelCase): try: return func(*_UpperCAmelCase , **_UpperCAmelCase) except HTTPError as err: if str(_UpperCAmelCase).startswith('500') or str(_UpperCAmelCase).startswith('502'): pytest.xfail(str(_UpperCAmelCase)) raise err return decorator.decorator(_wrapper , _UpperCAmelCase) class _snake_case : def __init__( self , a , a , a) -> List[str]: SCREAMING_SNAKE_CASE = returncode SCREAMING_SNAKE_CASE = stdout SCREAMING_SNAKE_CASE = stderr async def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): while True: SCREAMING_SNAKE_CASE = await stream.readline() if line: callback(_UpperCAmelCase) else: break async def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase=None , _UpperCAmelCase=None , _UpperCAmelCase=None , _UpperCAmelCase=False , _UpperCAmelCase=False): if echo: print('\nRunning: ' , ' '.join(_UpperCAmelCase)) SCREAMING_SNAKE_CASE = await asyncio.create_subprocess_exec( cmd[0] , *cmd[1:] , stdin=_UpperCAmelCase , stdout=asyncio.subprocess.PIPE , stderr=asyncio.subprocess.PIPE , env=_UpperCAmelCase , ) # note: there is a warning for a possible deadlock when using `wait` with huge amounts of data in the pipe # https://docs.python.org/3/library/asyncio-subprocess.html#asyncio.asyncio.subprocess.Process.wait # # If it starts hanging, will need to switch to the following code. The problem is that no data # will be seen until it's done and if it hangs for example there will be no debug info. # out, err = await p.communicate() # return _RunOutput(p.returncode, out, err) SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = [] def tee(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase=""): SCREAMING_SNAKE_CASE = line.decode('utf-8').rstrip() sink.append(_UpperCAmelCase) if not quiet: print(_UpperCAmelCase , _UpperCAmelCase , file=_UpperCAmelCase) # XXX: the timeout doesn't seem to make any difference here await asyncio.wait( [ _read_stream(p.stdout , lambda _UpperCAmelCase: tee(_UpperCAmelCase , _UpperCAmelCase , sys.stdout , label='stdout:')), _read_stream(p.stderr , lambda _UpperCAmelCase: tee(_UpperCAmelCase , _UpperCAmelCase , sys.stderr , label='stderr:')), ] , timeout=_UpperCAmelCase , ) return _RunOutput(await p.wait() , _UpperCAmelCase , _UpperCAmelCase) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase=None , _UpperCAmelCase=None , _UpperCAmelCase=180 , _UpperCAmelCase=False , _UpperCAmelCase=True): SCREAMING_SNAKE_CASE = asyncio.get_event_loop() SCREAMING_SNAKE_CASE = loop.run_until_complete( _stream_subprocess(_UpperCAmelCase , env=_UpperCAmelCase , stdin=_UpperCAmelCase , timeout=_UpperCAmelCase , quiet=_UpperCAmelCase , echo=_UpperCAmelCase)) SCREAMING_SNAKE_CASE = ' '.join(_UpperCAmelCase) if result.returncode > 0: SCREAMING_SNAKE_CASE = '\n'.join(result.stderr) raise RuntimeError( F'''\'{cmd_str}\' failed with returncode {result.returncode}\n\n''' F'''The combined stderr from workers follows:\n{stderr}''') # check that the subprocess actually did run and produced some output, should the test rely on # the remote side to do the testing if not result.stdout and not result.stderr: raise RuntimeError(F'''\'{cmd_str}\' produced no output.''') return result def lowerCamelCase__ (): SCREAMING_SNAKE_CASE = os.environ.get('PYTEST_XDIST_WORKER' , 'gw0') SCREAMING_SNAKE_CASE = re.sub(R'^gw' , '' , _UpperCAmelCase , 0 , re.M) return int(_UpperCAmelCase) def lowerCamelCase__ (): SCREAMING_SNAKE_CASE = 2_9500 SCREAMING_SNAKE_CASE = pytest_xdist_worker_id() return port + uniq_delta
73
import unittest from transformers import load_tool from .test_tools_common import ToolTesterMixin class _snake_case ( unittest.TestCase , A__ ): def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: SCREAMING_SNAKE_CASE = load_tool('text-classification') self.tool.setup() SCREAMING_SNAKE_CASE = load_tool('text-classification' , remote=a) def SCREAMING_SNAKE_CASE__ ( self) -> str: SCREAMING_SNAKE_CASE = self.tool('That\'s quite cool' , ['positive', 'negative']) self.assertEqual(a , 'positive') def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: SCREAMING_SNAKE_CASE = self.remote_tool('That\'s quite cool' , ['positive', 'negative']) self.assertEqual(a , 'positive') def SCREAMING_SNAKE_CASE__ ( self) -> int: SCREAMING_SNAKE_CASE = self.tool(text='That\'s quite cool' , labels=['positive', 'negative']) self.assertEqual(a , 'positive') def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: SCREAMING_SNAKE_CASE = self.remote_tool(text='That\'s quite cool' , labels=['positive', 'negative']) self.assertEqual(a , 'positive')
73
1
import unittest from transformers import load_tool from .test_tools_common import ToolTesterMixin class _snake_case ( unittest.TestCase , A__ ): def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: SCREAMING_SNAKE_CASE = load_tool('text-classification') self.tool.setup() SCREAMING_SNAKE_CASE = load_tool('text-classification' , remote=a) def SCREAMING_SNAKE_CASE__ ( self) -> str: SCREAMING_SNAKE_CASE = self.tool('That\'s quite cool' , ['positive', 'negative']) self.assertEqual(a , 'positive') def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: SCREAMING_SNAKE_CASE = self.remote_tool('That\'s quite cool' , ['positive', 'negative']) self.assertEqual(a , 'positive') def SCREAMING_SNAKE_CASE__ ( self) -> int: SCREAMING_SNAKE_CASE = self.tool(text='That\'s quite cool' , labels=['positive', 'negative']) self.assertEqual(a , 'positive') def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: SCREAMING_SNAKE_CASE = self.remote_tool(text='That\'s quite cool' , labels=['positive', 'negative']) self.assertEqual(a , 'positive')
73
import sys import turtle def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): return (pa[0] + pa[0]) / 2, (pa[1] + pa[1]) / 2 def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , ): my_pen.up() my_pen.goto(vertexa[0] , vertexa[1]) my_pen.down() my_pen.goto(vertexa[0] , vertexa[1]) my_pen.goto(vertexa[0] , vertexa[1]) my_pen.goto(vertexa[0] , vertexa[1]) if depth == 0: return triangle(_UpperCAmelCase , get_mid(_UpperCAmelCase , _UpperCAmelCase) , get_mid(_UpperCAmelCase , _UpperCAmelCase) , depth - 1) triangle(_UpperCAmelCase , get_mid(_UpperCAmelCase , _UpperCAmelCase) , get_mid(_UpperCAmelCase , _UpperCAmelCase) , depth - 1) triangle(_UpperCAmelCase , get_mid(_UpperCAmelCase , _UpperCAmelCase) , get_mid(_UpperCAmelCase , _UpperCAmelCase) , depth - 1) if __name__ == "__main__": if len(sys.argv) != 2: raise ValueError( 'Correct format for using this script: ' 'python fractals.py <int:depth_for_fractal>' ) a_ : Any = turtle.Turtle() my_pen.ht() my_pen.speed(5) my_pen.pencolor('red') a_ : str = [(-1_75, -1_25), (0, 1_75), (1_75, -1_25)] # vertices of triangle triangle(vertices[0], vertices[1], vertices[2], int(sys.argv[1]))
73
1
import math import os import sys def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = '' try: with open(_UpperCAmelCase , 'rb') as binary_file: SCREAMING_SNAKE_CASE = binary_file.read() for dat in data: SCREAMING_SNAKE_CASE = F'''{dat:08b}''' result += curr_byte return result except OSError: print('File not accessible') sys.exit() def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): lexicon.pop(_UpperCAmelCase) SCREAMING_SNAKE_CASE = last_match_id if math.loga(_UpperCAmelCase).is_integer(): for curr_key in lexicon: SCREAMING_SNAKE_CASE = '0' + lexicon[curr_key] SCREAMING_SNAKE_CASE = bin(_UpperCAmelCase)[2:] def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = {'0': '0', '1': '1'} SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = '', '' SCREAMING_SNAKE_CASE = len(_UpperCAmelCase) for i in range(len(_UpperCAmelCase)): curr_string += data_bits[i] if curr_string not in lexicon: continue SCREAMING_SNAKE_CASE = lexicon[curr_string] result += last_match_id add_key_to_lexicon(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) index += 1 SCREAMING_SNAKE_CASE = '' while curr_string != "" and curr_string not in lexicon: curr_string += "0" if curr_string != "": SCREAMING_SNAKE_CASE = lexicon[curr_string] result += last_match_id return result def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = os.path.getsize(_UpperCAmelCase) SCREAMING_SNAKE_CASE = bin(_UpperCAmelCase)[2:] SCREAMING_SNAKE_CASE = len(_UpperCAmelCase) return "0" * (length_length - 1) + file_length_binary + compressed def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = 8 try: with open(_UpperCAmelCase , 'wb') as opened_file: SCREAMING_SNAKE_CASE = [ to_write[i : i + byte_length] for i in range(0 , len(_UpperCAmelCase) , _UpperCAmelCase) ] 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(_UpperCAmelCase , 2).to_bytes(1 , byteorder='big')) except OSError: print('File not accessible') sys.exit() def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = read_file_binary(_UpperCAmelCase) SCREAMING_SNAKE_CASE = compress_data(_UpperCAmelCase) SCREAMING_SNAKE_CASE = add_file_length(_UpperCAmelCase , _UpperCAmelCase) write_file_binary(_UpperCAmelCase , _UpperCAmelCase) if __name__ == "__main__": compress(sys.argv[1], sys.argv[2])
73
import math import os from copy import deepcopy import datasets import evaluate import torch import transformers from datasets import load_dataset from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer from accelerate import Accelerator from accelerate.test_utils import RegressionDataset, RegressionModel from accelerate.utils import is_tpu_available, set_seed a_ : Any = 'true' def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase=82 , _UpperCAmelCase=16): set_seed(42) SCREAMING_SNAKE_CASE = RegressionModel() SCREAMING_SNAKE_CASE = deepcopy(_UpperCAmelCase) SCREAMING_SNAKE_CASE = RegressionDataset(length=_UpperCAmelCase) SCREAMING_SNAKE_CASE = DataLoader(_UpperCAmelCase , batch_size=_UpperCAmelCase) model.to(accelerator.device) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = accelerator.prepare(_UpperCAmelCase , _UpperCAmelCase) return model, ddp_model, dataloader def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase=False): SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained('hf-internal-testing/mrpc-bert-base-cased') SCREAMING_SNAKE_CASE = load_dataset('glue' , 'mrpc' , split='validation') def tokenize_function(_UpperCAmelCase): SCREAMING_SNAKE_CASE = tokenizer(examples['sentence1'] , examples['sentence2'] , truncation=_UpperCAmelCase , max_length=_UpperCAmelCase) return outputs with accelerator.main_process_first(): SCREAMING_SNAKE_CASE = dataset.map( _UpperCAmelCase , batched=_UpperCAmelCase , remove_columns=['idx', 'sentence1', 'sentence2'] , ) SCREAMING_SNAKE_CASE = tokenized_datasets.rename_column('label' , 'labels') def collate_fn(_UpperCAmelCase): if use_longest: return tokenizer.pad(_UpperCAmelCase , padding='longest' , return_tensors='pt') return tokenizer.pad(_UpperCAmelCase , padding='max_length' , max_length=128 , return_tensors='pt') return DataLoader(_UpperCAmelCase , shuffle=_UpperCAmelCase , collate_fn=_UpperCAmelCase , batch_size=16) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = Accelerator(dispatch_batches=_UpperCAmelCase , split_batches=_UpperCAmelCase) SCREAMING_SNAKE_CASE = get_dataloader(_UpperCAmelCase , not dispatch_batches) SCREAMING_SNAKE_CASE = AutoModelForSequenceClassification.from_pretrained( 'hf-internal-testing/mrpc-bert-base-cased' , return_dict=_UpperCAmelCase) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = accelerator.prepare(_UpperCAmelCase , _UpperCAmelCase) return {"ddp": [ddp_model, ddp_dataloader, "cuda:0"], "no": [model, dataloader, accelerator.device]}, accelerator def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = [] for batch in dataloader: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = batch.values() with torch.no_grad(): SCREAMING_SNAKE_CASE = model(_UpperCAmelCase) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = accelerator.gather_for_metrics((logit, target)) logits_and_targets.append((logit, target)) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = [], [] for logit, targ in logits_and_targets: logits.append(_UpperCAmelCase) targs.append(_UpperCAmelCase) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = torch.cat(_UpperCAmelCase), torch.cat(_UpperCAmelCase) return logits, targs def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase=82 , _UpperCAmelCase=False , _UpperCAmelCase=False , _UpperCAmelCase=16): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = get_basic_setup(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = generate_predictions(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) assert ( len(_UpperCAmelCase) == num_samples ), F'''Unexpected number of inputs:\n Expected: {num_samples}\n Actual: {len(_UpperCAmelCase)}''' def lowerCamelCase__ (_UpperCAmelCase = False , _UpperCAmelCase = False): SCREAMING_SNAKE_CASE = evaluate.load('glue' , 'mrpc') SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = get_mrpc_setup(_UpperCAmelCase , _UpperCAmelCase) # First do baseline SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = setup['no'] model.to(_UpperCAmelCase) model.eval() for batch in dataloader: batch.to(_UpperCAmelCase) with torch.inference_mode(): SCREAMING_SNAKE_CASE = model(**_UpperCAmelCase) SCREAMING_SNAKE_CASE = outputs.logits.argmax(dim=-1) metric.add_batch(predictions=_UpperCAmelCase , references=batch['labels']) SCREAMING_SNAKE_CASE = metric.compute() # Then do distributed SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = setup['ddp'] model.eval() for batch in dataloader: with torch.inference_mode(): SCREAMING_SNAKE_CASE = model(**_UpperCAmelCase) SCREAMING_SNAKE_CASE = outputs.logits.argmax(dim=-1) SCREAMING_SNAKE_CASE = batch['labels'] SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = accelerator.gather_for_metrics((preds, references)) metric.add_batch(predictions=_UpperCAmelCase , references=_UpperCAmelCase) SCREAMING_SNAKE_CASE = metric.compute() for key in "accuracy f1".split(): assert math.isclose( baseline[key] , distributed[key]), F'''Baseline and Distributed are not the same for key {key}:\n\tBaseline: {baseline[key]}\n\tDistributed: {distributed[key]}\n''' def lowerCamelCase__ (): SCREAMING_SNAKE_CASE = Accelerator(split_batches=_UpperCAmelCase , dispatch_batches=_UpperCAmelCase) if accelerator.is_local_main_process: datasets.utils.logging.set_verbosity_warning() transformers.utils.logging.set_verbosity_warning() else: datasets.utils.logging.set_verbosity_error() transformers.utils.logging.set_verbosity_error() # These are a bit slower so they should only be ran on the GPU or TPU if torch.cuda.is_available() or is_tpu_available(): if accelerator.is_local_main_process: print('**Testing gather_for_metrics**') for split_batches in [True, False]: for dispatch_batches in [True, False]: if accelerator.is_local_main_process: print(F'''With: `split_batches={split_batches}`, `dispatch_batches={dispatch_batches}`''') test_mrpc(_UpperCAmelCase , _UpperCAmelCase) accelerator.state._reset_state() if accelerator.is_local_main_process: print('**Test torch metrics**') for split_batches in [True, False]: for dispatch_batches in [True, False]: SCREAMING_SNAKE_CASE = Accelerator(split_batches=_UpperCAmelCase , dispatch_batches=_UpperCAmelCase) if accelerator.is_local_main_process: print(F'''With: `split_batches={split_batches}`, `dispatch_batches={dispatch_batches}`, length=99''') test_torch_metrics(_UpperCAmelCase , 99) accelerator.state._reset_state() if accelerator.is_local_main_process: print('**Test last batch is not dropped when perfectly divisible**') SCREAMING_SNAKE_CASE = Accelerator() test_torch_metrics(_UpperCAmelCase , 512) accelerator.state._reset_state() def lowerCamelCase__ (_UpperCAmelCase): # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
73
1
import inspect import warnings from typing import Any, Dict, Optional, Union from packaging import version def lowerCamelCase__ (*_UpperCAmelCase , _UpperCAmelCase = None , _UpperCAmelCase=True , _UpperCAmelCase=2): from .. import __version__ SCREAMING_SNAKE_CASE = take_from SCREAMING_SNAKE_CASE = () if not isinstance(args[0] , _UpperCAmelCase): SCREAMING_SNAKE_CASE = (args,) for attribute, version_name, message in args: if version.parse(version.parse(_UpperCAmelCase).base_version) >= version.parse(_UpperCAmelCase): raise ValueError( F'''The deprecation tuple {(attribute, version_name, message)} should be removed since diffusers\'''' F''' version {__version__} is >= {version_name}''') SCREAMING_SNAKE_CASE = None if isinstance(_UpperCAmelCase , _UpperCAmelCase) and attribute in deprecated_kwargs: values += (deprecated_kwargs.pop(_UpperCAmelCase),) SCREAMING_SNAKE_CASE = F'''The `{attribute}` argument is deprecated and will be removed in version {version_name}.''' elif hasattr(_UpperCAmelCase , _UpperCAmelCase): values += (getattr(_UpperCAmelCase , _UpperCAmelCase),) SCREAMING_SNAKE_CASE = F'''The `{attribute}` attribute is deprecated and will be removed in version {version_name}.''' elif deprecated_kwargs is None: SCREAMING_SNAKE_CASE = F'''`{attribute}` is deprecated and will be removed in version {version_name}.''' if warning is not None: SCREAMING_SNAKE_CASE = warning + ' ' if standard_warn else '' warnings.warn(warning + message , _UpperCAmelCase , stacklevel=_UpperCAmelCase) if isinstance(_UpperCAmelCase , _UpperCAmelCase) and len(_UpperCAmelCase) > 0: SCREAMING_SNAKE_CASE = inspect.getouterframes(inspect.currentframe())[1] SCREAMING_SNAKE_CASE = call_frame.filename SCREAMING_SNAKE_CASE = call_frame.lineno SCREAMING_SNAKE_CASE = call_frame.function SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = next(iter(deprecated_kwargs.items())) raise TypeError(F'''{function} in {filename} line {line_number-1} got an unexpected keyword argument `{key}`''') if len(_UpperCAmelCase) == 0: return elif len(_UpperCAmelCase) == 1: return values[0] return values
73
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available a_ : List[str] = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : Optional[Any] = ['GPTSw3Tokenizer'] if TYPE_CHECKING: try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_gpt_swa import GPTSwaTokenizer else: import sys a_ : Tuple = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
73
1
import os import sys import tempfile import unittest import unittest.mock as mock from pathlib import Path from huggingface_hub import HfFolder, delete_repo from huggingface_hub.file_download import http_get from requests.exceptions import HTTPError from transformers import ( AlbertTokenizer, AutoTokenizer, BertTokenizer, BertTokenizerFast, GPTaTokenizerFast, is_tokenizers_available, ) from transformers.testing_utils import TOKEN, USER, is_staging_test, require_tokenizers from transformers.tokenization_utils import Trie sys.path.append(str(Path(__file__).parent.parent / 'utils')) from test_module.custom_tokenization import CustomTokenizer # noqa E402 if is_tokenizers_available(): from test_module.custom_tokenization_fast import CustomTokenizerFast class _snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: # A mock response for an HTTP head request to emulate server down SCREAMING_SNAKE_CASE = mock.Mock() SCREAMING_SNAKE_CASE = 500 SCREAMING_SNAKE_CASE = {} SCREAMING_SNAKE_CASE = HTTPError SCREAMING_SNAKE_CASE = {} # Download this model to make sure it's in the cache. SCREAMING_SNAKE_CASE = BertTokenizer.from_pretrained('hf-internal-testing/tiny-random-bert') # Under the mock environment we get a 500 error when trying to reach the tokenizer. with mock.patch('requests.Session.request' , return_value=a) as mock_head: SCREAMING_SNAKE_CASE = BertTokenizer.from_pretrained('hf-internal-testing/tiny-random-bert') # This check we did call the fake head request mock_head.assert_called() @require_tokenizers def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: # A mock response for an HTTP head request to emulate server down SCREAMING_SNAKE_CASE = mock.Mock() SCREAMING_SNAKE_CASE = 500 SCREAMING_SNAKE_CASE = {} SCREAMING_SNAKE_CASE = HTTPError SCREAMING_SNAKE_CASE = {} # Download this model to make sure it's in the cache. SCREAMING_SNAKE_CASE = GPTaTokenizerFast.from_pretrained('gpt2') # Under the mock environment we get a 500 error when trying to reach the tokenizer. with mock.patch('requests.Session.request' , return_value=a) as mock_head: SCREAMING_SNAKE_CASE = GPTaTokenizerFast.from_pretrained('gpt2') # This check we did call the fake head request mock_head.assert_called() def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: # This test is for deprecated behavior and can be removed in v5 try: SCREAMING_SNAKE_CASE = tempfile.mktemp() with open(a , 'wb') as f: http_get('https://huggingface.co/albert-base-v1/resolve/main/spiece.model' , a) SCREAMING_SNAKE_CASE = AlbertTokenizer.from_pretrained(a) finally: os.remove(a) # Supporting this legacy load introduced a weird bug where the tokenizer would load local files if they are in # the current folder and have the right name. if os.path.isfile('tokenizer.json'): # We skip the test if the user has a `tokenizer.json` in this folder to avoid deleting it. return try: with open('tokenizer.json' , 'wb') as f: http_get('https://huggingface.co/hf-internal-testing/tiny-random-bert/blob/main/tokenizer.json' , a) SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained('hf-internal-testing/tiny-random-gpt2') # The tiny random BERT has a vocab size of 1024, tiny gpt2 as a vocab size of 1000 self.assertEqual(tokenizer.vocab_size , 1000) # Tokenizer should depend on the remote checkpoint, not the local tokenizer.json file. finally: os.remove('tokenizer.json') def SCREAMING_SNAKE_CASE__ ( self) -> int: # This test is for deprecated behavior and can be removed in v5 SCREAMING_SNAKE_CASE = AlbertTokenizer.from_pretrained('https://huggingface.co/albert-base-v1/resolve/main/spiece.model') @is_staging_test class _snake_case ( unittest.TestCase ): _lowercase : Optional[Any] = ['''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''bla''', '''blou'''] @classmethod def SCREAMING_SNAKE_CASE__ ( cls) -> int: SCREAMING_SNAKE_CASE = TOKEN HfFolder.save_token(a) @classmethod def SCREAMING_SNAKE_CASE__ ( cls) -> Dict: try: delete_repo(token=cls._token , repo_id='test-tokenizer') except HTTPError: pass try: delete_repo(token=cls._token , repo_id='valid_org/test-tokenizer-org') except HTTPError: pass try: delete_repo(token=cls._token , repo_id='test-dynamic-tokenizer') except HTTPError: pass def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: with tempfile.TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE = os.path.join(a , 'vocab.txt') with open(a , 'w' , encoding='utf-8') as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in self.vocab_tokens])) SCREAMING_SNAKE_CASE = BertTokenizer(a) tokenizer.push_to_hub('test-tokenizer' , use_auth_token=self._token) SCREAMING_SNAKE_CASE = BertTokenizer.from_pretrained(f'''{USER}/test-tokenizer''') self.assertDictEqual(new_tokenizer.vocab , tokenizer.vocab) # Reset repo delete_repo(token=self._token , repo_id='test-tokenizer') # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained(a , repo_id='test-tokenizer' , push_to_hub=a , use_auth_token=self._token) SCREAMING_SNAKE_CASE = BertTokenizer.from_pretrained(f'''{USER}/test-tokenizer''') self.assertDictEqual(new_tokenizer.vocab , tokenizer.vocab) def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: with tempfile.TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE = os.path.join(a , 'vocab.txt') with open(a , 'w' , encoding='utf-8') as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in self.vocab_tokens])) SCREAMING_SNAKE_CASE = BertTokenizer(a) tokenizer.push_to_hub('valid_org/test-tokenizer-org' , use_auth_token=self._token) SCREAMING_SNAKE_CASE = BertTokenizer.from_pretrained('valid_org/test-tokenizer-org') self.assertDictEqual(new_tokenizer.vocab , tokenizer.vocab) # Reset repo delete_repo(token=self._token , repo_id='valid_org/test-tokenizer-org') # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained( a , repo_id='valid_org/test-tokenizer-org' , push_to_hub=a , use_auth_token=self._token) SCREAMING_SNAKE_CASE = BertTokenizer.from_pretrained('valid_org/test-tokenizer-org') self.assertDictEqual(new_tokenizer.vocab , tokenizer.vocab) @require_tokenizers def SCREAMING_SNAKE_CASE__ ( self) -> int: CustomTokenizer.register_for_auto_class() with tempfile.TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE = os.path.join(a , 'vocab.txt') with open(a , 'w' , encoding='utf-8') as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in self.vocab_tokens])) SCREAMING_SNAKE_CASE = CustomTokenizer(a) # No fast custom tokenizer tokenizer.push_to_hub('test-dynamic-tokenizer' , use_auth_token=self._token) SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained(f'''{USER}/test-dynamic-tokenizer''' , trust_remote_code=a) # Can't make an isinstance check because the new_model.config is from the CustomTokenizer class of a dynamic module self.assertEqual(tokenizer.__class__.__name__ , 'CustomTokenizer') # Fast and slow custom tokenizer CustomTokenizerFast.register_for_auto_class() with tempfile.TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE = os.path.join(a , 'vocab.txt') with open(a , 'w' , encoding='utf-8') as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in self.vocab_tokens])) SCREAMING_SNAKE_CASE = BertTokenizerFast.from_pretrained(a) bert_tokenizer.save_pretrained(a) SCREAMING_SNAKE_CASE = CustomTokenizerFast.from_pretrained(a) tokenizer.push_to_hub('test-dynamic-tokenizer' , use_auth_token=self._token) SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained(f'''{USER}/test-dynamic-tokenizer''' , trust_remote_code=a) # Can't make an isinstance check because the new_model.config is from the FakeConfig class of a dynamic module self.assertEqual(tokenizer.__class__.__name__ , 'CustomTokenizerFast') SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained( f'''{USER}/test-dynamic-tokenizer''' , use_fast=a , trust_remote_code=a) # Can't make an isinstance check because the new_model.config is from the FakeConfig class of a dynamic module self.assertEqual(tokenizer.__class__.__name__ , 'CustomTokenizer') class _snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ ( self) -> Any: SCREAMING_SNAKE_CASE = Trie() trie.add('Hello 友達') self.assertEqual(trie.data , {'H': {'e': {'l': {'l': {'o': {' ': {'友': {'達': {'': 1}}}}}}}}}) trie.add('Hello') trie.data self.assertEqual(trie.data , {'H': {'e': {'l': {'l': {'o': {'': 1, ' ': {'友': {'達': {'': 1}}}}}}}}}) def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: SCREAMING_SNAKE_CASE = Trie() self.assertEqual(trie.split('[CLS] This is a extra_id_100') , ['[CLS] This is a extra_id_100']) trie.add('[CLS]') trie.add('extra_id_1') trie.add('extra_id_100') self.assertEqual(trie.split('[CLS] This is a extra_id_100') , ['[CLS]', ' This is a ', 'extra_id_100']) def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: SCREAMING_SNAKE_CASE = Trie() trie.add('A') self.assertEqual(trie.split('ABC') , ['A', 'BC']) self.assertEqual(trie.split('BCA') , ['BC', 'A']) def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: SCREAMING_SNAKE_CASE = Trie() trie.add('TOKEN]') trie.add('[SPECIAL_TOKEN]') self.assertEqual(trie.split('This is something [SPECIAL_TOKEN]') , ['This is something ', '[SPECIAL_TOKEN]']) def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: SCREAMING_SNAKE_CASE = Trie() trie.add('A') trie.add('P') trie.add('[SPECIAL_TOKEN]') self.assertEqual(trie.split('This is something [SPECIAL_TOKEN]') , ['This is something ', '[SPECIAL_TOKEN]']) def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: SCREAMING_SNAKE_CASE = Trie() trie.add('AB') trie.add('B') trie.add('C') self.assertEqual(trie.split('ABC') , ['AB', 'C']) def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: SCREAMING_SNAKE_CASE = Trie() trie.add('ABC') trie.add('B') trie.add('CD') self.assertEqual(trie.split('ABCD') , ['ABC', 'D']) def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: # Even if the offsets are wrong, we necessarily output correct string # parts. SCREAMING_SNAKE_CASE = Trie() SCREAMING_SNAKE_CASE = trie.cut_text('ABC' , [0, 0, 2, 1, 2, 3]) self.assertEqual(a , ['AB', 'C'])
73
import os from tempfile import TemporaryDirectory from unittest import TestCase import pytest from absl.testing import parameterized from datasets import config from datasets.arrow_reader import HF_GCP_BASE_URL from datasets.builder import DatasetBuilder from datasets.dataset_dict import IterableDatasetDict from datasets.iterable_dataset import IterableDataset from datasets.load import dataset_module_factory, import_main_class from datasets.utils.file_utils import cached_path a_ : str = [ {'dataset': 'wikipedia', 'config_name': '20220301.de'}, {'dataset': 'wikipedia', 'config_name': '20220301.en'}, {'dataset': 'wikipedia', 'config_name': '20220301.fr'}, {'dataset': 'wikipedia', 'config_name': '20220301.frr'}, {'dataset': 'wikipedia', 'config_name': '20220301.it'}, {'dataset': 'wikipedia', 'config_name': '20220301.simple'}, {'dataset': 'snli', 'config_name': 'plain_text'}, {'dataset': 'eli5', 'config_name': 'LFQA_reddit'}, {'dataset': 'wiki40b', 'config_name': 'en'}, {'dataset': 'wiki_dpr', 'config_name': 'psgs_w100.nq.compressed'}, {'dataset': 'wiki_dpr', 'config_name': 'psgs_w100.nq.no_index'}, {'dataset': 'wiki_dpr', 'config_name': 'psgs_w100.multiset.no_index'}, {'dataset': 'natural_questions', 'config_name': 'default'}, ] def lowerCamelCase__ (_UpperCAmelCase=True): if with_config: return [ { "testcase_name": d["dataset"] + "/" + d["config_name"], "dataset": d["dataset"], "config_name": d["config_name"], } for d in DATASETS_ON_HF_GCP ] else: return [ {"testcase_name": dataset, "dataset": dataset} for dataset in {d["dataset"] for d in DATASETS_ON_HF_GCP} ] @parameterized.named_parameters(list_datasets_on_hf_gcp_parameters(with_config=A__ ) ) class _snake_case ( A__ ): _lowercase : Optional[Any] = None _lowercase : Optional[Any] = None def SCREAMING_SNAKE_CASE__ ( self , a , a) -> Optional[Any]: with TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE = dataset_module_factory(a , cache_dir=a) SCREAMING_SNAKE_CASE = import_main_class(dataset_module.module_path , dataset=a) SCREAMING_SNAKE_CASE = builder_cls( cache_dir=a , config_name=a , hash=dataset_module.hash , ) SCREAMING_SNAKE_CASE = '/'.join( [ HF_GCP_BASE_URL, builder_instance._relative_data_dir(with_hash=a).replace(os.sep , '/'), config.DATASET_INFO_FILENAME, ]) SCREAMING_SNAKE_CASE = cached_path(a , cache_dir=a) self.assertTrue(os.path.exists(a)) @pytest.mark.integration def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = tmp_path_factory.mktemp('test_hf_gcp') / 'test_wikipedia_simple' SCREAMING_SNAKE_CASE = dataset_module_factory('wikipedia' , cache_dir=_UpperCAmelCase) SCREAMING_SNAKE_CASE = import_main_class(dataset_module.module_path) SCREAMING_SNAKE_CASE = builder_cls( cache_dir=_UpperCAmelCase , config_name='20220301.frr' , hash=dataset_module.hash , ) # use the HF cloud storage, not the original download_and_prepare that uses apache-beam SCREAMING_SNAKE_CASE = None builder_instance.download_and_prepare() SCREAMING_SNAKE_CASE = builder_instance.as_dataset() assert ds @pytest.mark.integration def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = dataset_module_factory('wikipedia' , cache_dir=_UpperCAmelCase) SCREAMING_SNAKE_CASE = import_main_class(dataset_module.module_path , dataset=_UpperCAmelCase) SCREAMING_SNAKE_CASE = builder_cls( cache_dir=_UpperCAmelCase , config_name='20220301.frr' , hash=dataset_module.hash , ) SCREAMING_SNAKE_CASE = builder_instance.as_streaming_dataset() assert ds assert isinstance(_UpperCAmelCase , _UpperCAmelCase) assert "train" in ds assert isinstance(ds['train'] , _UpperCAmelCase) assert next(iter(ds['train']))
73
1
import os import unittest from transformers import BertTokenizerFast from transformers.models.bert.tokenization_bert import ( VOCAB_FILES_NAMES, BasicTokenizer, BertTokenizer, WordpieceTokenizer, _is_control, _is_punctuation, _is_whitespace, ) from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin, filter_non_english @require_tokenizers class _snake_case ( A__ , unittest.TestCase ): _lowercase : int = BertTokenizer _lowercase : str = BertTokenizerFast _lowercase : List[Any] = True _lowercase : List[Any] = True _lowercase : Dict = filter_non_english def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: super().setUp() SCREAMING_SNAKE_CASE = [ '[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing', ',', 'low', 'lowest', ] SCREAMING_SNAKE_CASE = 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 SCREAMING_SNAKE_CASE__ ( self , a) -> Union[str, Any]: SCREAMING_SNAKE_CASE = 'UNwant\u00E9d,running' SCREAMING_SNAKE_CASE = 'unwanted, running' return input_text, output_text def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: SCREAMING_SNAKE_CASE = self.tokenizer_class(self.vocab_file) SCREAMING_SNAKE_CASE = tokenizer.tokenize('UNwant\u00E9d,running') self.assertListEqual(a , ['un', '##want', '##ed', ',', 'runn', '##ing']) self.assertListEqual(tokenizer.convert_tokens_to_ids(a) , [9, 6, 7, 12, 10, 11]) def SCREAMING_SNAKE_CASE__ ( self) -> Any: if not self.test_rust_tokenizer: return SCREAMING_SNAKE_CASE = self.get_tokenizer() SCREAMING_SNAKE_CASE = self.get_rust_tokenizer() SCREAMING_SNAKE_CASE = 'UNwant\u00E9d,running' SCREAMING_SNAKE_CASE = tokenizer.tokenize(a) SCREAMING_SNAKE_CASE = rust_tokenizer.tokenize(a) self.assertListEqual(a , a) SCREAMING_SNAKE_CASE = tokenizer.encode(a , add_special_tokens=a) SCREAMING_SNAKE_CASE = rust_tokenizer.encode(a , add_special_tokens=a) self.assertListEqual(a , a) SCREAMING_SNAKE_CASE = self.get_rust_tokenizer() SCREAMING_SNAKE_CASE = tokenizer.encode(a) SCREAMING_SNAKE_CASE = rust_tokenizer.encode(a) self.assertListEqual(a , a) # With lower casing SCREAMING_SNAKE_CASE = self.get_tokenizer(do_lower_case=a) SCREAMING_SNAKE_CASE = self.get_rust_tokenizer(do_lower_case=a) SCREAMING_SNAKE_CASE = 'UNwant\u00E9d,running' SCREAMING_SNAKE_CASE = tokenizer.tokenize(a) SCREAMING_SNAKE_CASE = rust_tokenizer.tokenize(a) self.assertListEqual(a , a) SCREAMING_SNAKE_CASE = tokenizer.encode(a , add_special_tokens=a) SCREAMING_SNAKE_CASE = rust_tokenizer.encode(a , add_special_tokens=a) self.assertListEqual(a , a) SCREAMING_SNAKE_CASE = self.get_rust_tokenizer() SCREAMING_SNAKE_CASE = tokenizer.encode(a) SCREAMING_SNAKE_CASE = rust_tokenizer.encode(a) self.assertListEqual(a , a) def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: SCREAMING_SNAKE_CASE = BasicTokenizer() self.assertListEqual(tokenizer.tokenize('ah\u535A\u63A8zz') , ['ah', '\u535A', '\u63A8', 'zz']) def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: SCREAMING_SNAKE_CASE = BasicTokenizer(do_lower_case=a) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? ') , ['hello', '!', 'how', 'are', 'you', '?']) self.assertListEqual(tokenizer.tokenize('H\u00E9llo') , ['hello']) def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: SCREAMING_SNAKE_CASE = BasicTokenizer(do_lower_case=a , strip_accents=a) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ') , ['hällo', '!', 'how', 'are', 'you', '?']) self.assertListEqual(tokenizer.tokenize('H\u00E9llo') , ['h\u00E9llo']) def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: SCREAMING_SNAKE_CASE = BasicTokenizer(do_lower_case=a , strip_accents=a) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ') , ['hallo', '!', 'how', 'are', 'you', '?']) self.assertListEqual(tokenizer.tokenize('H\u00E9llo') , ['hello']) def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: SCREAMING_SNAKE_CASE = BasicTokenizer(do_lower_case=a) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ') , ['hallo', '!', 'how', 'are', 'you', '?']) self.assertListEqual(tokenizer.tokenize('H\u00E9llo') , ['hello']) def SCREAMING_SNAKE_CASE__ ( self) -> str: SCREAMING_SNAKE_CASE = BasicTokenizer(do_lower_case=a) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? ') , ['HeLLo', '!', 'how', 'Are', 'yoU', '?']) def SCREAMING_SNAKE_CASE__ ( self) -> int: SCREAMING_SNAKE_CASE = BasicTokenizer(do_lower_case=a , strip_accents=a) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ') , ['HäLLo', '!', 'how', 'Are', 'yoU', '?']) def SCREAMING_SNAKE_CASE__ ( self) -> Dict: SCREAMING_SNAKE_CASE = BasicTokenizer(do_lower_case=a , strip_accents=a) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ') , ['HaLLo', '!', 'how', 'Are', 'yoU', '?']) def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: SCREAMING_SNAKE_CASE = BasicTokenizer(do_lower_case=a , never_split=['[UNK]']) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? [UNK]') , ['HeLLo', '!', 'how', 'Are', 'yoU', '?', '[UNK]']) def SCREAMING_SNAKE_CASE__ ( self) -> str: SCREAMING_SNAKE_CASE = BasicTokenizer() SCREAMING_SNAKE_CASE = 'a\n\'ll !!to?\'d of, can\'t.' SCREAMING_SNAKE_CASE = ['a', '\'', 'll', '!', '!', 'to', '?', '\'', 'd', 'of', ',', 'can', '\'', 't', '.'] self.assertListEqual(tokenizer.tokenize(a) , a) def SCREAMING_SNAKE_CASE__ ( self) -> str: SCREAMING_SNAKE_CASE = ['[UNK]', '[CLS]', '[SEP]', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing'] SCREAMING_SNAKE_CASE = {} for i, token in enumerate(a): SCREAMING_SNAKE_CASE = i SCREAMING_SNAKE_CASE = WordpieceTokenizer(vocab=a , unk_token='[UNK]') self.assertListEqual(tokenizer.tokenize('') , []) self.assertListEqual(tokenizer.tokenize('unwanted running') , ['un', '##want', '##ed', 'runn', '##ing']) self.assertListEqual(tokenizer.tokenize('unwantedX running') , ['[UNK]', 'runn', '##ing']) def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: self.assertTrue(_is_whitespace(' ')) self.assertTrue(_is_whitespace('\t')) self.assertTrue(_is_whitespace('\r')) self.assertTrue(_is_whitespace('\n')) self.assertTrue(_is_whitespace('\u00A0')) self.assertFalse(_is_whitespace('A')) self.assertFalse(_is_whitespace('-')) def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: self.assertTrue(_is_control('\u0005')) self.assertFalse(_is_control('A')) self.assertFalse(_is_control(' ')) self.assertFalse(_is_control('\t')) self.assertFalse(_is_control('\r')) def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: self.assertTrue(_is_punctuation('-')) self.assertTrue(_is_punctuation('$')) self.assertTrue(_is_punctuation('`')) self.assertTrue(_is_punctuation('.')) self.assertFalse(_is_punctuation('A')) self.assertFalse(_is_punctuation(' ')) def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: SCREAMING_SNAKE_CASE = self.get_tokenizer() SCREAMING_SNAKE_CASE = self.get_rust_tokenizer() # Example taken from the issue https://github.com/huggingface/tokenizers/issues/340 self.assertListEqual([tokenizer.tokenize(a) for t in ['Test', '\xad', 'test']] , [['[UNK]'], [], ['[UNK]']]) self.assertListEqual( [rust_tokenizer.tokenize(a) for t in ['Test', '\xad', 'test']] , [['[UNK]'], [], ['[UNK]']]) @slow def SCREAMING_SNAKE_CASE__ ( self) -> Any: SCREAMING_SNAKE_CASE = self.tokenizer_class.from_pretrained('bert-base-uncased') SCREAMING_SNAKE_CASE = tokenizer.encode('sequence builders' , add_special_tokens=a) SCREAMING_SNAKE_CASE = tokenizer.encode('multi-sequence build' , add_special_tokens=a) SCREAMING_SNAKE_CASE = tokenizer.build_inputs_with_special_tokens(a) SCREAMING_SNAKE_CASE = tokenizer.build_inputs_with_special_tokens(a , a) assert encoded_sentence == [101] + text + [102] assert encoded_pair == [101] + text + [102] + text_a + [102] def SCREAMING_SNAKE_CASE__ ( self) -> Dict: for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})'''): SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained(a , **a) SCREAMING_SNAKE_CASE = f'''A, naïve {tokenizer_r.mask_token} AllenNLP sentence.''' SCREAMING_SNAKE_CASE = tokenizer_r.encode_plus( a , return_attention_mask=a , return_token_type_ids=a , return_offsets_mapping=a , add_special_tokens=a , ) SCREAMING_SNAKE_CASE = tokenizer_r.do_lower_case if hasattr(a , 'do_lower_case') else False SCREAMING_SNAKE_CASE = ( [ ((0, 0), tokenizer_r.cls_token), ((0, 1), 'A'), ((1, 2), ','), ((3, 5), 'na'), ((5, 6), '##ï'), ((6, 8), '##ve'), ((9, 15), tokenizer_r.mask_token), ((16, 21), 'Allen'), ((21, 23), '##NL'), ((23, 24), '##P'), ((25, 33), 'sentence'), ((33, 34), '.'), ((0, 0), tokenizer_r.sep_token), ] if not do_lower_case else [ ((0, 0), tokenizer_r.cls_token), ((0, 1), 'a'), ((1, 2), ','), ((3, 8), 'naive'), ((9, 15), tokenizer_r.mask_token), ((16, 21), 'allen'), ((21, 23), '##nl'), ((23, 24), '##p'), ((25, 33), 'sentence'), ((33, 34), '.'), ((0, 0), tokenizer_r.sep_token), ] ) self.assertEqual( [e[1] for e in expected_results] , tokenizer_r.convert_ids_to_tokens(tokens['input_ids'])) self.assertEqual([e[0] for e in expected_results] , tokens['offset_mapping']) def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: SCREAMING_SNAKE_CASE = ['的', '人', '有'] SCREAMING_SNAKE_CASE = ''.join(a) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})'''): SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = self.tokenizer_class.from_pretrained(a , **a) SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained(a , **a) SCREAMING_SNAKE_CASE = tokenizer_p.encode(a , add_special_tokens=a) SCREAMING_SNAKE_CASE = tokenizer_r.encode(a , add_special_tokens=a) SCREAMING_SNAKE_CASE = tokenizer_r.convert_ids_to_tokens(a) SCREAMING_SNAKE_CASE = tokenizer_p.convert_ids_to_tokens(a) # it is expected that each Chinese character is not preceded by "##" self.assertListEqual(a , a) self.assertListEqual(a , a) SCREAMING_SNAKE_CASE = False SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained(a , **a) SCREAMING_SNAKE_CASE = self.tokenizer_class.from_pretrained(a , **a) SCREAMING_SNAKE_CASE = tokenizer_r.encode(a , add_special_tokens=a) SCREAMING_SNAKE_CASE = tokenizer_p.encode(a , add_special_tokens=a) SCREAMING_SNAKE_CASE = tokenizer_r.convert_ids_to_tokens(a) SCREAMING_SNAKE_CASE = tokenizer_p.convert_ids_to_tokens(a) # it is expected that only the first Chinese character is not preceded by "##". SCREAMING_SNAKE_CASE = [ f'''##{token}''' if idx != 0 else token for idx, token in enumerate(a) ] self.assertListEqual(a , a) self.assertListEqual(a , a)
73
from __future__ import annotations def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = 2 SCREAMING_SNAKE_CASE = [] while i * i <= n: if n % i: i += 1 else: n //= i factors.append(_UpperCAmelCase) if n > 1: factors.append(_UpperCAmelCase) return factors if __name__ == "__main__": import doctest doctest.testmod()
73
1
from __future__ import annotations import inspect import unittest from math import floor import numpy as np from transformers import CvtConfig 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 TFCvtForImageClassification, TFCvtModel from transformers.models.cvt.modeling_tf_cvt import TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class _snake_case ( A__ ): def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: SCREAMING_SNAKE_CASE = self.config_class(**self.inputs_dict) self.parent.assertTrue(hasattr(a , 'embed_dim')) self.parent.assertTrue(hasattr(a , 'num_heads')) class _snake_case : def __init__( self , a , a=13 , a=64 , a=3 , a=[16, 48, 96] , a=[1, 3, 6] , a=[1, 2, 10] , a=[7, 3, 3] , a=[4, 2, 2] , a=[2, 1, 1] , a=[2, 2, 2] , a=[False, False, True] , a=[0.0, 0.0, 0.0] , a=0.02 , a=1E-12 , a=True , a=True , a=2 , ) -> str: SCREAMING_SNAKE_CASE = parent SCREAMING_SNAKE_CASE = batch_size SCREAMING_SNAKE_CASE = image_size SCREAMING_SNAKE_CASE = patch_sizes SCREAMING_SNAKE_CASE = patch_stride SCREAMING_SNAKE_CASE = patch_padding SCREAMING_SNAKE_CASE = is_training SCREAMING_SNAKE_CASE = use_labels SCREAMING_SNAKE_CASE = num_labels SCREAMING_SNAKE_CASE = num_channels SCREAMING_SNAKE_CASE = embed_dim SCREAMING_SNAKE_CASE = num_heads SCREAMING_SNAKE_CASE = stride_kv SCREAMING_SNAKE_CASE = depth SCREAMING_SNAKE_CASE = cls_token SCREAMING_SNAKE_CASE = attention_drop_rate SCREAMING_SNAKE_CASE = initializer_range SCREAMING_SNAKE_CASE = layer_norm_eps def SCREAMING_SNAKE_CASE__ ( self) -> Any: SCREAMING_SNAKE_CASE = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) SCREAMING_SNAKE_CASE = None if self.use_labels: # create a random int32 tensor of given shape SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.num_labels) SCREAMING_SNAKE_CASE = self.get_config() return config, pixel_values, labels def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: return CvtConfig( image_size=self.image_size , num_labels=self.num_labels , num_channels=self.num_channels , embed_dim=self.embed_dim , num_heads=self.num_heads , patch_sizes=self.patch_sizes , patch_padding=self.patch_padding , patch_stride=self.patch_stride , stride_kv=self.stride_kv , depth=self.depth , cls_token=self.cls_token , attention_drop_rate=self.attention_drop_rate , initializer_range=self.initializer_range , ) def SCREAMING_SNAKE_CASE__ ( self , a , a , a) -> Dict: SCREAMING_SNAKE_CASE = TFCvtModel(config=a) SCREAMING_SNAKE_CASE = model(a , training=a) SCREAMING_SNAKE_CASE = (self.image_size, self.image_size) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = image_size[0], image_size[1] for i in range(len(self.depth)): SCREAMING_SNAKE_CASE = floor(((height + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1) SCREAMING_SNAKE_CASE = floor(((width + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.embed_dim[-1], height, width)) def SCREAMING_SNAKE_CASE__ ( self , a , a , a) -> List[str]: SCREAMING_SNAKE_CASE = self.num_labels SCREAMING_SNAKE_CASE = TFCvtForImageClassification(a) SCREAMING_SNAKE_CASE = model(a , labels=a , training=a) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels)) def SCREAMING_SNAKE_CASE__ ( self) -> int: SCREAMING_SNAKE_CASE = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = config_and_inputs SCREAMING_SNAKE_CASE = {'pixel_values': pixel_values} return config, inputs_dict @require_tf class _snake_case ( A__ , A__ , unittest.TestCase ): _lowercase : Optional[Any] = (TFCvtModel, TFCvtForImageClassification) if is_tf_available() else () _lowercase : str = ( {'''feature-extraction''': TFCvtModel, '''image-classification''': TFCvtForImageClassification} if is_tf_available() else {} ) _lowercase : Dict = False _lowercase : Optional[int] = False _lowercase : Optional[Any] = False _lowercase : Dict = False _lowercase : List[Any] = False def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: SCREAMING_SNAKE_CASE = TFCvtModelTester(self) SCREAMING_SNAKE_CASE = TFCvtConfigTester(self , config_class=a , has_text_modality=a , hidden_size=37) def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: self.config_tester.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() @unittest.skip(reason='Cvt does not output attentions') def SCREAMING_SNAKE_CASE__ ( self) -> Any: pass @unittest.skip(reason='Cvt does not use inputs_embeds') def SCREAMING_SNAKE_CASE__ ( self) -> str: pass @unittest.skip(reason='Cvt does not support input and output embeddings') def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: 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.' , ) def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: super().test_dataset_conversion() @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) -> Any: super().test_keras_fit() @unittest.skip(reason='Get `Failed to determine best cudnn convolution algo.` error after using TF 2.12+cuda 11.8') def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: SCREAMING_SNAKE_CASE = tf.keras.mixed_precision.Policy('mixed_float16') tf.keras.mixed_precision.set_global_policy(a) super().test_keras_fit() tf.keras.mixed_precision.set_global_policy('float32') def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE = model_class(a) SCREAMING_SNAKE_CASE = inspect.signature(model.call) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE = ['pixel_values'] self.assertListEqual(arg_names[:1] , a) def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: def check_hidden_states_output(a , a , a): SCREAMING_SNAKE_CASE = model_class(a) SCREAMING_SNAKE_CASE = model(**self._prepare_for_class(a , a)) SCREAMING_SNAKE_CASE = outputs.hidden_states SCREAMING_SNAKE_CASE = len(self.model_tester.depth) self.assertEqual(len(a) , a) # verify the first hidden states (first block) self.assertListEqual( list(hidden_states[0].shape[-3:]) , [ self.model_tester.embed_dim[0], self.model_tester.image_size // 4, self.model_tester.image_size // 4, ] , ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE = True check_hidden_states_output(a , a , a) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] SCREAMING_SNAKE_CASE = True check_hidden_states_output(a , a , a) def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a) def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*a) @slow def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: for model_name in TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE = TFCvtModel.from_pretrained(a) self.assertIsNotNone(a) def lowerCamelCase__ (): SCREAMING_SNAKE_CASE = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png') return image @require_tf @require_vision class _snake_case ( unittest.TestCase ): @cached_property def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: return AutoImageProcessor.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]) @slow def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: SCREAMING_SNAKE_CASE = TFCvtForImageClassification.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]) SCREAMING_SNAKE_CASE = self.default_image_processor SCREAMING_SNAKE_CASE = prepare_img() SCREAMING_SNAKE_CASE = image_processor(images=a , return_tensors='tf') # forward pass SCREAMING_SNAKE_CASE = model(**a) # verify the logits SCREAMING_SNAKE_CASE = tf.TensorShape((1, 1000)) self.assertEqual(outputs.logits.shape , a) SCREAMING_SNAKE_CASE = tf.constant([0.92_85, 0.90_15, -0.31_50]) self.assertTrue(np.allclose(outputs.logits[0, :3].numpy() , a , atol=1E-4))
73
import math import os import sys def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = '' try: with open(_UpperCAmelCase , 'rb') as binary_file: SCREAMING_SNAKE_CASE = binary_file.read() for dat in data: SCREAMING_SNAKE_CASE = F'''{dat:08b}''' result += curr_byte return result except OSError: print('File not accessible') sys.exit() def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): lexicon.pop(_UpperCAmelCase) SCREAMING_SNAKE_CASE = last_match_id if math.loga(_UpperCAmelCase).is_integer(): for curr_key in lexicon: SCREAMING_SNAKE_CASE = '0' + lexicon[curr_key] SCREAMING_SNAKE_CASE = bin(_UpperCAmelCase)[2:] def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = {'0': '0', '1': '1'} SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = '', '' SCREAMING_SNAKE_CASE = len(_UpperCAmelCase) for i in range(len(_UpperCAmelCase)): curr_string += data_bits[i] if curr_string not in lexicon: continue SCREAMING_SNAKE_CASE = lexicon[curr_string] result += last_match_id add_key_to_lexicon(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) index += 1 SCREAMING_SNAKE_CASE = '' while curr_string != "" and curr_string not in lexicon: curr_string += "0" if curr_string != "": SCREAMING_SNAKE_CASE = lexicon[curr_string] result += last_match_id return result def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = os.path.getsize(_UpperCAmelCase) SCREAMING_SNAKE_CASE = bin(_UpperCAmelCase)[2:] SCREAMING_SNAKE_CASE = len(_UpperCAmelCase) return "0" * (length_length - 1) + file_length_binary + compressed def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = 8 try: with open(_UpperCAmelCase , 'wb') as opened_file: SCREAMING_SNAKE_CASE = [ to_write[i : i + byte_length] for i in range(0 , len(_UpperCAmelCase) , _UpperCAmelCase) ] 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(_UpperCAmelCase , 2).to_bytes(1 , byteorder='big')) except OSError: print('File not accessible') sys.exit() def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = read_file_binary(_UpperCAmelCase) SCREAMING_SNAKE_CASE = compress_data(_UpperCAmelCase) SCREAMING_SNAKE_CASE = add_file_length(_UpperCAmelCase , _UpperCAmelCase) write_file_binary(_UpperCAmelCase , _UpperCAmelCase) if __name__ == "__main__": compress(sys.argv[1], sys.argv[2])
73
1
class _snake_case : def __init__( self , a) -> Optional[int]: SCREAMING_SNAKE_CASE = n SCREAMING_SNAKE_CASE = [None] * self.n SCREAMING_SNAKE_CASE = 0 # index of the first element SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = 0 def __len__( self) -> int: return self.size def SCREAMING_SNAKE_CASE__ ( self) -> bool: return self.size == 0 def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: return False if self.is_empty() else self.array[self.front] def SCREAMING_SNAKE_CASE__ ( self , a) -> Optional[Any]: if self.size >= self.n: raise Exception('QUEUE IS FULL') SCREAMING_SNAKE_CASE = data SCREAMING_SNAKE_CASE = (self.rear + 1) % self.n self.size += 1 return self def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: if self.size == 0: raise Exception('UNDERFLOW') SCREAMING_SNAKE_CASE = self.array[self.front] SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = (self.front + 1) % self.n self.size -= 1 return temp
73
import warnings from typing import Dict import numpy as np from ..utils import ExplicitEnum, add_end_docstrings, is_tf_available, is_torch_available from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline if is_tf_available(): from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if is_torch_available(): from ..models.auto.modeling_auto import MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING def lowerCamelCase__ (_UpperCAmelCase): return 1.0 / (1.0 + np.exp(-_outputs)) def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = np.max(_outputs , axis=-1 , keepdims=_UpperCAmelCase) SCREAMING_SNAKE_CASE = np.exp(_outputs - maxes) return shifted_exp / shifted_exp.sum(axis=-1 , keepdims=_UpperCAmelCase) class _snake_case ( A__ ): _lowercase : Tuple = '''sigmoid''' _lowercase : List[str] = '''softmax''' _lowercase : Tuple = '''none''' @add_end_docstrings( A__ , R''' return_all_scores (`bool`, *optional*, defaults to `False`): Whether to return all prediction scores or just the one of the predicted class. function_to_apply (`str`, *optional*, defaults to `"default"`): The function to apply to the model outputs in order to retrieve the scores. Accepts four different values: - `"default"`: if the model has a single label, will apply the sigmoid function on the output. If the model has several labels, will apply the softmax function on the output. - `"sigmoid"`: Applies the sigmoid function on the output. - `"softmax"`: Applies the softmax function on the output. - `"none"`: Does not apply any function on the output. ''' , ) class _snake_case ( A__ ): _lowercase : Optional[Any] = False _lowercase : Tuple = ClassificationFunction.NONE def __init__( self , **a) -> Optional[Any]: super().__init__(**a) self.check_model_type( TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if self.framework == 'tf' else MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING) def SCREAMING_SNAKE_CASE__ ( self , a=None , a=None , a="" , **a) -> Tuple: # Using "" as default argument because we're going to use `top_k=None` in user code to declare # "No top_k" SCREAMING_SNAKE_CASE = tokenizer_kwargs SCREAMING_SNAKE_CASE = {} if hasattr(self.model.config , 'return_all_scores') and return_all_scores is None: SCREAMING_SNAKE_CASE = self.model.config.return_all_scores if isinstance(a , a) or top_k is None: SCREAMING_SNAKE_CASE = top_k SCREAMING_SNAKE_CASE = False elif return_all_scores is not None: warnings.warn( '`return_all_scores` is now deprecated, if want a similar functionality use `top_k=None` instead of' ' `return_all_scores=True` or `top_k=1` instead of `return_all_scores=False`.' , a , ) if return_all_scores: SCREAMING_SNAKE_CASE = None else: SCREAMING_SNAKE_CASE = 1 if isinstance(a , a): SCREAMING_SNAKE_CASE = ClassificationFunction[function_to_apply.upper()] if function_to_apply is not None: SCREAMING_SNAKE_CASE = function_to_apply return preprocess_params, {}, postprocess_params def __call__( self , *a , **a) -> Optional[int]: SCREAMING_SNAKE_CASE = super().__call__(*a , **a) # TODO try and retrieve it in a nicer way from _sanitize_parameters. SCREAMING_SNAKE_CASE = 'top_k' not in kwargs if isinstance(args[0] , a) and _legacy: # This pipeline is odd, and return a list when single item is run return [result] else: return result def SCREAMING_SNAKE_CASE__ ( self , a , **a) -> Dict[str, GenericTensor]: SCREAMING_SNAKE_CASE = self.framework if isinstance(a , a): return self.tokenizer(**a , return_tensors=a , **a) elif isinstance(a , a) and len(a) == 1 and isinstance(inputs[0] , a) and len(inputs[0]) == 2: # It used to be valid to use a list of list of list for text pairs, keeping this path for BC return self.tokenizer( text=inputs[0][0] , text_pair=inputs[0][1] , return_tensors=a , **a) elif isinstance(a , a): # This is likely an invalid usage of the pipeline attempting to pass text pairs. raise ValueError( 'The pipeline received invalid inputs, if you are trying to send text pairs, you can try to send a' ' dictionary `{"text": "My text", "text_pair": "My pair"}` in order to send a text pair.') return self.tokenizer(a , return_tensors=a , **a) def SCREAMING_SNAKE_CASE__ ( self , a) -> Optional[Any]: return self.model(**a) def SCREAMING_SNAKE_CASE__ ( self , a , a=None , a=1 , a=True) -> Any: # `_legacy` is used to determine if we're running the naked pipeline and in backward # compatibility mode, or if running the pipeline with `pipeline(..., top_k=1)` we're running # the more natural result containing the list. # Default value before `set_parameters` if function_to_apply is None: if self.model.config.problem_type == "multi_label_classification" or self.model.config.num_labels == 1: SCREAMING_SNAKE_CASE = ClassificationFunction.SIGMOID elif self.model.config.problem_type == "single_label_classification" or self.model.config.num_labels > 1: SCREAMING_SNAKE_CASE = ClassificationFunction.SOFTMAX elif hasattr(self.model.config , 'function_to_apply') and function_to_apply is None: SCREAMING_SNAKE_CASE = self.model.config.function_to_apply else: SCREAMING_SNAKE_CASE = ClassificationFunction.NONE SCREAMING_SNAKE_CASE = model_outputs['logits'][0] SCREAMING_SNAKE_CASE = outputs.numpy() if function_to_apply == ClassificationFunction.SIGMOID: SCREAMING_SNAKE_CASE = sigmoid(a) elif function_to_apply == ClassificationFunction.SOFTMAX: SCREAMING_SNAKE_CASE = softmax(a) elif function_to_apply == ClassificationFunction.NONE: SCREAMING_SNAKE_CASE = outputs else: raise ValueError(f'''Unrecognized `function_to_apply` argument: {function_to_apply}''') if top_k == 1 and _legacy: return {"label": self.model.config.idalabel[scores.argmax().item()], "score": scores.max().item()} SCREAMING_SNAKE_CASE = [ {'label': self.model.config.idalabel[i], 'score': score.item()} for i, score in enumerate(a) ] if not _legacy: dict_scores.sort(key=lambda a: x["score"] , reverse=a) if top_k is not None: SCREAMING_SNAKE_CASE = dict_scores[:top_k] return dict_scores
73
1
import torch import torch.nn as nn from transformers.modeling_utils import ModuleUtilsMixin from transformers.models.ta.modeling_ta import TaBlock, TaConfig, TaLayerNorm from ...configuration_utils import ConfigMixin, register_to_config from ...models import ModelMixin class _snake_case ( A__ , A__ , A__ ): @register_to_config def __init__( self , a , a , a , a , a , a , a , a , a , a = False , ) -> int: super().__init__() SCREAMING_SNAKE_CASE = nn.Embedding(a , a) SCREAMING_SNAKE_CASE = nn.Embedding(a , a) SCREAMING_SNAKE_CASE = False SCREAMING_SNAKE_CASE = nn.Dropout(p=a) SCREAMING_SNAKE_CASE = TaConfig( vocab_size=a , d_model=a , num_heads=a , d_kv=a , d_ff=a , dropout_rate=a , feed_forward_proj=a , is_decoder=a , is_encoder_decoder=a , ) SCREAMING_SNAKE_CASE = nn.ModuleList() for lyr_num in range(a): SCREAMING_SNAKE_CASE = TaBlock(a) self.encoders.append(a) SCREAMING_SNAKE_CASE = TaLayerNorm(a) SCREAMING_SNAKE_CASE = nn.Dropout(p=a) def SCREAMING_SNAKE_CASE__ ( self , a , a) -> Optional[int]: SCREAMING_SNAKE_CASE = self.token_embedder(a) SCREAMING_SNAKE_CASE = encoder_input_tokens.shape[1] SCREAMING_SNAKE_CASE = torch.arange(a , device=encoder_input_tokens.device) x += self.position_encoding(a) SCREAMING_SNAKE_CASE = self.dropout_pre(a) # inverted the attention mask SCREAMING_SNAKE_CASE = encoder_input_tokens.size() SCREAMING_SNAKE_CASE = self.get_extended_attention_mask(a , a) for lyr in self.encoders: SCREAMING_SNAKE_CASE = lyr(a , a)[0] SCREAMING_SNAKE_CASE = self.layer_norm(a) return self.dropout_post(a), encoder_inputs_mask
73
import heapq as hq import math from collections.abc import Iterator class _snake_case : def __init__( self , a) -> Optional[Any]: SCREAMING_SNAKE_CASE = str(id_) SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = {} # {vertex:distance} def __lt__( self , a) -> Dict: return self.key < other.key def __repr__( self) -> Optional[Any]: return self.id def SCREAMING_SNAKE_CASE__ ( self , a) -> Optional[Any]: self.neighbors.append(a) def SCREAMING_SNAKE_CASE__ ( self , a , a) -> Tuple: SCREAMING_SNAKE_CASE = weight def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): # add the neighbors: graph[a - 1].add_neighbor(graph[b - 1]) graph[b - 1].add_neighbor(graph[a - 1]) # add the edges: graph[a - 1].add_edge(graph[b - 1] , _UpperCAmelCase) graph[b - 1].add_edge(graph[a - 1] , _UpperCAmelCase) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = [] for u in graph: SCREAMING_SNAKE_CASE = math.inf SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = graph[:] while q: SCREAMING_SNAKE_CASE = min(_UpperCAmelCase) q.remove(_UpperCAmelCase) for v in u.neighbors: if (v in q) and (u.edges[v.id] < v.key): SCREAMING_SNAKE_CASE = u SCREAMING_SNAKE_CASE = u.edges[v.id] for i in range(1 , len(_UpperCAmelCase)): a.append((int(graph[i].id) + 1, int(graph[i].pi.id) + 1)) return a def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): for u in graph: SCREAMING_SNAKE_CASE = math.inf SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = list(_UpperCAmelCase) hq.heapify(_UpperCAmelCase) while h: SCREAMING_SNAKE_CASE = hq.heappop(_UpperCAmelCase) for v in u.neighbors: if (v in h) and (u.edges[v.id] < v.key): SCREAMING_SNAKE_CASE = u SCREAMING_SNAKE_CASE = u.edges[v.id] hq.heapify(_UpperCAmelCase) for i in range(1 , len(_UpperCAmelCase)): yield (int(graph[i].id) + 1, int(graph[i].pi.id) + 1) def lowerCamelCase__ (): pass if __name__ == "__main__": import doctest doctest.testmod()
73
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, is_vision_available, ) a_ : Any = { 'configuration_owlvit': [ 'OWLVIT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'OwlViTConfig', 'OwlViTOnnxConfig', 'OwlViTTextConfig', 'OwlViTVisionConfig', ], 'processing_owlvit': ['OwlViTProcessor'], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : Union[str, Any] = ['OwlViTFeatureExtractor'] a_ : List[str] = ['OwlViTImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : Any = [ 'OWLVIT_PRETRAINED_MODEL_ARCHIVE_LIST', 'OwlViTModel', 'OwlViTPreTrainedModel', 'OwlViTTextModel', 'OwlViTVisionModel', 'OwlViTForObjectDetection', ] if TYPE_CHECKING: from .configuration_owlvit import ( OWLVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, OwlViTConfig, OwlViTOnnxConfig, OwlViTTextConfig, OwlViTVisionConfig, ) from .processing_owlvit import OwlViTProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_owlvit import OwlViTFeatureExtractor from .image_processing_owlvit import OwlViTImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_owlvit import ( OWLVIT_PRETRAINED_MODEL_ARCHIVE_LIST, OwlViTForObjectDetection, OwlViTModel, OwlViTPreTrainedModel, OwlViTTextModel, OwlViTVisionModel, ) else: import sys a_ : int = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
73
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available a_ : Optional[Any] = { 'configuration_mask2former': [ 'MASK2FORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'Mask2FormerConfig', ], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : Union[str, Any] = ['Mask2FormerImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : List[Any] = [ 'MASK2FORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'Mask2FormerForUniversalSegmentation', 'Mask2FormerModel', 'Mask2FormerPreTrainedModel', ] if TYPE_CHECKING: from .configuration_maskaformer import MASK2FORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, MaskaFormerConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_maskaformer import MaskaFormerImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_maskaformer import ( MASK2FORMER_PRETRAINED_MODEL_ARCHIVE_LIST, MaskaFormerForUniversalSegmentation, MaskaFormerModel, MaskaFormerPreTrainedModel, ) else: import sys a_ : str = _LazyModule(__name__, globals()['__file__'], _import_structure)
73
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available a_ : int = { 'configuration_rag': ['RagConfig'], 'retrieval_rag': ['RagRetriever'], 'tokenization_rag': ['RagTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : List[Any] = [ 'RagModel', 'RagPreTrainedModel', 'RagSequenceForGeneration', 'RagTokenForGeneration', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : Tuple = [ 'TFRagModel', 'TFRagPreTrainedModel', 'TFRagSequenceForGeneration', 'TFRagTokenForGeneration', ] if TYPE_CHECKING: from .configuration_rag import RagConfig from .retrieval_rag import RagRetriever from .tokenization_rag import RagTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_rag import RagModel, RagPreTrainedModel, RagSequenceForGeneration, RagTokenForGeneration try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_rag import ( TFRagModel, TFRagPreTrainedModel, TFRagSequenceForGeneration, TFRagTokenForGeneration, ) else: import sys a_ : Union[str, Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
73
from ...configuration_utils import PretrainedConfig from ...utils import logging a_ : Dict = logging.get_logger(__name__) a_ : Union[str, Any] = { 'edbeeching/decision-transformer-gym-hopper-medium': ( 'https://huggingface.co/edbeeching/decision-transformer-gym-hopper-medium/resolve/main/config.json' ), # See all DecisionTransformer models at https://huggingface.co/models?filter=decision_transformer } class _snake_case ( A__ ): _lowercase : Optional[Any] = '''decision_transformer''' _lowercase : str = ['''past_key_values'''] _lowercase : Union[str, Any] = { '''max_position_embeddings''': '''n_positions''', '''num_attention_heads''': '''n_head''', '''num_hidden_layers''': '''n_layer''', } def __init__( self , a=17 , a=4 , a=128 , a=4096 , a=True , a=1 , a=1024 , a=3 , a=1 , a=None , a="relu" , a=0.1 , a=0.1 , a=0.1 , a=1E-5 , a=0.02 , a=True , a=True , a=5_0256 , a=5_0256 , a=False , a=False , **a , ) -> List[str]: SCREAMING_SNAKE_CASE = state_dim SCREAMING_SNAKE_CASE = act_dim SCREAMING_SNAKE_CASE = hidden_size SCREAMING_SNAKE_CASE = max_ep_len SCREAMING_SNAKE_CASE = action_tanh SCREAMING_SNAKE_CASE = vocab_size SCREAMING_SNAKE_CASE = n_positions SCREAMING_SNAKE_CASE = n_layer SCREAMING_SNAKE_CASE = n_head SCREAMING_SNAKE_CASE = n_inner SCREAMING_SNAKE_CASE = activation_function SCREAMING_SNAKE_CASE = resid_pdrop SCREAMING_SNAKE_CASE = embd_pdrop SCREAMING_SNAKE_CASE = attn_pdrop SCREAMING_SNAKE_CASE = layer_norm_epsilon SCREAMING_SNAKE_CASE = initializer_range SCREAMING_SNAKE_CASE = scale_attn_weights SCREAMING_SNAKE_CASE = use_cache SCREAMING_SNAKE_CASE = scale_attn_by_inverse_layer_idx SCREAMING_SNAKE_CASE = reorder_and_upcast_attn SCREAMING_SNAKE_CASE = bos_token_id SCREAMING_SNAKE_CASE = eos_token_id super().__init__(bos_token_id=a , eos_token_id=a , **a)
73
1
# Author: OMKAR PATHAK, Nwachukwu Chidiebere # Use a Python dictionary to construct the graph. from __future__ import annotations from pprint import pformat from typing import Generic, TypeVar a_ : Tuple = TypeVar('T') class _snake_case ( Generic[T] ): def __init__( self , a = True) -> None: SCREAMING_SNAKE_CASE = {} # dictionary of lists SCREAMING_SNAKE_CASE = directed def SCREAMING_SNAKE_CASE__ ( self , a , a) -> GraphAdjacencyList[T]: if not self.directed: # For undirected graphs # if both source vertex and destination vertex are both present in the # adjacency list, add destination vertex to source vertex list of adjacent # vertices and add source vertex to destination vertex list of adjacent # vertices. if source_vertex in self.adj_list and destination_vertex in self.adj_list: self.adj_list[source_vertex].append(a) self.adj_list[destination_vertex].append(a) # if only source vertex is present in adjacency list, add destination vertex # to source vertex list of adjacent vertices, then create a new vertex with # destination vertex as key and assign a list containing the source vertex # as it's first adjacent vertex. elif source_vertex in self.adj_list: self.adj_list[source_vertex].append(a) SCREAMING_SNAKE_CASE = [source_vertex] # if only destination vertex is present in adjacency list, add source vertex # to destination vertex list of adjacent vertices, then create a new vertex # with source vertex as key and assign a list containing the source vertex # as it's first adjacent vertex. elif destination_vertex in self.adj_list: self.adj_list[destination_vertex].append(a) SCREAMING_SNAKE_CASE = [destination_vertex] # if both source vertex and destination vertex are not present in adjacency # list, create a new vertex with source vertex as key and assign a list # containing the destination vertex as it's first adjacent vertex also # create a new vertex with destination vertex as key and assign a list # containing the source vertex as it's first adjacent vertex. else: SCREAMING_SNAKE_CASE = [destination_vertex] SCREAMING_SNAKE_CASE = [source_vertex] else: # For directed graphs # if both source vertex and destination vertex are present in adjacency # list, add destination vertex to source vertex list of adjacent vertices. if source_vertex in self.adj_list and destination_vertex in self.adj_list: self.adj_list[source_vertex].append(a) # if only source vertex is present in adjacency list, add destination # vertex to source vertex list of adjacent vertices and create a new vertex # with destination vertex as key, which has no adjacent vertex elif source_vertex in self.adj_list: self.adj_list[source_vertex].append(a) SCREAMING_SNAKE_CASE = [] # if only destination vertex is present in adjacency list, create a new # vertex with source vertex as key and assign a list containing destination # vertex as first adjacent vertex elif destination_vertex in self.adj_list: SCREAMING_SNAKE_CASE = [destination_vertex] # if both source vertex and destination vertex are not present in adjacency # list, create a new vertex with source vertex as key and a list containing # destination vertex as it's first adjacent vertex. Then create a new vertex # with destination vertex as key, which has no adjacent vertex else: SCREAMING_SNAKE_CASE = [destination_vertex] SCREAMING_SNAKE_CASE = [] return self def __repr__( self) -> str: return pformat(self.adj_list)
73
import argparse import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType ######################################################################## # This is a fully working simple example to use Accelerate # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## a_ : Optional[int] = 16 a_ : Any = 32 def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase = 16): SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained('bert-base-cased') SCREAMING_SNAKE_CASE = load_dataset('glue' , 'mrpc') def tokenize_function(_UpperCAmelCase): # max_length=None => use the model max length (it's actually the default) SCREAMING_SNAKE_CASE = tokenizer(examples['sentence1'] , examples['sentence2'] , truncation=_UpperCAmelCase , max_length=_UpperCAmelCase) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): SCREAMING_SNAKE_CASE = datasets.map( _UpperCAmelCase , batched=_UpperCAmelCase , remove_columns=['idx', 'sentence1', 'sentence2'] , ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library SCREAMING_SNAKE_CASE = tokenized_datasets.rename_column('label' , 'labels') def collate_fn(_UpperCAmelCase): # On TPU it's best to pad everything to the same length or training will be very slow. SCREAMING_SNAKE_CASE = 128 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": SCREAMING_SNAKE_CASE = 16 elif accelerator.mixed_precision != "no": SCREAMING_SNAKE_CASE = 8 else: SCREAMING_SNAKE_CASE = None return tokenizer.pad( _UpperCAmelCase , padding='longest' , max_length=_UpperCAmelCase , pad_to_multiple_of=_UpperCAmelCase , return_tensors='pt' , ) # Instantiate dataloaders. SCREAMING_SNAKE_CASE = DataLoader( tokenized_datasets['train'] , shuffle=_UpperCAmelCase , collate_fn=_UpperCAmelCase , batch_size=_UpperCAmelCase , drop_last=_UpperCAmelCase) SCREAMING_SNAKE_CASE = DataLoader( tokenized_datasets['validation'] , shuffle=_UpperCAmelCase , collate_fn=_UpperCAmelCase , batch_size=_UpperCAmelCase , drop_last=(accelerator.mixed_precision == 'fp8') , ) return train_dataloader, eval_dataloader def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): # Initialize accelerator SCREAMING_SNAKE_CASE = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs SCREAMING_SNAKE_CASE = config['lr'] SCREAMING_SNAKE_CASE = int(config['num_epochs']) SCREAMING_SNAKE_CASE = int(config['seed']) SCREAMING_SNAKE_CASE = int(config['batch_size']) SCREAMING_SNAKE_CASE = evaluate.load('glue' , 'mrpc') # If the batch size is too big we use gradient accumulation SCREAMING_SNAKE_CASE = 1 if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU: SCREAMING_SNAKE_CASE = batch_size // MAX_GPU_BATCH_SIZE SCREAMING_SNAKE_CASE = MAX_GPU_BATCH_SIZE set_seed(_UpperCAmelCase) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = get_dataloaders(_UpperCAmelCase , _UpperCAmelCase) # Instantiate the model (we build the model here so that the seed also control new weights initialization) SCREAMING_SNAKE_CASE = AutoModelForSequenceClassification.from_pretrained('bert-base-cased' , return_dict=_UpperCAmelCase) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). SCREAMING_SNAKE_CASE = model.to(accelerator.device) # Instantiate optimizer SCREAMING_SNAKE_CASE = AdamW(params=model.parameters() , lr=_UpperCAmelCase) # Instantiate scheduler SCREAMING_SNAKE_CASE = get_linear_schedule_with_warmup( optimizer=_UpperCAmelCase , num_warmup_steps=100 , num_training_steps=(len(_UpperCAmelCase) * num_epochs) // gradient_accumulation_steps , ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = accelerator.prepare( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) # Now we train the model for epoch in range(_UpperCAmelCase): model.train() for step, batch in enumerate(_UpperCAmelCase): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device) SCREAMING_SNAKE_CASE = model(**_UpperCAmelCase) SCREAMING_SNAKE_CASE = outputs.loss SCREAMING_SNAKE_CASE = loss / gradient_accumulation_steps accelerator.backward(_UpperCAmelCase) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(_UpperCAmelCase): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device) with torch.no_grad(): SCREAMING_SNAKE_CASE = model(**_UpperCAmelCase) SCREAMING_SNAKE_CASE = outputs.logits.argmax(dim=-1) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = accelerator.gather_for_metrics((predictions, batch['labels'])) metric.add_batch( predictions=_UpperCAmelCase , references=_UpperCAmelCase , ) SCREAMING_SNAKE_CASE = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F'''epoch {epoch}:''' , _UpperCAmelCase) def lowerCamelCase__ (): SCREAMING_SNAKE_CASE = argparse.ArgumentParser(description='Simple example of training script.') parser.add_argument( '--mixed_precision' , type=_UpperCAmelCase , default=_UpperCAmelCase , choices=['no', 'fp16', 'bf16', 'fp8'] , help='Whether to use mixed precision. Choose' 'between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.' 'and an Nvidia Ampere GPU.' , ) parser.add_argument('--cpu' , action='store_true' , help='If passed, will train on the CPU.') SCREAMING_SNAKE_CASE = parser.parse_args() SCREAMING_SNAKE_CASE = {'lr': 2e-5, 'num_epochs': 3, 'seed': 42, 'batch_size': 16} training_function(_UpperCAmelCase , _UpperCAmelCase) if __name__ == "__main__": main()
73
1
import math def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): return math.pow(_UpperCAmelCase , 2) - a def lowerCamelCase__ (_UpperCAmelCase): return 2 * x def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = 2.0 while start <= a: SCREAMING_SNAKE_CASE = math.pow(_UpperCAmelCase , 2) return start def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase = 9999 , _UpperCAmelCase = 0.00_00_00_00_00_00_01): if a < 0: raise ValueError('math domain error') SCREAMING_SNAKE_CASE = get_initial_point(_UpperCAmelCase) for _ in range(_UpperCAmelCase): SCREAMING_SNAKE_CASE = value SCREAMING_SNAKE_CASE = value - fx(_UpperCAmelCase , _UpperCAmelCase) / fx_derivative(_UpperCAmelCase) if abs(prev_value - value) < tolerance: return value return value if __name__ == "__main__": from doctest import testmod testmod()
73
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available a_ : int = { 'configuration_rag': ['RagConfig'], 'retrieval_rag': ['RagRetriever'], 'tokenization_rag': ['RagTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : List[Any] = [ 'RagModel', 'RagPreTrainedModel', 'RagSequenceForGeneration', 'RagTokenForGeneration', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : Tuple = [ 'TFRagModel', 'TFRagPreTrainedModel', 'TFRagSequenceForGeneration', 'TFRagTokenForGeneration', ] if TYPE_CHECKING: from .configuration_rag import RagConfig from .retrieval_rag import RagRetriever from .tokenization_rag import RagTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_rag import RagModel, RagPreTrainedModel, RagSequenceForGeneration, RagTokenForGeneration try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_rag import ( TFRagModel, TFRagPreTrainedModel, TFRagSequenceForGeneration, TFRagTokenForGeneration, ) else: import sys a_ : Union[str, Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
73
1
from timeit import timeit a_ : str = { 'MALAYALAM': True, 'String': False, 'rotor': True, 'level': True, 'A': True, 'BB': True, 'ABC': False, 'amanaplanacanalpanama': True, # "a man a plan a canal panama" } # Ensure our test data is valid assert all((key == key[::-1]) is value for key, value in test_data.items()) def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = len(_UpperCAmelCase) - 1 while start_i < end_i: if s[start_i] == s[end_i]: start_i += 1 end_i -= 1 else: return False return True def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = len(_UpperCAmelCase) // 2 SCREAMING_SNAKE_CASE = len(_UpperCAmelCase) # We need to traverse till half of the length of string # as we can get access of the i'th last element from # i'th index. # eg: [0,1,2,3,4,5] => 4th index can be accessed # with the help of 1st index (i==n-i-1) # where n is length of string return all(s[i] == s[n - i - 1] for i in range(_UpperCAmelCase)) def lowerCamelCase__ (_UpperCAmelCase): if len(_UpperCAmelCase) <= 2: return True if s[0] == s[len(_UpperCAmelCase) - 1]: return is_palindrome_recursive(s[1:-1]) else: return False def lowerCamelCase__ (_UpperCAmelCase): return s == s[::-1] def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = F'''all({name}(key) is value for key, value in test_data.items())''' SCREAMING_SNAKE_CASE = F'''from __main__ import test_data, {name}''' SCREAMING_SNAKE_CASE = 50_0000 SCREAMING_SNAKE_CASE = timeit(stmt=_UpperCAmelCase , setup=_UpperCAmelCase , number=_UpperCAmelCase) print(F'''{name:<35} finished {number:,} runs in {result:.5f} seconds''') if __name__ == "__main__": for key, value in test_data.items(): assert is_palindrome(key) is is_palindrome_recursive(key) assert is_palindrome(key) is is_palindrome_slice(key) print(f"""{key:21} {value}""") print('a man a plan a canal panama') # finished 500,000 runs in 0.46793 seconds benchmark_function('is_palindrome_slice') # finished 500,000 runs in 0.85234 seconds benchmark_function('is_palindrome') # finished 500,000 runs in 1.32028 seconds benchmark_function('is_palindrome_recursive') # finished 500,000 runs in 2.08679 seconds benchmark_function('is_palindrome_traversal')
73
from __future__ import annotations from numpy import array, cos, cross, floataa, radians, sin from numpy.typing import NDArray def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase = False): if radian_mode: return [magnitude * cos(_UpperCAmelCase), magnitude * sin(_UpperCAmelCase)] return [magnitude * cos(radians(_UpperCAmelCase)), magnitude * sin(radians(_UpperCAmelCase))] def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase = 10**-1): SCREAMING_SNAKE_CASE = cross(_UpperCAmelCase , _UpperCAmelCase) SCREAMING_SNAKE_CASE = sum(_UpperCAmelCase) return abs(_UpperCAmelCase) < eps if __name__ == "__main__": # Test to check if it works a_ : int = array( [ polar_force(718.4, 1_80 - 30), polar_force(879.54, 45), polar_force(1_00, -90), ] ) a_ : NDArray[floataa] = array([[0, 0], [0, 0], [0, 0]]) assert in_static_equilibrium(forces, location) # Problem 1 in image_data/2D_problems.jpg a_ : Dict = array( [ polar_force(30 * 9.81, 15), polar_force(2_15, 1_80 - 45), polar_force(2_64, 90 - 30), ] ) a_ : Any = array([[0, 0], [0, 0], [0, 0]]) assert in_static_equilibrium(forces, location) # Problem in image_data/2D_problems_1.jpg a_ : int = array([[0, -20_00], [0, -12_00], [0, 1_56_00], [0, -1_24_00]]) a_ : Optional[Any] = array([[0, 0], [6, 0], [10, 0], [12, 0]]) assert in_static_equilibrium(forces, location) import doctest doctest.testmod()
73
1
import inspect import jax import jax.lax as lax import jax.numpy as jnp from ..utils import add_start_docstrings from ..utils.logging import get_logger a_ : Optional[Any] = get_logger(__name__) a_ : Dict = R'\n Args:\n input_ids (`jnp.ndarray` of shape `(batch_size, sequence_length)`):\n Indices of input sequence tokens in the vocabulary.\n\n Indices can be obtained using [`PreTrainedTokenizer`]. See [`PreTrainedTokenizer.encode`] and\n [`PreTrainedTokenizer.__call__`] for details.\n\n [What are input IDs?](../glossary#input-ids)\n scores (`jnp.ndarray` of shape `(batch_size, config.vocab_size)`):\n Prediction scores of a language modeling head. These can be logits for each vocabulary when not using beam\n search or log softmax for each vocabulary token when using beam search\n kwargs (`Dict[str, Any]`, *optional*):\n Additional logits processor specific kwargs.\n\n Return:\n `jnp.ndarray` of shape `(batch_size, config.vocab_size)`: The processed prediction scores.\n\n' class _snake_case : @add_start_docstrings(a) def __call__( self , a , a) -> jnp.ndarray: raise NotImplementedError( f'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.''') class _snake_case : @add_start_docstrings(a) def __call__( self , a , a) -> jnp.ndarray: raise NotImplementedError( f'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.''') class _snake_case ( A__ ): @add_start_docstrings(a) def __call__( self , a , a , a , **a) -> jnp.ndarray: for processor in self: SCREAMING_SNAKE_CASE = inspect.signature(processor.__call__).parameters if len(a) > 3: if not all(arg in kwargs for arg in list(function_args.keys())[2:]): raise ValueError( f'''Make sure that all the required parameters: {list(function_args.keys())} for ''' f'''{processor.__class__} are passed to the logits processor.''') SCREAMING_SNAKE_CASE = processor(a , a , a , **a) else: SCREAMING_SNAKE_CASE = processor(a , a , a) return scores class _snake_case ( A__ ): def __init__( self , a) -> List[str]: if not isinstance(a , a) or not (temperature > 0): raise ValueError(f'''`temperature` has to be a strictly positive float, but is {temperature}''') SCREAMING_SNAKE_CASE = temperature def __call__( self , a , a , a) -> jnp.ndarray: SCREAMING_SNAKE_CASE = scores / self.temperature return scores class _snake_case ( A__ ): def __init__( self , a , a = -float('Inf') , a = 1) -> Optional[Any]: if not isinstance(a , a) or (top_p < 0 or top_p > 1.0): raise ValueError(f'''`top_p` has to be a float > 0 and < 1, but is {top_p}''') if not isinstance(a , a) or (min_tokens_to_keep < 1): raise ValueError(f'''`min_tokens_to_keep` has to be a positive integer, but is {min_tokens_to_keep}''') SCREAMING_SNAKE_CASE = top_p SCREAMING_SNAKE_CASE = filter_value SCREAMING_SNAKE_CASE = min_tokens_to_keep def __call__( self , a , a , a) -> jnp.ndarray: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = lax.top_k(a , scores.shape[-1]) SCREAMING_SNAKE_CASE = jnp.full_like(a , self.filter_value) SCREAMING_SNAKE_CASE = jax.nn.softmax(a , axis=-1).cumsum(axis=-1) SCREAMING_SNAKE_CASE = cumulative_probs < self.top_p # include the token that is higher than top_p as well SCREAMING_SNAKE_CASE = jnp.roll(a , 1) score_mask |= score_mask.at[:, 0].set(a) # min tokens to keep SCREAMING_SNAKE_CASE = score_mask.at[:, : self.min_tokens_to_keep].set(a) SCREAMING_SNAKE_CASE = jnp.where(a , a , a) SCREAMING_SNAKE_CASE = jax.lax.sort_key_val(a , a)[-1] return next_scores class _snake_case ( A__ ): def __init__( self , a , a = -float('Inf') , a = 1) -> int: if not isinstance(a , a) or top_k <= 0: raise ValueError(f'''`top_k` has to be a strictly positive integer, but is {top_k}''') SCREAMING_SNAKE_CASE = max(a , a) SCREAMING_SNAKE_CASE = filter_value def __call__( self , a , a , a) -> jnp.ndarray: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = scores.shape SCREAMING_SNAKE_CASE = jnp.full(batch_size * vocab_size , self.filter_value) SCREAMING_SNAKE_CASE = min(self.top_k , scores.shape[-1]) # Safety check SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = lax.top_k(a , a) SCREAMING_SNAKE_CASE = jnp.broadcast_to((jnp.arange(a) * vocab_size)[:, None] , (batch_size, topk)).flatten() SCREAMING_SNAKE_CASE = topk_scores.flatten() SCREAMING_SNAKE_CASE = topk_indices.flatten() + shift SCREAMING_SNAKE_CASE = next_scores_flat.at[topk_indices_flat].set(a) SCREAMING_SNAKE_CASE = next_scores_flat.reshape(a , a) return next_scores class _snake_case ( A__ ): def __init__( self , a) -> Any: SCREAMING_SNAKE_CASE = bos_token_id def __call__( self , a , a , a) -> jnp.ndarray: SCREAMING_SNAKE_CASE = jnp.full(scores.shape , -float('inf')) SCREAMING_SNAKE_CASE = 1 - jnp.bool_(cur_len - 1) SCREAMING_SNAKE_CASE = jnp.where(a , new_scores.at[:, self.bos_token_id].set(0) , a) return scores class _snake_case ( A__ ): def __init__( self , a , a) -> int: SCREAMING_SNAKE_CASE = max_length SCREAMING_SNAKE_CASE = eos_token_id def __call__( self , a , a , a) -> jnp.ndarray: SCREAMING_SNAKE_CASE = jnp.full(scores.shape , -float('inf')) SCREAMING_SNAKE_CASE = 1 - jnp.bool_(cur_len - self.max_length + 1) SCREAMING_SNAKE_CASE = jnp.where(a , new_scores.at[:, self.eos_token_id].set(0) , a) return scores class _snake_case ( A__ ): def __init__( self , a , a) -> int: if not isinstance(a , a) or min_length < 0: raise ValueError(f'''`min_length` has to be a positive integer, but is {min_length}''') if not isinstance(a , a) or eos_token_id < 0: raise ValueError(f'''`eos_token_id` has to be a positive integer, but is {eos_token_id}''') SCREAMING_SNAKE_CASE = min_length SCREAMING_SNAKE_CASE = eos_token_id def __call__( self , a , a , a) -> jnp.ndarray: # create boolean flag to decide if min length penalty should be applied SCREAMING_SNAKE_CASE = 1 - jnp.clip(cur_len - self.min_length , 0 , 1) SCREAMING_SNAKE_CASE = jnp.where(a , scores.at[:, self.eos_token_id].set(-float('inf')) , a) return scores class _snake_case ( A__ ): def __init__( self , a , a) -> Any: SCREAMING_SNAKE_CASE = list(a) SCREAMING_SNAKE_CASE = begin_index def __call__( self , a , a , a) -> List[str]: SCREAMING_SNAKE_CASE = 1 - jnp.bool_(cur_len - self.begin_index) SCREAMING_SNAKE_CASE = jnp.where(a , scores.at[:, self.begin_suppress_tokens].set(-float('inf')) , a) return scores class _snake_case ( A__ ): def __init__( self , a) -> Any: SCREAMING_SNAKE_CASE = list(a) def __call__( self , a , a , a) -> jnp.ndarray: SCREAMING_SNAKE_CASE = scores.at[..., self.suppress_tokens].set(-float('inf')) return scores class _snake_case ( A__ ): def __init__( self , a) -> int: SCREAMING_SNAKE_CASE = dict(a) # Converts the dictionary of format {index: token} containing the tokens to be forced to an array, where the # index of the array corresponds to the index of the token to be forced, for XLA compatibility. # Indexes without forced tokens will have a negative value. SCREAMING_SNAKE_CASE = jnp.ones((max(force_token_map.keys()) + 1) , dtype=jnp.intaa) * -1 for index, token in force_token_map.items(): if token is not None: SCREAMING_SNAKE_CASE = force_token_array.at[index].set(a) SCREAMING_SNAKE_CASE = jnp.intaa(a) def __call__( self , a , a , a) -> jnp.ndarray: def _force_token(a): SCREAMING_SNAKE_CASE = scores.shape[0] SCREAMING_SNAKE_CASE = self.force_token_array[generation_idx] SCREAMING_SNAKE_CASE = jnp.ones_like(a , dtype=scores.dtype) * -float('inf') SCREAMING_SNAKE_CASE = jnp.zeros((batch_size, 1) , dtype=scores.dtype) SCREAMING_SNAKE_CASE = lax.dynamic_update_slice(a , a , (0, current_token)) return new_scores SCREAMING_SNAKE_CASE = lax.cond( cur_len >= self.force_token_array.shape[0] , lambda: scores , lambda: lax.cond( self.force_token_array[cur_len] >= 0 , lambda: _force_token(a) , lambda: scores , ) , ) return scores class _snake_case ( A__ ): def __init__( self , a , a , a) -> List[str]: SCREAMING_SNAKE_CASE = generate_config.eos_token_id SCREAMING_SNAKE_CASE = generate_config.no_timestamps_token_id SCREAMING_SNAKE_CASE = generate_config.no_timestamps_token_id + 1 SCREAMING_SNAKE_CASE = decoder_input_length + 1 if generate_config.is_multilingual: # room for language token and task token self.begin_index += 2 if hasattr(a , 'max_initial_timestamp_index'): SCREAMING_SNAKE_CASE = generate_config.max_initial_timestamp_index else: SCREAMING_SNAKE_CASE = model_config.vocab_size if self.max_initial_timestamp_index is None: SCREAMING_SNAKE_CASE = model_config.vocab_size def __call__( self , a , a , a) -> Tuple: # suppress <|notimestamps|> which is handled by without_timestamps SCREAMING_SNAKE_CASE = scores.at[:, self.no_timestamps_token_id].set(-float('inf')) def handle_pairs(a , a): SCREAMING_SNAKE_CASE = jnp.where((cur_len - self.begin_index) >= 1 , a , a) SCREAMING_SNAKE_CASE = jnp.where( input_ids_k[cur_len - 1] >= self.timestamp_begin , True and last_was_timestamp , a , ) SCREAMING_SNAKE_CASE = jnp.where((cur_len - self.begin_index) < 2 , a , a) SCREAMING_SNAKE_CASE = jnp.where( input_ids_k[cur_len - 2] >= self.timestamp_begin , a , a , ) return jnp.where( a , jnp.where( penultimate_was_timestamp > 0 , scores_k.at[self.timestamp_begin :].set(-float('inf')) , scores_k.at[: self.eos_token_id].set(-float('inf')) , ) , a , ) SCREAMING_SNAKE_CASE = jax.vmap(a)(a , a) SCREAMING_SNAKE_CASE = jnp.where(cur_len == self.begin_index , a , a) SCREAMING_SNAKE_CASE = jnp.where( self.max_initial_timestamp_index is not None , True and apply_max_initial_timestamp , a , ) SCREAMING_SNAKE_CASE = self.timestamp_begin + self.max_initial_timestamp_index SCREAMING_SNAKE_CASE = jnp.where( a , scores.at[:, last_allowed + 1 :].set(-float('inf')) , a , ) # if sum of probability over timestamps is above any other token, sample timestamp SCREAMING_SNAKE_CASE = jax.nn.log_softmax(a , axis=-1) def handle_cumulative_probs(a , a): SCREAMING_SNAKE_CASE = jax.nn.logsumexp(logprobs_k[self.timestamp_begin :] , axis=-1) SCREAMING_SNAKE_CASE = jnp.max(logprobs_k[: self.timestamp_begin]) return jnp.where( timestamp_logprob > max_text_token_logprob , scores_k.at[: self.timestamp_begin].set(-float('inf')) , a , ) SCREAMING_SNAKE_CASE = jax.vmap(a)(a , a) return scores
73
from ...configuration_utils import PretrainedConfig from ...utils import logging a_ : Optional[int] = logging.get_logger(__name__) a_ : int = { 'microsoft/cvt-13': 'https://huggingface.co/microsoft/cvt-13/resolve/main/config.json', # See all Cvt models at https://huggingface.co/models?filter=cvt } class _snake_case ( A__ ): _lowercase : Dict = '''cvt''' def __init__( self , a=3 , a=[7, 3, 3] , a=[4, 2, 2] , a=[2, 1, 1] , a=[64, 192, 384] , a=[1, 3, 6] , a=[1, 2, 10] , a=[4.0, 4.0, 4.0] , a=[0.0, 0.0, 0.0] , a=[0.0, 0.0, 0.0] , a=[0.0, 0.0, 0.1] , a=[True, True, True] , a=[False, False, True] , a=["dw_bn", "dw_bn", "dw_bn"] , a=[3, 3, 3] , a=[1, 1, 1] , a=[2, 2, 2] , a=[1, 1, 1] , a=[1, 1, 1] , a=0.02 , a=1E-12 , **a , ) -> List[Any]: super().__init__(**a) SCREAMING_SNAKE_CASE = num_channels SCREAMING_SNAKE_CASE = patch_sizes SCREAMING_SNAKE_CASE = patch_stride SCREAMING_SNAKE_CASE = patch_padding SCREAMING_SNAKE_CASE = embed_dim SCREAMING_SNAKE_CASE = num_heads SCREAMING_SNAKE_CASE = depth SCREAMING_SNAKE_CASE = mlp_ratio SCREAMING_SNAKE_CASE = attention_drop_rate SCREAMING_SNAKE_CASE = drop_rate SCREAMING_SNAKE_CASE = drop_path_rate SCREAMING_SNAKE_CASE = qkv_bias SCREAMING_SNAKE_CASE = cls_token SCREAMING_SNAKE_CASE = qkv_projection_method SCREAMING_SNAKE_CASE = kernel_qkv SCREAMING_SNAKE_CASE = padding_kv SCREAMING_SNAKE_CASE = stride_kv SCREAMING_SNAKE_CASE = padding_q SCREAMING_SNAKE_CASE = stride_q SCREAMING_SNAKE_CASE = initializer_range SCREAMING_SNAKE_CASE = layer_norm_eps
73
1
import unittest from transformers import XLMConfig, 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, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( XLMForMultipleChoice, XLMForQuestionAnswering, XLMForQuestionAnsweringSimple, XLMForSequenceClassification, XLMForTokenClassification, XLMModel, XLMWithLMHeadModel, ) from transformers.models.xlm.modeling_xlm import XLM_PRETRAINED_MODEL_ARCHIVE_LIST class _snake_case : def __init__( self , a , a=13 , a=7 , a=True , a=True , a=True , a=True , a=True , a=False , a=False , a=False , a=2 , a=99 , a=0 , a=32 , a=5 , a=4 , a=0.1 , a=0.1 , a=512 , a=2 , a=0.02 , a=2 , a=4 , a="last" , a=True , a=None , a=0 , ) -> Tuple: SCREAMING_SNAKE_CASE = parent SCREAMING_SNAKE_CASE = batch_size SCREAMING_SNAKE_CASE = seq_length SCREAMING_SNAKE_CASE = is_training SCREAMING_SNAKE_CASE = use_input_lengths SCREAMING_SNAKE_CASE = use_token_type_ids SCREAMING_SNAKE_CASE = use_labels SCREAMING_SNAKE_CASE = gelu_activation SCREAMING_SNAKE_CASE = sinusoidal_embeddings SCREAMING_SNAKE_CASE = causal SCREAMING_SNAKE_CASE = asm SCREAMING_SNAKE_CASE = n_langs SCREAMING_SNAKE_CASE = vocab_size SCREAMING_SNAKE_CASE = n_special SCREAMING_SNAKE_CASE = hidden_size SCREAMING_SNAKE_CASE = num_hidden_layers SCREAMING_SNAKE_CASE = num_attention_heads SCREAMING_SNAKE_CASE = hidden_dropout_prob SCREAMING_SNAKE_CASE = attention_probs_dropout_prob SCREAMING_SNAKE_CASE = max_position_embeddings SCREAMING_SNAKE_CASE = type_sequence_label_size SCREAMING_SNAKE_CASE = initializer_range SCREAMING_SNAKE_CASE = num_labels SCREAMING_SNAKE_CASE = num_choices SCREAMING_SNAKE_CASE = summary_type SCREAMING_SNAKE_CASE = use_proj SCREAMING_SNAKE_CASE = scope SCREAMING_SNAKE_CASE = bos_token_id def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size) SCREAMING_SNAKE_CASE = random_attention_mask([self.batch_size, self.seq_length]) SCREAMING_SNAKE_CASE = None if self.use_input_lengths: SCREAMING_SNAKE_CASE = ( ids_tensor([self.batch_size] , vocab_size=2) + self.seq_length - 2 ) # small variation of seq_length SCREAMING_SNAKE_CASE = None if self.use_token_type_ids: SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.n_langs) SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = None if self.use_labels: SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.type_sequence_label_size) SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.num_labels) SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , 2).float() SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.num_choices) SCREAMING_SNAKE_CASE = self.get_config() return ( config, input_ids, token_type_ids, input_lengths, sequence_labels, token_labels, is_impossible_labels, choice_labels, input_mask, ) def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: return XLMConfig( vocab_size=self.vocab_size , n_special=self.n_special , emb_dim=self.hidden_size , n_layers=self.num_hidden_layers , n_heads=self.num_attention_heads , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , gelu_activation=self.gelu_activation , sinusoidal_embeddings=self.sinusoidal_embeddings , asm=self.asm , causal=self.causal , n_langs=self.n_langs , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , summary_type=self.summary_type , use_proj=self.use_proj , num_labels=self.num_labels , bos_token_id=self.bos_token_id , ) def SCREAMING_SNAKE_CASE__ ( self , a , a , a , a , a , a , a , a , a , ) -> List[Any]: SCREAMING_SNAKE_CASE = XLMModel(config=a) model.to(a) model.eval() SCREAMING_SNAKE_CASE = model(a , lengths=a , langs=a) SCREAMING_SNAKE_CASE = model(a , langs=a) SCREAMING_SNAKE_CASE = model(a) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size)) def SCREAMING_SNAKE_CASE__ ( self , a , a , a , a , a , a , a , a , a , ) -> Optional[int]: SCREAMING_SNAKE_CASE = XLMWithLMHeadModel(a) model.to(a) model.eval() SCREAMING_SNAKE_CASE = model(a , token_type_ids=a , labels=a) self.parent.assertEqual(result.loss.shape , ()) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size)) def SCREAMING_SNAKE_CASE__ ( self , a , a , a , a , a , a , a , a , a , ) -> str: SCREAMING_SNAKE_CASE = XLMForQuestionAnsweringSimple(a) model.to(a) model.eval() SCREAMING_SNAKE_CASE = model(a) SCREAMING_SNAKE_CASE = model(a , start_positions=a , end_positions=a) SCREAMING_SNAKE_CASE = outputs 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 SCREAMING_SNAKE_CASE__ ( self , a , a , a , a , a , a , a , a , a , ) -> Tuple: SCREAMING_SNAKE_CASE = XLMForQuestionAnswering(a) model.to(a) model.eval() SCREAMING_SNAKE_CASE = model(a) SCREAMING_SNAKE_CASE = model( a , start_positions=a , end_positions=a , cls_index=a , is_impossible=a , p_mask=a , ) SCREAMING_SNAKE_CASE = model( a , start_positions=a , end_positions=a , cls_index=a , is_impossible=a , ) ((SCREAMING_SNAKE_CASE) , ) = result_with_labels.to_tuple() SCREAMING_SNAKE_CASE = model(a , start_positions=a , end_positions=a) ((SCREAMING_SNAKE_CASE) , ) = result_with_labels.to_tuple() self.parent.assertEqual(result_with_labels.loss.shape , ()) self.parent.assertEqual(result.start_top_log_probs.shape , (self.batch_size, model.config.start_n_top)) self.parent.assertEqual(result.start_top_index.shape , (self.batch_size, model.config.start_n_top)) self.parent.assertEqual( result.end_top_log_probs.shape , (self.batch_size, model.config.start_n_top * model.config.end_n_top)) self.parent.assertEqual( result.end_top_index.shape , (self.batch_size, model.config.start_n_top * model.config.end_n_top)) self.parent.assertEqual(result.cls_logits.shape , (self.batch_size,)) def SCREAMING_SNAKE_CASE__ ( self , a , a , a , a , a , a , a , a , a , ) -> Dict: SCREAMING_SNAKE_CASE = XLMForSequenceClassification(a) model.to(a) model.eval() SCREAMING_SNAKE_CASE = model(a) SCREAMING_SNAKE_CASE = model(a , labels=a) self.parent.assertEqual(result.loss.shape , ()) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size)) def SCREAMING_SNAKE_CASE__ ( self , a , a , a , a , a , a , a , a , a , ) -> int: SCREAMING_SNAKE_CASE = self.num_labels SCREAMING_SNAKE_CASE = XLMForTokenClassification(a) model.to(a) model.eval() SCREAMING_SNAKE_CASE = model(a , attention_mask=a , labels=a) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels)) def SCREAMING_SNAKE_CASE__ ( self , a , a , a , a , a , a , a , a , a , ) -> Optional[int]: SCREAMING_SNAKE_CASE = self.num_choices SCREAMING_SNAKE_CASE = XLMForMultipleChoice(config=a) model.to(a) model.eval() SCREAMING_SNAKE_CASE = input_ids.unsqueeze(1).expand(-1 , self.num_choices , -1).contiguous() SCREAMING_SNAKE_CASE = token_type_ids.unsqueeze(1).expand(-1 , self.num_choices , -1).contiguous() SCREAMING_SNAKE_CASE = input_mask.unsqueeze(1).expand(-1 , self.num_choices , -1).contiguous() SCREAMING_SNAKE_CASE = model( a , attention_mask=a , token_type_ids=a , labels=a , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices)) def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: SCREAMING_SNAKE_CASE = self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ) = config_and_inputs SCREAMING_SNAKE_CASE = {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'lengths': input_lengths} return config, inputs_dict @require_torch class _snake_case ( A__ , A__ , A__ , unittest.TestCase ): _lowercase : Optional[int] = ( ( XLMModel, XLMWithLMHeadModel, XLMForQuestionAnswering, XLMForSequenceClassification, XLMForQuestionAnsweringSimple, XLMForTokenClassification, XLMForMultipleChoice, ) if is_torch_available() else () ) _lowercase : Union[str, Any] = ( (XLMWithLMHeadModel,) if is_torch_available() else () ) # TODO (PVP): Check other models whether language generation is also applicable _lowercase : List[Any] = ( { '''feature-extraction''': XLMModel, '''fill-mask''': XLMWithLMHeadModel, '''question-answering''': XLMForQuestionAnsweringSimple, '''text-classification''': XLMForSequenceClassification, '''text-generation''': XLMWithLMHeadModel, '''token-classification''': XLMForTokenClassification, '''zero-shot''': XLMForSequenceClassification, } if is_torch_available() else {} ) def SCREAMING_SNAKE_CASE__ ( self , a , a , a , a , a) -> int: if ( pipeline_test_casse_name == "QAPipelineTests" and tokenizer_name is not None and not tokenizer_name.endswith('Fast') ): # `QAPipelineTests` fails for a few models when the slower tokenizer are used. # (The slower tokenizers were never used for pipeline tests before the pipeline testing rework) # TODO: check (and possibly fix) the `QAPipelineTests` with slower tokenizer return True return False def SCREAMING_SNAKE_CASE__ ( self , a , a , a=False) -> List[Any]: SCREAMING_SNAKE_CASE = super()._prepare_for_class(a , a , return_labels=a) if return_labels: if model_class.__name__ == "XLMForQuestionAnswering": SCREAMING_SNAKE_CASE = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=a) SCREAMING_SNAKE_CASE = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=a) return inputs_dict def SCREAMING_SNAKE_CASE__ ( self) -> str: SCREAMING_SNAKE_CASE = XLMModelTester(self) SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=a , emb_dim=37) def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_model(*a) def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_lm_head(*a) def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_simple_qa(*a) def SCREAMING_SNAKE_CASE__ ( self) -> Dict: SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_qa(*a) def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_sequence_classif(*a) def SCREAMING_SNAKE_CASE__ ( self) -> str: SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_token_classif(*a) def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_for_multiple_choice(*a) def SCREAMING_SNAKE_CASE__ ( self , a , a , a , a , a , a=False , a=1) -> List[str]: self.assertIsInstance(a , a) self.assertListEqual( [isinstance(a , a) for iter_attentions in attentions] , [True] * len(a)) self.assertEqual(len(a) , (max_length - min_length) * num_beam_groups) for idx, iter_attentions in enumerate(a): # adds PAD dummy token SCREAMING_SNAKE_CASE = min_length + idx + 1 SCREAMING_SNAKE_CASE = min_length + idx + 1 SCREAMING_SNAKE_CASE = ( batch_size * num_beam_groups, config.num_attention_heads, tgt_len, src_len, ) # check attn size self.assertListEqual( [layer_attention.shape for layer_attention in iter_attentions] , [expected_shape] * len(a)) def SCREAMING_SNAKE_CASE__ ( self , a , a , a , a , a , a=False , a=1) -> Dict: self.assertIsInstance(a , a) self.assertListEqual( [isinstance(a , a) for iter_hidden_states in hidden_states] , [True] * len(a) , ) self.assertEqual(len(a) , (max_length - min_length) * num_beam_groups) for idx, iter_hidden_states in enumerate(a): # adds PAD dummy token SCREAMING_SNAKE_CASE = min_length + idx + 1 SCREAMING_SNAKE_CASE = (batch_size * num_beam_groups, seq_len, config.hidden_size) # check hidden size self.assertListEqual( [layer_hidden_states.shape for layer_hidden_states in iter_hidden_states] , [expected_shape] * len(a) , ) pass @slow def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: for model_name in XLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE = XLMModel.from_pretrained(a) self.assertIsNotNone(a) @require_torch class _snake_case ( unittest.TestCase ): @slow def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: SCREAMING_SNAKE_CASE = XLMWithLMHeadModel.from_pretrained('xlm-mlm-en-2048') model.to(a) SCREAMING_SNAKE_CASE = torch.tensor([[14, 447]] , dtype=torch.long , device=a) # the president SCREAMING_SNAKE_CASE = [ 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, ] # the president the president the president the president the president the president the president the president the president the president # TODO(PVP): this and other input_ids I tried for generation give pretty bad results. Not sure why. Model might just not be made for auto-regressive inference SCREAMING_SNAKE_CASE = model.generate(a , do_sample=a) self.assertListEqual(output_ids[0].cpu().numpy().tolist() , a)
73
def lowerCamelCase__ (_UpperCAmelCase = 10 , _UpperCAmelCase = 1000 , _UpperCAmelCase = True): assert ( isinstance(_UpperCAmelCase , _UpperCAmelCase) and isinstance(_UpperCAmelCase , _UpperCAmelCase) and isinstance(_UpperCAmelCase , _UpperCAmelCase) ), "Invalid type of value(s) specified to function!" if min_val > max_val: raise ValueError('Invalid value for min_val or max_val (min_value < max_value)') return min_val if option else max_val def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): return int((number_a + number_a) / 2) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): assert ( isinstance(_UpperCAmelCase , _UpperCAmelCase) and isinstance(_UpperCAmelCase , _UpperCAmelCase) and isinstance(_UpperCAmelCase , _UpperCAmelCase) ), 'argument values must be type of "int"' if lower > higher: raise ValueError('argument value for lower and higher must be(lower > higher)') if not lower < to_guess < higher: raise ValueError( 'guess value must be within the range of lower and higher value') def answer(_UpperCAmelCase) -> str: if number > to_guess: return "high" elif number < to_guess: return "low" else: return "same" print('started...') SCREAMING_SNAKE_CASE = lower SCREAMING_SNAKE_CASE = higher SCREAMING_SNAKE_CASE = [] while True: SCREAMING_SNAKE_CASE = get_avg(_UpperCAmelCase , _UpperCAmelCase) last_numbers.append(_UpperCAmelCase) if answer(_UpperCAmelCase) == "low": SCREAMING_SNAKE_CASE = number elif answer(_UpperCAmelCase) == "high": SCREAMING_SNAKE_CASE = number else: break print(F'''guess the number : {last_numbers[-1]}''') print(F'''details : {last_numbers!s}''') def lowerCamelCase__ (): SCREAMING_SNAKE_CASE = int(input('Enter lower value : ').strip()) SCREAMING_SNAKE_CASE = int(input('Enter high value : ').strip()) SCREAMING_SNAKE_CASE = int(input('Enter value to guess : ').strip()) guess_the_number(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) if __name__ == "__main__": main()
73
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) a_ : List[Any] = { 'configuration_wav2vec2': ['WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP', 'Wav2Vec2Config'], 'feature_extraction_wav2vec2': ['Wav2Vec2FeatureExtractor'], 'processing_wav2vec2': ['Wav2Vec2Processor'], 'tokenization_wav2vec2': ['Wav2Vec2CTCTokenizer', 'Wav2Vec2Tokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : str = [ 'WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST', 'Wav2Vec2ForAudioFrameClassification', 'Wav2Vec2ForCTC', 'Wav2Vec2ForMaskedLM', 'Wav2Vec2ForPreTraining', 'Wav2Vec2ForSequenceClassification', 'Wav2Vec2ForXVector', 'Wav2Vec2Model', 'Wav2Vec2PreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : List[str] = [ 'TF_WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFWav2Vec2ForCTC', 'TFWav2Vec2Model', 'TFWav2Vec2PreTrainedModel', 'TFWav2Vec2ForSequenceClassification', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : Optional[Any] = [ 'FlaxWav2Vec2ForCTC', 'FlaxWav2Vec2ForPreTraining', 'FlaxWav2Vec2Model', 'FlaxWav2Vec2PreTrainedModel', ] if TYPE_CHECKING: from .configuration_wavaveca import WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP, WavaVecaConfig from .feature_extraction_wavaveca import WavaVecaFeatureExtractor from .processing_wavaveca import WavaVecaProcessor from .tokenization_wavaveca import WavaVecaCTCTokenizer, WavaVecaTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_wavaveca import ( WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST, WavaVecaForAudioFrameClassification, WavaVecaForCTC, WavaVecaForMaskedLM, WavaVecaForPreTraining, WavaVecaForSequenceClassification, WavaVecaForXVector, WavaVecaModel, WavaVecaPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_wavaveca import ( TF_WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST, TFWavaVecaForCTC, TFWavaVecaForSequenceClassification, TFWavaVecaModel, TFWavaVecaPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_wavaveca import ( FlaxWavaVecaForCTC, FlaxWavaVecaForPreTraining, FlaxWavaVecaModel, FlaxWavaVecaPreTrainedModel, ) else: import sys a_ : str = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
73
import unittest from parameterized import parameterized from transformers import OpenLlamaConfig, is_torch_available, set_seed from transformers.testing_utils import require_torch, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import OpenLlamaForCausalLM, OpenLlamaForSequenceClassification, OpenLlamaModel class _snake_case : def __init__( self , a , a=13 , a=7 , a=True , a=True , a=False , a=True , a=99 , a=32 , a=5 , a=4 , a=37 , a="gelu" , a=0.1 , a=0.1 , a=512 , a=16 , a=2 , a=0.02 , a=3 , a=4 , a=None , ) -> Union[str, Any]: SCREAMING_SNAKE_CASE = parent SCREAMING_SNAKE_CASE = batch_size SCREAMING_SNAKE_CASE = seq_length SCREAMING_SNAKE_CASE = is_training SCREAMING_SNAKE_CASE = use_input_mask SCREAMING_SNAKE_CASE = use_token_type_ids SCREAMING_SNAKE_CASE = use_labels SCREAMING_SNAKE_CASE = vocab_size SCREAMING_SNAKE_CASE = hidden_size SCREAMING_SNAKE_CASE = num_hidden_layers SCREAMING_SNAKE_CASE = num_attention_heads SCREAMING_SNAKE_CASE = intermediate_size SCREAMING_SNAKE_CASE = hidden_act SCREAMING_SNAKE_CASE = hidden_dropout_prob SCREAMING_SNAKE_CASE = attention_probs_dropout_prob SCREAMING_SNAKE_CASE = max_position_embeddings SCREAMING_SNAKE_CASE = type_vocab_size SCREAMING_SNAKE_CASE = type_sequence_label_size SCREAMING_SNAKE_CASE = initializer_range SCREAMING_SNAKE_CASE = num_labels SCREAMING_SNAKE_CASE = num_choices SCREAMING_SNAKE_CASE = scope def SCREAMING_SNAKE_CASE__ ( self) -> Dict: SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size) SCREAMING_SNAKE_CASE = None if self.use_input_mask: SCREAMING_SNAKE_CASE = random_attention_mask([self.batch_size, self.seq_length]) SCREAMING_SNAKE_CASE = None if self.use_token_type_ids: SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size) SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = None if self.use_labels: SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.type_sequence_label_size) SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.num_labels) SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.num_choices) SCREAMING_SNAKE_CASE = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: return OpenLlamaConfig( 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 , is_decoder=a , initializer_range=self.initializer_range , use_stable_embedding=a , ) def SCREAMING_SNAKE_CASE__ ( self , a , a , a , a , a , a , a) -> Any: SCREAMING_SNAKE_CASE = OpenLlamaModel(config=a) model.to(a) model.eval() SCREAMING_SNAKE_CASE = model(a , attention_mask=a) SCREAMING_SNAKE_CASE = model(a) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size)) def SCREAMING_SNAKE_CASE__ ( self , a , a , a , a , a , a , a , a , a , ) -> str: SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = OpenLlamaModel(a) model.to(a) model.eval() SCREAMING_SNAKE_CASE = model( a , attention_mask=a , encoder_hidden_states=a , encoder_attention_mask=a , ) SCREAMING_SNAKE_CASE = model( a , attention_mask=a , encoder_hidden_states=a , ) SCREAMING_SNAKE_CASE = model(a , attention_mask=a) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size)) def SCREAMING_SNAKE_CASE__ ( self , a , a , a , a , a , a , a , a , a , ) -> int: SCREAMING_SNAKE_CASE = OpenLlamaForCausalLM(config=a) model.to(a) model.eval() SCREAMING_SNAKE_CASE = model(a , attention_mask=a , labels=a) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size)) def SCREAMING_SNAKE_CASE__ ( self , a , a , a , a , a , a , a , a , a , ) -> str: SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = OpenLlamaForCausalLM(config=a) model.to(a) model.eval() # first forward pass SCREAMING_SNAKE_CASE = model( a , attention_mask=a , encoder_hidden_states=a , encoder_attention_mask=a , use_cache=a , ) SCREAMING_SNAKE_CASE = outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids SCREAMING_SNAKE_CASE = ids_tensor((self.batch_size, 3) , config.vocab_size) SCREAMING_SNAKE_CASE = ids_tensor((self.batch_size, 3) , vocab_size=2) # append to next input_ids and SCREAMING_SNAKE_CASE = torch.cat([input_ids, next_tokens] , dim=-1) SCREAMING_SNAKE_CASE = torch.cat([input_mask, next_mask] , dim=-1) SCREAMING_SNAKE_CASE = model( a , attention_mask=a , encoder_hidden_states=a , encoder_attention_mask=a , output_hidden_states=a , )['hidden_states'][0] SCREAMING_SNAKE_CASE = model( a , attention_mask=a , encoder_hidden_states=a , encoder_attention_mask=a , past_key_values=a , output_hidden_states=a , )['hidden_states'][0] # select random slice SCREAMING_SNAKE_CASE = ids_tensor((1,) , output_from_past.shape[-1]).item() SCREAMING_SNAKE_CASE = output_from_no_past[:, -3:, random_slice_idx].detach() SCREAMING_SNAKE_CASE = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1]) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(a , a , atol=1E-3)) def SCREAMING_SNAKE_CASE__ ( self) -> str: SCREAMING_SNAKE_CASE = self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ) = config_and_inputs SCREAMING_SNAKE_CASE = {'input_ids': input_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class _snake_case ( A__ , A__ , A__ , unittest.TestCase ): _lowercase : List[Any] = ( (OpenLlamaModel, OpenLlamaForCausalLM, OpenLlamaForSequenceClassification) if is_torch_available() else () ) _lowercase : str = (OpenLlamaForCausalLM,) if is_torch_available() else () _lowercase : List[str] = ( { '''feature-extraction''': OpenLlamaModel, '''text-classification''': OpenLlamaForSequenceClassification, '''text-generation''': OpenLlamaForCausalLM, '''zero-shot''': OpenLlamaForSequenceClassification, } if is_torch_available() else {} ) _lowercase : List[str] = False _lowercase : Optional[int] = False def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: SCREAMING_SNAKE_CASE = OpenLlamaModelTester(self) SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=a , hidden_size=37) def SCREAMING_SNAKE_CASE__ ( self) -> str: self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE__ ( self) -> Any: SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a) def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: SCREAMING_SNAKE_CASE = type self.model_tester.create_and_check_model(*a) def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE = 3 SCREAMING_SNAKE_CASE = input_dict['input_ids'] SCREAMING_SNAKE_CASE = input_ids.ne(1).to(a) SCREAMING_SNAKE_CASE = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size) SCREAMING_SNAKE_CASE = OpenLlamaForSequenceClassification(a) model.to(a) model.eval() SCREAMING_SNAKE_CASE = model(a , attention_mask=a , labels=a) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels)) def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE = 3 SCREAMING_SNAKE_CASE = 'single_label_classification' SCREAMING_SNAKE_CASE = input_dict['input_ids'] SCREAMING_SNAKE_CASE = input_ids.ne(1).to(a) SCREAMING_SNAKE_CASE = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size) SCREAMING_SNAKE_CASE = OpenLlamaForSequenceClassification(a) model.to(a) model.eval() SCREAMING_SNAKE_CASE = model(a , attention_mask=a , labels=a) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels)) def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE = 3 SCREAMING_SNAKE_CASE = 'multi_label_classification' SCREAMING_SNAKE_CASE = input_dict['input_ids'] SCREAMING_SNAKE_CASE = input_ids.ne(1).to(a) SCREAMING_SNAKE_CASE = ids_tensor( [self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size).to(torch.float) SCREAMING_SNAKE_CASE = OpenLlamaForSequenceClassification(a) model.to(a) model.eval() SCREAMING_SNAKE_CASE = model(a , attention_mask=a , labels=a) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels)) @unittest.skip('Open-Llama buffers include complex numbers, which breaks this test') def SCREAMING_SNAKE_CASE__ ( self) -> Any: pass @parameterized.expand([('linear',), ('dynamic',)]) def SCREAMING_SNAKE_CASE__ ( self , a) -> Dict: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE = ids_tensor([1, 10] , config.vocab_size) SCREAMING_SNAKE_CASE = ids_tensor([1, int(config.max_position_embeddings * 1.5)] , config.vocab_size) set_seed(42) # Fixed seed at init time so the two models get the same random weights SCREAMING_SNAKE_CASE = OpenLlamaModel(a) original_model.to(a) original_model.eval() SCREAMING_SNAKE_CASE = original_model(a).last_hidden_state SCREAMING_SNAKE_CASE = original_model(a).last_hidden_state set_seed(42) # Fixed seed at init time so the two models get the same random weights SCREAMING_SNAKE_CASE = {'type': scaling_type, 'factor': 10.0} SCREAMING_SNAKE_CASE = OpenLlamaModel(a) scaled_model.to(a) scaled_model.eval() SCREAMING_SNAKE_CASE = scaled_model(a).last_hidden_state SCREAMING_SNAKE_CASE = scaled_model(a).last_hidden_state # Dynamic scaling does not change the RoPE embeddings until it receives an input longer than the original # maximum sequence length, so the outputs for the short input should match. if scaling_type == "dynamic": self.assertTrue(torch.allclose(a , a , atol=1E-5)) else: self.assertFalse(torch.allclose(a , a , atol=1E-5)) # The output should be different for long inputs self.assertFalse(torch.allclose(a , a , atol=1E-5))
73
1
from collections import defaultdict from typing import Optional from ..image_utils import load_image from ..utils import ( add_end_docstrings, is_torch_available, logging, requires_backends, ) from .base import PIPELINE_INIT_ARGS, ChunkPipeline if is_torch_available(): import torch from ..models.auto.modeling_auto import MODEL_FOR_MASK_GENERATION_MAPPING a_ : int = logging.get_logger(__name__) @add_end_docstrings(A__ ) class _snake_case ( A__ ): def __init__( self , **a) -> Dict: super().__init__(**a) requires_backends(self , 'vision') requires_backends(self , 'torch') if self.framework != "pt": raise ValueError(f'''The {self.__class__} is only available in PyTorch.''') self.check_model_type(a) def SCREAMING_SNAKE_CASE__ ( self , **a) -> Tuple: SCREAMING_SNAKE_CASE = {} SCREAMING_SNAKE_CASE = {} SCREAMING_SNAKE_CASE = {} # preprocess args if "points_per_batch" in kwargs: SCREAMING_SNAKE_CASE = kwargs['points_per_batch'] if "points_per_crop" in kwargs: SCREAMING_SNAKE_CASE = kwargs['points_per_crop'] if "crops_n_layers" in kwargs: SCREAMING_SNAKE_CASE = kwargs['crops_n_layers'] if "crop_overlap_ratio" in kwargs: SCREAMING_SNAKE_CASE = kwargs['crop_overlap_ratio'] if "crop_n_points_downscale_factor" in kwargs: SCREAMING_SNAKE_CASE = kwargs['crop_n_points_downscale_factor'] # postprocess args if "pred_iou_thresh" in kwargs: SCREAMING_SNAKE_CASE = kwargs['pred_iou_thresh'] if "stability_score_offset" in kwargs: SCREAMING_SNAKE_CASE = kwargs['stability_score_offset'] if "mask_threshold" in kwargs: SCREAMING_SNAKE_CASE = kwargs['mask_threshold'] if "stability_score_thresh" in kwargs: SCREAMING_SNAKE_CASE = kwargs['stability_score_thresh'] if "crops_nms_thresh" in kwargs: SCREAMING_SNAKE_CASE = kwargs['crops_nms_thresh'] if "output_rle_mask" in kwargs: SCREAMING_SNAKE_CASE = kwargs['output_rle_mask'] if "output_bboxes_mask" in kwargs: SCREAMING_SNAKE_CASE = kwargs['output_bboxes_mask'] return preprocess_kwargs, forward_params, postprocess_kwargs def __call__( self , a , *a , a=None , a=None , **a) -> List[str]: return super().__call__(a , *a , num_workers=a , batch_size=a , **a) def SCREAMING_SNAKE_CASE__ ( self , a , a=64 , a = 0 , a = 512 / 1500 , a = 32 , a = 1 , ) -> List[Any]: SCREAMING_SNAKE_CASE = load_image(a) SCREAMING_SNAKE_CASE = self.image_processor.size['longest_edge'] SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.image_processor.generate_crop_boxes( a , a , a , a , a , a) SCREAMING_SNAKE_CASE = self.image_processor(images=a , return_tensors='pt') with self.device_placement(): if self.framework == "pt": SCREAMING_SNAKE_CASE = self.get_inference_context() with inference_context(): SCREAMING_SNAKE_CASE = self._ensure_tensor_on_device(a , device=self.device) SCREAMING_SNAKE_CASE = self.model.get_image_embeddings(model_inputs.pop('pixel_values')) SCREAMING_SNAKE_CASE = image_embeddings SCREAMING_SNAKE_CASE = grid_points.shape[1] SCREAMING_SNAKE_CASE = points_per_batch if points_per_batch is not None else n_points if points_per_batch <= 0: raise ValueError( 'Cannot have points_per_batch<=0. Must be >=1 to returned batched outputs. ' 'To return all points at once, set points_per_batch to None') for i in range(0 , a , a): SCREAMING_SNAKE_CASE = grid_points[:, i : i + points_per_batch, :, :] SCREAMING_SNAKE_CASE = input_labels[:, i : i + points_per_batch] SCREAMING_SNAKE_CASE = i == n_points - points_per_batch yield { "input_points": batched_points, "input_labels": labels, "input_boxes": crop_boxes, "is_last": is_last, **model_inputs, } def SCREAMING_SNAKE_CASE__ ( self , a , a=0.88 , a=0.95 , a=0 , a=1 , ) -> Tuple: SCREAMING_SNAKE_CASE = model_inputs.pop('input_boxes') SCREAMING_SNAKE_CASE = model_inputs.pop('is_last') SCREAMING_SNAKE_CASE = model_inputs.pop('original_sizes').tolist() SCREAMING_SNAKE_CASE = model_inputs.pop('reshaped_input_sizes').tolist() SCREAMING_SNAKE_CASE = self.model(**a) # post processing happens here in order to avoid CPU GPU copies of ALL the masks SCREAMING_SNAKE_CASE = model_outputs['pred_masks'] SCREAMING_SNAKE_CASE = self.image_processor.post_process_masks( a , a , a , a , binarize=a) SCREAMING_SNAKE_CASE = model_outputs['iou_scores'] SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.image_processor.filter_masks( masks[0] , iou_scores[0] , original_sizes[0] , input_boxes[0] , a , a , a , a , ) return { "masks": masks, "is_last": is_last, "boxes": boxes, "iou_scores": iou_scores, } def SCREAMING_SNAKE_CASE__ ( self , a , a=False , a=False , a=0.7 , ) -> Union[str, Any]: SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = [] for model_output in model_outputs: all_scores.append(model_output.pop('iou_scores')) all_masks.extend(model_output.pop('masks')) all_boxes.append(model_output.pop('boxes')) SCREAMING_SNAKE_CASE = torch.cat(a) SCREAMING_SNAKE_CASE = torch.cat(a) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.image_processor.post_process_for_mask_generation( a , a , a , a) SCREAMING_SNAKE_CASE = defaultdict(a) for output in model_outputs: for k, v in output.items(): extra[k].append(a) SCREAMING_SNAKE_CASE = {} if output_rle_mask: SCREAMING_SNAKE_CASE = rle_mask if output_bboxes_mask: SCREAMING_SNAKE_CASE = bounding_boxes return {"masks": output_masks, "scores": iou_scores, **optional, **extra}
73
from __future__ import annotations a_ : str = [] def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): for i in range(len(_UpperCAmelCase)): if board[row][i] == 1: return False for i in range(len(_UpperCAmelCase)): if board[i][column] == 1: return False for i, j in zip(range(_UpperCAmelCase , -1 , -1) , range(_UpperCAmelCase , -1 , -1)): if board[i][j] == 1: return False for i, j in zip(range(_UpperCAmelCase , -1 , -1) , range(_UpperCAmelCase , len(_UpperCAmelCase))): if board[i][j] == 1: return False return True def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): if row >= len(_UpperCAmelCase): solution.append(_UpperCAmelCase) printboard(_UpperCAmelCase) print() return True for i in range(len(_UpperCAmelCase)): if is_safe(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = 1 solve(_UpperCAmelCase , row + 1) SCREAMING_SNAKE_CASE = 0 return False def lowerCamelCase__ (_UpperCAmelCase): for i in range(len(_UpperCAmelCase)): for j in range(len(_UpperCAmelCase)): if board[i][j] == 1: print('Q' , end=' ') else: print('.' , end=' ') print() # n=int(input("The no. of queens")) a_ : Tuple = 8 a_ : int = [[0 for i in range(n)] for j in range(n)] solve(board, 0) print('The total no. of solutions are :', len(solution))
73
1
def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = [0] * len(_UpperCAmelCase) SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = [1] * len(_UpperCAmelCase) for values in graph.values(): for i in values: indegree[i] += 1 for i in range(len(_UpperCAmelCase)): if indegree[i] == 0: queue.append(_UpperCAmelCase) while queue: SCREAMING_SNAKE_CASE = queue.pop(0) for x in graph[vertex]: indegree[x] -= 1 if long_dist[vertex] + 1 > long_dist[x]: SCREAMING_SNAKE_CASE = long_dist[vertex] + 1 if indegree[x] == 0: queue.append(_UpperCAmelCase) print(max(_UpperCAmelCase)) # Adjacency list of Graph a_ : Dict = {0: [2, 3, 4], 1: [2, 7], 2: [5], 3: [5, 7], 4: [7], 5: [6], 6: [7], 7: []} longest_distance(graph)
73
import gc import random import tempfile import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMInverseScheduler, DDIMScheduler, DPMSolverMultistepInverseScheduler, DPMSolverMultistepScheduler, StableDiffusionDiffEditPipeline, UNetaDConditionModel, ) from diffusers.utils import load_image, slow from diffusers.utils.testing_utils import enable_full_determinism, floats_tensor, require_torch_gpu, torch_device from ..pipeline_params import TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class _snake_case ( A__ , A__ , unittest.TestCase ): _lowercase : List[Any] = StableDiffusionDiffEditPipeline _lowercase : List[str] = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS - {'''height''', '''width''', '''image'''} | {'''image_latents'''} _lowercase : Optional[int] = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS - {'''image'''} | {'''image_latents'''} _lowercase : List[str] = frozenset( [] ) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess _lowercase : List[str] = frozenset([] ) def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: torch.manual_seed(0) SCREAMING_SNAKE_CASE = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D') , up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D') , cross_attention_dim=32 , attention_head_dim=(2, 4) , use_linear_projection=a , ) SCREAMING_SNAKE_CASE = DDIMScheduler( beta_start=0.0_00_85 , beta_end=0.0_12 , beta_schedule='scaled_linear' , clip_sample=a , set_alpha_to_one=a , ) SCREAMING_SNAKE_CASE = DDIMInverseScheduler( beta_start=0.0_00_85 , beta_end=0.0_12 , beta_schedule='scaled_linear' , clip_sample=a , set_alpha_to_zero=a , ) torch.manual_seed(0) SCREAMING_SNAKE_CASE = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D'] , up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D'] , latent_channels=4 , sample_size=128 , ) torch.manual_seed(0) SCREAMING_SNAKE_CASE = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , hidden_act='gelu' , projection_dim=512 , ) SCREAMING_SNAKE_CASE = CLIPTextModel(a) SCREAMING_SNAKE_CASE = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip') SCREAMING_SNAKE_CASE = { 'unet': unet, 'scheduler': scheduler, 'inverse_scheduler': inverse_scheduler, 'vae': vae, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'safety_checker': None, 'feature_extractor': None, } return components def SCREAMING_SNAKE_CASE__ ( self , a , a=0) -> List[Any]: SCREAMING_SNAKE_CASE = floats_tensor((1, 16, 16) , rng=random.Random(a)).to(a) SCREAMING_SNAKE_CASE = floats_tensor((1, 2, 4, 16, 16) , rng=random.Random(a)).to(a) if str(a).startswith('mps'): SCREAMING_SNAKE_CASE = torch.manual_seed(a) else: SCREAMING_SNAKE_CASE = torch.Generator(device=a).manual_seed(a) SCREAMING_SNAKE_CASE = { 'prompt': 'a dog and a newt', 'mask_image': mask, 'image_latents': latents, 'generator': generator, 'num_inference_steps': 2, 'inpaint_strength': 1.0, 'guidance_scale': 6.0, 'output_type': 'numpy', } return inputs def SCREAMING_SNAKE_CASE__ ( self , a , a=0) -> List[Any]: SCREAMING_SNAKE_CASE = floats_tensor((1, 3, 32, 32) , rng=random.Random(a)).to(a) SCREAMING_SNAKE_CASE = image.cpu().permute(0 , 2 , 3 , 1)[0] SCREAMING_SNAKE_CASE = Image.fromarray(np.uinta(a)).convert('RGB') if str(a).startswith('mps'): SCREAMING_SNAKE_CASE = torch.manual_seed(a) else: SCREAMING_SNAKE_CASE = torch.Generator(device=a).manual_seed(a) SCREAMING_SNAKE_CASE = { 'image': image, 'source_prompt': 'a cat and a frog', 'target_prompt': 'a dog and a newt', 'generator': generator, 'num_inference_steps': 2, 'num_maps_per_mask': 2, 'mask_encode_strength': 1.0, 'guidance_scale': 6.0, 'output_type': 'numpy', } return inputs def SCREAMING_SNAKE_CASE__ ( self , a , a=0) -> Optional[int]: SCREAMING_SNAKE_CASE = floats_tensor((1, 3, 32, 32) , rng=random.Random(a)).to(a) SCREAMING_SNAKE_CASE = image.cpu().permute(0 , 2 , 3 , 1)[0] SCREAMING_SNAKE_CASE = Image.fromarray(np.uinta(a)).convert('RGB') if str(a).startswith('mps'): SCREAMING_SNAKE_CASE = torch.manual_seed(a) else: SCREAMING_SNAKE_CASE = torch.Generator(device=a).manual_seed(a) SCREAMING_SNAKE_CASE = { 'image': image, 'prompt': 'a cat and a frog', 'generator': generator, 'num_inference_steps': 2, 'inpaint_strength': 1.0, 'guidance_scale': 6.0, 'decode_latents': True, 'output_type': 'numpy', } return inputs def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: if not hasattr(self.pipeline_class , '_optional_components'): return SCREAMING_SNAKE_CASE = self.get_dummy_components() SCREAMING_SNAKE_CASE = self.pipeline_class(**a) pipe.to(a) pipe.set_progress_bar_config(disable=a) # set all optional components to None and update pipeline config accordingly for optional_component in pipe._optional_components: setattr(a , a , a) pipe.register_modules(**{optional_component: None for optional_component in pipe._optional_components}) SCREAMING_SNAKE_CASE = self.get_dummy_inputs(a) SCREAMING_SNAKE_CASE = pipe(**a)[0] with tempfile.TemporaryDirectory() as tmpdir: pipe.save_pretrained(a) SCREAMING_SNAKE_CASE = self.pipeline_class.from_pretrained(a) pipe_loaded.to(a) pipe_loaded.set_progress_bar_config(disable=a) for optional_component in pipe._optional_components: self.assertTrue( getattr(a , a) is None , f'''`{optional_component}` did not stay set to None after loading.''' , ) SCREAMING_SNAKE_CASE = self.get_dummy_inputs(a) SCREAMING_SNAKE_CASE = pipe_loaded(**a)[0] SCREAMING_SNAKE_CASE = np.abs(output - output_loaded).max() self.assertLess(a , 1E-4) def SCREAMING_SNAKE_CASE__ ( self) -> str: SCREAMING_SNAKE_CASE = 'cpu' SCREAMING_SNAKE_CASE = self.get_dummy_components() SCREAMING_SNAKE_CASE = self.pipeline_class(**a) pipe.to(a) pipe.set_progress_bar_config(disable=a) SCREAMING_SNAKE_CASE = self.get_dummy_mask_inputs(a) SCREAMING_SNAKE_CASE = pipe.generate_mask(**a) SCREAMING_SNAKE_CASE = mask[0, -3:, -3:] self.assertEqual(mask.shape , (1, 16, 16)) SCREAMING_SNAKE_CASE = np.array([0] * 9) SCREAMING_SNAKE_CASE = np.abs(mask_slice.flatten() - expected_slice).max() self.assertLessEqual(a , 1E-3) self.assertEqual(mask[0, -3, -4] , 0) def SCREAMING_SNAKE_CASE__ ( self) -> str: SCREAMING_SNAKE_CASE = 'cpu' SCREAMING_SNAKE_CASE = self.get_dummy_components() SCREAMING_SNAKE_CASE = self.pipeline_class(**a) pipe.to(a) pipe.set_progress_bar_config(disable=a) SCREAMING_SNAKE_CASE = self.get_dummy_inversion_inputs(a) SCREAMING_SNAKE_CASE = pipe.invert(**a).images SCREAMING_SNAKE_CASE = image[0, -1, -3:, -3:] self.assertEqual(image.shape , (2, 32, 32, 3)) SCREAMING_SNAKE_CASE = np.array( [0.51_50, 0.51_34, 0.50_43, 0.53_76, 0.46_94, 0.5_10_50, 0.50_15, 0.44_07, 0.47_99] , ) SCREAMING_SNAKE_CASE = np.abs(image_slice.flatten() - expected_slice).max() self.assertLessEqual(a , 1E-3) def SCREAMING_SNAKE_CASE__ ( self) -> Dict: super().test_inference_batch_single_identical(expected_max_diff=5E-3) def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: SCREAMING_SNAKE_CASE = 'cpu' SCREAMING_SNAKE_CASE = self.get_dummy_components() SCREAMING_SNAKE_CASE = {'beta_start': 0.0_00_85, 'beta_end': 0.0_12, 'beta_schedule': 'scaled_linear'} SCREAMING_SNAKE_CASE = DPMSolverMultistepScheduler(**a) SCREAMING_SNAKE_CASE = DPMSolverMultistepInverseScheduler(**a) SCREAMING_SNAKE_CASE = self.pipeline_class(**a) pipe.to(a) pipe.set_progress_bar_config(disable=a) SCREAMING_SNAKE_CASE = self.get_dummy_inversion_inputs(a) SCREAMING_SNAKE_CASE = pipe.invert(**a).images SCREAMING_SNAKE_CASE = image[0, -1, -3:, -3:] self.assertEqual(image.shape , (2, 32, 32, 3)) SCREAMING_SNAKE_CASE = np.array( [0.51_50, 0.51_34, 0.50_43, 0.53_76, 0.46_94, 0.5_10_50, 0.50_15, 0.44_07, 0.47_99] , ) SCREAMING_SNAKE_CASE = np.abs(image_slice.flatten() - expected_slice).max() self.assertLessEqual(a , 1E-3) @require_torch_gpu @slow class _snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ ( self) -> Any: super().tearDown() gc.collect() torch.cuda.empty_cache() @classmethod def SCREAMING_SNAKE_CASE__ ( cls) -> List[Any]: SCREAMING_SNAKE_CASE = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/diffedit/fruit.png') SCREAMING_SNAKE_CASE = raw_image.convert('RGB').resize((768, 768)) SCREAMING_SNAKE_CASE = raw_image def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: SCREAMING_SNAKE_CASE = torch.manual_seed(0) SCREAMING_SNAKE_CASE = StableDiffusionDiffEditPipeline.from_pretrained( 'stabilityai/stable-diffusion-2-1' , safety_checker=a , torch_dtype=torch.floataa) SCREAMING_SNAKE_CASE = DDIMScheduler.from_config(pipe.scheduler.config) SCREAMING_SNAKE_CASE = DDIMInverseScheduler.from_config(pipe.scheduler.config) pipe.enable_model_cpu_offload() pipe.set_progress_bar_config(disable=a) SCREAMING_SNAKE_CASE = 'a bowl of fruit' SCREAMING_SNAKE_CASE = 'a bowl of pears' SCREAMING_SNAKE_CASE = pipe.generate_mask( image=self.raw_image , source_prompt=a , target_prompt=a , generator=a , ) SCREAMING_SNAKE_CASE = pipe.invert( prompt=a , image=self.raw_image , inpaint_strength=0.7 , generator=a).latents SCREAMING_SNAKE_CASE = pipe( prompt=a , mask_image=a , image_latents=a , generator=a , negative_prompt=a , inpaint_strength=0.7 , output_type='numpy' , ).images[0] SCREAMING_SNAKE_CASE = ( np.array( load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/diffedit/pears.png').resize((768, 768))) / 255 ) assert np.abs((expected_image - image).max()) < 5E-1 def SCREAMING_SNAKE_CASE__ ( self) -> str: SCREAMING_SNAKE_CASE = torch.manual_seed(0) SCREAMING_SNAKE_CASE = StableDiffusionDiffEditPipeline.from_pretrained( 'stabilityai/stable-diffusion-2-1' , safety_checker=a , torch_dtype=torch.floataa) SCREAMING_SNAKE_CASE = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config) SCREAMING_SNAKE_CASE = DPMSolverMultistepInverseScheduler.from_config(pipe.scheduler.config) pipe.enable_model_cpu_offload() pipe.set_progress_bar_config(disable=a) SCREAMING_SNAKE_CASE = 'a bowl of fruit' SCREAMING_SNAKE_CASE = 'a bowl of pears' SCREAMING_SNAKE_CASE = pipe.generate_mask( image=self.raw_image , source_prompt=a , target_prompt=a , generator=a , ) SCREAMING_SNAKE_CASE = pipe.invert( prompt=a , image=self.raw_image , inpaint_strength=0.7 , generator=a , num_inference_steps=25 , ).latents SCREAMING_SNAKE_CASE = pipe( prompt=a , mask_image=a , image_latents=a , generator=a , negative_prompt=a , inpaint_strength=0.7 , num_inference_steps=25 , output_type='numpy' , ).images[0] SCREAMING_SNAKE_CASE = ( np.array( load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/diffedit/pears.png').resize((768, 768))) / 255 ) assert np.abs((expected_image - image).max()) < 5E-1
73
1
import warnings from typing import Any, Dict, List, Optional, Union import numpy as np from ...audio_utils import mel_filter_bank, optimal_fft_length, spectrogram, window_function from ...feature_extraction_sequence_utils import SequenceFeatureExtractor from ...feature_extraction_utils import BatchFeature from ...utils import PaddingStrategy, TensorType, logging a_ : Dict = logging.get_logger(__name__) class _snake_case ( A__ ): _lowercase : int = ['''input_values''', '''attention_mask'''] def __init__( self , a = 1 , a = 1_6000 , a = 0.0 , a = False , a = 80 , a = 16 , a = 64 , a = "hann_window" , a = 1.0 , a = 80 , a = 7600 , a = 1E-10 , a = 2 , a = True , **a , ) -> Tuple: super().__init__(feature_size=a , sampling_rate=a , padding_value=a , **a) SCREAMING_SNAKE_CASE = do_normalize SCREAMING_SNAKE_CASE = return_attention_mask SCREAMING_SNAKE_CASE = num_mel_bins SCREAMING_SNAKE_CASE = hop_length SCREAMING_SNAKE_CASE = win_length SCREAMING_SNAKE_CASE = win_function SCREAMING_SNAKE_CASE = frame_signal_scale SCREAMING_SNAKE_CASE = fmin SCREAMING_SNAKE_CASE = fmax SCREAMING_SNAKE_CASE = mel_floor SCREAMING_SNAKE_CASE = reduction_factor SCREAMING_SNAKE_CASE = win_length * sampling_rate // 1000 SCREAMING_SNAKE_CASE = hop_length * sampling_rate // 1000 SCREAMING_SNAKE_CASE = optimal_fft_length(self.sample_size) SCREAMING_SNAKE_CASE = (self.n_fft // 2) + 1 SCREAMING_SNAKE_CASE = window_function(window_length=self.sample_size , name=self.win_function , periodic=a) SCREAMING_SNAKE_CASE = mel_filter_bank( num_frequency_bins=self.n_freqs , num_mel_filters=self.num_mel_bins , min_frequency=self.fmin , max_frequency=self.fmax , sampling_rate=self.sampling_rate , norm='slaney' , mel_scale='slaney' , ) if frame_signal_scale != 1.0: warnings.warn( 'The argument `frame_signal_scale` is deprecated and will be removed in version 4.30.0 of Transformers' , a , ) if reduction_factor != 2.0: warnings.warn( 'The argument `reduction_factor` is deprecated and will be removed in version 4.30.0 of Transformers' , a , ) @staticmethod # Copied from transformers.models.wav2vec2.feature_extraction_wav2vec2.Wav2Vec2FeatureExtractor.zero_mean_unit_var_norm def SCREAMING_SNAKE_CASE__ ( a , a , a = 0.0) -> List[np.ndarray]: if attention_mask is not None: SCREAMING_SNAKE_CASE = np.array(a , np.intaa) SCREAMING_SNAKE_CASE = [] for vector, length in zip(a , attention_mask.sum(-1)): SCREAMING_SNAKE_CASE = (vector - vector[:length].mean()) / np.sqrt(vector[:length].var() + 1E-7) if length < normed_slice.shape[0]: SCREAMING_SNAKE_CASE = padding_value normed_input_values.append(a) else: SCREAMING_SNAKE_CASE = [(x - x.mean()) / np.sqrt(x.var() + 1E-7) for x in input_values] return normed_input_values def SCREAMING_SNAKE_CASE__ ( self , a , ) -> np.ndarray: SCREAMING_SNAKE_CASE = spectrogram( a , window=self.window , frame_length=self.sample_size , hop_length=self.sample_stride , fft_length=self.n_fft , mel_filters=self.mel_filters , mel_floor=self.mel_floor , log_mel='log10' , ) return log_mel_spec.T def __call__( self , a = None , a = None , a = False , a = None , a = False , a = None , a = None , a = None , a = None , **a , ) -> BatchFeature: if audio is None and audio_target is None: raise ValueError('You must provide either `audio` or `audio_target` values.') if sampling_rate is not None: if sampling_rate != self.sampling_rate: raise ValueError( f'''The model corresponding to this feature extractor: {self} was trained using a sampling rate of''' f''' {self.sampling_rate}. Please make sure that the provided audio input was sampled with''' f''' {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.') if audio is not None: SCREAMING_SNAKE_CASE = self._process_audio( a , a , a , a , a , a , a , a , **a , ) else: SCREAMING_SNAKE_CASE = None if audio_target is not None: SCREAMING_SNAKE_CASE = self._process_audio( a , a , a , a , a , a , a , a , **a , ) if inputs is None: return inputs_target else: SCREAMING_SNAKE_CASE = inputs_target['input_values'] SCREAMING_SNAKE_CASE = inputs_target.get('attention_mask') if decoder_attention_mask is not None: SCREAMING_SNAKE_CASE = decoder_attention_mask return inputs def SCREAMING_SNAKE_CASE__ ( self , a , a = False , a = False , a = None , a = False , a = None , a = None , a = None , **a , ) -> BatchFeature: SCREAMING_SNAKE_CASE = isinstance(a , np.ndarray) and len(speech.shape) > 1 if is_batched_numpy and len(speech.shape) > 2: raise ValueError(f'''Only mono-channel audio is supported for input to {self}''') SCREAMING_SNAKE_CASE = is_batched_numpy or ( isinstance(a , (list, tuple)) and (isinstance(speech[0] , (np.ndarray, tuple, list))) ) if is_batched: SCREAMING_SNAKE_CASE = [np.asarray(a , dtype=np.floataa) for speech in speech] elif not is_batched and not isinstance(a , np.ndarray): SCREAMING_SNAKE_CASE = np.asarray(a , dtype=np.floataa) elif isinstance(a , np.ndarray) and speech.dtype is np.dtype(np.floataa): SCREAMING_SNAKE_CASE = speech.astype(np.floataa) # always return batch if not is_batched: SCREAMING_SNAKE_CASE = [speech] # needed to make pad() work on spectrogram inputs SCREAMING_SNAKE_CASE = self.feature_size # convert into correct format for padding if is_target: SCREAMING_SNAKE_CASE = [self._extract_mel_features(a) for waveform in speech] SCREAMING_SNAKE_CASE = BatchFeature({'input_values': features}) SCREAMING_SNAKE_CASE = self.num_mel_bins else: SCREAMING_SNAKE_CASE = BatchFeature({'input_values': speech}) SCREAMING_SNAKE_CASE = self.pad( a , padding=a , max_length=a , truncation=a , pad_to_multiple_of=a , return_attention_mask=a , **a , ) SCREAMING_SNAKE_CASE = feature_size_hack # convert input values to correct format SCREAMING_SNAKE_CASE = padded_inputs['input_values'] if not isinstance(input_values[0] , np.ndarray): SCREAMING_SNAKE_CASE = [np.asarray(a , dtype=np.floataa) for array in input_values] elif ( not isinstance(a , np.ndarray) and isinstance(input_values[0] , np.ndarray) and input_values[0].dtype is np.dtype(np.floataa) ): SCREAMING_SNAKE_CASE = [array.astype(np.floataa) for array in input_values] elif isinstance(a , np.ndarray) and input_values.dtype is np.dtype(np.floataa): SCREAMING_SNAKE_CASE = input_values.astype(np.floataa) # convert attention_mask to correct format SCREAMING_SNAKE_CASE = padded_inputs.get('attention_mask') if attention_mask is not None: SCREAMING_SNAKE_CASE = [np.asarray(a , dtype=np.intaa) for array in attention_mask] # zero-mean and unit-variance normalization if not is_target and self.do_normalize: SCREAMING_SNAKE_CASE = ( attention_mask if self._get_padding_strategies(a , max_length=a) is not PaddingStrategy.DO_NOT_PAD else None ) SCREAMING_SNAKE_CASE = self.zero_mean_unit_var_norm( padded_inputs['input_values'] , attention_mask=a , padding_value=self.padding_value) if return_tensors is not None: SCREAMING_SNAKE_CASE = padded_inputs.convert_to_tensors(a) return padded_inputs def SCREAMING_SNAKE_CASE__ ( self) -> Dict[str, Any]: SCREAMING_SNAKE_CASE = super().to_dict() # Don't serialize these as they are derived from the other properties. SCREAMING_SNAKE_CASE = ['window', 'mel_filters', 'sample_size', 'sample_stride', 'n_fft', 'n_freqs'] for name in names: if name in output: del output[name] return output
73
import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging a_ : List[str] = logging.get_logger(__name__) a_ : Any = { 'microsoft/unispeech-large-1500h-cv': ( 'https://huggingface.co/microsoft/unispeech-large-1500h-cv/resolve/main/config.json' ), # See all UniSpeech models at https://huggingface.co/models?filter=unispeech } class _snake_case ( A__ ): _lowercase : Optional[int] = '''unispeech''' def __init__( self , a=32 , a=768 , a=12 , a=12 , a=3072 , a="gelu" , a=0.1 , a=0.1 , a=0.1 , a=0.0 , a=0.0 , a=0.1 , a=0.1 , a=0.02 , a=1E-5 , a="group" , a="gelu" , a=(512, 512, 512, 512, 512, 512, 512) , a=(5, 2, 2, 2, 2, 2, 2) , a=(10, 3, 3, 3, 3, 2, 2) , a=False , a=128 , a=16 , a=False , a=True , a=0.05 , a=10 , a=2 , a=0.0 , a=10 , a=0 , a=320 , a=2 , a=0.1 , a=100 , a=256 , a=256 , a=0.1 , a="mean" , a=False , a=False , a=256 , a=80 , a=0 , a=1 , a=2 , a=0.5 , **a , ) -> Optional[int]: super().__init__(**a , pad_token_id=a , bos_token_id=a , eos_token_id=a) SCREAMING_SNAKE_CASE = hidden_size SCREAMING_SNAKE_CASE = feat_extract_norm SCREAMING_SNAKE_CASE = feat_extract_activation SCREAMING_SNAKE_CASE = list(a) SCREAMING_SNAKE_CASE = list(a) SCREAMING_SNAKE_CASE = list(a) SCREAMING_SNAKE_CASE = conv_bias SCREAMING_SNAKE_CASE = num_conv_pos_embeddings SCREAMING_SNAKE_CASE = num_conv_pos_embedding_groups SCREAMING_SNAKE_CASE = len(self.conv_dim) SCREAMING_SNAKE_CASE = num_hidden_layers SCREAMING_SNAKE_CASE = intermediate_size SCREAMING_SNAKE_CASE = hidden_act SCREAMING_SNAKE_CASE = num_attention_heads SCREAMING_SNAKE_CASE = hidden_dropout SCREAMING_SNAKE_CASE = attention_dropout SCREAMING_SNAKE_CASE = activation_dropout SCREAMING_SNAKE_CASE = feat_proj_dropout SCREAMING_SNAKE_CASE = final_dropout SCREAMING_SNAKE_CASE = layerdrop SCREAMING_SNAKE_CASE = layer_norm_eps SCREAMING_SNAKE_CASE = initializer_range SCREAMING_SNAKE_CASE = num_ctc_classes SCREAMING_SNAKE_CASE = vocab_size SCREAMING_SNAKE_CASE = do_stable_layer_norm SCREAMING_SNAKE_CASE = use_weighted_layer_sum SCREAMING_SNAKE_CASE = classifier_proj_size if ( (len(self.conv_stride) != self.num_feat_extract_layers) or (len(self.conv_kernel) != self.num_feat_extract_layers) or (len(self.conv_dim) != self.num_feat_extract_layers) ): raise ValueError( 'Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` ==' ' `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) =' f''' {len(self.conv_dim)}`, `len(config.conv_stride) = {len(self.conv_stride)}`,''' f''' `len(config.conv_kernel) = {len(self.conv_kernel)}`.''') # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 SCREAMING_SNAKE_CASE = apply_spec_augment SCREAMING_SNAKE_CASE = mask_time_prob SCREAMING_SNAKE_CASE = mask_time_length SCREAMING_SNAKE_CASE = mask_time_min_masks SCREAMING_SNAKE_CASE = mask_feature_prob SCREAMING_SNAKE_CASE = mask_feature_length SCREAMING_SNAKE_CASE = mask_feature_min_masks # parameters for pretraining with codevector quantized representations SCREAMING_SNAKE_CASE = num_codevectors_per_group SCREAMING_SNAKE_CASE = num_codevector_groups SCREAMING_SNAKE_CASE = contrastive_logits_temperature SCREAMING_SNAKE_CASE = feat_quantizer_dropout SCREAMING_SNAKE_CASE = num_negatives SCREAMING_SNAKE_CASE = codevector_dim SCREAMING_SNAKE_CASE = proj_codevector_dim SCREAMING_SNAKE_CASE = diversity_loss_weight # ctc loss SCREAMING_SNAKE_CASE = ctc_loss_reduction SCREAMING_SNAKE_CASE = ctc_zero_infinity # pretraining loss SCREAMING_SNAKE_CASE = replace_prob @property def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: return functools.reduce(operator.mul , self.conv_stride , 1)
73
1
from __future__ import annotations from fractions import Fraction from math import gcd, sqrt def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = int(number**0.5) return number == sq * sq def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = x_num * y_den * z_den + y_num * x_den * z_den + z_num * x_den * y_den SCREAMING_SNAKE_CASE = x_den * y_den * z_den SCREAMING_SNAKE_CASE = gcd(_UpperCAmelCase , _UpperCAmelCase) top //= hcf bottom //= hcf return top, bottom def lowerCamelCase__ (_UpperCAmelCase = 35): SCREAMING_SNAKE_CASE = set() SCREAMING_SNAKE_CASE = 42 SCREAMING_SNAKE_CASE = Fraction(0) SCREAMING_SNAKE_CASE = 42 for x_num in range(1 , order + 1): for x_den in range(x_num + 1 , order + 1): for y_num in range(1 , order + 1): for y_den in range(y_num + 1 , order + 1): # n=1 SCREAMING_SNAKE_CASE = x_num * y_den + x_den * y_num SCREAMING_SNAKE_CASE = x_den * y_den SCREAMING_SNAKE_CASE = gcd(_UpperCAmelCase , _UpperCAmelCase) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: SCREAMING_SNAKE_CASE = add_three( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) unique_s.add(_UpperCAmelCase) # n=2 SCREAMING_SNAKE_CASE = ( x_num * x_num * y_den * y_den + x_den * x_den * y_num * y_num ) SCREAMING_SNAKE_CASE = x_den * x_den * y_den * y_den if is_sq(_UpperCAmelCase) and is_sq(_UpperCAmelCase): SCREAMING_SNAKE_CASE = int(sqrt(_UpperCAmelCase)) SCREAMING_SNAKE_CASE = int(sqrt(_UpperCAmelCase)) SCREAMING_SNAKE_CASE = gcd(_UpperCAmelCase , _UpperCAmelCase) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: SCREAMING_SNAKE_CASE = add_three( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) unique_s.add(_UpperCAmelCase) # n=-1 SCREAMING_SNAKE_CASE = x_num * y_num SCREAMING_SNAKE_CASE = x_den * y_num + x_num * y_den SCREAMING_SNAKE_CASE = gcd(_UpperCAmelCase , _UpperCAmelCase) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: SCREAMING_SNAKE_CASE = add_three( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) unique_s.add(_UpperCAmelCase) # n=2 SCREAMING_SNAKE_CASE = x_num * x_num * y_num * y_num SCREAMING_SNAKE_CASE = ( x_den * x_den * y_num * y_num + x_num * x_num * y_den * y_den ) if is_sq(_UpperCAmelCase) and is_sq(_UpperCAmelCase): SCREAMING_SNAKE_CASE = int(sqrt(_UpperCAmelCase)) SCREAMING_SNAKE_CASE = int(sqrt(_UpperCAmelCase)) SCREAMING_SNAKE_CASE = gcd(_UpperCAmelCase , _UpperCAmelCase) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: SCREAMING_SNAKE_CASE = add_three( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) unique_s.add(_UpperCAmelCase) for num, den in unique_s: total += Fraction(_UpperCAmelCase , _UpperCAmelCase) return total.denominator + total.numerator if __name__ == "__main__": print(f"""{solution() = }""")
73
import argparse import collections import json import os import re import string import sys import numpy as np a_ : Optional[Any] = re.compile(R'\b(a|an|the)\b', re.UNICODE) a_ : List[str] = None def lowerCamelCase__ (): SCREAMING_SNAKE_CASE = argparse.ArgumentParser('Official evaluation script for SQuAD version 2.0.') parser.add_argument('data_file' , metavar='data.json' , help='Input data JSON file.') parser.add_argument('pred_file' , metavar='pred.json' , help='Model predictions.') parser.add_argument( '--out-file' , '-o' , metavar='eval.json' , help='Write accuracy metrics to file (default is stdout).') parser.add_argument( '--na-prob-file' , '-n' , metavar='na_prob.json' , help='Model estimates of probability of no answer.') parser.add_argument( '--na-prob-thresh' , '-t' , type=_UpperCAmelCase , default=1.0 , help='Predict "" if no-answer probability exceeds this (default = 1.0).' , ) parser.add_argument( '--out-image-dir' , '-p' , metavar='out_images' , default=_UpperCAmelCase , help='Save precision-recall curves to directory.') parser.add_argument('--verbose' , '-v' , action='store_true') if len(sys.argv) == 1: parser.print_help() sys.exit(1) return parser.parse_args() def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = {} for article in dataset: for p in article["paragraphs"]: for qa in p["qas"]: SCREAMING_SNAKE_CASE = bool(qa['answers']['text']) return qid_to_has_ans def lowerCamelCase__ (_UpperCAmelCase): def remove_articles(_UpperCAmelCase): return ARTICLES_REGEX.sub(' ' , _UpperCAmelCase) def white_space_fix(_UpperCAmelCase): return " ".join(text.split()) def remove_punc(_UpperCAmelCase): SCREAMING_SNAKE_CASE = set(string.punctuation) return "".join(ch for ch in text if ch not in exclude) def lower(_UpperCAmelCase): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(_UpperCAmelCase)))) def lowerCamelCase__ (_UpperCAmelCase): if not s: return [] return normalize_answer(_UpperCAmelCase).split() def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): return int(normalize_answer(_UpperCAmelCase) == normalize_answer(_UpperCAmelCase)) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = get_tokens(_UpperCAmelCase) SCREAMING_SNAKE_CASE = get_tokens(_UpperCAmelCase) SCREAMING_SNAKE_CASE = collections.Counter(_UpperCAmelCase) & collections.Counter(_UpperCAmelCase) SCREAMING_SNAKE_CASE = sum(common.values()) if len(_UpperCAmelCase) == 0 or len(_UpperCAmelCase) == 0: # If either is no-answer, then F1 is 1 if they agree, 0 otherwise return int(gold_toks == pred_toks) if num_same == 0: return 0 SCREAMING_SNAKE_CASE = 1.0 * num_same / len(_UpperCAmelCase) SCREAMING_SNAKE_CASE = 1.0 * num_same / len(_UpperCAmelCase) SCREAMING_SNAKE_CASE = (2 * precision * recall) / (precision + recall) return fa def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = {} SCREAMING_SNAKE_CASE = {} for article in dataset: for p in article["paragraphs"]: for qa in p["qas"]: SCREAMING_SNAKE_CASE = qa['id'] SCREAMING_SNAKE_CASE = [t for t in qa['answers']['text'] if normalize_answer(_UpperCAmelCase)] if not gold_answers: # For unanswerable questions, only correct answer is empty string SCREAMING_SNAKE_CASE = [''] if qid not in preds: print(F'''Missing prediction for {qid}''') continue SCREAMING_SNAKE_CASE = preds[qid] # Take max over all gold answers SCREAMING_SNAKE_CASE = max(compute_exact(_UpperCAmelCase , _UpperCAmelCase) for a in gold_answers) SCREAMING_SNAKE_CASE = max(compute_fa(_UpperCAmelCase , _UpperCAmelCase) for a in gold_answers) return exact_scores, fa_scores def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = {} for qid, s in scores.items(): SCREAMING_SNAKE_CASE = na_probs[qid] > na_prob_thresh if pred_na: SCREAMING_SNAKE_CASE = float(not qid_to_has_ans[qid]) else: SCREAMING_SNAKE_CASE = s return new_scores def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase=None): if not qid_list: SCREAMING_SNAKE_CASE = len(_UpperCAmelCase) return collections.OrderedDict( [ ('exact', 1_00.0 * sum(exact_scores.values()) / total), ('f1', 1_00.0 * sum(fa_scores.values()) / total), ('total', total), ]) else: SCREAMING_SNAKE_CASE = len(_UpperCAmelCase) return collections.OrderedDict( [ ('exact', 1_00.0 * sum(exact_scores[k] for k in qid_list) / total), ('f1', 1_00.0 * sum(fa_scores[k] for k in qid_list) / total), ('total', total), ]) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): for k in new_eval: SCREAMING_SNAKE_CASE = new_eval[k] def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): plt.step(_UpperCAmelCase , _UpperCAmelCase , color='b' , alpha=0.2 , where='post') plt.fill_between(_UpperCAmelCase , _UpperCAmelCase , step='post' , alpha=0.2 , color='b') plt.xlabel('Recall') plt.ylabel('Precision') plt.xlim([0.0, 1.05]) plt.ylim([0.0, 1.05]) plt.title(_UpperCAmelCase) plt.savefig(_UpperCAmelCase) plt.clf() def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase=None , _UpperCAmelCase=None): SCREAMING_SNAKE_CASE = sorted(_UpperCAmelCase , key=lambda _UpperCAmelCase: na_probs[k]) SCREAMING_SNAKE_CASE = 0.0 SCREAMING_SNAKE_CASE = 1.0 SCREAMING_SNAKE_CASE = 0.0 SCREAMING_SNAKE_CASE = [1.0] SCREAMING_SNAKE_CASE = [0.0] SCREAMING_SNAKE_CASE = 0.0 for i, qid in enumerate(_UpperCAmelCase): if qid_to_has_ans[qid]: true_pos += scores[qid] SCREAMING_SNAKE_CASE = true_pos / float(i + 1) SCREAMING_SNAKE_CASE = true_pos / float(_UpperCAmelCase) if i == len(_UpperCAmelCase) - 1 or na_probs[qid] != na_probs[qid_list[i + 1]]: # i.e., if we can put a threshold after this point avg_prec += cur_p * (cur_r - recalls[-1]) precisions.append(_UpperCAmelCase) recalls.append(_UpperCAmelCase) if out_image: plot_pr_curve(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) return {"ap": 1_00.0 * avg_prec} def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): if out_image_dir and not os.path.exists(_UpperCAmelCase): os.makedirs(_UpperCAmelCase) SCREAMING_SNAKE_CASE = sum(1 for v in qid_to_has_ans.values() if v) if num_true_pos == 0: return SCREAMING_SNAKE_CASE = make_precision_recall_eval( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , out_image=os.path.join(_UpperCAmelCase , 'pr_exact.png') , title='Precision-Recall curve for Exact Match score' , ) SCREAMING_SNAKE_CASE = make_precision_recall_eval( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , out_image=os.path.join(_UpperCAmelCase , 'pr_f1.png') , title='Precision-Recall curve for F1 score' , ) SCREAMING_SNAKE_CASE = {k: float(_UpperCAmelCase) for k, v in qid_to_has_ans.items()} SCREAMING_SNAKE_CASE = make_precision_recall_eval( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , out_image=os.path.join(_UpperCAmelCase , 'pr_oracle.png') , title='Oracle Precision-Recall curve (binary task of HasAns vs. NoAns)' , ) merge_eval(_UpperCAmelCase , _UpperCAmelCase , 'pr_exact') merge_eval(_UpperCAmelCase , _UpperCAmelCase , 'pr_f1') merge_eval(_UpperCAmelCase , _UpperCAmelCase , 'pr_oracle') def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): if not qid_list: return SCREAMING_SNAKE_CASE = [na_probs[k] for k in qid_list] SCREAMING_SNAKE_CASE = np.ones_like(_UpperCAmelCase) / float(len(_UpperCAmelCase)) plt.hist(_UpperCAmelCase , weights=_UpperCAmelCase , bins=20 , range=(0.0, 1.0)) plt.xlabel('Model probability of no-answer') plt.ylabel('Proportion of dataset') plt.title(F'''Histogram of no-answer probability: {name}''') plt.savefig(os.path.join(_UpperCAmelCase , F'''na_prob_hist_{name}.png''')) plt.clf() def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = sum(1 for k in qid_to_has_ans if not qid_to_has_ans[k]) SCREAMING_SNAKE_CASE = num_no_ans SCREAMING_SNAKE_CASE = cur_score SCREAMING_SNAKE_CASE = 0.0 SCREAMING_SNAKE_CASE = sorted(_UpperCAmelCase , key=lambda _UpperCAmelCase: na_probs[k]) for i, qid in enumerate(_UpperCAmelCase): if qid not in scores: continue if qid_to_has_ans[qid]: SCREAMING_SNAKE_CASE = scores[qid] else: if preds[qid]: SCREAMING_SNAKE_CASE = -1 else: SCREAMING_SNAKE_CASE = 0 cur_score += diff if cur_score > best_score: SCREAMING_SNAKE_CASE = cur_score SCREAMING_SNAKE_CASE = na_probs[qid] return 1_00.0 * best_score / len(_UpperCAmelCase), best_thresh def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = find_best_thresh(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = find_best_thresh(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) SCREAMING_SNAKE_CASE = best_exact SCREAMING_SNAKE_CASE = exact_thresh SCREAMING_SNAKE_CASE = best_fa SCREAMING_SNAKE_CASE = fa_thresh def lowerCamelCase__ (): with open(OPTS.data_file) as f: SCREAMING_SNAKE_CASE = json.load(_UpperCAmelCase) SCREAMING_SNAKE_CASE = dataset_json['data'] with open(OPTS.pred_file) as f: SCREAMING_SNAKE_CASE = json.load(_UpperCAmelCase) if OPTS.na_prob_file: with open(OPTS.na_prob_file) as f: SCREAMING_SNAKE_CASE = json.load(_UpperCAmelCase) else: SCREAMING_SNAKE_CASE = {k: 0.0 for k in preds} SCREAMING_SNAKE_CASE = make_qid_to_has_ans(_UpperCAmelCase) # maps qid to True/False SCREAMING_SNAKE_CASE = [k for k, v in qid_to_has_ans.items() if v] SCREAMING_SNAKE_CASE = [k for k, v in qid_to_has_ans.items() if not v] SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = get_raw_scores(_UpperCAmelCase , _UpperCAmelCase) SCREAMING_SNAKE_CASE = apply_no_ans_threshold(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , OPTS.na_prob_thresh) SCREAMING_SNAKE_CASE = apply_no_ans_threshold(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , OPTS.na_prob_thresh) SCREAMING_SNAKE_CASE = make_eval_dict(_UpperCAmelCase , _UpperCAmelCase) if has_ans_qids: SCREAMING_SNAKE_CASE = make_eval_dict(_UpperCAmelCase , _UpperCAmelCase , qid_list=_UpperCAmelCase) merge_eval(_UpperCAmelCase , _UpperCAmelCase , 'HasAns') if no_ans_qids: SCREAMING_SNAKE_CASE = make_eval_dict(_UpperCAmelCase , _UpperCAmelCase , qid_list=_UpperCAmelCase) merge_eval(_UpperCAmelCase , _UpperCAmelCase , 'NoAns') if OPTS.na_prob_file: find_all_best_thresh(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) if OPTS.na_prob_file and OPTS.out_image_dir: run_precision_recall_analysis(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , OPTS.out_image_dir) histogram_na_prob(_UpperCAmelCase , _UpperCAmelCase , OPTS.out_image_dir , 'hasAns') histogram_na_prob(_UpperCAmelCase , _UpperCAmelCase , OPTS.out_image_dir , 'noAns') if OPTS.out_file: with open(OPTS.out_file , 'w') as f: json.dump(_UpperCAmelCase , _UpperCAmelCase) else: print(json.dumps(_UpperCAmelCase , indent=2)) if __name__ == "__main__": a_ : Any = parse_args() if OPTS.out_image_dir: import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt main()
73
1
from __future__ import annotations def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = [] create_all_state(1 , _UpperCAmelCase , _UpperCAmelCase , [] , _UpperCAmelCase) return result def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , ): if level == 0: total_list.append(current_list[:]) return for i in range(_UpperCAmelCase , total_number - level + 2): current_list.append(_UpperCAmelCase) create_all_state(i + 1 , _UpperCAmelCase , level - 1 , _UpperCAmelCase , _UpperCAmelCase) current_list.pop() def lowerCamelCase__ (_UpperCAmelCase): for i in total_list: print(*_UpperCAmelCase) if __name__ == "__main__": a_ : List[str] = 4 a_ : str = 2 a_ : List[Any] = generate_all_combinations(n, k) print_all_state(total_list)
73
import warnings from ...utils import logging from .image_processing_glpn import GLPNImageProcessor a_ : Dict = logging.get_logger(__name__) class _snake_case ( A__ ): def __init__( self , *a , **a) -> None: warnings.warn( 'The class GLPNFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please' ' use GLPNImageProcessor instead.' , a , ) super().__init__(*a , **a)
73
1
import inspect import unittest from transformers import ConvNextConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_backbone_common import BackboneTesterMixin 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 ConvNextBackbone, ConvNextForImageClassification, ConvNextModel from transformers.models.convnext.modeling_convnext import CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class _snake_case : def __init__( self , a , a=13 , a=32 , a=3 , a=4 , a=[10, 20, 30, 40] , a=[2, 2, 3, 2] , a=True , a=True , a=37 , a="gelu" , a=10 , a=0.02 , a=["stage2", "stage3", "stage4"] , a=[2, 3, 4] , a=None , ) -> str: SCREAMING_SNAKE_CASE = parent SCREAMING_SNAKE_CASE = batch_size SCREAMING_SNAKE_CASE = image_size SCREAMING_SNAKE_CASE = num_channels SCREAMING_SNAKE_CASE = num_stages SCREAMING_SNAKE_CASE = hidden_sizes SCREAMING_SNAKE_CASE = depths SCREAMING_SNAKE_CASE = is_training SCREAMING_SNAKE_CASE = use_labels SCREAMING_SNAKE_CASE = intermediate_size SCREAMING_SNAKE_CASE = hidden_act SCREAMING_SNAKE_CASE = num_labels SCREAMING_SNAKE_CASE = initializer_range SCREAMING_SNAKE_CASE = out_features SCREAMING_SNAKE_CASE = out_indices SCREAMING_SNAKE_CASE = scope def SCREAMING_SNAKE_CASE__ ( self) -> Dict: SCREAMING_SNAKE_CASE = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) SCREAMING_SNAKE_CASE = None if self.use_labels: SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.num_labels) SCREAMING_SNAKE_CASE = self.get_config() return config, pixel_values, labels def SCREAMING_SNAKE_CASE__ ( self) -> str: return ConvNextConfig( num_channels=self.num_channels , hidden_sizes=self.hidden_sizes , depths=self.depths , num_stages=self.num_stages , hidden_act=self.hidden_act , is_decoder=a , initializer_range=self.initializer_range , out_features=self.out_features , out_indices=self.out_indices , num_labels=self.num_labels , ) def SCREAMING_SNAKE_CASE__ ( self , a , a , a) -> int: SCREAMING_SNAKE_CASE = ConvNextModel(config=a) model.to(a) model.eval() SCREAMING_SNAKE_CASE = model(a) # 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 , a , a , a) -> Any: SCREAMING_SNAKE_CASE = ConvNextForImageClassification(a) model.to(a) model.eval() SCREAMING_SNAKE_CASE = model(a , labels=a) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels)) def SCREAMING_SNAKE_CASE__ ( self , a , a , a) -> Dict: SCREAMING_SNAKE_CASE = ConvNextBackbone(config=a) model.to(a) model.eval() SCREAMING_SNAKE_CASE = model(a) # verify hidden states self.parent.assertEqual(len(result.feature_maps) , len(config.out_features)) self.parent.assertListEqual(list(result.feature_maps[0].shape) , [self.batch_size, self.hidden_sizes[1], 4, 4]) # verify channels self.parent.assertEqual(len(model.channels) , len(config.out_features)) self.parent.assertListEqual(model.channels , config.hidden_sizes[1:]) # verify backbone works with out_features=None SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = ConvNextBackbone(config=a) model.to(a) model.eval() SCREAMING_SNAKE_CASE = model(a) # verify feature maps self.parent.assertEqual(len(result.feature_maps) , 1) self.parent.assertListEqual(list(result.feature_maps[0].shape) , [self.batch_size, self.hidden_sizes[-1], 1, 1]) # verify channels self.parent.assertEqual(len(model.channels) , 1) self.parent.assertListEqual(model.channels , [config.hidden_sizes[-1]]) def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: SCREAMING_SNAKE_CASE = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = config_and_inputs SCREAMING_SNAKE_CASE = {'pixel_values': pixel_values} return config, inputs_dict @require_torch class _snake_case ( A__ , A__ , unittest.TestCase ): _lowercase : List[str] = ( ( ConvNextModel, ConvNextForImageClassification, ConvNextBackbone, ) if is_torch_available() else () ) _lowercase : Optional[Any] = ( {'''feature-extraction''': ConvNextModel, '''image-classification''': ConvNextForImageClassification} if is_torch_available() else {} ) _lowercase : str = True _lowercase : List[Any] = False _lowercase : Dict = False _lowercase : Optional[Any] = False _lowercase : int = False def SCREAMING_SNAKE_CASE__ ( self) -> Dict: SCREAMING_SNAKE_CASE = ConvNextModelTester(self) SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=a , has_text_modality=a , hidden_size=37) def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: 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 SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: return @unittest.skip(reason='ConvNext does not use inputs_embeds') def SCREAMING_SNAKE_CASE__ ( self) -> Dict: pass @unittest.skip(reason='ConvNext does not support input and output embeddings') def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: pass @unittest.skip(reason='ConvNext does not use feedforward chunking') def SCREAMING_SNAKE_CASE__ ( self) -> Any: pass def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE = model_class(a) SCREAMING_SNAKE_CASE = inspect.signature(model.forward) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE = ['pixel_values'] self.assertListEqual(arg_names[:1] , a) def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a) def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_backbone(*a) def SCREAMING_SNAKE_CASE__ ( self) -> Dict: def check_hidden_states_output(a , a , a): SCREAMING_SNAKE_CASE = model_class(a) model.to(a) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE = model(**self._prepare_for_class(a , a)) SCREAMING_SNAKE_CASE = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states SCREAMING_SNAKE_CASE = self.model_tester.num_stages self.assertEqual(len(a) , expected_num_stages + 1) # ConvNext'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 // 4, self.model_tester.image_size // 4] , ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE = True check_hidden_states_output(a , a , a) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] SCREAMING_SNAKE_CASE = True check_hidden_states_output(a , a , a) def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*a) @slow def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: for model_name in CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE = ConvNextModel.from_pretrained(a) self.assertIsNotNone(a) def lowerCamelCase__ (): SCREAMING_SNAKE_CASE = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png') return image @require_torch @require_vision class _snake_case ( unittest.TestCase ): @cached_property def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: return AutoImageProcessor.from_pretrained('facebook/convnext-tiny-224') if is_vision_available() else None @slow def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: SCREAMING_SNAKE_CASE = ConvNextForImageClassification.from_pretrained('facebook/convnext-tiny-224').to(a) SCREAMING_SNAKE_CASE = self.default_image_processor SCREAMING_SNAKE_CASE = prepare_img() SCREAMING_SNAKE_CASE = image_processor(images=a , return_tensors='pt').to(a) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE = model(**a) # verify the logits SCREAMING_SNAKE_CASE = torch.Size((1, 1000)) self.assertEqual(outputs.logits.shape , a) SCREAMING_SNAKE_CASE = torch.tensor([-0.02_60, -0.47_39, 0.19_11]).to(a) self.assertTrue(torch.allclose(outputs.logits[0, :3] , a , atol=1E-4)) @require_torch class _snake_case ( unittest.TestCase , A__ ): _lowercase : Tuple = (ConvNextBackbone,) if is_torch_available() else () _lowercase : Tuple = ConvNextConfig _lowercase : int = False def SCREAMING_SNAKE_CASE__ ( self) -> int: SCREAMING_SNAKE_CASE = ConvNextModelTester(self)
73
import unittest from transformers import load_tool from .test_tools_common import ToolTesterMixin class _snake_case ( unittest.TestCase , A__ ): def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: SCREAMING_SNAKE_CASE = load_tool('text-classification') self.tool.setup() SCREAMING_SNAKE_CASE = load_tool('text-classification' , remote=a) def SCREAMING_SNAKE_CASE__ ( self) -> str: SCREAMING_SNAKE_CASE = self.tool('That\'s quite cool' , ['positive', 'negative']) self.assertEqual(a , 'positive') def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: SCREAMING_SNAKE_CASE = self.remote_tool('That\'s quite cool' , ['positive', 'negative']) self.assertEqual(a , 'positive') def SCREAMING_SNAKE_CASE__ ( self) -> int: SCREAMING_SNAKE_CASE = self.tool(text='That\'s quite cool' , labels=['positive', 'negative']) self.assertEqual(a , 'positive') def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: SCREAMING_SNAKE_CASE = self.remote_tool(text='That\'s quite cool' , labels=['positive', 'negative']) self.assertEqual(a , 'positive')
73
1
from __future__ import annotations a_ : Dict = 10 def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = 1 SCREAMING_SNAKE_CASE = max(_UpperCAmelCase) while placement <= max_digit: # declare and initialize empty buckets SCREAMING_SNAKE_CASE = [[] for _ in range(_UpperCAmelCase)] # split list_of_ints between the buckets for i in list_of_ints: SCREAMING_SNAKE_CASE = int((i / placement) % RADIX) buckets[tmp].append(_UpperCAmelCase) # put each buckets' contents into list_of_ints SCREAMING_SNAKE_CASE = 0 for b in range(_UpperCAmelCase): for i in buckets[b]: SCREAMING_SNAKE_CASE = i a += 1 # move to next placement *= RADIX return list_of_ints if __name__ == "__main__": import doctest doctest.testmod()
73
import sys import turtle def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): return (pa[0] + pa[0]) / 2, (pa[1] + pa[1]) / 2 def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , ): my_pen.up() my_pen.goto(vertexa[0] , vertexa[1]) my_pen.down() my_pen.goto(vertexa[0] , vertexa[1]) my_pen.goto(vertexa[0] , vertexa[1]) my_pen.goto(vertexa[0] , vertexa[1]) if depth == 0: return triangle(_UpperCAmelCase , get_mid(_UpperCAmelCase , _UpperCAmelCase) , get_mid(_UpperCAmelCase , _UpperCAmelCase) , depth - 1) triangle(_UpperCAmelCase , get_mid(_UpperCAmelCase , _UpperCAmelCase) , get_mid(_UpperCAmelCase , _UpperCAmelCase) , depth - 1) triangle(_UpperCAmelCase , get_mid(_UpperCAmelCase , _UpperCAmelCase) , get_mid(_UpperCAmelCase , _UpperCAmelCase) , depth - 1) if __name__ == "__main__": if len(sys.argv) != 2: raise ValueError( 'Correct format for using this script: ' 'python fractals.py <int:depth_for_fractal>' ) a_ : Any = turtle.Turtle() my_pen.ht() my_pen.speed(5) my_pen.pencolor('red') a_ : str = [(-1_75, -1_25), (0, 1_75), (1_75, -1_25)] # vertices of triangle triangle(vertices[0], vertices[1], vertices[2], int(sys.argv[1]))
73
1
from ...configuration_utils import PretrainedConfig from ...utils import logging a_ : Optional[int] = logging.get_logger(__name__) a_ : List[Any] = { 'google/canine-s': 'https://huggingface.co/google/canine-s/resolve/main/config.json', # See all CANINE models at https://huggingface.co/models?filter=canine } class _snake_case ( A__ ): _lowercase : Union[str, Any] = '''canine''' def __init__( self , a=768 , a=12 , a=12 , a=3072 , a="gelu" , a=0.1 , a=0.1 , a=1_6384 , a=16 , a=0.02 , a=1E-12 , a=0 , a=0xe0_00 , a=0xe0_01 , a=4 , a=4 , a=8 , a=1_6384 , a=128 , **a , ) -> str: super().__init__(pad_token_id=a , bos_token_id=a , eos_token_id=a , **a) SCREAMING_SNAKE_CASE = max_position_embeddings SCREAMING_SNAKE_CASE = hidden_size SCREAMING_SNAKE_CASE = num_hidden_layers SCREAMING_SNAKE_CASE = num_attention_heads SCREAMING_SNAKE_CASE = intermediate_size SCREAMING_SNAKE_CASE = hidden_act SCREAMING_SNAKE_CASE = hidden_dropout_prob SCREAMING_SNAKE_CASE = attention_probs_dropout_prob SCREAMING_SNAKE_CASE = initializer_range SCREAMING_SNAKE_CASE = type_vocab_size SCREAMING_SNAKE_CASE = layer_norm_eps # Character config: SCREAMING_SNAKE_CASE = downsampling_rate SCREAMING_SNAKE_CASE = upsampling_kernel_size SCREAMING_SNAKE_CASE = num_hash_functions SCREAMING_SNAKE_CASE = num_hash_buckets SCREAMING_SNAKE_CASE = local_transformer_stride
73
import math import os from copy import deepcopy import datasets import evaluate import torch import transformers from datasets import load_dataset from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer from accelerate import Accelerator from accelerate.test_utils import RegressionDataset, RegressionModel from accelerate.utils import is_tpu_available, set_seed a_ : Any = 'true' def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase=82 , _UpperCAmelCase=16): set_seed(42) SCREAMING_SNAKE_CASE = RegressionModel() SCREAMING_SNAKE_CASE = deepcopy(_UpperCAmelCase) SCREAMING_SNAKE_CASE = RegressionDataset(length=_UpperCAmelCase) SCREAMING_SNAKE_CASE = DataLoader(_UpperCAmelCase , batch_size=_UpperCAmelCase) model.to(accelerator.device) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = accelerator.prepare(_UpperCAmelCase , _UpperCAmelCase) return model, ddp_model, dataloader def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase=False): SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained('hf-internal-testing/mrpc-bert-base-cased') SCREAMING_SNAKE_CASE = load_dataset('glue' , 'mrpc' , split='validation') def tokenize_function(_UpperCAmelCase): SCREAMING_SNAKE_CASE = tokenizer(examples['sentence1'] , examples['sentence2'] , truncation=_UpperCAmelCase , max_length=_UpperCAmelCase) return outputs with accelerator.main_process_first(): SCREAMING_SNAKE_CASE = dataset.map( _UpperCAmelCase , batched=_UpperCAmelCase , remove_columns=['idx', 'sentence1', 'sentence2'] , ) SCREAMING_SNAKE_CASE = tokenized_datasets.rename_column('label' , 'labels') def collate_fn(_UpperCAmelCase): if use_longest: return tokenizer.pad(_UpperCAmelCase , padding='longest' , return_tensors='pt') return tokenizer.pad(_UpperCAmelCase , padding='max_length' , max_length=128 , return_tensors='pt') return DataLoader(_UpperCAmelCase , shuffle=_UpperCAmelCase , collate_fn=_UpperCAmelCase , batch_size=16) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = Accelerator(dispatch_batches=_UpperCAmelCase , split_batches=_UpperCAmelCase) SCREAMING_SNAKE_CASE = get_dataloader(_UpperCAmelCase , not dispatch_batches) SCREAMING_SNAKE_CASE = AutoModelForSequenceClassification.from_pretrained( 'hf-internal-testing/mrpc-bert-base-cased' , return_dict=_UpperCAmelCase) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = accelerator.prepare(_UpperCAmelCase , _UpperCAmelCase) return {"ddp": [ddp_model, ddp_dataloader, "cuda:0"], "no": [model, dataloader, accelerator.device]}, accelerator def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = [] for batch in dataloader: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = batch.values() with torch.no_grad(): SCREAMING_SNAKE_CASE = model(_UpperCAmelCase) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = accelerator.gather_for_metrics((logit, target)) logits_and_targets.append((logit, target)) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = [], [] for logit, targ in logits_and_targets: logits.append(_UpperCAmelCase) targs.append(_UpperCAmelCase) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = torch.cat(_UpperCAmelCase), torch.cat(_UpperCAmelCase) return logits, targs def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase=82 , _UpperCAmelCase=False , _UpperCAmelCase=False , _UpperCAmelCase=16): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = get_basic_setup(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = generate_predictions(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) assert ( len(_UpperCAmelCase) == num_samples ), F'''Unexpected number of inputs:\n Expected: {num_samples}\n Actual: {len(_UpperCAmelCase)}''' def lowerCamelCase__ (_UpperCAmelCase = False , _UpperCAmelCase = False): SCREAMING_SNAKE_CASE = evaluate.load('glue' , 'mrpc') SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = get_mrpc_setup(_UpperCAmelCase , _UpperCAmelCase) # First do baseline SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = setup['no'] model.to(_UpperCAmelCase) model.eval() for batch in dataloader: batch.to(_UpperCAmelCase) with torch.inference_mode(): SCREAMING_SNAKE_CASE = model(**_UpperCAmelCase) SCREAMING_SNAKE_CASE = outputs.logits.argmax(dim=-1) metric.add_batch(predictions=_UpperCAmelCase , references=batch['labels']) SCREAMING_SNAKE_CASE = metric.compute() # Then do distributed SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = setup['ddp'] model.eval() for batch in dataloader: with torch.inference_mode(): SCREAMING_SNAKE_CASE = model(**_UpperCAmelCase) SCREAMING_SNAKE_CASE = outputs.logits.argmax(dim=-1) SCREAMING_SNAKE_CASE = batch['labels'] SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = accelerator.gather_for_metrics((preds, references)) metric.add_batch(predictions=_UpperCAmelCase , references=_UpperCAmelCase) SCREAMING_SNAKE_CASE = metric.compute() for key in "accuracy f1".split(): assert math.isclose( baseline[key] , distributed[key]), F'''Baseline and Distributed are not the same for key {key}:\n\tBaseline: {baseline[key]}\n\tDistributed: {distributed[key]}\n''' def lowerCamelCase__ (): SCREAMING_SNAKE_CASE = Accelerator(split_batches=_UpperCAmelCase , dispatch_batches=_UpperCAmelCase) if accelerator.is_local_main_process: datasets.utils.logging.set_verbosity_warning() transformers.utils.logging.set_verbosity_warning() else: datasets.utils.logging.set_verbosity_error() transformers.utils.logging.set_verbosity_error() # These are a bit slower so they should only be ran on the GPU or TPU if torch.cuda.is_available() or is_tpu_available(): if accelerator.is_local_main_process: print('**Testing gather_for_metrics**') for split_batches in [True, False]: for dispatch_batches in [True, False]: if accelerator.is_local_main_process: print(F'''With: `split_batches={split_batches}`, `dispatch_batches={dispatch_batches}`''') test_mrpc(_UpperCAmelCase , _UpperCAmelCase) accelerator.state._reset_state() if accelerator.is_local_main_process: print('**Test torch metrics**') for split_batches in [True, False]: for dispatch_batches in [True, False]: SCREAMING_SNAKE_CASE = Accelerator(split_batches=_UpperCAmelCase , dispatch_batches=_UpperCAmelCase) if accelerator.is_local_main_process: print(F'''With: `split_batches={split_batches}`, `dispatch_batches={dispatch_batches}`, length=99''') test_torch_metrics(_UpperCAmelCase , 99) accelerator.state._reset_state() if accelerator.is_local_main_process: print('**Test last batch is not dropped when perfectly divisible**') SCREAMING_SNAKE_CASE = Accelerator() test_torch_metrics(_UpperCAmelCase , 512) accelerator.state._reset_state() def lowerCamelCase__ (_UpperCAmelCase): # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
73
1
import inspect from typing import List, Optional, Tuple, Union import torch from ...models import UNetaDModel, VQModel from ...schedulers import DDIMScheduler from ...utils import randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput class _snake_case ( A__ ): def __init__( self , a , a , a) -> Optional[int]: super().__init__() self.register_modules(vqvae=a , unet=a , scheduler=a) @torch.no_grad() def __call__( self , a = 1 , a = None , a = 0.0 , a = 50 , a = "pil" , a = True , **a , ) -> Union[Tuple, ImagePipelineOutput]: SCREAMING_SNAKE_CASE = randn_tensor( (batch_size, self.unet.config.in_channels, self.unet.config.sample_size, self.unet.config.sample_size) , generator=a , ) SCREAMING_SNAKE_CASE = latents.to(self.device) # scale the initial noise by the standard deviation required by the scheduler SCREAMING_SNAKE_CASE = latents * self.scheduler.init_noise_sigma self.scheduler.set_timesteps(a) # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature SCREAMING_SNAKE_CASE = 'eta' in set(inspect.signature(self.scheduler.step).parameters.keys()) SCREAMING_SNAKE_CASE = {} if accepts_eta: SCREAMING_SNAKE_CASE = eta for t in self.progress_bar(self.scheduler.timesteps): SCREAMING_SNAKE_CASE = self.scheduler.scale_model_input(a , a) # predict the noise residual SCREAMING_SNAKE_CASE = self.unet(a , a).sample # compute the previous noisy sample x_t -> x_t-1 SCREAMING_SNAKE_CASE = self.scheduler.step(a , a , a , **a).prev_sample # decode the image latents with the VAE SCREAMING_SNAKE_CASE = self.vqvae.decode(a).sample SCREAMING_SNAKE_CASE = (image / 2 + 0.5).clamp(0 , 1) SCREAMING_SNAKE_CASE = image.cpu().permute(0 , 2 , 3 , 1).numpy() if output_type == "pil": SCREAMING_SNAKE_CASE = self.numpy_to_pil(a) if not return_dict: return (image,) return ImagePipelineOutput(images=a)
73
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available a_ : List[str] = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : Optional[Any] = ['GPTSw3Tokenizer'] if TYPE_CHECKING: try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_gpt_swa import GPTSwaTokenizer else: import sys a_ : Tuple = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
73
1
a_ : str = 'Alexander Joslin' import operator as op from .stack import Stack def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = {'*': op.mul, '/': op.truediv, '+': op.add, '-': op.sub} SCREAMING_SNAKE_CASE = Stack() SCREAMING_SNAKE_CASE = Stack() for i in equation: if i.isdigit(): # RULE 1 operand_stack.push(int(_UpperCAmelCase)) elif i in operators: # RULE 2 operator_stack.push(_UpperCAmelCase) elif i == ")": # RULE 4 SCREAMING_SNAKE_CASE = operator_stack.peek() operator_stack.pop() SCREAMING_SNAKE_CASE = operand_stack.peek() operand_stack.pop() SCREAMING_SNAKE_CASE = operand_stack.peek() operand_stack.pop() SCREAMING_SNAKE_CASE = operators[opr](_UpperCAmelCase , _UpperCAmelCase) operand_stack.push(_UpperCAmelCase) # RULE 5 return operand_stack.peek() if __name__ == "__main__": a_ : Dict = '(5 + ((4 * 2) * (2 + 3)))' # answer = 45 print(f"""{equation} = {dijkstras_two_stack_algorithm(equation)}""")
73
import os from tempfile import TemporaryDirectory from unittest import TestCase import pytest from absl.testing import parameterized from datasets import config from datasets.arrow_reader import HF_GCP_BASE_URL from datasets.builder import DatasetBuilder from datasets.dataset_dict import IterableDatasetDict from datasets.iterable_dataset import IterableDataset from datasets.load import dataset_module_factory, import_main_class from datasets.utils.file_utils import cached_path a_ : str = [ {'dataset': 'wikipedia', 'config_name': '20220301.de'}, {'dataset': 'wikipedia', 'config_name': '20220301.en'}, {'dataset': 'wikipedia', 'config_name': '20220301.fr'}, {'dataset': 'wikipedia', 'config_name': '20220301.frr'}, {'dataset': 'wikipedia', 'config_name': '20220301.it'}, {'dataset': 'wikipedia', 'config_name': '20220301.simple'}, {'dataset': 'snli', 'config_name': 'plain_text'}, {'dataset': 'eli5', 'config_name': 'LFQA_reddit'}, {'dataset': 'wiki40b', 'config_name': 'en'}, {'dataset': 'wiki_dpr', 'config_name': 'psgs_w100.nq.compressed'}, {'dataset': 'wiki_dpr', 'config_name': 'psgs_w100.nq.no_index'}, {'dataset': 'wiki_dpr', 'config_name': 'psgs_w100.multiset.no_index'}, {'dataset': 'natural_questions', 'config_name': 'default'}, ] def lowerCamelCase__ (_UpperCAmelCase=True): if with_config: return [ { "testcase_name": d["dataset"] + "/" + d["config_name"], "dataset": d["dataset"], "config_name": d["config_name"], } for d in DATASETS_ON_HF_GCP ] else: return [ {"testcase_name": dataset, "dataset": dataset} for dataset in {d["dataset"] for d in DATASETS_ON_HF_GCP} ] @parameterized.named_parameters(list_datasets_on_hf_gcp_parameters(with_config=A__ ) ) class _snake_case ( A__ ): _lowercase : Optional[Any] = None _lowercase : Optional[Any] = None def SCREAMING_SNAKE_CASE__ ( self , a , a) -> Optional[Any]: with TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE = dataset_module_factory(a , cache_dir=a) SCREAMING_SNAKE_CASE = import_main_class(dataset_module.module_path , dataset=a) SCREAMING_SNAKE_CASE = builder_cls( cache_dir=a , config_name=a , hash=dataset_module.hash , ) SCREAMING_SNAKE_CASE = '/'.join( [ HF_GCP_BASE_URL, builder_instance._relative_data_dir(with_hash=a).replace(os.sep , '/'), config.DATASET_INFO_FILENAME, ]) SCREAMING_SNAKE_CASE = cached_path(a , cache_dir=a) self.assertTrue(os.path.exists(a)) @pytest.mark.integration def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = tmp_path_factory.mktemp('test_hf_gcp') / 'test_wikipedia_simple' SCREAMING_SNAKE_CASE = dataset_module_factory('wikipedia' , cache_dir=_UpperCAmelCase) SCREAMING_SNAKE_CASE = import_main_class(dataset_module.module_path) SCREAMING_SNAKE_CASE = builder_cls( cache_dir=_UpperCAmelCase , config_name='20220301.frr' , hash=dataset_module.hash , ) # use the HF cloud storage, not the original download_and_prepare that uses apache-beam SCREAMING_SNAKE_CASE = None builder_instance.download_and_prepare() SCREAMING_SNAKE_CASE = builder_instance.as_dataset() assert ds @pytest.mark.integration def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = dataset_module_factory('wikipedia' , cache_dir=_UpperCAmelCase) SCREAMING_SNAKE_CASE = import_main_class(dataset_module.module_path , dataset=_UpperCAmelCase) SCREAMING_SNAKE_CASE = builder_cls( cache_dir=_UpperCAmelCase , config_name='20220301.frr' , hash=dataset_module.hash , ) SCREAMING_SNAKE_CASE = builder_instance.as_streaming_dataset() assert ds assert isinstance(_UpperCAmelCase , _UpperCAmelCase) assert "train" in ds assert isinstance(ds['train'] , _UpperCAmelCase) assert next(iter(ds['train']))
73
1
def lowerCamelCase__ (_UpperCAmelCase = 50): SCREAMING_SNAKE_CASE = [[0] * 3 for _ in range(length + 1)] for row_length in range(length + 1): for tile_length in range(2 , 5): for tile_start in range(row_length - tile_length + 1): different_colour_ways_number[row_length][tile_length - 2] += ( different_colour_ways_number[row_length - tile_start - tile_length][ tile_length - 2 ] + 1 ) return sum(different_colour_ways_number[length]) if __name__ == "__main__": print(f"""{solution() = }""")
73
from __future__ import annotations def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = 2 SCREAMING_SNAKE_CASE = [] while i * i <= n: if n % i: i += 1 else: n //= i factors.append(_UpperCAmelCase) if n > 1: factors.append(_UpperCAmelCase) return factors if __name__ == "__main__": import doctest doctest.testmod()
73
1
a_ : Union[str, Any] = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' def lowerCamelCase__ (_UpperCAmelCase): # Make sure the supplied data is a bytes-like object if not isinstance(_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = F'''a bytes-like object is required, not \'{data.__class__.__name__}\'''' raise TypeError(_UpperCAmelCase) SCREAMING_SNAKE_CASE = ''.join(bin(_UpperCAmelCase)[2:].zfill(8) for byte in data) SCREAMING_SNAKE_CASE = len(_UpperCAmelCase) % 6 != 0 if padding_needed: # The padding that will be added later SCREAMING_SNAKE_CASE = B'=' * ((6 - len(_UpperCAmelCase) % 6) // 2) # Append binary_stream with arbitrary binary digits (0's by default) to make its # length a multiple of 6. binary_stream += "0" * (6 - len(_UpperCAmelCase) % 6) else: SCREAMING_SNAKE_CASE = B'' # Encode every 6 binary digits to their corresponding Base64 character return ( "".join( B64_CHARSET[int(binary_stream[index : index + 6] , 2)] for index in range(0 , len(_UpperCAmelCase) , 6)).encode() + padding ) def lowerCamelCase__ (_UpperCAmelCase): # Make sure encoded_data is either a string or a bytes-like object if not isinstance(_UpperCAmelCase , _UpperCAmelCase) and not isinstance(_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = ( 'argument should be a bytes-like object or ASCII string, ' F'''not \'{encoded_data.__class__.__name__}\'''' ) raise TypeError(_UpperCAmelCase) # In case encoded_data is a bytes-like object, make sure it contains only # ASCII characters so we convert it to a string object if isinstance(_UpperCAmelCase , _UpperCAmelCase): try: SCREAMING_SNAKE_CASE = encoded_data.decode('utf-8') except UnicodeDecodeError: raise ValueError('base64 encoded data should only contain ASCII characters') SCREAMING_SNAKE_CASE = encoded_data.count('=') # Check if the encoded string contains non base64 characters if padding: assert all( char in B64_CHARSET for char in encoded_data[:-padding]), "Invalid base64 character(s) found." else: assert all( char in B64_CHARSET for char in encoded_data), "Invalid base64 character(s) found." # Check the padding assert len(_UpperCAmelCase) % 4 == 0 and padding < 3, "Incorrect padding" if padding: # Remove padding if there is one SCREAMING_SNAKE_CASE = encoded_data[:-padding] SCREAMING_SNAKE_CASE = ''.join( bin(B64_CHARSET.index(_UpperCAmelCase))[2:].zfill(6) for char in encoded_data)[: -padding * 2] else: SCREAMING_SNAKE_CASE = ''.join( bin(B64_CHARSET.index(_UpperCAmelCase))[2:].zfill(6) for char in encoded_data) SCREAMING_SNAKE_CASE = [ int(binary_stream[index : index + 8] , 2) for index in range(0 , len(_UpperCAmelCase) , 8) ] return bytes(_UpperCAmelCase) if __name__ == "__main__": import doctest doctest.testmod()
73
import math import os import sys def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = '' try: with open(_UpperCAmelCase , 'rb') as binary_file: SCREAMING_SNAKE_CASE = binary_file.read() for dat in data: SCREAMING_SNAKE_CASE = F'''{dat:08b}''' result += curr_byte return result except OSError: print('File not accessible') sys.exit() def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): lexicon.pop(_UpperCAmelCase) SCREAMING_SNAKE_CASE = last_match_id if math.loga(_UpperCAmelCase).is_integer(): for curr_key in lexicon: SCREAMING_SNAKE_CASE = '0' + lexicon[curr_key] SCREAMING_SNAKE_CASE = bin(_UpperCAmelCase)[2:] def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = {'0': '0', '1': '1'} SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = '', '' SCREAMING_SNAKE_CASE = len(_UpperCAmelCase) for i in range(len(_UpperCAmelCase)): curr_string += data_bits[i] if curr_string not in lexicon: continue SCREAMING_SNAKE_CASE = lexicon[curr_string] result += last_match_id add_key_to_lexicon(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) index += 1 SCREAMING_SNAKE_CASE = '' while curr_string != "" and curr_string not in lexicon: curr_string += "0" if curr_string != "": SCREAMING_SNAKE_CASE = lexicon[curr_string] result += last_match_id return result def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = os.path.getsize(_UpperCAmelCase) SCREAMING_SNAKE_CASE = bin(_UpperCAmelCase)[2:] SCREAMING_SNAKE_CASE = len(_UpperCAmelCase) return "0" * (length_length - 1) + file_length_binary + compressed def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = 8 try: with open(_UpperCAmelCase , 'wb') as opened_file: SCREAMING_SNAKE_CASE = [ to_write[i : i + byte_length] for i in range(0 , len(_UpperCAmelCase) , _UpperCAmelCase) ] 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(_UpperCAmelCase , 2).to_bytes(1 , byteorder='big')) except OSError: print('File not accessible') sys.exit() def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = read_file_binary(_UpperCAmelCase) SCREAMING_SNAKE_CASE = compress_data(_UpperCAmelCase) SCREAMING_SNAKE_CASE = add_file_length(_UpperCAmelCase , _UpperCAmelCase) write_file_binary(_UpperCAmelCase , _UpperCAmelCase) if __name__ == "__main__": compress(sys.argv[1], sys.argv[2])
73
1
import json import logging import math import os import sys from dataclasses import dataclass, field from typing import Optional from datasets import Dataset, load_dataset import transformers from transformers import ( CONFIG_MAPPING, MODEL_FOR_MASKED_LM_MAPPING, AutoConfig, AutoModelForMaskedLM, AutoTokenizer, DataCollatorForWholeWordMask, HfArgumentParser, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import get_last_checkpoint, is_main_process a_ : str = logging.getLogger(__name__) a_ : Dict = list(MODEL_FOR_MASKED_LM_MAPPING.keys()) a_ : Tuple = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES) @dataclass class _snake_case : _lowercase : Optional[str] = field( default=A__ , metadata={ '''help''': ( '''The model checkpoint for weights initialization.Don\'t set if you want to train a model from scratch.''' ) } , ) _lowercase : Optional[str] = field( default=A__ , metadata={'''help''': '''If training from scratch, pass a model type from the list: ''' + ''', '''.join(A__ )} , ) _lowercase : Optional[str] = field( default=A__ , metadata={ '''help''': ( '''Override some existing default config settings when a model is trained from scratch. Example: ''' '''n_embd=10,resid_pdrop=0.2,scale_attn_weights=false,summary_type=cls_index''' ) } , ) _lowercase : Optional[str] = field( default=A__ , metadata={'''help''': '''Pretrained config name or path if not the same as model_name'''} ) _lowercase : Optional[str] = field( default=A__ , metadata={'''help''': '''Pretrained tokenizer name or path if not the same as model_name'''} ) _lowercase : Optional[str] = field( default=A__ , metadata={'''help''': '''Where do you want to store the pretrained models downloaded from huggingface.co'''} , ) _lowercase : bool = field( default=A__ , metadata={'''help''': '''Whether to use one of the fast tokenizer (backed by the tokenizers library) or not.'''} , ) _lowercase : str = field( default='''main''' , metadata={'''help''': '''The specific model version to use (can be a branch name, tag name or commit id).'''} , ) _lowercase : 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 SCREAMING_SNAKE_CASE__ ( self) -> List[str]: if self.config_overrides is not None and (self.config_name is not None or self.model_name_or_path is not None): raise ValueError( '--config_overrides can\'t be used in combination with --config_name or --model_name_or_path') @dataclass class _snake_case : _lowercase : Optional[str] = field( default=A__ , metadata={'''help''': '''The name of the dataset to use (via the datasets library).'''} ) _lowercase : Optional[str] = field( default=A__ , metadata={'''help''': '''The configuration name of the dataset to use (via the datasets library).'''} ) _lowercase : Optional[str] = field(default=A__ , metadata={'''help''': '''The input training data file (a text file).'''} ) _lowercase : Optional[str] = field( default=A__ , metadata={'''help''': '''An optional input evaluation data file to evaluate the perplexity on (a text file).'''} , ) _lowercase : Optional[str] = field( default=A__ , metadata={'''help''': '''An optional input train ref data file for whole word masking in Chinese.'''} , ) _lowercase : Optional[str] = field( default=A__ , metadata={'''help''': '''An optional input validation ref data file for whole word masking in Chinese.'''} , ) _lowercase : bool = field( default=A__ , metadata={'''help''': '''Overwrite the cached training and evaluation sets'''} ) _lowercase : Optional[int] = field( default=5 , metadata={ '''help''': '''The percentage of the train set used as validation set in case there\'s no validation split''' } , ) _lowercase : Optional[int] = field( default=A__ , metadata={ '''help''': ( '''The maximum total input sequence length after tokenization. Sequences longer ''' '''than this will be truncated. Default to the max input length of the model.''' ) } , ) _lowercase : Optional[int] = field( default=A__ , metadata={'''help''': '''The number of processes to use for the preprocessing.'''} , ) _lowercase : float = field( default=0.15 , metadata={'''help''': '''Ratio of tokens to mask for masked language modeling loss'''} ) _lowercase : 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.''' ) } , ) def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: if self.train_file is not None: SCREAMING_SNAKE_CASE = self.train_file.split('.')[-1] assert extension in ["csv", "json", "txt"], "`train_file` should be a csv, a json or a txt file." if self.validation_file is not None: SCREAMING_SNAKE_CASE = self.validation_file.split('.')[-1] assert extension in ["csv", "json", "txt"], "`validation_file` should be a csv, a json or a txt file." def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): with open(_UpperCAmelCase , 'r' , encoding='utf-8') as f: SCREAMING_SNAKE_CASE = [json.loads(_UpperCAmelCase) for line in f.read().splitlines() if (len(_UpperCAmelCase) > 0 and not line.isspace())] assert len(_UpperCAmelCase) == len(_UpperCAmelCase) SCREAMING_SNAKE_CASE = {c: dataset[c] for c in dataset.column_names} SCREAMING_SNAKE_CASE = refs return Dataset.from_dict(_UpperCAmelCase) def lowerCamelCase__ (): # 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. SCREAMING_SNAKE_CASE = 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. SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1])) else: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = parser.parse_args_into_dataclasses() # Detecting last checkpoint. SCREAMING_SNAKE_CASE = None if os.path.isdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir: SCREAMING_SNAKE_CASE = 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: 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.') # 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)] , ) logger.setLevel(logging.INFO if is_main_process(training_args.local_rank) else logging.WARN) # 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}''') # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank): transformers.utils.logging.set_verbosity_info() transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() logger.info('Training/evaluation parameters %s' , _UpperCAmelCase) # Set seed before initializing model. set_seed(training_args.seed) # Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below) # or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/ # (the dataset will be downloaded automatically from the datasets Hub). # # For CSV/JSON files, this script will use the column called 'text' or the first column if no column called # 'text' is found. 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. SCREAMING_SNAKE_CASE = load_dataset(data_args.dataset_name , data_args.dataset_config_name) if "validation" not in datasets.keys(): SCREAMING_SNAKE_CASE = load_dataset( data_args.dataset_name , data_args.dataset_config_name , split=F'''train[:{data_args.validation_split_percentage}%]''' , ) SCREAMING_SNAKE_CASE = load_dataset( data_args.dataset_name , data_args.dataset_config_name , split=F'''train[{data_args.validation_split_percentage}%:]''' , ) else: SCREAMING_SNAKE_CASE = {} if data_args.train_file is not None: SCREAMING_SNAKE_CASE = data_args.train_file if data_args.validation_file is not None: SCREAMING_SNAKE_CASE = data_args.validation_file SCREAMING_SNAKE_CASE = data_args.train_file.split('.')[-1] if extension == "txt": SCREAMING_SNAKE_CASE = 'text' SCREAMING_SNAKE_CASE = load_dataset(_UpperCAmelCase , data_files=_UpperCAmelCase) # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at # https://huggingface.co/docs/datasets/loading_datasets.html. # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. SCREAMING_SNAKE_CASE = { 'cache_dir': model_args.cache_dir, 'revision': model_args.model_revision, 'use_auth_token': True if model_args.use_auth_token else None, } if model_args.config_name: SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained(model_args.config_name , **_UpperCAmelCase) elif model_args.model_name_or_path: SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained(model_args.model_name_or_path , **_UpperCAmelCase) else: SCREAMING_SNAKE_CASE = CONFIG_MAPPING[model_args.model_type]() logger.warning('You are instantiating a new config instance from scratch.') if model_args.config_overrides is not None: logger.info(F'''Overriding config: {model_args.config_overrides}''') config.update_from_string(model_args.config_overrides) logger.info(F'''New config: {config}''') SCREAMING_SNAKE_CASE = { '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, } if model_args.tokenizer_name: SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained(model_args.tokenizer_name , **_UpperCAmelCase) elif model_args.model_name_or_path: SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained(model_args.model_name_or_path , **_UpperCAmelCase) else: raise ValueError( 'You are instantiating a new tokenizer from scratch. This is not supported by this script.' 'You can do it from another script, save it, and load it from here, using --tokenizer_name.') if model_args.model_name_or_path: SCREAMING_SNAKE_CASE = AutoModelForMaskedLM.from_pretrained( model_args.model_name_or_path , from_tf=bool('.ckpt' in model_args.model_name_or_path) , config=_UpperCAmelCase , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) else: logger.info('Training new model from scratch') SCREAMING_SNAKE_CASE = AutoModelForMaskedLM.from_config(_UpperCAmelCase) model.resize_token_embeddings(len(_UpperCAmelCase)) # Preprocessing the datasets. # First we tokenize all the texts. if training_args.do_train: SCREAMING_SNAKE_CASE = datasets['train'].column_names else: SCREAMING_SNAKE_CASE = datasets['validation'].column_names SCREAMING_SNAKE_CASE = 'text' if 'text' in column_names else column_names[0] SCREAMING_SNAKE_CASE = 'max_length' if data_args.pad_to_max_length else False def tokenize_function(_UpperCAmelCase): # Remove empty lines SCREAMING_SNAKE_CASE = [line for line in examples['text'] if len(_UpperCAmelCase) > 0 and not line.isspace()] return tokenizer(examples['text'] , padding=_UpperCAmelCase , truncation=_UpperCAmelCase , max_length=data_args.max_seq_length) SCREAMING_SNAKE_CASE = datasets.map( _UpperCAmelCase , batched=_UpperCAmelCase , num_proc=data_args.preprocessing_num_workers , remove_columns=[text_column_name] , load_from_cache_file=not data_args.overwrite_cache , ) # Add the chinese references if provided if data_args.train_ref_file is not None: SCREAMING_SNAKE_CASE = add_chinese_references(tokenized_datasets['train'] , data_args.train_ref_file) if data_args.validation_ref_file is not None: SCREAMING_SNAKE_CASE = add_chinese_references( tokenized_datasets['validation'] , data_args.validation_ref_file) # If we have ref files, need to avoid it removed by trainer SCREAMING_SNAKE_CASE = data_args.train_ref_file or data_args.validation_ref_file if has_ref: SCREAMING_SNAKE_CASE = False # Data collator # This one will take care of randomly masking the tokens. SCREAMING_SNAKE_CASE = DataCollatorForWholeWordMask(tokenizer=_UpperCAmelCase , mlm_probability=data_args.mlm_probability) # Initialize our Trainer SCREAMING_SNAKE_CASE = Trainer( model=_UpperCAmelCase , args=_UpperCAmelCase , train_dataset=tokenized_datasets['train'] if training_args.do_train else None , eval_dataset=tokenized_datasets['validation'] if training_args.do_eval else None , tokenizer=_UpperCAmelCase , data_collator=_UpperCAmelCase , ) # Training if training_args.do_train: if last_checkpoint is not None: SCREAMING_SNAKE_CASE = last_checkpoint elif model_args.model_name_or_path is not None and os.path.isdir(model_args.model_name_or_path): SCREAMING_SNAKE_CASE = model_args.model_name_or_path else: SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = trainer.train(resume_from_checkpoint=_UpperCAmelCase) trainer.save_model() # Saves the tokenizer too for easy upload SCREAMING_SNAKE_CASE = os.path.join(training_args.output_dir , 'train_results.txt') if trainer.is_world_process_zero(): with open(_UpperCAmelCase , 'w') as writer: logger.info('***** Train results *****') for key, value in sorted(train_result.metrics.items()): logger.info(F''' {key} = {value}''') writer.write(F'''{key} = {value}\n''') # Need to save the state, since Trainer.save_model saves only the tokenizer with the model trainer.state.save_to_json(os.path.join(training_args.output_dir , 'trainer_state.json')) # Evaluation SCREAMING_SNAKE_CASE = {} if training_args.do_eval: logger.info('*** Evaluate ***') SCREAMING_SNAKE_CASE = trainer.evaluate() SCREAMING_SNAKE_CASE = math.exp(eval_output['eval_loss']) SCREAMING_SNAKE_CASE = perplexity SCREAMING_SNAKE_CASE = os.path.join(training_args.output_dir , 'eval_results_mlm_wwm.txt') if trainer.is_world_process_zero(): with open(_UpperCAmelCase , 'w') as writer: logger.info('***** Eval results *****') for key, value in sorted(results.items()): logger.info(F''' {key} = {value}''') writer.write(F'''{key} = {value}\n''') return results def lowerCamelCase__ (_UpperCAmelCase): # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
73
import warnings from typing import Dict import numpy as np from ..utils import ExplicitEnum, add_end_docstrings, is_tf_available, is_torch_available from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline if is_tf_available(): from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if is_torch_available(): from ..models.auto.modeling_auto import MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING def lowerCamelCase__ (_UpperCAmelCase): return 1.0 / (1.0 + np.exp(-_outputs)) def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = np.max(_outputs , axis=-1 , keepdims=_UpperCAmelCase) SCREAMING_SNAKE_CASE = np.exp(_outputs - maxes) return shifted_exp / shifted_exp.sum(axis=-1 , keepdims=_UpperCAmelCase) class _snake_case ( A__ ): _lowercase : Tuple = '''sigmoid''' _lowercase : List[str] = '''softmax''' _lowercase : Tuple = '''none''' @add_end_docstrings( A__ , R''' return_all_scores (`bool`, *optional*, defaults to `False`): Whether to return all prediction scores or just the one of the predicted class. function_to_apply (`str`, *optional*, defaults to `"default"`): The function to apply to the model outputs in order to retrieve the scores. Accepts four different values: - `"default"`: if the model has a single label, will apply the sigmoid function on the output. If the model has several labels, will apply the softmax function on the output. - `"sigmoid"`: Applies the sigmoid function on the output. - `"softmax"`: Applies the softmax function on the output. - `"none"`: Does not apply any function on the output. ''' , ) class _snake_case ( A__ ): _lowercase : Optional[Any] = False _lowercase : Tuple = ClassificationFunction.NONE def __init__( self , **a) -> Optional[Any]: super().__init__(**a) self.check_model_type( TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if self.framework == 'tf' else MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING) def SCREAMING_SNAKE_CASE__ ( self , a=None , a=None , a="" , **a) -> Tuple: # Using "" as default argument because we're going to use `top_k=None` in user code to declare # "No top_k" SCREAMING_SNAKE_CASE = tokenizer_kwargs SCREAMING_SNAKE_CASE = {} if hasattr(self.model.config , 'return_all_scores') and return_all_scores is None: SCREAMING_SNAKE_CASE = self.model.config.return_all_scores if isinstance(a , a) or top_k is None: SCREAMING_SNAKE_CASE = top_k SCREAMING_SNAKE_CASE = False elif return_all_scores is not None: warnings.warn( '`return_all_scores` is now deprecated, if want a similar functionality use `top_k=None` instead of' ' `return_all_scores=True` or `top_k=1` instead of `return_all_scores=False`.' , a , ) if return_all_scores: SCREAMING_SNAKE_CASE = None else: SCREAMING_SNAKE_CASE = 1 if isinstance(a , a): SCREAMING_SNAKE_CASE = ClassificationFunction[function_to_apply.upper()] if function_to_apply is not None: SCREAMING_SNAKE_CASE = function_to_apply return preprocess_params, {}, postprocess_params def __call__( self , *a , **a) -> Optional[int]: SCREAMING_SNAKE_CASE = super().__call__(*a , **a) # TODO try and retrieve it in a nicer way from _sanitize_parameters. SCREAMING_SNAKE_CASE = 'top_k' not in kwargs if isinstance(args[0] , a) and _legacy: # This pipeline is odd, and return a list when single item is run return [result] else: return result def SCREAMING_SNAKE_CASE__ ( self , a , **a) -> Dict[str, GenericTensor]: SCREAMING_SNAKE_CASE = self.framework if isinstance(a , a): return self.tokenizer(**a , return_tensors=a , **a) elif isinstance(a , a) and len(a) == 1 and isinstance(inputs[0] , a) and len(inputs[0]) == 2: # It used to be valid to use a list of list of list for text pairs, keeping this path for BC return self.tokenizer( text=inputs[0][0] , text_pair=inputs[0][1] , return_tensors=a , **a) elif isinstance(a , a): # This is likely an invalid usage of the pipeline attempting to pass text pairs. raise ValueError( 'The pipeline received invalid inputs, if you are trying to send text pairs, you can try to send a' ' dictionary `{"text": "My text", "text_pair": "My pair"}` in order to send a text pair.') return self.tokenizer(a , return_tensors=a , **a) def SCREAMING_SNAKE_CASE__ ( self , a) -> Optional[Any]: return self.model(**a) def SCREAMING_SNAKE_CASE__ ( self , a , a=None , a=1 , a=True) -> Any: # `_legacy` is used to determine if we're running the naked pipeline and in backward # compatibility mode, or if running the pipeline with `pipeline(..., top_k=1)` we're running # the more natural result containing the list. # Default value before `set_parameters` if function_to_apply is None: if self.model.config.problem_type == "multi_label_classification" or self.model.config.num_labels == 1: SCREAMING_SNAKE_CASE = ClassificationFunction.SIGMOID elif self.model.config.problem_type == "single_label_classification" or self.model.config.num_labels > 1: SCREAMING_SNAKE_CASE = ClassificationFunction.SOFTMAX elif hasattr(self.model.config , 'function_to_apply') and function_to_apply is None: SCREAMING_SNAKE_CASE = self.model.config.function_to_apply else: SCREAMING_SNAKE_CASE = ClassificationFunction.NONE SCREAMING_SNAKE_CASE = model_outputs['logits'][0] SCREAMING_SNAKE_CASE = outputs.numpy() if function_to_apply == ClassificationFunction.SIGMOID: SCREAMING_SNAKE_CASE = sigmoid(a) elif function_to_apply == ClassificationFunction.SOFTMAX: SCREAMING_SNAKE_CASE = softmax(a) elif function_to_apply == ClassificationFunction.NONE: SCREAMING_SNAKE_CASE = outputs else: raise ValueError(f'''Unrecognized `function_to_apply` argument: {function_to_apply}''') if top_k == 1 and _legacy: return {"label": self.model.config.idalabel[scores.argmax().item()], "score": scores.max().item()} SCREAMING_SNAKE_CASE = [ {'label': self.model.config.idalabel[i], 'score': score.item()} for i, score in enumerate(a) ] if not _legacy: dict_scores.sort(key=lambda a: x["score"] , reverse=a) if top_k is not None: SCREAMING_SNAKE_CASE = dict_scores[:top_k] return dict_scores
73
1
from math import sqrt def lowerCamelCase__ (_UpperCAmelCase): if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(sqrt(_UpperCAmelCase) + 1) , 6): if number % i == 0 or number % (i + 2) == 0: return False return True def lowerCamelCase__ (_UpperCAmelCase = 1_0001): SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = 1 while count != nth and number < 3: number += 1 if is_prime(_UpperCAmelCase): count += 1 while count != nth: number += 2 if is_prime(_UpperCAmelCase): count += 1 return number if __name__ == "__main__": print(f"""{solution() = }""")
73
import heapq as hq import math from collections.abc import Iterator class _snake_case : def __init__( self , a) -> Optional[Any]: SCREAMING_SNAKE_CASE = str(id_) SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = {} # {vertex:distance} def __lt__( self , a) -> Dict: return self.key < other.key def __repr__( self) -> Optional[Any]: return self.id def SCREAMING_SNAKE_CASE__ ( self , a) -> Optional[Any]: self.neighbors.append(a) def SCREAMING_SNAKE_CASE__ ( self , a , a) -> Tuple: SCREAMING_SNAKE_CASE = weight def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): # add the neighbors: graph[a - 1].add_neighbor(graph[b - 1]) graph[b - 1].add_neighbor(graph[a - 1]) # add the edges: graph[a - 1].add_edge(graph[b - 1] , _UpperCAmelCase) graph[b - 1].add_edge(graph[a - 1] , _UpperCAmelCase) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = [] for u in graph: SCREAMING_SNAKE_CASE = math.inf SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = graph[:] while q: SCREAMING_SNAKE_CASE = min(_UpperCAmelCase) q.remove(_UpperCAmelCase) for v in u.neighbors: if (v in q) and (u.edges[v.id] < v.key): SCREAMING_SNAKE_CASE = u SCREAMING_SNAKE_CASE = u.edges[v.id] for i in range(1 , len(_UpperCAmelCase)): a.append((int(graph[i].id) + 1, int(graph[i].pi.id) + 1)) return a def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): for u in graph: SCREAMING_SNAKE_CASE = math.inf SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = list(_UpperCAmelCase) hq.heapify(_UpperCAmelCase) while h: SCREAMING_SNAKE_CASE = hq.heappop(_UpperCAmelCase) for v in u.neighbors: if (v in h) and (u.edges[v.id] < v.key): SCREAMING_SNAKE_CASE = u SCREAMING_SNAKE_CASE = u.edges[v.id] hq.heapify(_UpperCAmelCase) for i in range(1 , len(_UpperCAmelCase)): yield (int(graph[i].id) + 1, int(graph[i].pi.id) + 1) def lowerCamelCase__ (): pass if __name__ == "__main__": import doctest doctest.testmod()
73
1
import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class _snake_case ( A__ ): _lowercase : Tuple = ['''image_processor''', '''tokenizer'''] _lowercase : List[Any] = '''ViTImageProcessor''' _lowercase : Optional[Any] = ('''CLIPTokenizer''', '''CLIPTokenizerFast''') def __init__( self , a=None , a=None , **a) -> Optional[Any]: SCREAMING_SNAKE_CASE = None if "feature_extractor" in kwargs: warnings.warn( 'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`' ' instead.' , a , ) SCREAMING_SNAKE_CASE = kwargs.pop('feature_extractor') SCREAMING_SNAKE_CASE = 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__(a , a) def __call__( self , a=None , a=None , a=None , a=None , **a) -> int: if text is None and visual_prompt is None and images is None: raise ValueError('You have to specify either text, visual prompt or images.') if text is not None and visual_prompt is not None: raise ValueError('You have to specify exactly one type of prompt. Either text or visual prompt.') if text is not None: SCREAMING_SNAKE_CASE = self.tokenizer(a , return_tensors=a , **a) if visual_prompt is not None: SCREAMING_SNAKE_CASE = self.image_processor(a , return_tensors=a , **a) if images is not None: SCREAMING_SNAKE_CASE = self.image_processor(a , return_tensors=a , **a) if visual_prompt is not None and images is not None: SCREAMING_SNAKE_CASE = { 'pixel_values': image_features.pixel_values, 'conditional_pixel_values': prompt_features.pixel_values, } return encoding elif text is not None and images is not None: SCREAMING_SNAKE_CASE = image_features.pixel_values return encoding elif text is not None: return encoding elif visual_prompt is not None: SCREAMING_SNAKE_CASE = { 'conditional_pixel_values': prompt_features.pixel_values, } return encoding else: return BatchEncoding(data=dict(**a) , tensor_type=a) def SCREAMING_SNAKE_CASE__ ( self , *a , **a) -> List[str]: return self.tokenizer.batch_decode(*a , **a) def SCREAMING_SNAKE_CASE__ ( self , *a , **a) -> int: return self.tokenizer.decode(*a , **a) @property def SCREAMING_SNAKE_CASE__ ( self) -> str: warnings.warn( '`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.' , a , ) return self.image_processor_class @property def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: warnings.warn( '`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.' , a , ) return self.image_processor
73
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available a_ : Optional[Any] = { 'configuration_mask2former': [ 'MASK2FORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'Mask2FormerConfig', ], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : Union[str, Any] = ['Mask2FormerImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : List[Any] = [ 'MASK2FORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'Mask2FormerForUniversalSegmentation', 'Mask2FormerModel', 'Mask2FormerPreTrainedModel', ] if TYPE_CHECKING: from .configuration_maskaformer import MASK2FORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, MaskaFormerConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_maskaformer import MaskaFormerImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_maskaformer import ( MASK2FORMER_PRETRAINED_MODEL_ARCHIVE_LIST, MaskaFormerForUniversalSegmentation, MaskaFormerModel, MaskaFormerPreTrainedModel, ) else: import sys a_ : str = _LazyModule(__name__, globals()['__file__'], _import_structure)
73
1
import unittest from transformers import DonutProcessor a_ : Any = 'naver-clova-ix/donut-base' class _snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: SCREAMING_SNAKE_CASE = DonutProcessor.from_pretrained(a) def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: SCREAMING_SNAKE_CASE = { 'name': 'John Doe', 'age': '99', 'city': 'Atlanta', 'state': 'GA', 'zip': '30301', 'phone': '123-4567', 'nicknames': [{'nickname': 'Johnny'}, {'nickname': 'JD'}], } SCREAMING_SNAKE_CASE = ( '<s_name>John Doe</s_name><s_age>99</s_age><s_city>Atlanta</s_city>' '<s_state>GA</s_state><s_zip>30301</s_zip><s_phone>123-4567</s_phone>' '<s_nicknames><s_nickname>Johnny</s_nickname>' '<sep/><s_nickname>JD</s_nickname></s_nicknames>' ) SCREAMING_SNAKE_CASE = self.processor.tokenajson(a) self.assertDictEqual(a , a)
73
from ...configuration_utils import PretrainedConfig from ...utils import logging a_ : Dict = logging.get_logger(__name__) a_ : Union[str, Any] = { 'edbeeching/decision-transformer-gym-hopper-medium': ( 'https://huggingface.co/edbeeching/decision-transformer-gym-hopper-medium/resolve/main/config.json' ), # See all DecisionTransformer models at https://huggingface.co/models?filter=decision_transformer } class _snake_case ( A__ ): _lowercase : Optional[Any] = '''decision_transformer''' _lowercase : str = ['''past_key_values'''] _lowercase : Union[str, Any] = { '''max_position_embeddings''': '''n_positions''', '''num_attention_heads''': '''n_head''', '''num_hidden_layers''': '''n_layer''', } def __init__( self , a=17 , a=4 , a=128 , a=4096 , a=True , a=1 , a=1024 , a=3 , a=1 , a=None , a="relu" , a=0.1 , a=0.1 , a=0.1 , a=1E-5 , a=0.02 , a=True , a=True , a=5_0256 , a=5_0256 , a=False , a=False , **a , ) -> List[str]: SCREAMING_SNAKE_CASE = state_dim SCREAMING_SNAKE_CASE = act_dim SCREAMING_SNAKE_CASE = hidden_size SCREAMING_SNAKE_CASE = max_ep_len SCREAMING_SNAKE_CASE = action_tanh SCREAMING_SNAKE_CASE = vocab_size SCREAMING_SNAKE_CASE = n_positions SCREAMING_SNAKE_CASE = n_layer SCREAMING_SNAKE_CASE = n_head SCREAMING_SNAKE_CASE = n_inner SCREAMING_SNAKE_CASE = activation_function SCREAMING_SNAKE_CASE = resid_pdrop SCREAMING_SNAKE_CASE = embd_pdrop SCREAMING_SNAKE_CASE = attn_pdrop SCREAMING_SNAKE_CASE = layer_norm_epsilon SCREAMING_SNAKE_CASE = initializer_range SCREAMING_SNAKE_CASE = scale_attn_weights SCREAMING_SNAKE_CASE = use_cache SCREAMING_SNAKE_CASE = scale_attn_by_inverse_layer_idx SCREAMING_SNAKE_CASE = reorder_and_upcast_attn SCREAMING_SNAKE_CASE = bos_token_id SCREAMING_SNAKE_CASE = eos_token_id super().__init__(bos_token_id=a , eos_token_id=a , **a)
73
1
import gc import unittest import numpy as np import torch import torch.nn.functional as F from transformers import ( ClapTextConfig, ClapTextModelWithProjection, RobertaTokenizer, SpeechTaHifiGan, SpeechTaHifiGanConfig, ) from diffusers import ( AudioLDMPipeline, AutoencoderKL, DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionModel, ) from diffusers.utils import is_xformers_available, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism from ..pipeline_params import TEXT_TO_AUDIO_BATCH_PARAMS, TEXT_TO_AUDIO_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class _snake_case ( A__ , unittest.TestCase ): _lowercase : Optional[int] = AudioLDMPipeline _lowercase : Union[str, Any] = TEXT_TO_AUDIO_PARAMS _lowercase : List[str] = TEXT_TO_AUDIO_BATCH_PARAMS _lowercase : Tuple = frozenset( [ '''num_inference_steps''', '''num_waveforms_per_prompt''', '''generator''', '''latents''', '''output_type''', '''return_dict''', '''callback''', '''callback_steps''', ] ) def SCREAMING_SNAKE_CASE__ ( self) -> Dict: torch.manual_seed(0) SCREAMING_SNAKE_CASE = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D') , up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D') , cross_attention_dim=(32, 64) , class_embed_type='simple_projection' , projection_class_embeddings_input_dim=32 , class_embeddings_concat=a , ) SCREAMING_SNAKE_CASE = DDIMScheduler( beta_start=0.0_00_85 , beta_end=0.0_12 , beta_schedule='scaled_linear' , clip_sample=a , set_alpha_to_one=a , ) torch.manual_seed(0) SCREAMING_SNAKE_CASE = AutoencoderKL( block_out_channels=[32, 64] , in_channels=1 , out_channels=1 , down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D'] , up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D'] , latent_channels=4 , ) torch.manual_seed(0) SCREAMING_SNAKE_CASE = ClapTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , projection_dim=32 , ) SCREAMING_SNAKE_CASE = ClapTextModelWithProjection(a) SCREAMING_SNAKE_CASE = RobertaTokenizer.from_pretrained('hf-internal-testing/tiny-random-roberta' , model_max_length=77) SCREAMING_SNAKE_CASE = SpeechTaHifiGanConfig( model_in_dim=8 , sampling_rate=1_6000 , upsample_initial_channel=16 , upsample_rates=[2, 2] , upsample_kernel_sizes=[4, 4] , resblock_kernel_sizes=[3, 7] , resblock_dilation_sizes=[[1, 3, 5], [1, 3, 5]] , normalize_before=a , ) SCREAMING_SNAKE_CASE = SpeechTaHifiGan(a) SCREAMING_SNAKE_CASE = { 'unet': unet, 'scheduler': scheduler, 'vae': vae, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'vocoder': vocoder, } return components def SCREAMING_SNAKE_CASE__ ( self , a , a=0) -> int: if str(a).startswith('mps'): SCREAMING_SNAKE_CASE = torch.manual_seed(a) else: SCREAMING_SNAKE_CASE = torch.Generator(device=a).manual_seed(a) SCREAMING_SNAKE_CASE = { 'prompt': 'A hammer hitting a wooden surface', 'generator': generator, 'num_inference_steps': 2, 'guidance_scale': 6.0, } return inputs def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: SCREAMING_SNAKE_CASE = 'cpu' # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE = self.get_dummy_components() SCREAMING_SNAKE_CASE = AudioLDMPipeline(**a) SCREAMING_SNAKE_CASE = audioldm_pipe.to(a) audioldm_pipe.set_progress_bar_config(disable=a) SCREAMING_SNAKE_CASE = self.get_dummy_inputs(a) SCREAMING_SNAKE_CASE = audioldm_pipe(**a) SCREAMING_SNAKE_CASE = output.audios[0] assert audio.ndim == 1 assert len(a) == 256 SCREAMING_SNAKE_CASE = audio[:10] SCREAMING_SNAKE_CASE = np.array( [-0.00_50, 0.00_50, -0.00_60, 0.00_33, -0.00_26, 0.00_33, -0.00_27, 0.00_33, -0.00_28, 0.00_33]) assert np.abs(audio_slice - expected_slice).max() < 1E-2 def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: SCREAMING_SNAKE_CASE = self.get_dummy_components() SCREAMING_SNAKE_CASE = AudioLDMPipeline(**a) SCREAMING_SNAKE_CASE = audioldm_pipe.to(a) SCREAMING_SNAKE_CASE = audioldm_pipe.to(a) audioldm_pipe.set_progress_bar_config(disable=a) SCREAMING_SNAKE_CASE = self.get_dummy_inputs(a) SCREAMING_SNAKE_CASE = 3 * [inputs['prompt']] # forward SCREAMING_SNAKE_CASE = audioldm_pipe(**a) SCREAMING_SNAKE_CASE = output.audios[0] SCREAMING_SNAKE_CASE = self.get_dummy_inputs(a) SCREAMING_SNAKE_CASE = 3 * [inputs.pop('prompt')] SCREAMING_SNAKE_CASE = audioldm_pipe.tokenizer( a , padding='max_length' , max_length=audioldm_pipe.tokenizer.model_max_length , truncation=a , return_tensors='pt' , ) SCREAMING_SNAKE_CASE = text_inputs['input_ids'].to(a) SCREAMING_SNAKE_CASE = audioldm_pipe.text_encoder( a , ) SCREAMING_SNAKE_CASE = prompt_embeds.text_embeds # additional L_2 normalization over each hidden-state SCREAMING_SNAKE_CASE = F.normalize(a , dim=-1) SCREAMING_SNAKE_CASE = prompt_embeds # forward SCREAMING_SNAKE_CASE = audioldm_pipe(**a) SCREAMING_SNAKE_CASE = output.audios[0] assert np.abs(audio_a - audio_a).max() < 1E-2 def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: SCREAMING_SNAKE_CASE = self.get_dummy_components() SCREAMING_SNAKE_CASE = AudioLDMPipeline(**a) SCREAMING_SNAKE_CASE = audioldm_pipe.to(a) SCREAMING_SNAKE_CASE = audioldm_pipe.to(a) audioldm_pipe.set_progress_bar_config(disable=a) SCREAMING_SNAKE_CASE = self.get_dummy_inputs(a) SCREAMING_SNAKE_CASE = 3 * ['this is a negative prompt'] SCREAMING_SNAKE_CASE = negative_prompt SCREAMING_SNAKE_CASE = 3 * [inputs['prompt']] # forward SCREAMING_SNAKE_CASE = audioldm_pipe(**a) SCREAMING_SNAKE_CASE = output.audios[0] SCREAMING_SNAKE_CASE = self.get_dummy_inputs(a) SCREAMING_SNAKE_CASE = 3 * [inputs.pop('prompt')] SCREAMING_SNAKE_CASE = [] for p in [prompt, negative_prompt]: SCREAMING_SNAKE_CASE = audioldm_pipe.tokenizer( a , padding='max_length' , max_length=audioldm_pipe.tokenizer.model_max_length , truncation=a , return_tensors='pt' , ) SCREAMING_SNAKE_CASE = text_inputs['input_ids'].to(a) SCREAMING_SNAKE_CASE = audioldm_pipe.text_encoder( a , ) SCREAMING_SNAKE_CASE = text_embeds.text_embeds # additional L_2 normalization over each hidden-state SCREAMING_SNAKE_CASE = F.normalize(a , dim=-1) embeds.append(a) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = embeds # forward SCREAMING_SNAKE_CASE = audioldm_pipe(**a) SCREAMING_SNAKE_CASE = output.audios[0] assert np.abs(audio_a - audio_a).max() < 1E-2 def SCREAMING_SNAKE_CASE__ ( self) -> Dict: SCREAMING_SNAKE_CASE = 'cpu' # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE = self.get_dummy_components() SCREAMING_SNAKE_CASE = PNDMScheduler(skip_prk_steps=a) SCREAMING_SNAKE_CASE = AudioLDMPipeline(**a) SCREAMING_SNAKE_CASE = audioldm_pipe.to(a) audioldm_pipe.set_progress_bar_config(disable=a) SCREAMING_SNAKE_CASE = self.get_dummy_inputs(a) SCREAMING_SNAKE_CASE = 'egg cracking' SCREAMING_SNAKE_CASE = audioldm_pipe(**a , negative_prompt=a) SCREAMING_SNAKE_CASE = output.audios[0] assert audio.ndim == 1 assert len(a) == 256 SCREAMING_SNAKE_CASE = audio[:10] SCREAMING_SNAKE_CASE = np.array( [-0.00_51, 0.00_50, -0.00_60, 0.00_34, -0.00_26, 0.00_33, -0.00_27, 0.00_33, -0.00_28, 0.00_32]) assert np.abs(audio_slice - expected_slice).max() < 1E-2 def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: SCREAMING_SNAKE_CASE = 'cpu' # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE = self.get_dummy_components() SCREAMING_SNAKE_CASE = PNDMScheduler(skip_prk_steps=a) SCREAMING_SNAKE_CASE = AudioLDMPipeline(**a) SCREAMING_SNAKE_CASE = audioldm_pipe.to(a) audioldm_pipe.set_progress_bar_config(disable=a) SCREAMING_SNAKE_CASE = 'A hammer hitting a wooden surface' # test num_waveforms_per_prompt=1 (default) SCREAMING_SNAKE_CASE = audioldm_pipe(a , num_inference_steps=2).audios assert audios.shape == (1, 256) # test num_waveforms_per_prompt=1 (default) for batch of prompts SCREAMING_SNAKE_CASE = 2 SCREAMING_SNAKE_CASE = audioldm_pipe([prompt] * batch_size , num_inference_steps=2).audios assert audios.shape == (batch_size, 256) # test num_waveforms_per_prompt for single prompt SCREAMING_SNAKE_CASE = 2 SCREAMING_SNAKE_CASE = audioldm_pipe(a , num_inference_steps=2 , num_waveforms_per_prompt=a).audios assert audios.shape == (num_waveforms_per_prompt, 256) # test num_waveforms_per_prompt for batch of prompts SCREAMING_SNAKE_CASE = 2 SCREAMING_SNAKE_CASE = audioldm_pipe( [prompt] * batch_size , num_inference_steps=2 , num_waveforms_per_prompt=a).audios assert audios.shape == (batch_size * num_waveforms_per_prompt, 256) def SCREAMING_SNAKE_CASE__ ( self) -> str: SCREAMING_SNAKE_CASE = 'cpu' # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE = self.get_dummy_components() SCREAMING_SNAKE_CASE = AudioLDMPipeline(**a) SCREAMING_SNAKE_CASE = audioldm_pipe.to(a) audioldm_pipe.set_progress_bar_config(disable=a) SCREAMING_SNAKE_CASE = audioldm_pipe.vocoder.config.sampling_rate SCREAMING_SNAKE_CASE = self.get_dummy_inputs(a) SCREAMING_SNAKE_CASE = audioldm_pipe(audio_length_in_s=0.0_16 , **a) SCREAMING_SNAKE_CASE = output.audios[0] assert audio.ndim == 1 assert len(a) / vocoder_sampling_rate == 0.0_16 SCREAMING_SNAKE_CASE = audioldm_pipe(audio_length_in_s=0.0_32 , **a) SCREAMING_SNAKE_CASE = output.audios[0] assert audio.ndim == 1 assert len(a) / vocoder_sampling_rate == 0.0_32 def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: SCREAMING_SNAKE_CASE = self.get_dummy_components() SCREAMING_SNAKE_CASE = AudioLDMPipeline(**a) SCREAMING_SNAKE_CASE = audioldm_pipe.to(a) audioldm_pipe.set_progress_bar_config(disable=a) SCREAMING_SNAKE_CASE = ['hey'] SCREAMING_SNAKE_CASE = audioldm_pipe(a , num_inference_steps=1) SCREAMING_SNAKE_CASE = output.audios.shape assert audio_shape == (1, 256) SCREAMING_SNAKE_CASE = audioldm_pipe.vocoder.config config.model_in_dim *= 2 SCREAMING_SNAKE_CASE = SpeechTaHifiGan(a).to(a) SCREAMING_SNAKE_CASE = audioldm_pipe(a , num_inference_steps=1) SCREAMING_SNAKE_CASE = output.audios.shape # waveform shape is unchanged, we just have 2x the number of mel channels in the spectrogram assert audio_shape == (1, 256) def SCREAMING_SNAKE_CASE__ ( self) -> Dict: self._test_attention_slicing_forward_pass(test_mean_pixel_difference=a) def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: self._test_inference_batch_single_identical(test_mean_pixel_difference=a) @unittest.skipIf( torch_device != 'cuda' or not is_xformers_available() , reason='XFormers attention is only available with CUDA and `xformers` installed' , ) def SCREAMING_SNAKE_CASE__ ( self) -> int: self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=a) @slow class _snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: super().tearDown() gc.collect() torch.cuda.empty_cache() def SCREAMING_SNAKE_CASE__ ( self , a , a="cpu" , a=torch.floataa , a=0) -> Dict: SCREAMING_SNAKE_CASE = torch.Generator(device=a).manual_seed(a) SCREAMING_SNAKE_CASE = np.random.RandomState(a).standard_normal((1, 8, 128, 16)) SCREAMING_SNAKE_CASE = torch.from_numpy(a).to(device=a , dtype=a) SCREAMING_SNAKE_CASE = { 'prompt': 'A hammer hitting a wooden surface', 'latents': latents, 'generator': generator, 'num_inference_steps': 3, 'guidance_scale': 2.5, } return inputs def SCREAMING_SNAKE_CASE__ ( self) -> Any: SCREAMING_SNAKE_CASE = AudioLDMPipeline.from_pretrained('cvssp/audioldm') SCREAMING_SNAKE_CASE = audioldm_pipe.to(a) audioldm_pipe.set_progress_bar_config(disable=a) SCREAMING_SNAKE_CASE = self.get_inputs(a) SCREAMING_SNAKE_CASE = 25 SCREAMING_SNAKE_CASE = audioldm_pipe(**a).audios[0] assert audio.ndim == 1 assert len(a) == 8_1920 SCREAMING_SNAKE_CASE = audio[7_7230:7_7240] SCREAMING_SNAKE_CASE = np.array( [-0.48_84, -0.46_07, 0.00_23, 0.50_07, 0.58_96, 0.51_51, 0.38_13, -0.02_08, -0.36_87, -0.43_15]) SCREAMING_SNAKE_CASE = np.abs(expected_slice - audio_slice).max() assert max_diff < 1E-2 def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: SCREAMING_SNAKE_CASE = AudioLDMPipeline.from_pretrained('cvssp/audioldm') SCREAMING_SNAKE_CASE = LMSDiscreteScheduler.from_config(audioldm_pipe.scheduler.config) SCREAMING_SNAKE_CASE = audioldm_pipe.to(a) audioldm_pipe.set_progress_bar_config(disable=a) SCREAMING_SNAKE_CASE = self.get_inputs(a) SCREAMING_SNAKE_CASE = audioldm_pipe(**a).audios[0] assert audio.ndim == 1 assert len(a) == 8_1920 SCREAMING_SNAKE_CASE = audio[2_7780:2_7790] SCREAMING_SNAKE_CASE = np.array([-0.21_31, -0.08_73, -0.01_24, -0.01_89, 0.05_69, 0.13_73, 0.18_83, 0.28_86, 0.32_97, 0.22_12]) SCREAMING_SNAKE_CASE = np.abs(expected_slice - audio_slice).max() assert max_diff < 3E-2
73
import argparse import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType ######################################################################## # This is a fully working simple example to use Accelerate # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## a_ : Optional[int] = 16 a_ : Any = 32 def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase = 16): SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained('bert-base-cased') SCREAMING_SNAKE_CASE = load_dataset('glue' , 'mrpc') def tokenize_function(_UpperCAmelCase): # max_length=None => use the model max length (it's actually the default) SCREAMING_SNAKE_CASE = tokenizer(examples['sentence1'] , examples['sentence2'] , truncation=_UpperCAmelCase , max_length=_UpperCAmelCase) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): SCREAMING_SNAKE_CASE = datasets.map( _UpperCAmelCase , batched=_UpperCAmelCase , remove_columns=['idx', 'sentence1', 'sentence2'] , ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library SCREAMING_SNAKE_CASE = tokenized_datasets.rename_column('label' , 'labels') def collate_fn(_UpperCAmelCase): # On TPU it's best to pad everything to the same length or training will be very slow. SCREAMING_SNAKE_CASE = 128 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": SCREAMING_SNAKE_CASE = 16 elif accelerator.mixed_precision != "no": SCREAMING_SNAKE_CASE = 8 else: SCREAMING_SNAKE_CASE = None return tokenizer.pad( _UpperCAmelCase , padding='longest' , max_length=_UpperCAmelCase , pad_to_multiple_of=_UpperCAmelCase , return_tensors='pt' , ) # Instantiate dataloaders. SCREAMING_SNAKE_CASE = DataLoader( tokenized_datasets['train'] , shuffle=_UpperCAmelCase , collate_fn=_UpperCAmelCase , batch_size=_UpperCAmelCase , drop_last=_UpperCAmelCase) SCREAMING_SNAKE_CASE = DataLoader( tokenized_datasets['validation'] , shuffle=_UpperCAmelCase , collate_fn=_UpperCAmelCase , batch_size=_UpperCAmelCase , drop_last=(accelerator.mixed_precision == 'fp8') , ) return train_dataloader, eval_dataloader def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): # Initialize accelerator SCREAMING_SNAKE_CASE = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs SCREAMING_SNAKE_CASE = config['lr'] SCREAMING_SNAKE_CASE = int(config['num_epochs']) SCREAMING_SNAKE_CASE = int(config['seed']) SCREAMING_SNAKE_CASE = int(config['batch_size']) SCREAMING_SNAKE_CASE = evaluate.load('glue' , 'mrpc') # If the batch size is too big we use gradient accumulation SCREAMING_SNAKE_CASE = 1 if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU: SCREAMING_SNAKE_CASE = batch_size // MAX_GPU_BATCH_SIZE SCREAMING_SNAKE_CASE = MAX_GPU_BATCH_SIZE set_seed(_UpperCAmelCase) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = get_dataloaders(_UpperCAmelCase , _UpperCAmelCase) # Instantiate the model (we build the model here so that the seed also control new weights initialization) SCREAMING_SNAKE_CASE = AutoModelForSequenceClassification.from_pretrained('bert-base-cased' , return_dict=_UpperCAmelCase) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). SCREAMING_SNAKE_CASE = model.to(accelerator.device) # Instantiate optimizer SCREAMING_SNAKE_CASE = AdamW(params=model.parameters() , lr=_UpperCAmelCase) # Instantiate scheduler SCREAMING_SNAKE_CASE = get_linear_schedule_with_warmup( optimizer=_UpperCAmelCase , num_warmup_steps=100 , num_training_steps=(len(_UpperCAmelCase) * num_epochs) // gradient_accumulation_steps , ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = accelerator.prepare( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) # Now we train the model for epoch in range(_UpperCAmelCase): model.train() for step, batch in enumerate(_UpperCAmelCase): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device) SCREAMING_SNAKE_CASE = model(**_UpperCAmelCase) SCREAMING_SNAKE_CASE = outputs.loss SCREAMING_SNAKE_CASE = loss / gradient_accumulation_steps accelerator.backward(_UpperCAmelCase) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(_UpperCAmelCase): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device) with torch.no_grad(): SCREAMING_SNAKE_CASE = model(**_UpperCAmelCase) SCREAMING_SNAKE_CASE = outputs.logits.argmax(dim=-1) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = accelerator.gather_for_metrics((predictions, batch['labels'])) metric.add_batch( predictions=_UpperCAmelCase , references=_UpperCAmelCase , ) SCREAMING_SNAKE_CASE = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F'''epoch {epoch}:''' , _UpperCAmelCase) def lowerCamelCase__ (): SCREAMING_SNAKE_CASE = argparse.ArgumentParser(description='Simple example of training script.') parser.add_argument( '--mixed_precision' , type=_UpperCAmelCase , default=_UpperCAmelCase , choices=['no', 'fp16', 'bf16', 'fp8'] , help='Whether to use mixed precision. Choose' 'between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.' 'and an Nvidia Ampere GPU.' , ) parser.add_argument('--cpu' , action='store_true' , help='If passed, will train on the CPU.') SCREAMING_SNAKE_CASE = parser.parse_args() SCREAMING_SNAKE_CASE = {'lr': 2e-5, 'num_epochs': 3, 'seed': 42, 'batch_size': 16} training_function(_UpperCAmelCase , _UpperCAmelCase) if __name__ == "__main__": main()
73
1
# We ignore warnings about stepping the scheduler since we step it ourselves during gradient accumulation import warnings from .state import AcceleratorState, GradientState warnings.filterwarnings('ignore', category=UserWarning, module='torch.optim.lr_scheduler') class _snake_case : def __init__( self , a , a , a = True , a = False) -> Optional[int]: SCREAMING_SNAKE_CASE = scheduler SCREAMING_SNAKE_CASE = optimizers if isinstance(a , (list, tuple)) else [optimizers] SCREAMING_SNAKE_CASE = split_batches SCREAMING_SNAKE_CASE = step_with_optimizer SCREAMING_SNAKE_CASE = GradientState() def SCREAMING_SNAKE_CASE__ ( self , *a , **a) -> List[Any]: if not self.step_with_optimizer: # No link between scheduler and optimizer -> just step self.scheduler.step(*a , **a) return # Otherwise, first make sure the optimizer was stepped. if not self.gradient_state.sync_gradients: if self.gradient_state.adjust_scheduler: self.scheduler._step_count += 1 return for opt in self.optimizers: if opt.step_was_skipped: return if self.split_batches: # Split batches -> the training dataloader batch size is not changed so one step per training step self.scheduler.step(*a , **a) else: # Otherwise the training dataloader batch size was multiplied by `num_processes`, so we need to do # num_processes steps per training step SCREAMING_SNAKE_CASE = AcceleratorState().num_processes for _ in range(a): # Special case when using OneCycle and `drop_last` was not used if hasattr(self.scheduler , 'total_steps'): if self.scheduler._step_count <= self.scheduler.total_steps: self.scheduler.step(*a , **a) else: self.scheduler.step(*a , **a) def SCREAMING_SNAKE_CASE__ ( self) -> Any: return self.scheduler.get_last_lr() def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: return self.scheduler.state_dict() def SCREAMING_SNAKE_CASE__ ( self , a) -> Optional[Any]: self.scheduler.load_state_dict(a) def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: return self.scheduler.get_lr() def SCREAMING_SNAKE_CASE__ ( self , *a , **a) -> str: return self.scheduler.print_lr(*a , **a)
73
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available a_ : int = { 'configuration_rag': ['RagConfig'], 'retrieval_rag': ['RagRetriever'], 'tokenization_rag': ['RagTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : List[Any] = [ 'RagModel', 'RagPreTrainedModel', 'RagSequenceForGeneration', 'RagTokenForGeneration', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : Tuple = [ 'TFRagModel', 'TFRagPreTrainedModel', 'TFRagSequenceForGeneration', 'TFRagTokenForGeneration', ] if TYPE_CHECKING: from .configuration_rag import RagConfig from .retrieval_rag import RagRetriever from .tokenization_rag import RagTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_rag import RagModel, RagPreTrainedModel, RagSequenceForGeneration, RagTokenForGeneration try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_rag import ( TFRagModel, TFRagPreTrainedModel, TFRagSequenceForGeneration, TFRagTokenForGeneration, ) else: import sys a_ : Union[str, Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
73
1
import math def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = 0 while num > 0: SCREAMING_SNAKE_CASE = num % 8 SCREAMING_SNAKE_CASE = octal + (remainder * math.floor(math.pow(10 , _UpperCAmelCase))) counter += 1 SCREAMING_SNAKE_CASE = math.floor(num / 8) # basically /= 8 without remainder if any # This formatting removes trailing '.0' from `octal`. return F'''0o{int(_UpperCAmelCase)}''' def lowerCamelCase__ (): print('\n2 in octal is:') print(decimal_to_octal(2)) # = 2 print('\n8 in octal is:') print(decimal_to_octal(8)) # = 10 print('\n65 in octal is:') print(decimal_to_octal(65)) # = 101 print('\n216 in octal is:') print(decimal_to_octal(216)) # = 330 print('\n512 in octal is:') print(decimal_to_octal(512)) # = 1000 print('\n') if __name__ == "__main__": main()
73
from __future__ import annotations from numpy import array, cos, cross, floataa, radians, sin from numpy.typing import NDArray def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase = False): if radian_mode: return [magnitude * cos(_UpperCAmelCase), magnitude * sin(_UpperCAmelCase)] return [magnitude * cos(radians(_UpperCAmelCase)), magnitude * sin(radians(_UpperCAmelCase))] def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase = 10**-1): SCREAMING_SNAKE_CASE = cross(_UpperCAmelCase , _UpperCAmelCase) SCREAMING_SNAKE_CASE = sum(_UpperCAmelCase) return abs(_UpperCAmelCase) < eps if __name__ == "__main__": # Test to check if it works a_ : int = array( [ polar_force(718.4, 1_80 - 30), polar_force(879.54, 45), polar_force(1_00, -90), ] ) a_ : NDArray[floataa] = array([[0, 0], [0, 0], [0, 0]]) assert in_static_equilibrium(forces, location) # Problem 1 in image_data/2D_problems.jpg a_ : Dict = array( [ polar_force(30 * 9.81, 15), polar_force(2_15, 1_80 - 45), polar_force(2_64, 90 - 30), ] ) a_ : Any = array([[0, 0], [0, 0], [0, 0]]) assert in_static_equilibrium(forces, location) # Problem in image_data/2D_problems_1.jpg a_ : int = array([[0, -20_00], [0, -12_00], [0, 1_56_00], [0, -1_24_00]]) a_ : Optional[Any] = array([[0, 0], [6, 0], [10, 0], [12, 0]]) assert in_static_equilibrium(forces, location) import doctest doctest.testmod()
73
1
import warnings from diffusers import StableDiffusionImgaImgPipeline # noqa F401 warnings.warn( 'The `image_to_image.py` script is outdated. Please use directly `from diffusers import' ' StableDiffusionImg2ImgPipeline` instead.' )
73
from ...configuration_utils import PretrainedConfig from ...utils import logging a_ : Optional[int] = logging.get_logger(__name__) a_ : int = { 'microsoft/cvt-13': 'https://huggingface.co/microsoft/cvt-13/resolve/main/config.json', # See all Cvt models at https://huggingface.co/models?filter=cvt } class _snake_case ( A__ ): _lowercase : Dict = '''cvt''' def __init__( self , a=3 , a=[7, 3, 3] , a=[4, 2, 2] , a=[2, 1, 1] , a=[64, 192, 384] , a=[1, 3, 6] , a=[1, 2, 10] , a=[4.0, 4.0, 4.0] , a=[0.0, 0.0, 0.0] , a=[0.0, 0.0, 0.0] , a=[0.0, 0.0, 0.1] , a=[True, True, True] , a=[False, False, True] , a=["dw_bn", "dw_bn", "dw_bn"] , a=[3, 3, 3] , a=[1, 1, 1] , a=[2, 2, 2] , a=[1, 1, 1] , a=[1, 1, 1] , a=0.02 , a=1E-12 , **a , ) -> List[Any]: super().__init__(**a) SCREAMING_SNAKE_CASE = num_channels SCREAMING_SNAKE_CASE = patch_sizes SCREAMING_SNAKE_CASE = patch_stride SCREAMING_SNAKE_CASE = patch_padding SCREAMING_SNAKE_CASE = embed_dim SCREAMING_SNAKE_CASE = num_heads SCREAMING_SNAKE_CASE = depth SCREAMING_SNAKE_CASE = mlp_ratio SCREAMING_SNAKE_CASE = attention_drop_rate SCREAMING_SNAKE_CASE = drop_rate SCREAMING_SNAKE_CASE = drop_path_rate SCREAMING_SNAKE_CASE = qkv_bias SCREAMING_SNAKE_CASE = cls_token SCREAMING_SNAKE_CASE = qkv_projection_method SCREAMING_SNAKE_CASE = kernel_qkv SCREAMING_SNAKE_CASE = padding_kv SCREAMING_SNAKE_CASE = stride_kv SCREAMING_SNAKE_CASE = padding_q SCREAMING_SNAKE_CASE = stride_q SCREAMING_SNAKE_CASE = initializer_range SCREAMING_SNAKE_CASE = layer_norm_eps
73
1