code
stringlengths
87
55.2k
code_codestyle
int64
0
349
style_context
stringlengths
135
49.1k
style_context_codestyle
int64
0
349
label
int64
0
1
import pytest from datasets import inspect_metric, list_metrics, load_metric @pytest.fixture def lowerCamelCase_ ( _UpperCamelCase ) -> List[Any]: """simple docstring""" monkeypatch.setattr('''datasets.utils.deprecation_utils._emitted_deprecation_warnings''' , set() ) @pytest.fixture def lowerCamelCase_ ( _UpperCamelCase ) -> List[str]: """simple docstring""" class __lowerCAmelCase : def __init__(self , __magic_name__ ) -> Optional[Any]: '''simple docstring''' snake_case_ : Union[str, Any] = metric_id class __lowerCAmelCase : lowerCamelCase_ : Optional[Any] = [MetricMock(_a ) for metric_id in ['''accuracy''', '''mse''', '''precision''', '''codeparrot/apps_metric''']] def lowerCamelCase (self ) -> str: '''simple docstring''' return self._metrics monkeypatch.setattr('''datasets.inspect.huggingface_hub''' , HfhMock() ) @pytest.mark.parametrize( '''func, args''' , [(load_metric, ('''metrics/mse''',)), (list_metrics, ()), (inspect_metric, ('''metrics/mse''', '''tmp_path'''))] ) def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) -> str: """simple docstring""" if "tmp_path" in args: snake_case_ : Any = tuple(arg if arg != '''tmp_path''' else tmp_path for arg in args ) with pytest.warns(lowerCamelCase__ , match='''https://huggingface.co/docs/evaluate''' ): func(*lowerCamelCase__ )
279
import json import os import subprocess import unittest from ast import literal_eval import pytest from parameterized import parameterized, parameterized_class from . import is_sagemaker_available if is_sagemaker_available(): from sagemaker import Session, TrainingJobAnalytics from sagemaker.huggingface import HuggingFace @pytest.mark.skipif( literal_eval(os.getenv('''TEST_SAGEMAKER''' , '''False''' ) ) is not True , reason='''Skipping test because should only be run when releasing minor transformers version''' , ) @pytest.mark.usefixtures('''sm_env''' ) @parameterized_class( [ { '''framework''': '''pytorch''', '''script''': '''run_glue_model_parallelism.py''', '''model_name_or_path''': '''roberta-large''', '''instance_type''': '''ml.p3dn.24xlarge''', '''results''': {'''train_runtime''': 1_600, '''eval_accuracy''': 0.3, '''eval_loss''': 1.2}, }, { '''framework''': '''pytorch''', '''script''': '''run_glue.py''', '''model_name_or_path''': '''roberta-large''', '''instance_type''': '''ml.p3dn.24xlarge''', '''results''': {'''train_runtime''': 1_600, '''eval_accuracy''': 0.3, '''eval_loss''': 1.2}, }, ] ) class A_ ( unittest.TestCase ): def lowerCAmelCase ( self : Union[str, Any]): if self.framework == "pytorch": subprocess.run( F"cp ./examples/pytorch/text-classification/run_glue.py {self.env.test_path}/run_glue.py".split() ,encoding='utf-8' ,check=SCREAMING_SNAKE_CASE__ ,) assert hasattr(self ,'env') def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : int): # configuration for running training on smdistributed Model Parallel __lowerCamelCase : Any = { 'enabled': True, 'processes_per_host': 8, } __lowerCamelCase : List[Any] = { 'enabled': True, 'parameters': { 'microbatches': 4, 'placement_strategy': 'spread', 'pipeline': 'interleaved', 'optimize': 'speed', 'partitions': 4, 'ddp': True, }, } __lowerCamelCase : str = {'smdistributed': {'modelparallel': smp_options}, 'mpi': mpi_options} __lowerCamelCase : List[str] = 'trainer' if self.script == 'run_glue.py' else 'smtrainer' # creates estimator return HuggingFace( entry_point=self.script ,source_dir=self.env.test_path ,role=self.env.role ,image_uri=self.env.image_uri ,base_job_name=F"{self.env.base_job_name}-{instance_count}-smp-{name_extension}" ,instance_count=SCREAMING_SNAKE_CASE__ ,instance_type=self.instance_type ,debugger_hook_config=SCREAMING_SNAKE_CASE__ ,hyperparameters={ **self.env.hyperparameters, 'model_name_or_path': self.model_name_or_path, 'max_steps': 5_0_0, } ,metric_definitions=self.env.metric_definitions ,distribution=SCREAMING_SNAKE_CASE__ ,py_version='py36' ,) def lowerCAmelCase ( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : Any): TrainingJobAnalytics(SCREAMING_SNAKE_CASE__).export_csv(F"{self.env.test_path}/{job_name}_metrics.csv") @parameterized.expand([(1,)]) def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : Optional[Any]): # create estimator __lowerCamelCase : str = self.create_estimator(SCREAMING_SNAKE_CASE__) # run training estimator.fit() # result dataframe __lowerCamelCase : List[str] = TrainingJobAnalytics(estimator.latest_training_job.name).dataframe() # extract kpis __lowerCamelCase : Optional[int] = list(result_metrics_df[result_metrics_df.metric_name == 'eval_accuracy']['value']) __lowerCamelCase : Any = list(result_metrics_df[result_metrics_df.metric_name == 'eval_loss']['value']) # get train time from SageMaker job, this includes starting, preprocessing, stopping __lowerCamelCase : str = ( Session().describe_training_job(estimator.latest_training_job.name).get('TrainingTimeInSeconds' ,9_9_9_9_9_9) ) # assert kpis assert train_runtime <= self.results["train_runtime"] assert all(t >= self.results['eval_accuracy'] for t in eval_accuracy) assert all(t <= self.results['eval_loss'] for t in eval_loss) # dump tests result into json file to share in PR with open(F"{estimator.latest_training_job.name}.json" ,'w') as outfile: json.dump({'train_time': train_runtime, 'eval_accuracy': eval_accuracy, 'eval_loss': eval_loss} ,SCREAMING_SNAKE_CASE__)
73
0
'''simple docstring''' import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_convbert import ConvBertTokenizer _UpperCAmelCase : Optional[Any] = logging.get_logger(__name__) _UpperCAmelCase : List[Any] = {"""vocab_file""": """vocab.txt"""} _UpperCAmelCase : int = { """vocab_file""": { """YituTech/conv-bert-base""": """https://huggingface.co/YituTech/conv-bert-base/resolve/main/vocab.txt""", """YituTech/conv-bert-medium-small""": ( """https://huggingface.co/YituTech/conv-bert-medium-small/resolve/main/vocab.txt""" ), """YituTech/conv-bert-small""": """https://huggingface.co/YituTech/conv-bert-small/resolve/main/vocab.txt""", } } _UpperCAmelCase : Optional[Any] = { """YituTech/conv-bert-base""": 5_1_2, """YituTech/conv-bert-medium-small""": 5_1_2, """YituTech/conv-bert-small""": 5_1_2, } _UpperCAmelCase : str = { """YituTech/conv-bert-base""": {"""do_lower_case""": True}, """YituTech/conv-bert-medium-small""": {"""do_lower_case""": True}, """YituTech/conv-bert-small""": {"""do_lower_case""": True}, } class a__ ( __A ): """simple docstring""" __UpperCamelCase : Dict = VOCAB_FILES_NAMES __UpperCamelCase : int = PRETRAINED_VOCAB_FILES_MAP __UpperCamelCase : List[Any] = PRETRAINED_INIT_CONFIGURATION __UpperCamelCase : Optional[int] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCamelCase : Optional[int] = ConvBertTokenizer def __init__(self , __lowercase=None , __lowercase=None , __lowercase=True , __lowercase="[UNK]" , __lowercase="[SEP]" , __lowercase="[PAD]" , __lowercase="[CLS]" , __lowercase="[MASK]" , __lowercase=True , __lowercase=None , **__lowercase , ): super().__init__( SCREAMING_SNAKE_CASE__ , tokenizer_file=SCREAMING_SNAKE_CASE__ , do_lower_case=SCREAMING_SNAKE_CASE__ , unk_token=SCREAMING_SNAKE_CASE__ , sep_token=SCREAMING_SNAKE_CASE__ , pad_token=SCREAMING_SNAKE_CASE__ , cls_token=SCREAMING_SNAKE_CASE__ , mask_token=SCREAMING_SNAKE_CASE__ , tokenize_chinese_chars=SCREAMING_SNAKE_CASE__ , strip_accents=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) __lowerCAmelCase = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('''lowercase''' , SCREAMING_SNAKE_CASE__ ) != do_lower_case or normalizer_state.get('''strip_accents''' , SCREAMING_SNAKE_CASE__ ) != strip_accents or normalizer_state.get('''handle_chinese_chars''' , SCREAMING_SNAKE_CASE__ ) != tokenize_chinese_chars ): __lowerCAmelCase = getattr(SCREAMING_SNAKE_CASE__ , normalizer_state.pop('''type''' ) ) __lowerCAmelCase = do_lower_case __lowerCAmelCase = strip_accents __lowerCAmelCase = tokenize_chinese_chars __lowerCAmelCase = normalizer_class(**SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase = do_lower_case def _snake_case (self , __lowercase , __lowercase=None ): __lowerCAmelCase = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def _snake_case (self , __lowercase , __lowercase = None ): __lowerCAmelCase = [self.sep_token_id] __lowerCAmelCase = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def _snake_case (self , __lowercase , __lowercase = None ): __lowerCAmelCase = self._tokenizer.model.save(SCREAMING_SNAKE_CASE__ , name=SCREAMING_SNAKE_CASE__ ) return tuple(SCREAMING_SNAKE_CASE__ )
174
import unittest import numpy as np from transformers import DistilBertConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask if is_flax_available(): import jax.numpy as jnp from transformers.models.distilbert.modeling_flax_distilbert import ( FlaxDistilBertForMaskedLM, FlaxDistilBertForMultipleChoice, FlaxDistilBertForQuestionAnswering, FlaxDistilBertForSequenceClassification, FlaxDistilBertForTokenClassification, FlaxDistilBertModel, ) class A_ ( unittest.TestCase ): def __init__( self : Tuple ,SCREAMING_SNAKE_CASE__ : List[str] ,SCREAMING_SNAKE_CASE__ : Any=1_3 ,SCREAMING_SNAKE_CASE__ : int=7 ,SCREAMING_SNAKE_CASE__ : str=True ,SCREAMING_SNAKE_CASE__ : Dict=True ,SCREAMING_SNAKE_CASE__ : str=True ,SCREAMING_SNAKE_CASE__ : Dict=True ,SCREAMING_SNAKE_CASE__ : List[Any]=9_9 ,SCREAMING_SNAKE_CASE__ : List[Any]=3_2 ,SCREAMING_SNAKE_CASE__ : int=5 ,SCREAMING_SNAKE_CASE__ : List[Any]=4 ,SCREAMING_SNAKE_CASE__ : Optional[Any]=3_7 ,SCREAMING_SNAKE_CASE__ : Union[str, Any]="gelu" ,SCREAMING_SNAKE_CASE__ : int=0.1 ,SCREAMING_SNAKE_CASE__ : Optional[int]=0.1 ,SCREAMING_SNAKE_CASE__ : Optional[int]=5_1_2 ,SCREAMING_SNAKE_CASE__ : Dict=1_6 ,SCREAMING_SNAKE_CASE__ : Dict=2 ,SCREAMING_SNAKE_CASE__ : Optional[int]=0.02 ,SCREAMING_SNAKE_CASE__ : Dict=4 ,): __lowerCamelCase : int = parent __lowerCamelCase : Dict = batch_size __lowerCamelCase : Union[str, Any] = seq_length __lowerCamelCase : List[Any] = is_training __lowerCamelCase : Tuple = use_attention_mask __lowerCamelCase : List[str] = use_token_type_ids __lowerCamelCase : Any = use_labels __lowerCamelCase : List[str] = vocab_size __lowerCamelCase : Any = hidden_size __lowerCamelCase : Tuple = num_hidden_layers __lowerCamelCase : Union[str, Any] = num_attention_heads __lowerCamelCase : Union[str, Any] = intermediate_size __lowerCamelCase : List[Any] = hidden_act __lowerCamelCase : int = hidden_dropout_prob __lowerCamelCase : int = attention_probs_dropout_prob __lowerCamelCase : Union[str, Any] = max_position_embeddings __lowerCamelCase : Union[str, Any] = type_vocab_size __lowerCamelCase : List[str] = type_sequence_label_size __lowerCamelCase : Tuple = initializer_range __lowerCamelCase : Optional[int] = num_choices def lowerCAmelCase ( self : Union[str, Any]): __lowerCamelCase : Dict = ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size) __lowerCamelCase : Union[str, Any] = None if self.use_attention_mask: __lowerCamelCase : Any = random_attention_mask([self.batch_size, self.seq_length]) __lowerCamelCase : str = DistilBertConfig( vocab_size=self.vocab_size ,dim=self.hidden_size ,n_layers=self.num_hidden_layers ,n_heads=self.num_attention_heads ,hidden_dim=self.intermediate_size ,hidden_act=self.hidden_act ,dropout=self.hidden_dropout_prob ,attention_dropout=self.attention_probs_dropout_prob ,max_position_embeddings=self.max_position_embeddings ,initializer_range=self.initializer_range ,tie_weights_=SCREAMING_SNAKE_CASE__ ,) return config, input_ids, attention_mask def lowerCAmelCase ( self : List[Any]): __lowerCamelCase : List[str] = self.prepare_config_and_inputs() __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : Dict = config_and_inputs __lowerCamelCase : Any = {'input_ids': input_ids, 'attention_mask': attention_mask} return config, inputs_dict @require_flax class A_ ( SCREAMING_SNAKE_CASE , unittest.TestCase ): _UpperCAmelCase : Dict = ( ( FlaxDistilBertModel, FlaxDistilBertForMaskedLM, FlaxDistilBertForMultipleChoice, FlaxDistilBertForQuestionAnswering, FlaxDistilBertForSequenceClassification, FlaxDistilBertForTokenClassification, FlaxDistilBertForQuestionAnswering, ) if is_flax_available() else () ) def lowerCAmelCase ( self : Optional[Any]): __lowerCamelCase : Tuple = FlaxDistilBertModelTester(self) @slow def lowerCAmelCase ( self : int): for model_class_name in self.all_model_classes: __lowerCamelCase : List[Any] = model_class_name.from_pretrained('distilbert-base-uncased') __lowerCamelCase : List[str] = model(np.ones((1, 1))) self.assertIsNotNone(SCREAMING_SNAKE_CASE__) @require_flax class A_ ( unittest.TestCase ): @slow def lowerCAmelCase ( self : str): __lowerCamelCase : Union[str, Any] = FlaxDistilBertModel.from_pretrained('distilbert-base-uncased') __lowerCamelCase : str = np.array([[0, 3_4_5, 2_3_2, 3_2_8, 7_4_0, 1_4_0, 1_6_9_5, 6_9, 6_0_7_8, 1_5_8_8, 2]]) __lowerCamelCase : List[Any] = np.array([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]) __lowerCamelCase : Union[str, Any] = model(SCREAMING_SNAKE_CASE__ ,attention_mask=SCREAMING_SNAKE_CASE__)[0] __lowerCamelCase : Optional[int] = (1, 1_1, 7_6_8) self.assertEqual(output.shape ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Union[str, Any] = np.array([[[-0.1639, 0.3299, 0.1648], [-0.1746, 0.3289, 0.1710], [-0.1884, 0.3357, 0.1810]]]) self.assertTrue(jnp.allclose(output[:, 1:4, 1:4] ,SCREAMING_SNAKE_CASE__ ,atol=1E-4))
73
0
import importlib.util import os import platform from argparse import ArgumentParser import huggingface_hub from .. import __version__ as version from ..utils import ( is_accelerate_available, is_flax_available, is_safetensors_available, is_tf_available, is_torch_available, ) from . import BaseTransformersCLICommand def A (__A : List[Any] ) -> Optional[int]: """simple docstring""" return EnvironmentCommand() def A (__A : Union[str, Any] ) -> Union[str, Any]: """simple docstring""" return EnvironmentCommand(args.accelerate_config_file ) class __snake_case ( a ): @staticmethod def lowerCamelCase ( _snake_case : ArgumentParser): """simple docstring""" UpperCAmelCase_ = parser.add_parser('''env''') download_parser.set_defaults(func=SCREAMING_SNAKE_CASE__) download_parser.add_argument( '''--accelerate-config_file''' , default=SCREAMING_SNAKE_CASE__ , help='''The accelerate config file to use for the default values in the launching script.''' , ) download_parser.set_defaults(func=SCREAMING_SNAKE_CASE__) def __init__( self : Optional[Any] , _snake_case : Any , *_snake_case : Tuple): """simple docstring""" UpperCAmelCase_ = accelerate_config_file def lowerCamelCase ( self : Any): """simple docstring""" UpperCAmelCase_ = 'not installed' if is_safetensors_available(): import safetensors UpperCAmelCase_ = safetensors.__version__ elif importlib.util.find_spec('''safetensors''') is not None: import safetensors UpperCAmelCase_ = F"""{safetensors.__version__} but is ignored because of PyTorch version too old.""" UpperCAmelCase_ = 'not installed' UpperCAmelCase_ = 'not found' if is_accelerate_available(): import accelerate from accelerate.commands.config import default_config_file, load_config_from_file UpperCAmelCase_ = accelerate.__version__ # Get the default from the config file. if self._accelerate_config_file is not None or os.path.isfile(SCREAMING_SNAKE_CASE__): UpperCAmelCase_ = load_config_from_file(self._accelerate_config_file).to_dict() UpperCAmelCase_ = ( '\n'.join([F"""\t- {prop}: {val}""" for prop, val in accelerate_config.items()]) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__) else F"""\t{accelerate_config}""" ) UpperCAmelCase_ = 'not installed' UpperCAmelCase_ = 'NA' if is_torch_available(): import torch UpperCAmelCase_ = torch.__version__ UpperCAmelCase_ = torch.cuda.is_available() UpperCAmelCase_ = 'not installed' UpperCAmelCase_ = 'NA' if is_tf_available(): import tensorflow as tf UpperCAmelCase_ = tf.__version__ try: # deprecated in v2.1 UpperCAmelCase_ = tf.test.is_gpu_available() except AttributeError: # returns list of devices, convert to bool UpperCAmelCase_ = bool(tf.config.list_physical_devices('''GPU''')) UpperCAmelCase_ = 'not installed' UpperCAmelCase_ = 'not installed' UpperCAmelCase_ = 'not installed' UpperCAmelCase_ = 'NA' if is_flax_available(): import flax import jax import jaxlib UpperCAmelCase_ = flax.__version__ UpperCAmelCase_ = jax.__version__ UpperCAmelCase_ = jaxlib.__version__ UpperCAmelCase_ = jax.lib.xla_bridge.get_backend().platform UpperCAmelCase_ = { '`transformers` version': version, 'Platform': platform.platform(), 'Python version': platform.python_version(), 'Huggingface_hub version': huggingface_hub.__version__, 'Safetensors version': F"""{safetensors_version}""", 'Accelerate version': F"""{accelerate_version}""", 'Accelerate config': F"""{accelerate_config_str}""", 'PyTorch version (GPU?)': F"""{pt_version} ({pt_cuda_available})""", 'Tensorflow version (GPU?)': F"""{tf_version} ({tf_cuda_available})""", 'Flax version (CPU?/GPU?/TPU?)': F"""{flax_version} ({jax_backend})""", 'Jax version': F"""{jax_version}""", 'JaxLib version': F"""{jaxlib_version}""", 'Using GPU in script?': '<fill in>', 'Using distributed or parallel set-up in script?': '<fill in>', } print('''\nCopy-and-paste the text below in your GitHub issue and FILL OUT the two last points.\n''') print(self.format_dict(SCREAMING_SNAKE_CASE__)) return info @staticmethod def lowerCamelCase ( _snake_case : Any): """simple docstring""" return "\n".join([F"""- {prop}: {val}""" for prop, val in d.items()]) + "\n"
51
import csv import tweepy # Twitter API credentials a ="""""" a ="""""" a ="""""" a ="""""" def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> None: # authorize twitter, initialize tweepy __lowerCamelCase : Tuple = tweepy.OAuthHandler(lowerCamelCase__ , lowerCamelCase__ ) auth.set_access_token(lowerCamelCase__ , lowerCamelCase__ ) __lowerCamelCase : Optional[int] = tweepy.API(lowerCamelCase__ ) # initialize a list to hold all the tweepy Tweets __lowerCamelCase : str = [] # make initial request for most recent tweets (200 is the maximum allowed count) __lowerCamelCase : Union[str, Any] = api.user_timeline(screen_name=lowerCamelCase__ , count=2_0_0 ) # save most recent tweets alltweets.extend(lowerCamelCase__ ) # save the id of the oldest tweet less one __lowerCamelCase : Any = alltweets[-1].id - 1 # keep grabbing tweets until there are no tweets left to grab while len(lowerCamelCase__ ) > 0: print(F"getting tweets before {oldest}" ) # all subsequent requests use the max_id param to prevent duplicates __lowerCamelCase : str = api.user_timeline( screen_name=lowerCamelCase__ , count=2_0_0 , max_id=lowerCamelCase__ ) # save most recent tweets alltweets.extend(lowerCamelCase__ ) # update the id of the oldest tweet less one __lowerCamelCase : Optional[int] = alltweets[-1].id - 1 print(F"...{len(lowerCamelCase__ )} tweets downloaded so far" ) # transform the tweepy tweets into a 2D array that will populate the csv __lowerCamelCase : str = [[tweet.id_str, tweet.created_at, tweet.text] for tweet in alltweets] # write the csv with open(F"new_{screen_name}_tweets.csv" , 'w' ) as f: __lowerCamelCase : Any = csv.writer(lowerCamelCase__ ) writer.writerow(['id', 'created_at', 'text'] ) writer.writerows(lowerCamelCase__ ) if __name__ == "__main__": # pass in the username of the account you want to download get_all_tweets("""FirePing32""")
73
0
import os import sys __snake_case = os.path.join(os.path.dirname(__file__), """src""") sys.path.append(SRC_DIR) from transformers import ( AutoConfig, AutoModel, AutoModelForCausalLM, AutoModelForMaskedLM, AutoModelForQuestionAnswering, AutoModelForSequenceClassification, AutoTokenizer, add_start_docstrings, ) __snake_case = [ """torch""", """numpy""", """tokenizers""", """filelock""", """requests""", """tqdm""", """regex""", """sentencepiece""", """sacremoses""", """importlib_metadata""", """huggingface_hub""", ] @add_start_docstrings(AutoConfig.__doc__ ) def _lowercase ( *UpperCamelCase_ , **UpperCamelCase_ ) -> int: '''simple docstring''' return AutoConfig.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ ) @add_start_docstrings(AutoTokenizer.__doc__ ) def _lowercase ( *UpperCamelCase_ , **UpperCamelCase_ ) -> Optional[Any]: '''simple docstring''' return AutoTokenizer.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ ) @add_start_docstrings(AutoModel.__doc__ ) def _lowercase ( *UpperCamelCase_ , **UpperCamelCase_ ) -> List[str]: '''simple docstring''' return AutoModel.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ ) @add_start_docstrings(AutoModelForCausalLM.__doc__ ) def _lowercase ( *UpperCamelCase_ , **UpperCamelCase_ ) -> Any: '''simple docstring''' return AutoModelForCausalLM.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ ) @add_start_docstrings(AutoModelForMaskedLM.__doc__ ) def _lowercase ( *UpperCamelCase_ , **UpperCamelCase_ ) -> List[str]: '''simple docstring''' return AutoModelForMaskedLM.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ ) @add_start_docstrings(AutoModelForSequenceClassification.__doc__ ) def _lowercase ( *UpperCamelCase_ , **UpperCamelCase_ ) -> List[str]: '''simple docstring''' return AutoModelForSequenceClassification.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ ) @add_start_docstrings(AutoModelForQuestionAnswering.__doc__ ) def _lowercase ( *UpperCamelCase_ , **UpperCamelCase_ ) -> Tuple: '''simple docstring''' return AutoModelForQuestionAnswering.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ )
176
import numpy as np from scipy.spatial.distance import cdist from sklearn.metrics import fa_score import datasets a ="""\ @inproceedings{kakwani2020indicnlpsuite, title={{IndicNLPSuite: Monolingual Corpora, Evaluation Benchmarks and Pre-trained Multilingual Language Models for Indian Languages}}, author={Divyanshu Kakwani and Anoop Kunchukuttan and Satish Golla and Gokul N.C. and Avik Bhattacharyya and Mitesh M. Khapra and Pratyush Kumar}, year={2020}, booktitle={Findings of EMNLP}, } """ a ="""\ IndicGLUE is a natural language understanding benchmark for Indian languages. It contains a wide variety of tasks and covers 11 major Indian languages - as, bn, gu, hi, kn, ml, mr, or, pa, ta, te. """ a =""" Compute IndicGLUE evaluation metric associated to each IndicGLUE dataset. Args: predictions: list of predictions to score (as int64), except for 'cvit-mkb-clsr' where each prediction is a vector (of float32). references: list of ground truth labels corresponding to the predictions (as int64), except for 'cvit-mkb-clsr' where each reference is a vector (of float32). Returns: depending on the IndicGLUE subset, one or several of: \"accuracy\": Accuracy \"f1\": F1 score \"precision\": Precision@10 Examples: >>> indic_glue_metric = datasets.load_metric('indic_glue', 'wnli') # 'wnli' or any of [\"copa\", \"sna\", \"csqa\", \"wstp\", \"inltkh\", \"bbca\", \"iitp-mr\", \"iitp-pr\", \"actsa-sc\", \"md\"] >>> references = [0, 1] >>> predictions = [0, 1] >>> results = indic_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {'accuracy': 1.0} >>> indic_glue_metric = datasets.load_metric('indic_glue', 'wiki-ner') >>> references = [0, 1] >>> predictions = [0, 1] >>> results = indic_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {'accuracy': 1.0, 'f1': 1.0} >>> indic_glue_metric = datasets.load_metric('indic_glue', 'cvit-mkb-clsr') >>> references = [[0.5, 0.5, 0.5], [0.1, 0.2, 0.3]] >>> predictions = [[0.5, 0.5, 0.5], [0.1, 0.2, 0.3]] >>> results = indic_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {'precision@10': 1.0} """ def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> List[str]: return float((preds == labels).mean() ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> List[str]: __lowerCamelCase : Optional[Any] = simple_accuracy(lowerCamelCase__ , lowerCamelCase__ ) __lowerCamelCase : Tuple = float(fa_score(y_true=lowerCamelCase__ , y_pred=lowerCamelCase__ ) ) return { "accuracy": acc, "f1": fa, } def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> Optional[Any]: __lowerCamelCase : Any = np.array(lowerCamelCase__ ) __lowerCamelCase : List[Any] = np.array(lowerCamelCase__ ) __lowerCamelCase : Any = en_sentvecs.shape[0] # mean centering __lowerCamelCase : Union[str, Any] = en_sentvecs - np.mean(lowerCamelCase__ , axis=0 ) __lowerCamelCase : Dict = in_sentvecs - np.mean(lowerCamelCase__ , axis=0 ) __lowerCamelCase : Optional[int] = cdist(lowerCamelCase__ , lowerCamelCase__ , 'cosine' ) __lowerCamelCase : Optional[Any] = np.array(range(lowerCamelCase__ ) ) __lowerCamelCase : Dict = sim.argsort(axis=1 )[:, :1_0] __lowerCamelCase : Optional[int] = np.any(preds == actual[:, None] , axis=1 ) return float(matches.mean() ) @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class A_ ( datasets.Metric ): def lowerCAmelCase ( self : Optional[Any]): if self.config_name not in [ "wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", "cvit-mkb-clsr", "iitp-mr", "iitp-pr", "actsa-sc", "md", "wiki-ner", ]: raise KeyError( 'You should supply a configuration name selected in ' '["wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", ' '"cvit-mkb-clsr", "iitp-mr", "iitp-pr", "actsa-sc", "md", ' '"wiki-ner"]') return datasets.MetricInfo( description=_DESCRIPTION ,citation=_CITATION ,inputs_description=_KWARGS_DESCRIPTION ,features=datasets.Features( { 'predictions': datasets.Value('int64') if self.config_name != 'cvit-mkb-clsr' else datasets.Sequence(datasets.Value('float32')), 'references': datasets.Value('int64') if self.config_name != 'cvit-mkb-clsr' else datasets.Sequence(datasets.Value('float32')), }) ,codebase_urls=[] ,reference_urls=[] ,format='numpy' if self.config_name != 'cvit-mkb-clsr' else None ,) def lowerCAmelCase ( self : Any ,SCREAMING_SNAKE_CASE__ : Tuple ,SCREAMING_SNAKE_CASE__ : Optional[Any]): if self.config_name == "cvit-mkb-clsr": return {"precision@10": precision_at_aa(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__)} elif self.config_name in ["wiki-ner"]: return acc_and_fa(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) elif self.config_name in [ "wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", "iitp-mr", "iitp-pr", "actsa-sc", "md", ]: return {"accuracy": simple_accuracy(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__)} else: raise KeyError( 'You should supply a configuration name selected in ' '["wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", ' '"cvit-mkb-clsr", "iitp-mr", "iitp-pr", "actsa-sc", "md", ' '"wiki-ner"]')
73
0
from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging __lowerCAmelCase : Any = logging.get_logger(__name__) __lowerCAmelCase : List[str] = { 'sail/poolformer_s12': 'https://huggingface.co/sail/poolformer_s12/resolve/main/config.json', # See all PoolFormer models at https://huggingface.co/models?filter=poolformer } class snake_case__ (_UpperCamelCase ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = '''poolformer''' def __init__( self : Optional[Any] , __lowerCamelCase : Optional[int]=3 , __lowerCamelCase : Any=16 , __lowerCamelCase : Tuple=16 , __lowerCamelCase : List[Any]=3 , __lowerCamelCase : Optional[int]=4.0 , __lowerCamelCase : int=[2, 2, 6, 2] , __lowerCamelCase : Dict=[64, 1_28, 3_20, 5_12] , __lowerCamelCase : Tuple=[7, 3, 3, 3] , __lowerCamelCase : int=[4, 2, 2, 2] , __lowerCamelCase : int=[2, 1, 1, 1] , __lowerCamelCase : Optional[Any]=4 , __lowerCamelCase : Any=0.0 , __lowerCamelCase : Optional[Any]="gelu" , __lowerCamelCase : int=True , __lowerCamelCase : str=1e-5 , __lowerCamelCase : List[Any]=0.02 , **__lowerCamelCase : Tuple , ) -> Any: a = num_channels a = patch_size a = stride a = padding a = pool_size a = hidden_sizes a = mlp_ratio a = depths a = patch_sizes a = strides a = num_encoder_blocks a = drop_path_rate a = hidden_act a = use_layer_scale a = layer_scale_init_value a = initializer_range super().__init__(**SCREAMING_SNAKE_CASE__ ) class snake_case__ (_UpperCamelCase ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = version.parse("""1.11""" ) @property def __UpperCAmelCase ( self : Dict ) -> str: return OrderedDict( [ ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}), ] ) @property def __UpperCAmelCase ( self : Optional[Any] ) -> List[str]: return 2e-3
107
from __future__ import annotations from scipy.special import comb # type: ignore class A_ : def __init__( self : List[str] ,SCREAMING_SNAKE_CASE__ : list[tuple[float, float]]): __lowerCamelCase : Union[str, Any] = list_of_points # Degree determines the flexibility of the curve. # Degree = 1 will produce a straight line. __lowerCamelCase : int = len(SCREAMING_SNAKE_CASE__) - 1 def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : float): assert 0 <= t <= 1, "Time t must be between 0 and 1." __lowerCamelCase : list[float] = [] for i in range(len(self.list_of_points)): # basis function for each i output_values.append( comb(self.degree ,SCREAMING_SNAKE_CASE__) * ((1 - t) ** (self.degree - i)) * (t**i)) # the basis must sum up to 1 for it to produce a valid Bezier curve. assert round(sum(SCREAMING_SNAKE_CASE__) ,5) == 1 return output_values def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : float): assert 0 <= t <= 1, "Time t must be between 0 and 1." __lowerCamelCase : Tuple = self.basis_function(SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = 0.0 __lowerCamelCase : Optional[Any] = 0.0 for i in range(len(self.list_of_points)): # For all points, sum up the product of i-th basis function and i-th point. x += basis_function[i] * self.list_of_points[i][0] y += basis_function[i] * self.list_of_points[i][1] return (x, y) def lowerCAmelCase ( self : int ,SCREAMING_SNAKE_CASE__ : float = 0.01): from matplotlib import pyplot as plt # type: ignore __lowerCamelCase : list[float] = [] # x coordinates of points to plot __lowerCamelCase : list[float] = [] # y coordinates of points to plot __lowerCamelCase : Any = 0.0 while t <= 1: __lowerCamelCase : List[Any] = self.bezier_curve_function(SCREAMING_SNAKE_CASE__) to_plot_x.append(value[0]) to_plot_y.append(value[1]) t += step_size __lowerCamelCase : Optional[Any] = [i[0] for i in self.list_of_points] __lowerCamelCase : List[str] = [i[1] for i in self.list_of_points] plt.plot( SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,color='blue' ,label='Curve of Degree ' + str(self.degree) ,) plt.scatter(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,color='red' ,label='Control Points') plt.legend() plt.show() if __name__ == "__main__": import doctest doctest.testmod() BezierCurve([(1, 2), (3, 5)]).plot_curve() # degree 1 BezierCurve([(0, 0), (5, 5), (5, 0)]).plot_curve() # degree 2 BezierCurve([(0, 0), (5, 5), (5, 0), (2.5, -2.5)]).plot_curve() # degree 3
73
0
import doctest import logging import os import unittest from pathlib import Path from typing import List, Union import transformers from transformers.testing_utils import require_tf, require_torch, slow UpperCamelCase = logging.getLogger() @unittest.skip("Temporarily disable the doc tests." ) @require_torch @require_tf @slow class __UpperCAmelCase (unittest.TestCase ): def UpperCamelCase ( self: str , UpperCAmelCase_: Path , UpperCAmelCase_: Union[str, None] = None , UpperCAmelCase_: Union[List[str], None] = None , UpperCAmelCase_: Union[str, List[str], None] = None , UpperCAmelCase_: bool = True , ): '''simple docstring''' _SCREAMING_SNAKE_CASE = [file for file in os.listdir(SCREAMING_SNAKE_CASE__ ) if os.path.isfile(os.path.join(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) )] if identifier is not None: _SCREAMING_SNAKE_CASE = [file for file in files if identifier in file] if n_identifier is not None: if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): for n_ in n_identifier: _SCREAMING_SNAKE_CASE = [file for file in files if n_ not in file] else: _SCREAMING_SNAKE_CASE = [file for file in files if n_identifier not in file] _SCREAMING_SNAKE_CASE = ignore_files or [] ignore_files.append("""__init__.py""" ) _SCREAMING_SNAKE_CASE = [file for file in files if file not in ignore_files] for file in files: # Open all files print("""Testing""" , SCREAMING_SNAKE_CASE__ ) if only_modules: _SCREAMING_SNAKE_CASE = file.split(""".""" )[0] try: _SCREAMING_SNAKE_CASE = getattr(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) _SCREAMING_SNAKE_CASE = doctest.DocTestSuite(SCREAMING_SNAKE_CASE__ ) _SCREAMING_SNAKE_CASE = unittest.TextTestRunner().run(SCREAMING_SNAKE_CASE__ ) self.assertIs(len(result.failures ) , 0 ) except AttributeError: logger.info(F'{module_identifier} is not a module.' ) else: _SCREAMING_SNAKE_CASE = doctest.testfile(str("""..""" / directory / file ) , optionflags=doctest.ELLIPSIS ) self.assertIs(result.failed , 0 ) def UpperCamelCase ( self: Optional[Any] ): '''simple docstring''' _SCREAMING_SNAKE_CASE = Path("""src/transformers""" ) _SCREAMING_SNAKE_CASE = 'modeling' _SCREAMING_SNAKE_CASE = [ 'modeling_ctrl.py', 'modeling_tf_ctrl.py', ] self.analyze_directory(SCREAMING_SNAKE_CASE__ , identifier=SCREAMING_SNAKE_CASE__ , ignore_files=SCREAMING_SNAKE_CASE__ ) def UpperCamelCase ( self: List[str] ): '''simple docstring''' _SCREAMING_SNAKE_CASE = Path("""src/transformers""" ) _SCREAMING_SNAKE_CASE = 'tokenization' self.analyze_directory(SCREAMING_SNAKE_CASE__ , identifier=SCREAMING_SNAKE_CASE__ ) def UpperCamelCase ( self: Optional[Any] ): '''simple docstring''' _SCREAMING_SNAKE_CASE = Path("""src/transformers""" ) _SCREAMING_SNAKE_CASE = 'configuration' self.analyze_directory(SCREAMING_SNAKE_CASE__ , identifier=SCREAMING_SNAKE_CASE__ ) def UpperCamelCase ( self: List[str] ): '''simple docstring''' _SCREAMING_SNAKE_CASE = Path("""src/transformers""" ) _SCREAMING_SNAKE_CASE = ['configuration', 'modeling', 'tokenization'] self.analyze_directory(SCREAMING_SNAKE_CASE__ , n_identifier=SCREAMING_SNAKE_CASE__ ) def UpperCamelCase ( self: Dict ): '''simple docstring''' _SCREAMING_SNAKE_CASE = Path("""docs/source""" ) _SCREAMING_SNAKE_CASE = ['favicon.ico'] self.analyze_directory(SCREAMING_SNAKE_CASE__ , ignore_files=SCREAMING_SNAKE_CASE__ , only_modules=SCREAMING_SNAKE_CASE__ )
306
from __future__ import annotations import time a =list[tuple[int, int]] a =[ [0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles [0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0], [1, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0], ] a =[[-1, 0], [0, -1], [1, 0], [0, 1]] # up, left, down, right class A_ : def __init__( self : List[str] ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : Node | None): __lowerCamelCase : Tuple = pos_x __lowerCamelCase : List[str] = pos_y __lowerCamelCase : str = (pos_y, pos_x) __lowerCamelCase : str = goal_x __lowerCamelCase : int = goal_y __lowerCamelCase : List[Any] = parent class A_ : def __init__( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : tuple[int, int] ,SCREAMING_SNAKE_CASE__ : tuple[int, int]): __lowerCamelCase : Any = Node(start[1] ,start[0] ,goal[1] ,goal[0] ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = Node(goal[1] ,goal[0] ,goal[1] ,goal[0] ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Union[str, Any] = [self.start] __lowerCamelCase : List[str] = False def lowerCAmelCase ( self : List[Any]): while self.node_queue: __lowerCamelCase : Any = self.node_queue.pop(0) if current_node.pos == self.target.pos: __lowerCamelCase : Dict = True return self.retrace_path(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Tuple = self.get_successors(SCREAMING_SNAKE_CASE__) for node in successors: self.node_queue.append(SCREAMING_SNAKE_CASE__) if not self.reached: return [self.start.pos] return None def lowerCAmelCase ( self : str ,SCREAMING_SNAKE_CASE__ : Node): __lowerCamelCase : Union[str, Any] = [] for action in delta: __lowerCamelCase : Optional[Any] = parent.pos_x + action[1] __lowerCamelCase : Optional[int] = parent.pos_y + action[0] if not (0 <= pos_x <= len(grid[0]) - 1 and 0 <= pos_y <= len(SCREAMING_SNAKE_CASE__) - 1): continue if grid[pos_y][pos_x] != 0: continue successors.append( Node(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,self.target.pos_y ,self.target.pos_x ,SCREAMING_SNAKE_CASE__)) return successors def lowerCAmelCase ( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : Node | None): __lowerCamelCase : List[Any] = node __lowerCamelCase : int = [] while current_node is not None: path.append((current_node.pos_y, current_node.pos_x)) __lowerCamelCase : int = current_node.parent path.reverse() return path class A_ : def __init__( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : int): __lowerCamelCase : int = BreadthFirstSearch(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = BreadthFirstSearch(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = False def lowerCAmelCase ( self : str): while self.fwd_bfs.node_queue or self.bwd_bfs.node_queue: __lowerCamelCase : Any = self.fwd_bfs.node_queue.pop(0) __lowerCamelCase : Any = self.bwd_bfs.node_queue.pop(0) if current_bwd_node.pos == current_fwd_node.pos: __lowerCamelCase : List[str] = True return self.retrace_bidirectional_path( SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = current_bwd_node __lowerCamelCase : int = current_fwd_node __lowerCamelCase : str = { self.fwd_bfs: self.fwd_bfs.get_successors(SCREAMING_SNAKE_CASE__), self.bwd_bfs: self.bwd_bfs.get_successors(SCREAMING_SNAKE_CASE__), } for bfs in [self.fwd_bfs, self.bwd_bfs]: for node in successors[bfs]: bfs.node_queue.append(SCREAMING_SNAKE_CASE__) if not self.reached: return [self.fwd_bfs.start.pos] return None def lowerCAmelCase ( self : Dict ,SCREAMING_SNAKE_CASE__ : Node ,SCREAMING_SNAKE_CASE__ : Node): __lowerCamelCase : List[Any] = self.fwd_bfs.retrace_path(SCREAMING_SNAKE_CASE__) __lowerCamelCase : str = self.bwd_bfs.retrace_path(SCREAMING_SNAKE_CASE__) bwd_path.pop() bwd_path.reverse() __lowerCamelCase : List[Any] = fwd_path + bwd_path return path if __name__ == "__main__": # all coordinates are given in format [y,x] import doctest doctest.testmod() a =(0, 0) a =(len(grid) - 1, len(grid[0]) - 1) for elem in grid: print(elem) a =time.time() a =BreadthFirstSearch(init, goal) a =bfs.search() a =time.time() - start_bfs_time print("""Unidirectional BFS computation time : """, bfs_time) a =time.time() a =BidirectionalBreadthFirstSearch(init, goal) a =bd_bfs.search() a =time.time() - start_bd_bfs_time print("""Bidirectional BFS computation time : """, bd_bfs_time)
73
0
from ...configuration_utils import PretrainedConfig from ...utils import logging a__ = logging.get_logger(__name__) a__ = { """google/realm-cc-news-pretrained-embedder""": ( """https://huggingface.co/google/realm-cc-news-pretrained-embedder/resolve/main/config.json""" ), """google/realm-cc-news-pretrained-encoder""": ( """https://huggingface.co/google/realm-cc-news-pretrained-encoder/resolve/main/config.json""" ), """google/realm-cc-news-pretrained-scorer""": ( """https://huggingface.co/google/realm-cc-news-pretrained-scorer/resolve/main/config.json""" ), """google/realm-cc-news-pretrained-openqa""": ( """https://huggingface.co/google/realm-cc-news-pretrained-openqa/aresolve/main/config.json""" ), """google/realm-orqa-nq-openqa""": """https://huggingface.co/google/realm-orqa-nq-openqa/resolve/main/config.json""", """google/realm-orqa-nq-reader""": """https://huggingface.co/google/realm-orqa-nq-reader/resolve/main/config.json""", """google/realm-orqa-wq-openqa""": """https://huggingface.co/google/realm-orqa-wq-openqa/resolve/main/config.json""", """google/realm-orqa-wq-reader""": """https://huggingface.co/google/realm-orqa-wq-reader/resolve/main/config.json""", # See all REALM models at https://huggingface.co/models?filter=realm } class snake_case ( SCREAMING_SNAKE_CASE_ ): '''simple docstring''' snake_case_ : Union[str, Any] = '''realm''' def __init__( self : List[Any] , lowerCAmelCase : str=3_0522 , lowerCAmelCase : Union[str, Any]=768 , lowerCAmelCase : int=128 , lowerCAmelCase : Union[str, Any]=12 , lowerCAmelCase : List[str]=12 , lowerCAmelCase : Any=8 , lowerCAmelCase : Union[str, Any]=3072 , lowerCAmelCase : int="gelu_new" , lowerCAmelCase : Union[str, Any]=0.1 , lowerCAmelCase : int=0.1 , lowerCAmelCase : List[str]=512 , lowerCAmelCase : Optional[int]=2 , lowerCAmelCase : int=0.02 , lowerCAmelCase : Dict=1E-12 , lowerCAmelCase : Dict=256 , lowerCAmelCase : str=10 , lowerCAmelCase : Any=1E-3 , lowerCAmelCase : List[str]=5 , lowerCAmelCase : str=320 , lowerCAmelCase : int=1335_3718 , lowerCAmelCase : Dict=5000 , lowerCAmelCase : int=1 , lowerCAmelCase : List[Any]=0 , lowerCAmelCase : Optional[int]=2 , **lowerCAmelCase : Union[str, Any] , ) -> List[str]: """simple docstring""" super().__init__(pad_token_id=SCREAMING_SNAKE_CASE__ , bos_token_id=SCREAMING_SNAKE_CASE__ , eos_token_id=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__) # Common config _snake_case : Optional[int] = vocab_size _snake_case : str = max_position_embeddings _snake_case : str = hidden_size _snake_case : List[str] = retriever_proj_size _snake_case : int = num_hidden_layers _snake_case : str = num_attention_heads _snake_case : List[Any] = num_candidates _snake_case : List[Any] = intermediate_size _snake_case : Optional[Any] = hidden_act _snake_case : Optional[Any] = hidden_dropout_prob _snake_case : str = attention_probs_dropout_prob _snake_case : Union[str, Any] = initializer_range _snake_case : Dict = type_vocab_size _snake_case : List[str] = layer_norm_eps # Reader config _snake_case : Dict = span_hidden_size _snake_case : List[Any] = max_span_width _snake_case : Dict = reader_layer_norm_eps _snake_case : List[str] = reader_beam_size _snake_case : Optional[Any] = reader_seq_len # Retrieval config _snake_case : Optional[Any] = num_block_records _snake_case : Optional[Any] = searcher_beam_size
317
import qiskit def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> qiskit.result.counts.Counts: __lowerCamelCase : Optional[int] = qiskit.Aer.get_backend('aer_simulator' ) # Create a Quantum Circuit acting on the q register __lowerCamelCase : List[str] = qiskit.QuantumCircuit(lowerCamelCase__ , lowerCamelCase__ ) # Map the quantum measurement to the classical bits circuit.measure([0] , [0] ) # Execute the circuit on the simulator __lowerCamelCase : List[Any] = qiskit.execute(lowerCamelCase__ , lowerCamelCase__ , shots=1_0_0_0 ) # Return the histogram data of the results of the experiment. return job.result().get_counts(lowerCamelCase__ ) if __name__ == "__main__": print(F"""Total count for various states are: {single_qubit_measure(1, 1)}""")
73
0
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase_ = logging.get_logger(__name__) lowerCamelCase_ = { '''EleutherAI/gpt-neox-20b''': '''https://huggingface.co/EleutherAI/gpt-neox-20b/resolve/main/config.json''', # See all GPTNeoX models at https://huggingface.co/models?filter=gpt_neox } class _UpperCAmelCase ( snake_case_ ): """simple docstring""" snake_case = '''gpt_neox''' def __init__( self : Dict , __UpperCAmelCase : Tuple=50432 , __UpperCAmelCase : Optional[Any]=6144 , __UpperCAmelCase : List[str]=44 , __UpperCAmelCase : str=64 , __UpperCAmelCase : Any=24576 , __UpperCAmelCase : Union[str, Any]="gelu" , __UpperCAmelCase : List[str]=0.25 , __UpperCAmelCase : int=10000 , __UpperCAmelCase : Dict=0.0 , __UpperCAmelCase : Optional[Any]=0.0 , __UpperCAmelCase : int=0.1 , __UpperCAmelCase : Any=2048 , __UpperCAmelCase : Any=0.02 , __UpperCAmelCase : List[Any]=1E-5 , __UpperCAmelCase : str=True , __UpperCAmelCase : Any=0 , __UpperCAmelCase : List[str]=2 , __UpperCAmelCase : Optional[Any]=False , __UpperCAmelCase : Tuple=True , __UpperCAmelCase : Any=None , **__UpperCAmelCase : Tuple , ): '''simple docstring''' super().__init__(bos_token_id=SCREAMING_SNAKE_CASE__ , eos_token_id=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) _A = vocab_size _A = max_position_embeddings _A = hidden_size _A = num_hidden_layers _A = num_attention_heads _A = intermediate_size _A = hidden_act _A = rotary_pct _A = rotary_emb_base _A = attention_dropout _A = hidden_dropout _A = classifier_dropout _A = initializer_range _A = layer_norm_eps _A = use_cache _A = tie_word_embeddings _A = use_parallel_residual _A = rope_scaling self._rope_scaling_validation() if self.hidden_size % self.num_attention_heads != 0: raise ValueError( "The hidden size is not divisble by the number of attention heads! Make sure to update them!" ) def lowerCAmelCase ( self : Optional[int] ): '''simple docstring''' if self.rope_scaling is None: return if not isinstance(self.rope_scaling , SCREAMING_SNAKE_CASE__ ) or len(self.rope_scaling ) != 2: raise ValueError( "`rope_scaling` must be a dictionary with with two fields, `name` and `factor`, " f'''got {self.rope_scaling}''' ) _A = self.rope_scaling.get("type" , SCREAMING_SNAKE_CASE__ ) _A = self.rope_scaling.get("factor" , SCREAMING_SNAKE_CASE__ ) if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]: raise ValueError( f'''`rope_scaling`\'s name field must be one of [\'linear\', \'dynamic\'], got {rope_scaling_type}''' ) if rope_scaling_factor is None or not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) or rope_scaling_factor <= 1.0: raise ValueError(f'''`rope_scaling`\'s factor field must be an float > 1, got {rope_scaling_factor}''' )
79
import os import sys a =os.path.join(os.path.dirname(__file__), """src""") sys.path.append(SRC_DIR) from transformers import ( AutoConfig, AutoModel, AutoModelForCausalLM, AutoModelForMaskedLM, AutoModelForQuestionAnswering, AutoModelForSequenceClassification, AutoTokenizer, add_start_docstrings, ) a =[ """torch""", """numpy""", """tokenizers""", """filelock""", """requests""", """tqdm""", """regex""", """sentencepiece""", """sacremoses""", """importlib_metadata""", """huggingface_hub""", ] @add_start_docstrings(AutoConfig.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> int: return AutoConfig.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ ) @add_start_docstrings(AutoTokenizer.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> Optional[Any]: return AutoTokenizer.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ ) @add_start_docstrings(AutoModel.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> List[str]: return AutoModel.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ ) @add_start_docstrings(AutoModelForCausalLM.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> Any: return AutoModelForCausalLM.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ ) @add_start_docstrings(AutoModelForMaskedLM.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> List[str]: return AutoModelForMaskedLM.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ ) @add_start_docstrings(AutoModelForSequenceClassification.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> List[str]: return AutoModelForSequenceClassification.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ ) @add_start_docstrings(AutoModelForQuestionAnswering.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> Tuple: return AutoModelForQuestionAnswering.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ )
73
0
import inspect import unittest from transformers import RegNetConfig, is_flax_available from transformers.testing_utils import require_flax, slow from transformers.utils import cached_property, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor if is_flax_available(): import jax import jax.numpy as jnp from transformers.models.regnet.modeling_flax_regnet import FlaxRegNetForImageClassification, FlaxRegNetModel if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class _SCREAMING_SNAKE_CASE ( unittest.TestCase): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=32 , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=10 , _SCREAMING_SNAKE_CASE=[10, 20, 30, 40] , _SCREAMING_SNAKE_CASE=[1, 1, 2, 1] , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE="relu" , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=None , )-> Dict: lowerCamelCase_ =parent lowerCamelCase_ =batch_size lowerCamelCase_ =image_size lowerCamelCase_ =num_channels lowerCamelCase_ =embeddings_size lowerCamelCase_ =hidden_sizes lowerCamelCase_ =depths lowerCamelCase_ =is_training lowerCamelCase_ =use_labels lowerCamelCase_ =hidden_act lowerCamelCase_ =num_labels lowerCamelCase_ =scope lowerCamelCase_ =len(SCREAMING_SNAKE_CASE__ ) def _snake_case ( self )-> str: lowerCamelCase_ =floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) lowerCamelCase_ =self.get_config() return config, pixel_values def _snake_case ( self )-> str: return RegNetConfig( num_channels=self.num_channels , embeddings_size=self.embeddings_size , hidden_sizes=self.hidden_sizes , depths=self.depths , hidden_act=self.hidden_act , num_labels=self.num_labels , image_size=self.image_size , ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )-> Dict: lowerCamelCase_ =FlaxRegNetModel(config=SCREAMING_SNAKE_CASE__ ) lowerCamelCase_ =model(SCREAMING_SNAKE_CASE__ ) # Output shape (b, c, h, w) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) , ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )-> List[Any]: lowerCamelCase_ =self.num_labels lowerCamelCase_ =FlaxRegNetForImageClassification(config=SCREAMING_SNAKE_CASE__ ) lowerCamelCase_ =model(SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _snake_case ( self )-> Optional[int]: lowerCamelCase_ =self.prepare_config_and_inputs() lowerCamelCase_ =config_and_inputs lowerCamelCase_ ={'pixel_values': pixel_values} return config, inputs_dict @require_flax class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__ , unittest.TestCase): _UpperCamelCase:str = (FlaxRegNetModel, FlaxRegNetForImageClassification) if is_flax_available() else () _UpperCamelCase:Optional[Any] = False _UpperCamelCase:Optional[Any] = False _UpperCamelCase:List[str] = False def _snake_case ( self )-> Dict: lowerCamelCase_ =FlaxRegNetModelTester(self ) lowerCamelCase_ =ConfigTester(self , config_class=SCREAMING_SNAKE_CASE__ , has_text_modality=SCREAMING_SNAKE_CASE__ ) def _snake_case ( self )-> str: 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 _snake_case ( self )-> int: return def _snake_case ( self )-> Optional[Any]: lowerCamelCase_ =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE__ ) def _snake_case ( self )-> List[Any]: lowerCamelCase_ =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*SCREAMING_SNAKE_CASE__ ) @unittest.skip(reason="""RegNet does not use inputs_embeds""" ) def _snake_case ( self )-> Optional[Any]: pass @unittest.skip(reason="""RegNet does not support input and output embeddings""" ) def _snake_case ( self )-> List[Any]: pass def _snake_case ( self )-> Union[str, Any]: lowerCamelCase_ =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCamelCase_ =model_class(SCREAMING_SNAKE_CASE__ ) lowerCamelCase_ =inspect.signature(model.__call__ ) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowerCamelCase_ =[*signature.parameters.keys()] lowerCamelCase_ =['pixel_values'] self.assertListEqual(arg_names[:1] , SCREAMING_SNAKE_CASE__ ) def _snake_case ( self )-> Union[str, Any]: def check_hidden_states_output(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): lowerCamelCase_ =model_class(SCREAMING_SNAKE_CASE__ ) lowerCamelCase_ =model(**self._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) lowerCamelCase_ =outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states lowerCamelCase_ =self.model_tester.num_stages self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , expected_num_stages + 1 ) lowerCamelCase_ =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCamelCase_ =True check_hidden_states_output(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] lowerCamelCase_ =True check_hidden_states_output(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def _snake_case ( self )-> int: lowerCamelCase_ =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): lowerCamelCase_ =self._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) lowerCamelCase_ =model_class(SCREAMING_SNAKE_CASE__ ) @jax.jit def model_jitted(_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ): return model(pixel_values=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) with self.subTest("""JIT Enabled""" ): lowerCamelCase_ =model_jitted(**SCREAMING_SNAKE_CASE__ ).to_tuple() with self.subTest("""JIT Disabled""" ): with jax.disable_jit(): lowerCamelCase_ =model_jitted(**SCREAMING_SNAKE_CASE__ ).to_tuple() self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , len(SCREAMING_SNAKE_CASE__ ) ) for jitted_output, output in zip(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): self.assertEqual(jitted_output.shape , output.shape ) def __UpperCamelCase ( ) ->Any: """simple docstring""" lowerCamelCase_ =Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_flax class _SCREAMING_SNAKE_CASE ( unittest.TestCase): @cached_property def _snake_case ( self )-> Optional[int]: return AutoImageProcessor.from_pretrained("""facebook/regnet-y-040""" ) if is_vision_available() else None @slow def _snake_case ( self )-> List[Any]: lowerCamelCase_ =FlaxRegNetForImageClassification.from_pretrained("""facebook/regnet-y-040""" ) lowerCamelCase_ =self.default_image_processor lowerCamelCase_ =prepare_img() lowerCamelCase_ =image_processor(images=SCREAMING_SNAKE_CASE__ , return_tensors="""np""" ) lowerCamelCase_ =model(**SCREAMING_SNAKE_CASE__ ) # verify the logits lowerCamelCase_ =(1, 1000) self.assertEqual(outputs.logits.shape , SCREAMING_SNAKE_CASE__ ) lowerCamelCase_ =jnp.array([-0.4_1_8_0, -1.5_0_5_1, -3.4_8_3_6] ) self.assertTrue(jnp.allclose(outputs.logits[0, :3] , SCREAMING_SNAKE_CASE__ , atol=1E-4 ) )
154
from typing import Optional from urllib.parse import quote import huggingface_hub as hfh from packaging import version def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ = None ) -> str: if version.parse(hfh.__version__ ).release < version.parse('0.11.0' ).release: # old versions of hfh don't url-encode the file path __lowerCamelCase : int = quote(lowerCamelCase__ ) return hfh.hf_hub_url(lowerCamelCase__ , lowerCamelCase__ , repo_type='dataset' , revision=lowerCamelCase__ )
73
0
"""simple docstring""" from scipy.stats import spearmanr import datasets lowerCAmelCase__ = ''' The Spearman rank-order correlation coefficient is a measure of the relationship between two datasets. Like other correlation coefficients, this one varies between -1 and +1 with 0 implying no correlation. Positive correlations imply that as data in dataset x increases, so does data in dataset y. Negative correlations imply that as x increases, y decreases. Correlations of -1 or +1 imply an exact monotonic relationship. Unlike the Pearson correlation, the Spearman correlation does not assume that both datasets are normally distributed. The p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Spearman correlation at least as extreme as the one computed from these datasets. The p-values are not entirely reliable but are probably reasonable for datasets larger than 500 or so. ''' lowerCAmelCase__ = ''' Args: predictions (`List[float]`): Predicted labels, as returned by a model. references (`List[float]`): Ground truth labels. return_pvalue (`bool`): If `True`, returns the p-value. If `False`, returns only the spearmanr score. Defaults to `False`. Returns: spearmanr (`float`): Spearman correlation coefficient. p-value (`float`): p-value. **Note**: is only returned if `return_pvalue=True` is input. Examples: Example 1: >>> spearmanr_metric = datasets.load_metric(\"spearmanr\") >>> results = spearmanr_metric.compute(references=[1, 2, 3, 4, 5], predictions=[10, 9, 2.5, 6, 4]) >>> print(results) {\'spearmanr\': -0.7} Example 2: >>> spearmanr_metric = datasets.load_metric(\"spearmanr\") >>> results = spearmanr_metric.compute(references=[1, 2, 3, 4, 5], ... predictions=[10, 9, 2.5, 6, 4], ... return_pvalue=True) >>> print(results[\'spearmanr\']) -0.7 >>> print(round(results[\'spearmanr_pvalue\'], 2)) 0.19 ''' lowerCAmelCase__ = R'''\ @book{kokoska2000crc, title={CRC standard probability and statistics tables and formulae}, author={Kokoska, Stephen and Zwillinger, Daniel}, year={2000}, publisher={Crc Press} } @article{2020SciPy-NMeth, author = {Virtanen, Pauli and Gommers, Ralf and Oliphant, Travis E. and Haberland, Matt and Reddy, Tyler and Cournapeau, David and Burovski, Evgeni and Peterson, Pearu and Weckesser, Warren and Bright, Jonathan and {van der Walt}, St{\'e}fan J. and Brett, Matthew and Wilson, Joshua and Millman, K. Jarrod and Mayorov, Nikolay and Nelson, Andrew R. J. and Jones, Eric and Kern, Robert and Larson, Eric and Carey, C J and Polat, {\.I}lhan and Feng, Yu and Moore, Eric W. and {VanderPlas}, Jake and Laxalde, Denis and Perktold, Josef and Cimrman, Robert and Henriksen, Ian and Quintero, E. A. and Harris, Charles R. and Archibald, Anne M. and Ribeiro, Ant{\^o}nio H. and Pedregosa, Fabian and {van Mulbregt}, Paul and {SciPy 1.0 Contributors}}, title = {{{SciPy} 1.0: Fundamental Algorithms for Scientific Computing in Python}}, journal = {Nature Methods}, year = {2020}, volume = {17}, pages = {261--272}, adsurl = {https://rdcu.be/b08Wh}, doi = {10.1038/s41592-019-0686-2}, } ''' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION) class __snake_case ( datasets.Metric): def SCREAMING_SNAKE_CASE ( self : Tuple ): """simple docstring""" return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Value('''float''' ), '''references''': datasets.Value('''float''' ), } ) , reference_urls=['''https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.spearmanr.html'''] , ) def SCREAMING_SNAKE_CASE ( self : Optional[Any] , __lowerCAmelCase : Dict , __lowerCAmelCase : str , __lowerCAmelCase : int=False ): """simple docstring""" _lowerCamelCase : Any = spearmanr(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if return_pvalue: return {"spearmanr": results[0], "spearmanr_pvalue": results[1]} else: return {"spearmanr": results[0]}
72
def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , ) -> float: __lowerCamelCase : Dict = [redshift, radiation_density, matter_density, dark_energy] if any(p < 0 for p in parameters ): raise ValueError('All input parameters must be positive' ) if any(p > 1 for p in parameters[1:4] ): raise ValueError('Relative densities cannot be greater than one' ) else: __lowerCamelCase : Dict = 1 - (matter_density + radiation_density + dark_energy) __lowerCamelCase : Union[str, Any] = ( radiation_density * (redshift + 1) ** 4 + matter_density * (redshift + 1) ** 3 + curvature * (redshift + 1) ** 2 + dark_energy ) __lowerCamelCase : List[Any] = hubble_constant * e_a ** (1 / 2) return hubble if __name__ == "__main__": import doctest # run doctest doctest.testmod() # demo LCDM approximation a =0.3 print( hubble_parameter( hubble_constant=68.3, radiation_density=1E-4, matter_density=matter_density, dark_energy=1 - matter_density, redshift=0, ) )
73
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __snake_case = { '''configuration_blip_2''': [ '''BLIP_2_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''Blip2Config''', '''Blip2QFormerConfig''', '''Blip2VisionConfig''', ], '''processing_blip_2''': ['''Blip2Processor'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __snake_case = [ '''BLIP_2_PRETRAINED_MODEL_ARCHIVE_LIST''', '''Blip2Model''', '''Blip2QFormerModel''', '''Blip2PreTrainedModel''', '''Blip2ForConditionalGeneration''', '''Blip2VisionModel''', ] if TYPE_CHECKING: from .configuration_blip_a import ( BLIP_2_PRETRAINED_CONFIG_ARCHIVE_MAP, BlipaConfig, BlipaQFormerConfig, BlipaVisionConfig, ) from .processing_blip_a import BlipaProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_blip_a import ( BLIP_2_PRETRAINED_MODEL_ARCHIVE_LIST, BlipaForConditionalGeneration, BlipaModel, BlipaPreTrainedModel, BlipaQFormerModel, BlipaVisionModel, ) else: import sys __snake_case = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
97
from typing import List, Optional, Union from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : Optional[Any] = ['''image_processor''', '''tokenizer'''] _UpperCAmelCase : Union[str, Any] = '''Pix2StructImageProcessor''' _UpperCAmelCase : Any = ('''T5Tokenizer''', '''T5TokenizerFast''') def __init__( self : List[str] ,SCREAMING_SNAKE_CASE__ : str ,SCREAMING_SNAKE_CASE__ : int): __lowerCamelCase : List[Any] = False super().__init__(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) def __call__( self : str ,SCREAMING_SNAKE_CASE__ : Any=None ,SCREAMING_SNAKE_CASE__ : Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None ,SCREAMING_SNAKE_CASE__ : bool = True ,SCREAMING_SNAKE_CASE__ : Union[bool, str, PaddingStrategy] = False ,SCREAMING_SNAKE_CASE__ : Union[bool, str, TruncationStrategy] = None ,SCREAMING_SNAKE_CASE__ : Optional[int] = None ,SCREAMING_SNAKE_CASE__ : Optional[int] = 2_0_4_8 ,SCREAMING_SNAKE_CASE__ : int = 0 ,SCREAMING_SNAKE_CASE__ : Optional[int] = None ,SCREAMING_SNAKE_CASE__ : Optional[bool] = None ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = True ,SCREAMING_SNAKE_CASE__ : Optional[Union[str, TensorType]] = None ,**SCREAMING_SNAKE_CASE__ : Dict ,): if images is None and text is None: raise ValueError('You have to specify either images or text.') # Get only text if images is None and not self.image_processor.is_vqa: __lowerCamelCase : Tuple = self.tokenizer __lowerCamelCase : Dict = self.tokenizer( text=SCREAMING_SNAKE_CASE__ ,add_special_tokens=SCREAMING_SNAKE_CASE__ ,padding=SCREAMING_SNAKE_CASE__ ,truncation=SCREAMING_SNAKE_CASE__ ,max_length=SCREAMING_SNAKE_CASE__ ,stride=SCREAMING_SNAKE_CASE__ ,pad_to_multiple_of=SCREAMING_SNAKE_CASE__ ,return_attention_mask=SCREAMING_SNAKE_CASE__ ,return_overflowing_tokens=SCREAMING_SNAKE_CASE__ ,return_special_tokens_mask=SCREAMING_SNAKE_CASE__ ,return_offsets_mapping=SCREAMING_SNAKE_CASE__ ,return_token_type_ids=SCREAMING_SNAKE_CASE__ ,return_length=SCREAMING_SNAKE_CASE__ ,verbose=SCREAMING_SNAKE_CASE__ ,return_tensors=SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__ ,) return text_encoding if not self.image_processor.is_vqa: # add pixel_values __lowerCamelCase : List[Any] = self.image_processor( SCREAMING_SNAKE_CASE__ ,return_tensors=SCREAMING_SNAKE_CASE__ ,max_patches=SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) else: # add pixel_values and bbox __lowerCamelCase : List[Any] = self.image_processor( SCREAMING_SNAKE_CASE__ ,return_tensors=SCREAMING_SNAKE_CASE__ ,max_patches=SCREAMING_SNAKE_CASE__ ,header_text=SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) if text is not None and not self.image_processor.is_vqa: __lowerCamelCase : List[Any] = self.tokenizer( text=SCREAMING_SNAKE_CASE__ ,add_special_tokens=SCREAMING_SNAKE_CASE__ ,padding=SCREAMING_SNAKE_CASE__ ,truncation=SCREAMING_SNAKE_CASE__ ,max_length=SCREAMING_SNAKE_CASE__ ,stride=SCREAMING_SNAKE_CASE__ ,pad_to_multiple_of=SCREAMING_SNAKE_CASE__ ,return_attention_mask=SCREAMING_SNAKE_CASE__ ,return_overflowing_tokens=SCREAMING_SNAKE_CASE__ ,return_special_tokens_mask=SCREAMING_SNAKE_CASE__ ,return_offsets_mapping=SCREAMING_SNAKE_CASE__ ,return_token_type_ids=SCREAMING_SNAKE_CASE__ ,return_length=SCREAMING_SNAKE_CASE__ ,verbose=SCREAMING_SNAKE_CASE__ ,return_tensors=SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__ ,) if "attention_mask" in text_encoding: __lowerCamelCase : List[Any] = text_encoding.pop('attention_mask') if "input_ids" in text_encoding: __lowerCamelCase : Dict = text_encoding.pop('input_ids') else: __lowerCamelCase : Optional[int] = None if text_encoding is not None: encoding_image_processor.update(SCREAMING_SNAKE_CASE__) return encoding_image_processor def lowerCAmelCase ( self : Dict ,*SCREAMING_SNAKE_CASE__ : str ,**SCREAMING_SNAKE_CASE__ : int): return self.tokenizer.batch_decode(*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : List[str] ,*SCREAMING_SNAKE_CASE__ : int ,**SCREAMING_SNAKE_CASE__ : Dict): return self.tokenizer.decode(*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) @property def lowerCAmelCase ( self : int): __lowerCamelCase : Dict = self.tokenizer.model_input_names __lowerCamelCase : int = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
73
0
from string import ascii_uppercase lowerCAmelCase_ = {str(ord(c) - 5_5): c for c in ascii_uppercase} def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase ) -> str: """simple docstring""" if isinstance(lowerCamelCase__ , lowerCamelCase__ ): raise TypeError('''int() can\'t convert non-string with explicit base''' ) if num < 0: raise ValueError('''parameter must be positive int''' ) if isinstance(lowerCamelCase__ , lowerCamelCase__ ): raise TypeError('''\'str\' object cannot be interpreted as an integer''' ) if isinstance(lowerCamelCase__ , lowerCamelCase__ ): raise TypeError('''\'float\' object cannot be interpreted as an integer''' ) if base in (0, 1): raise ValueError('''base must be >= 2''' ) if base > 36: raise ValueError('''base must be <= 36''' ) snake_case_ : List[str] = '' snake_case_ : List[Any] = 0 snake_case_ : Optional[int] = 0 while div != 1: snake_case_ : List[Any] = divmod(lowerCamelCase__ , lowerCamelCase__ ) if base >= 11 and 9 < mod < 36: snake_case_ : Optional[int] = ALPHABET_VALUES[str(lowerCamelCase__ )] else: snake_case_ : Optional[Any] = str(lowerCamelCase__ ) new_value += actual_value snake_case_ : Union[str, Any] = num // base snake_case_ : Union[str, Any] = div if div == 0: return str(new_value[::-1] ) elif div == 1: new_value += str(lowerCamelCase__ ) return str(new_value[::-1] ) return new_value[::-1] if __name__ == "__main__": import doctest doctest.testmod() for base in range(2, 3_7): for num in range(1_0_0_0): assert int(decimal_to_any(num, base), base) == num, ( num, base, decimal_to_any(num, base), int(decimal_to_any(num, base), base), )
279
from bisect import bisect from itertools import accumulate def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> Union[str, Any]: __lowerCamelCase : Optional[Any] = sorted(zip(lowerCamelCase__ , lowerCamelCase__ ) , key=lambda lowerCamelCase__ : x[0] / x[1] , reverse=lowerCamelCase__ ) __lowerCamelCase , __lowerCamelCase : Any = [i[0] for i in r], [i[1] for i in r] __lowerCamelCase : List[str] = list(accumulate(lowerCamelCase__ ) ) __lowerCamelCase : Union[str, Any] = bisect(lowerCamelCase__ , lowerCamelCase__ ) return ( 0 if k == 0 else sum(vl[:k] ) + (w - acc[k - 1]) * (vl[k]) / (wt[k]) if k != n else sum(vl[:k] ) ) if __name__ == "__main__": import doctest doctest.testmod()
73
0
'''simple docstring''' import copy import tempfile import unittest from huggingface_hub import HfFolder, delete_repo from parameterized import parameterized from requests.exceptions import HTTPError from transformers import AutoConfig, GenerationConfig from transformers.testing_utils import TOKEN, USER, is_staging_test class a__ ( unittest.TestCase ): """simple docstring""" @parameterized.expand([(None,), ('''foo.json''',)] ) def _snake_case (self , __lowercase ): __lowerCAmelCase = GenerationConfig( do_sample=SCREAMING_SNAKE_CASE__ , temperature=0.7 , length_penalty=1.0 , bad_words_ids=[[1, 2, 3], [4, 5]] , ) with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained(SCREAMING_SNAKE_CASE__ , config_name=SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase = GenerationConfig.from_pretrained(SCREAMING_SNAKE_CASE__ , config_name=SCREAMING_SNAKE_CASE__ ) # Checks parameters that were specified self.assertEqual(loaded_config.do_sample , SCREAMING_SNAKE_CASE__ ) self.assertEqual(loaded_config.temperature , 0.7 ) self.assertEqual(loaded_config.length_penalty , 1.0 ) self.assertEqual(loaded_config.bad_words_ids , [[1, 2, 3], [4, 5]] ) # Checks parameters that were not specified (defaults) self.assertEqual(loaded_config.top_k , 50 ) self.assertEqual(loaded_config.max_length , 20 ) self.assertEqual(loaded_config.max_time , SCREAMING_SNAKE_CASE__ ) def _snake_case (self ): __lowerCAmelCase = AutoConfig.from_pretrained('''gpt2''' ) __lowerCAmelCase = GenerationConfig.from_model_config(SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase = GenerationConfig() # The generation config has loaded a few non-default parameters from the model config self.assertNotEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # One of those parameters is eos_token_id -- check if it matches self.assertNotEqual(generation_config_from_model.eos_token_id , default_generation_config.eos_token_id ) self.assertEqual(generation_config_from_model.eos_token_id , model_config.eos_token_id ) def _snake_case (self ): __lowerCAmelCase = GenerationConfig() __lowerCAmelCase = { 'max_new_tokens': 10_24, 'foo': 'bar', } __lowerCAmelCase = copy.deepcopy(SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase = generation_config.update(**SCREAMING_SNAKE_CASE__ ) # update_kwargs was not modified (no side effects) self.assertEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # update_kwargs was used to update the config on valid attributes self.assertEqual(generation_config.max_new_tokens , 10_24 ) # `.update()` returns a dictionary of unused kwargs self.assertEqual(SCREAMING_SNAKE_CASE__ , {'''foo''': '''bar'''} ) def _snake_case (self ): __lowerCAmelCase = GenerationConfig() __lowerCAmelCase = 'bar' with tempfile.TemporaryDirectory('''test-generation-config''' ) as tmp_dir: generation_config.save_pretrained(SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase = GenerationConfig.from_pretrained(SCREAMING_SNAKE_CASE__ ) # update_kwargs was used to update the config on valid attributes self.assertEqual(new_config.foo , '''bar''' ) __lowerCAmelCase = GenerationConfig.from_model_config(SCREAMING_SNAKE_CASE__ ) assert not hasattr(SCREAMING_SNAKE_CASE__ , '''foo''' ) # no new kwargs should be initialized if from config def _snake_case (self ): __lowerCAmelCase = GenerationConfig() self.assertEqual(default_config.temperature , 1.0 ) self.assertEqual(default_config.do_sample , SCREAMING_SNAKE_CASE__ ) self.assertEqual(default_config.num_beams , 1 ) __lowerCAmelCase = GenerationConfig( do_sample=SCREAMING_SNAKE_CASE__ , temperature=0.7 , length_penalty=1.0 , bad_words_ids=[[1, 2, 3], [4, 5]] , ) self.assertEqual(config.temperature , 0.7 ) self.assertEqual(config.do_sample , SCREAMING_SNAKE_CASE__ ) self.assertEqual(config.num_beams , 1 ) with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained(SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase = GenerationConfig.from_pretrained(SCREAMING_SNAKE_CASE__ , temperature=1.0 ) self.assertEqual(loaded_config.temperature , 1.0 ) self.assertEqual(loaded_config.do_sample , SCREAMING_SNAKE_CASE__ ) self.assertEqual(loaded_config.num_beams , 1 ) # default value @is_staging_test class a__ ( unittest.TestCase ): """simple docstring""" @classmethod def _snake_case (cls ): __lowerCAmelCase = TOKEN HfFolder.save_token(SCREAMING_SNAKE_CASE__ ) @classmethod def _snake_case (cls ): try: delete_repo(token=cls._token , repo_id='''test-generation-config''' ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id='''valid_org/test-generation-config-org''' ) except HTTPError: pass def _snake_case (self ): __lowerCAmelCase = GenerationConfig( do_sample=SCREAMING_SNAKE_CASE__ , temperature=0.7 , length_penalty=1.0 , ) config.push_to_hub('''test-generation-config''' , use_auth_token=self._token ) __lowerCAmelCase = GenerationConfig.from_pretrained(F"""{USER}/test-generation-config""" ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(SCREAMING_SNAKE_CASE__ , getattr(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) # Reset repo delete_repo(token=self._token , repo_id='''test-generation-config''' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained( SCREAMING_SNAKE_CASE__ , repo_id='''test-generation-config''' , push_to_hub=SCREAMING_SNAKE_CASE__ , use_auth_token=self._token ) __lowerCAmelCase = GenerationConfig.from_pretrained(F"""{USER}/test-generation-config""" ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(SCREAMING_SNAKE_CASE__ , getattr(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) def _snake_case (self ): __lowerCAmelCase = GenerationConfig( do_sample=SCREAMING_SNAKE_CASE__ , temperature=0.7 , length_penalty=1.0 , ) config.push_to_hub('''valid_org/test-generation-config-org''' , use_auth_token=self._token ) __lowerCAmelCase = GenerationConfig.from_pretrained('''valid_org/test-generation-config-org''' ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(SCREAMING_SNAKE_CASE__ , getattr(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) # Reset repo delete_repo(token=self._token , repo_id='''valid_org/test-generation-config-org''' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained( SCREAMING_SNAKE_CASE__ , repo_id='''valid_org/test-generation-config-org''' , push_to_hub=SCREAMING_SNAKE_CASE__ , use_auth_token=self._token ) __lowerCAmelCase = GenerationConfig.from_pretrained('''valid_org/test-generation-config-org''' ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(SCREAMING_SNAKE_CASE__ , getattr(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) )
174
from __future__ import annotations import math def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> list: if len(lowerCamelCase__ ) != 2 or len(a[0] ) != 2 or len(lowerCamelCase__ ) != 2 or len(b[0] ) != 2: raise Exception('Matrices are not 2x2' ) __lowerCamelCase : Optional[int] = [ [a[0][0] * b[0][0] + a[0][1] * b[1][0], a[0][0] * b[0][1] + a[0][1] * b[1][1]], [a[1][0] * b[0][0] + a[1][1] * b[1][0], a[1][0] * b[0][1] + a[1][1] * b[1][1]], ] return new_matrix def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> Optional[int]: return [ [matrix_a[row][col] + matrix_b[row][col] for col in range(len(matrix_a[row] ) )] for row in range(len(lowerCamelCase__ ) ) ] def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> List[str]: return [ [matrix_a[row][col] - matrix_b[row][col] for col in range(len(matrix_a[row] ) )] for row in range(len(lowerCamelCase__ ) ) ] def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> tuple[list, list, list, list]: if len(lowerCamelCase__ ) % 2 != 0 or len(a[0] ) % 2 != 0: raise Exception('Odd matrices are not supported!' ) __lowerCamelCase : Tuple = len(lowerCamelCase__ ) __lowerCamelCase : List[Any] = matrix_length // 2 __lowerCamelCase : Dict = [[a[i][j] for j in range(lowerCamelCase__ , lowerCamelCase__ )] for i in range(lowerCamelCase__ )] __lowerCamelCase : str = [ [a[i][j] for j in range(lowerCamelCase__ , lowerCamelCase__ )] for i in range(lowerCamelCase__ , lowerCamelCase__ ) ] __lowerCamelCase : Dict = [[a[i][j] for j in range(lowerCamelCase__ )] for i in range(lowerCamelCase__ )] __lowerCamelCase : Optional[Any] = [[a[i][j] for j in range(lowerCamelCase__ )] for i in range(lowerCamelCase__ , lowerCamelCase__ )] return top_left, top_right, bot_left, bot_right def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> tuple[int, int]: return len(lowerCamelCase__ ), len(matrix[0] ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> None: print('\n'.join(str(lowerCamelCase__ ) for line in matrix ) ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> list: if matrix_dimensions(lowerCamelCase__ ) == (2, 2): return default_matrix_multiplication(lowerCamelCase__ , lowerCamelCase__ ) __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : Optional[Any] = split_matrix(lowerCamelCase__ ) __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : Optional[Any] = split_matrix(lowerCamelCase__ ) __lowerCamelCase : str = actual_strassen(lowerCamelCase__ , matrix_subtraction(lowerCamelCase__ , lowerCamelCase__ ) ) __lowerCamelCase : List[str] = actual_strassen(matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) , lowerCamelCase__ ) __lowerCamelCase : List[Any] = actual_strassen(matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) , lowerCamelCase__ ) __lowerCamelCase : Tuple = actual_strassen(lowerCamelCase__ , matrix_subtraction(lowerCamelCase__ , lowerCamelCase__ ) ) __lowerCamelCase : Optional[int] = actual_strassen(matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) , matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) ) __lowerCamelCase : Dict = actual_strassen(matrix_subtraction(lowerCamelCase__ , lowerCamelCase__ ) , matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) ) __lowerCamelCase : Tuple = actual_strassen(matrix_subtraction(lowerCamelCase__ , lowerCamelCase__ ) , matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) ) __lowerCamelCase : Dict = matrix_addition(matrix_subtraction(matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) , lowerCamelCase__ ) , lowerCamelCase__ ) __lowerCamelCase : Tuple = matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) __lowerCamelCase : List[str] = matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) __lowerCamelCase : Any = matrix_subtraction(matrix_subtraction(matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) , lowerCamelCase__ ) , lowerCamelCase__ ) # construct the new matrix from our 4 quadrants __lowerCamelCase : List[Any] = [] for i in range(len(lowerCamelCase__ ) ): new_matrix.append(top_left[i] + top_right[i] ) for i in range(len(lowerCamelCase__ ) ): new_matrix.append(bot_left[i] + bot_right[i] ) return new_matrix def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> list: if matrix_dimensions(lowerCamelCase__ )[1] != matrix_dimensions(lowerCamelCase__ )[0]: __lowerCamelCase : Any = ( 'Unable to multiply these matrices, please check the dimensions.\n' F"Matrix A: {matrixa}\n" F"Matrix B: {matrixa}" ) raise Exception(lowerCamelCase__ ) __lowerCamelCase : str = matrix_dimensions(lowerCamelCase__ ) __lowerCamelCase : List[str] = matrix_dimensions(lowerCamelCase__ ) if dimensiona[0] == dimensiona[1] and dimensiona[0] == dimensiona[1]: return [matrixa, matrixa] __lowerCamelCase : str = max(*lowerCamelCase__ , *lowerCamelCase__ ) __lowerCamelCase : List[str] = int(math.pow(2 , math.ceil(math.loga(lowerCamelCase__ ) ) ) ) __lowerCamelCase : Any = matrixa __lowerCamelCase : int = matrixa # Adding zeros to the matrices so that the arrays dimensions are the same and also # power of 2 for i in range(0 , lowerCamelCase__ ): if i < dimensiona[0]: for _ in range(dimensiona[1] , lowerCamelCase__ ): new_matrixa[i].append(0 ) else: new_matrixa.append([0] * maxim ) if i < dimensiona[0]: for _ in range(dimensiona[1] , lowerCamelCase__ ): new_matrixa[i].append(0 ) else: new_matrixa.append([0] * maxim ) __lowerCamelCase : List[str] = actual_strassen(lowerCamelCase__ , lowerCamelCase__ ) # Removing the additional zeros for i in range(0 , lowerCamelCase__ ): if i < dimensiona[0]: for _ in range(dimensiona[1] , lowerCamelCase__ ): final_matrix[i].pop() else: final_matrix.pop() return final_matrix if __name__ == "__main__": a =[ [2, 3, 4, 5], [6, 4, 3, 1], [2, 3, 6, 7], [3, 1, 2, 4], [2, 3, 4, 5], [6, 4, 3, 1], [2, 3, 6, 7], [3, 1, 2, 4], [2, 3, 4, 5], [6, 2, 3, 1], ] a =[[0, 2, 1, 1], [16, 2, 3, 3], [2, 2, 7, 7], [13, 11, 22, 4]] print(strassen(matrixa, matrixa))
73
0
def A (__A : Union[str, Any] ) -> str: """simple docstring""" if not all(char in '''01''' for char in bin_string ): raise ValueError('''Non-binary value was passed to the function''' ) if not bin_string: raise ValueError('''Empty string was passed to the function''' ) UpperCAmelCase_ = '' while len(lowerCamelCase__ ) % 3 != 0: UpperCAmelCase_ = '0' + bin_string UpperCAmelCase_ = [ bin_string[index : index + 3] for index in range(len(lowerCamelCase__ ) ) if index % 3 == 0 ] for bin_group in bin_string_in_3_list: UpperCAmelCase_ = 0 for index, val in enumerate(lowerCamelCase__ ): oct_val += int(2 ** (2 - index) * int(lowerCamelCase__ ) ) oct_string += str(lowerCamelCase__ ) return oct_string if __name__ == "__main__": from doctest import testmod testmod()
51
from math import isclose, sqrt def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> tuple[float, float, float]: __lowerCamelCase : Tuple = point_y / 4 / point_x __lowerCamelCase : Tuple = 2 * normal_gradient / (1 + normal_gradient * normal_gradient) __lowerCamelCase : List[Any] = (1 - normal_gradient * normal_gradient) / ( 1 + normal_gradient * normal_gradient ) __lowerCamelCase : int = (sa - ca * incoming_gradient) / (ca + sa * incoming_gradient) # to find the next point, solve the simultaeneous equations: # y^2 + 4x^2 = 100 # y - b = m * (x - a) # ==> A x^2 + B x + C = 0 __lowerCamelCase : Any = outgoing_gradient**2 + 4 __lowerCamelCase : Optional[int] = 2 * outgoing_gradient * (point_y - outgoing_gradient * point_x) __lowerCamelCase : str = (point_y - outgoing_gradient * point_x) ** 2 - 1_0_0 __lowerCamelCase : str = ( -linear_term - sqrt(linear_term**2 - 4 * quadratic_term * constant_term ) ) / (2 * quadratic_term) __lowerCamelCase : Optional[Any] = ( -linear_term + sqrt(linear_term**2 - 4 * quadratic_term * constant_term ) ) / (2 * quadratic_term) # two solutions, one of which is our input point __lowerCamelCase : Optional[Any] = x_minus if isclose(lowerCamelCase__ , lowerCamelCase__ ) else x_plus __lowerCamelCase : Tuple = point_y + outgoing_gradient * (next_x - point_x) return next_x, next_y, outgoing_gradient def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ = 1.4 , lowerCamelCase__ = -9.6 ) -> int: __lowerCamelCase : int = 0 __lowerCamelCase : float = first_x_coord __lowerCamelCase : float = first_y_coord __lowerCamelCase : float = (10.1 - point_y) / (0.0 - point_x) while not (-0.01 <= point_x <= 0.01 and point_y > 0): __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : Any = next_point(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) num_reflections += 1 return num_reflections if __name__ == "__main__": print(F"""{solution() = }""")
73
0
# This is the module that test_patching.py uses to test patch_submodule() import os # noqa: this is just for tests import os as renamed_os # noqa: this is just for tests from os import path # noqa: this is just for tests from os import path as renamed_path # noqa: this is just for tests from os.path import join # noqa: this is just for tests from os.path import join as renamed_join # noqa: this is just for tests __snake_case = open # noqa: we just need to have a builtin inside this module to test it properly
176
import os import unicodedata from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging a =logging.get_logger(__name__) a ={"""vocab_file""": """spiece.model"""} a ={ """vocab_file""": { """albert-base-v1""": """https://huggingface.co/albert-base-v1/resolve/main/spiece.model""", """albert-large-v1""": """https://huggingface.co/albert-large-v1/resolve/main/spiece.model""", """albert-xlarge-v1""": """https://huggingface.co/albert-xlarge-v1/resolve/main/spiece.model""", """albert-xxlarge-v1""": """https://huggingface.co/albert-xxlarge-v1/resolve/main/spiece.model""", """albert-base-v2""": """https://huggingface.co/albert-base-v2/resolve/main/spiece.model""", """albert-large-v2""": """https://huggingface.co/albert-large-v2/resolve/main/spiece.model""", """albert-xlarge-v2""": """https://huggingface.co/albert-xlarge-v2/resolve/main/spiece.model""", """albert-xxlarge-v2""": """https://huggingface.co/albert-xxlarge-v2/resolve/main/spiece.model""", } } a ={ """albert-base-v1""": 512, """albert-large-v1""": 512, """albert-xlarge-v1""": 512, """albert-xxlarge-v1""": 512, """albert-base-v2""": 512, """albert-large-v2""": 512, """albert-xlarge-v2""": 512, """albert-xxlarge-v2""": 512, } a ="""▁""" class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : List[Any] = VOCAB_FILES_NAMES _UpperCAmelCase : List[str] = PRETRAINED_VOCAB_FILES_MAP _UpperCAmelCase : Optional[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self : str ,SCREAMING_SNAKE_CASE__ : Optional[int] ,SCREAMING_SNAKE_CASE__ : Tuple=True ,SCREAMING_SNAKE_CASE__ : str=True ,SCREAMING_SNAKE_CASE__ : List[str]=False ,SCREAMING_SNAKE_CASE__ : Any="[CLS]" ,SCREAMING_SNAKE_CASE__ : Optional[int]="[SEP]" ,SCREAMING_SNAKE_CASE__ : Optional[Any]="<unk>" ,SCREAMING_SNAKE_CASE__ : Any="[SEP]" ,SCREAMING_SNAKE_CASE__ : Optional[int]="<pad>" ,SCREAMING_SNAKE_CASE__ : Any="[CLS]" ,SCREAMING_SNAKE_CASE__ : Union[str, Any]="[MASK]" ,SCREAMING_SNAKE_CASE__ : Optional[Dict[str, Any]] = None ,**SCREAMING_SNAKE_CASE__ : Dict ,): # Mask token behave like a normal word, i.e. include the space before it and # is included in the raw text, there should be a match in a non-normalized sentence. __lowerCamelCase : Dict = ( AddedToken(SCREAMING_SNAKE_CASE__ ,lstrip=SCREAMING_SNAKE_CASE__ ,rstrip=SCREAMING_SNAKE_CASE__ ,normalized=SCREAMING_SNAKE_CASE__) if isinstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) else mask_token ) __lowerCamelCase : str = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( do_lower_case=SCREAMING_SNAKE_CASE__ ,remove_space=SCREAMING_SNAKE_CASE__ ,keep_accents=SCREAMING_SNAKE_CASE__ ,bos_token=SCREAMING_SNAKE_CASE__ ,eos_token=SCREAMING_SNAKE_CASE__ ,unk_token=SCREAMING_SNAKE_CASE__ ,sep_token=SCREAMING_SNAKE_CASE__ ,pad_token=SCREAMING_SNAKE_CASE__ ,cls_token=SCREAMING_SNAKE_CASE__ ,mask_token=SCREAMING_SNAKE_CASE__ ,sp_model_kwargs=self.sp_model_kwargs ,**SCREAMING_SNAKE_CASE__ ,) __lowerCamelCase : Any = do_lower_case __lowerCamelCase : Union[str, Any] = remove_space __lowerCamelCase : Tuple = keep_accents __lowerCamelCase : Dict = vocab_file __lowerCamelCase : str = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.Load(SCREAMING_SNAKE_CASE__) @property def lowerCAmelCase ( self : Optional[Any]): return len(self.sp_model) def lowerCAmelCase ( self : Optional[Any]): __lowerCamelCase : Optional[int] = {self.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__): i for i in range(self.vocab_size)} vocab.update(self.added_tokens_encoder) return vocab def __getstate__( self : Union[str, Any]): __lowerCamelCase : str = self.__dict__.copy() __lowerCamelCase : Tuple = None return state def __setstate__( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : str): __lowerCamelCase : List[str] = d # for backward compatibility if not hasattr(self ,'sp_model_kwargs'): __lowerCamelCase : List[str] = {} __lowerCamelCase : int = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.Load(self.vocab_file) def lowerCAmelCase ( self : Dict ,SCREAMING_SNAKE_CASE__ : List[Any]): if self.remove_space: __lowerCamelCase : Dict = ' '.join(inputs.strip().split()) else: __lowerCamelCase : Optional[Any] = inputs __lowerCamelCase : Tuple = outputs.replace('``' ,'"').replace('\'\'' ,'"') if not self.keep_accents: __lowerCamelCase : List[str] = unicodedata.normalize('NFKD' ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : str = ''.join([c for c in outputs if not unicodedata.combining(SCREAMING_SNAKE_CASE__)]) if self.do_lower_case: __lowerCamelCase : Optional[Any] = outputs.lower() return outputs def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : str): __lowerCamelCase : Tuple = self.preprocess_text(SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = self.sp_model.encode(SCREAMING_SNAKE_CASE__ ,out_type=SCREAMING_SNAKE_CASE__) __lowerCamelCase : Tuple = [] for piece in pieces: if len(SCREAMING_SNAKE_CASE__) > 1 and piece[-1] == str(',') and piece[-2].isdigit(): __lowerCamelCase : int = self.sp_model.EncodeAsPieces(piece[:-1].replace(SCREAMING_SNAKE_CASE__ ,'')) if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE: if len(cur_pieces[0]) == 1: __lowerCamelCase : Union[str, Any] = cur_pieces[1:] else: __lowerCamelCase : Dict = cur_pieces[0][1:] cur_pieces.append(piece[-1]) new_pieces.extend(SCREAMING_SNAKE_CASE__) else: new_pieces.append(SCREAMING_SNAKE_CASE__) return new_pieces def lowerCAmelCase ( self : Any ,SCREAMING_SNAKE_CASE__ : List[str]): return self.sp_model.PieceToId(SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : str ,SCREAMING_SNAKE_CASE__ : Any): return self.sp_model.IdToPiece(SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Tuple ,SCREAMING_SNAKE_CASE__ : int): __lowerCamelCase : Optional[Any] = [] __lowerCamelCase : int = '' __lowerCamelCase : Optional[int] = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(SCREAMING_SNAKE_CASE__) + token __lowerCamelCase : List[Any] = True __lowerCamelCase : Any = [] else: current_sub_tokens.append(SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = False out_string += self.sp_model.decode(SCREAMING_SNAKE_CASE__) return out_string.strip() def lowerCAmelCase ( self : Dict ,SCREAMING_SNAKE_CASE__ : List[int] ,SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None): __lowerCamelCase : Union[str, Any] = [self.sep_token_id] __lowerCamelCase : int = [self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def lowerCAmelCase ( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : List[int] ,SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ,SCREAMING_SNAKE_CASE__ : bool = False): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=SCREAMING_SNAKE_CASE__ ,token_ids_a=SCREAMING_SNAKE_CASE__ ,already_has_special_tokens=SCREAMING_SNAKE_CASE__) if token_ids_a is not None: return [1] + ([0] * len(SCREAMING_SNAKE_CASE__)) + [1] + ([0] * len(SCREAMING_SNAKE_CASE__)) + [1] return [1] + ([0] * len(SCREAMING_SNAKE_CASE__)) + [1] def lowerCAmelCase ( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : List[int] ,SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None): __lowerCamelCase : Tuple = [self.sep_token_id] __lowerCamelCase : List[Any] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep) * [0] return len(cls + token_ids_a + sep) * [0] + len(token_ids_a + sep) * [1] def lowerCAmelCase ( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : str ,SCREAMING_SNAKE_CASE__ : Optional[str] = None): if not os.path.isdir(SCREAMING_SNAKE_CASE__): logger.error(F"Vocabulary path ({save_directory}) should be a directory") return __lowerCamelCase : List[str] = os.path.join( SCREAMING_SNAKE_CASE__ ,(filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file']) if os.path.abspath(self.vocab_file) != os.path.abspath(SCREAMING_SNAKE_CASE__) and os.path.isfile(self.vocab_file): copyfile(self.vocab_file ,SCREAMING_SNAKE_CASE__) elif not os.path.isfile(self.vocab_file): with open(SCREAMING_SNAKE_CASE__ ,'wb') as fi: __lowerCamelCase : str = self.sp_model.serialized_model_proto() fi.write(SCREAMING_SNAKE_CASE__) return (out_vocab_file,)
73
0
from typing import Any class snake_case__ : """simple docstring""" def __init__( self : Optional[int] , __lowerCamelCase : Any ) -> Tuple: a = data a = None class snake_case__ : """simple docstring""" def __init__( self : List[Any] ) -> Union[str, Any]: a = None def __UpperCAmelCase ( self : Any ) -> Optional[int]: a = self.head while temp is not None: print(temp.data , end=" " ) a = temp.next print() def __UpperCAmelCase ( self : str , __lowerCamelCase : Any ) -> Any: a = Node(SCREAMING_SNAKE_CASE__ ) a = self.head a = new_node def __UpperCAmelCase ( self : Dict , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : Optional[Any] ) -> Dict: if node_data_a == node_data_a: return else: a = self.head while node_a is not None and node_a.data != node_data_a: a = node_a.next a = self.head while node_a is not None and node_a.data != node_data_a: a = node_a.next if node_a is None or node_a is None: return a = node_a.data, node_a.data if __name__ == "__main__": __lowerCAmelCase : str = LinkedList() for i in range(5, 0, -1): ll.push(i) ll.print_list() ll.swap_nodes(1, 4) print('After swapping') ll.print_list()
107
def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> float: if discount_rate < 0: raise ValueError('Discount rate cannot be negative' ) if not cash_flows: raise ValueError('Cash flows list cannot be empty' ) __lowerCamelCase : int = sum( cash_flow / ((1 + discount_rate) ** i) for i, cash_flow in enumerate(lowerCamelCase__ ) ) return round(lowerCamelCase__ , ndigits=2 ) if __name__ == "__main__": import doctest doctest.testmod()
73
0
import torch from transformers import CamembertForMaskedLM, CamembertTokenizer def __lowerCamelCase ( snake_case__ ,snake_case__ ,snake_case__ ,snake_case__=5 ) -> int: """simple docstring""" assert masked_input.count("""<mask>""" ) == 1 _SCREAMING_SNAKE_CASE = torch.tensor(tokenizer.encode(lowerCamelCase__ ,add_special_tokens=lowerCamelCase__ ) ).unsqueeze(0 ) # Batch size 1 _SCREAMING_SNAKE_CASE = model(lowerCamelCase__ )[0] # The last hidden-state is the first element of the output tuple _SCREAMING_SNAKE_CASE = (input_ids.squeeze() == tokenizer.mask_token_id).nonzero().item() _SCREAMING_SNAKE_CASE = logits[0, masked_index, :] _SCREAMING_SNAKE_CASE = logits.softmax(dim=0 ) _SCREAMING_SNAKE_CASE = prob.topk(k=lowerCamelCase__ ,dim=0 ) _SCREAMING_SNAKE_CASE = ' '.join( [tokenizer.convert_ids_to_tokens(indices[i].item() ) for i in range(len(lowerCamelCase__ ) )] ) _SCREAMING_SNAKE_CASE = tokenizer.mask_token _SCREAMING_SNAKE_CASE = [] for index, predicted_token_bpe in enumerate(topk_predicted_token_bpe.split(""" """ ) ): _SCREAMING_SNAKE_CASE = predicted_token_bpe.replace("""\u2581""" ,""" """ ) if " {0}".format(lowerCamelCase__ ) in masked_input: topk_filled_outputs.append( ( masked_input.replace(""" {0}""".format(lowerCamelCase__ ) ,lowerCamelCase__ ), values[index].item(), predicted_token, ) ) else: topk_filled_outputs.append( ( masked_input.replace(lowerCamelCase__ ,lowerCamelCase__ ), values[index].item(), predicted_token, ) ) return topk_filled_outputs UpperCamelCase = CamembertTokenizer.from_pretrained('''camembert-base''') UpperCamelCase = CamembertForMaskedLM.from_pretrained('''camembert-base''') model.eval() UpperCamelCase = '''Le camembert est <mask> :)''' print(fill_mask(masked_input, model, tokenizer, topk=3))
306
import copy from typing import Dict, List, Optional from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING a ={ """facebook/mask2former-swin-small-coco-instance""": ( """https://huggingface.co/facebook/mask2former-swin-small-coco-instance/blob/main/config.json""" ) # See all Mask2Former models at https://huggingface.co/models?filter=mask2former } a =logging.get_logger(__name__) class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : Dict = '''mask2former''' _UpperCAmelCase : Dict = ['''swin'''] _UpperCAmelCase : Optional[int] = {'''hidden_size''': '''hidden_dim'''} def __init__( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : Optional[Dict] = None ,SCREAMING_SNAKE_CASE__ : int = 2_5_6 ,SCREAMING_SNAKE_CASE__ : int = 2_5_6 ,SCREAMING_SNAKE_CASE__ : int = 2_5_6 ,SCREAMING_SNAKE_CASE__ : int = 1_0_2_4 ,SCREAMING_SNAKE_CASE__ : str = "relu" ,SCREAMING_SNAKE_CASE__ : int = 6 ,SCREAMING_SNAKE_CASE__ : int = 1_0 ,SCREAMING_SNAKE_CASE__ : int = 8 ,SCREAMING_SNAKE_CASE__ : float = 0.0 ,SCREAMING_SNAKE_CASE__ : int = 2_0_4_8 ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : int = 4 ,SCREAMING_SNAKE_CASE__ : int = 2_5_5 ,SCREAMING_SNAKE_CASE__ : int = 1_0_0 ,SCREAMING_SNAKE_CASE__ : float = 0.1 ,SCREAMING_SNAKE_CASE__ : float = 2.0 ,SCREAMING_SNAKE_CASE__ : float = 5.0 ,SCREAMING_SNAKE_CASE__ : float = 5.0 ,SCREAMING_SNAKE_CASE__ : int = 1_2_5_4_4 ,SCREAMING_SNAKE_CASE__ : float = 3.0 ,SCREAMING_SNAKE_CASE__ : float = 0.75 ,SCREAMING_SNAKE_CASE__ : float = 0.02 ,SCREAMING_SNAKE_CASE__ : float = 1.0 ,SCREAMING_SNAKE_CASE__ : bool = True ,SCREAMING_SNAKE_CASE__ : List[int] = [4, 8, 1_6, 3_2] ,SCREAMING_SNAKE_CASE__ : bool = None ,**SCREAMING_SNAKE_CASE__ : Optional[Any] ,): if backbone_config is None: logger.info('`backbone_config` is `None`. Initializing the config with the default `Swin` backbone.') __lowerCamelCase : Optional[Any] = CONFIG_MAPPING['swin']( image_size=2_2_4 ,in_channels=3 ,patch_size=4 ,embed_dim=9_6 ,depths=[2, 2, 1_8, 2] ,num_heads=[3, 6, 1_2, 2_4] ,window_size=7 ,drop_path_rate=0.3 ,use_absolute_embeddings=SCREAMING_SNAKE_CASE__ ,out_features=['stage1', 'stage2', 'stage3', 'stage4'] ,) if isinstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__): __lowerCamelCase : Union[str, Any] = backbone_config.pop('model_type') __lowerCamelCase : Dict = CONFIG_MAPPING[backbone_model_type] __lowerCamelCase : int = config_class.from_dict(SCREAMING_SNAKE_CASE__) # verify that the backbone is supported if backbone_config.model_type not in self.backbones_supported: logger.warning_once( F"Backbone {backbone_config.model_type} is not a supported model and may not be compatible with Mask2Former. " F"Supported model types: {','.join(self.backbones_supported)}") __lowerCamelCase : Dict = backbone_config __lowerCamelCase : int = feature_size __lowerCamelCase : List[str] = mask_feature_size __lowerCamelCase : int = hidden_dim __lowerCamelCase : str = encoder_feedforward_dim __lowerCamelCase : Optional[int] = activation_function __lowerCamelCase : int = encoder_layers __lowerCamelCase : List[Any] = decoder_layers __lowerCamelCase : Union[str, Any] = num_attention_heads __lowerCamelCase : Tuple = dropout __lowerCamelCase : Dict = dim_feedforward __lowerCamelCase : Union[str, Any] = pre_norm __lowerCamelCase : List[str] = enforce_input_projection __lowerCamelCase : Optional[int] = common_stride __lowerCamelCase : Dict = ignore_value __lowerCamelCase : Optional[Any] = num_queries __lowerCamelCase : int = no_object_weight __lowerCamelCase : Optional[Any] = class_weight __lowerCamelCase : str = mask_weight __lowerCamelCase : List[str] = dice_weight __lowerCamelCase : Dict = train_num_points __lowerCamelCase : Optional[int] = oversample_ratio __lowerCamelCase : Optional[Any] = importance_sample_ratio __lowerCamelCase : List[Any] = init_std __lowerCamelCase : Tuple = init_xavier_std __lowerCamelCase : Union[str, Any] = use_auxiliary_loss __lowerCamelCase : List[Any] = feature_strides __lowerCamelCase : Any = output_auxiliary_logits __lowerCamelCase : List[Any] = decoder_layers super().__init__(**SCREAMING_SNAKE_CASE__) @classmethod def lowerCAmelCase ( cls : str ,SCREAMING_SNAKE_CASE__ : PretrainedConfig ,**SCREAMING_SNAKE_CASE__ : Tuple): return cls( backbone_config=SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__ ,) def lowerCAmelCase ( self : str): __lowerCamelCase : List[Any] = copy.deepcopy(self.__dict__) __lowerCamelCase : List[Any] = self.backbone_config.to_dict() __lowerCamelCase : Union[str, Any] = self.__class__.model_type return output
73
0
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.""" )
317
import string # frequency taken from https://en.wikipedia.org/wiki/Letter_frequency a ={ """E""": 12.70, """T""": 9.06, """A""": 8.17, """O""": 7.51, """I""": 6.97, """N""": 6.75, """S""": 6.33, """H""": 6.09, """R""": 5.99, """D""": 4.25, """L""": 4.03, """C""": 2.78, """U""": 2.76, """M""": 2.41, """W""": 2.36, """F""": 2.23, """G""": 2.02, """Y""": 1.97, """P""": 1.93, """B""": 1.29, """V""": 0.98, """K""": 0.77, """J""": 0.15, """X""": 0.15, """Q""": 0.10, """Z""": 0.07, } a ="""ETAOINSHRDLCUMWFGYPBVKJXQZ""" a ="""ABCDEFGHIJKLMNOPQRSTUVWXYZ""" def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> dict[str, int]: __lowerCamelCase : Tuple = {letter: 0 for letter in string.ascii_uppercase} for letter in message.upper(): if letter in LETTERS: letter_count[letter] += 1 return letter_count def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> str: return x[0] def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> str: __lowerCamelCase : List[str] = get_letter_count(lowerCamelCase__ ) __lowerCamelCase : dict[int, list[str]] = { freq: [] for letter, freq in letter_to_freq.items() } for letter in LETTERS: freq_to_letter[letter_to_freq[letter]].append(lowerCamelCase__ ) __lowerCamelCase : dict[int, str] = {} for freq in freq_to_letter: freq_to_letter[freq].sort(key=ETAOIN.find , reverse=lowerCamelCase__ ) __lowerCamelCase : Optional[Any] = ''.join(freq_to_letter[freq] ) __lowerCamelCase : int = list(freq_to_letter_str.items() ) freq_pairs.sort(key=lowerCamelCase__ , reverse=lowerCamelCase__ ) __lowerCamelCase : list[str] = [freq_pair[1] for freq_pair in freq_pairs] return "".join(lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> int: __lowerCamelCase : str = get_frequency_order(lowerCamelCase__ ) __lowerCamelCase : Optional[Any] = 0 for common_letter in ETAOIN[:6]: if common_letter in freq_order[:6]: match_score += 1 for uncommon_letter in ETAOIN[-6:]: if uncommon_letter in freq_order[-6:]: match_score += 1 return match_score if __name__ == "__main__": import doctest doctest.testmod()
73
0
'''simple docstring''' import argparse import json import os import fairseq import torch from fairseq.data import Dictionary from transformers import ( UniSpeechConfig, UniSpeechForCTC, UniSpeechForPreTraining, WavaVecaFeatureExtractor, WavaVecaPhonemeCTCTokenizer, WavaVecaProcessor, logging, ) logging.set_verbosity_info() lowerCamelCase_ = logging.get_logger(__name__) lowerCamelCase_ = { '''post_extract_proj''': '''feature_projection.projection''', '''encoder.pos_conv.0''': '''encoder.pos_conv_embed.conv''', '''self_attn.k_proj''': '''encoder.layers.*.attention.k_proj''', '''self_attn.v_proj''': '''encoder.layers.*.attention.v_proj''', '''self_attn.q_proj''': '''encoder.layers.*.attention.q_proj''', '''self_attn.out_proj''': '''encoder.layers.*.attention.out_proj''', '''self_attn_layer_norm''': '''encoder.layers.*.layer_norm''', '''fc1''': '''encoder.layers.*.feed_forward.intermediate_dense''', '''fc2''': '''encoder.layers.*.feed_forward.output_dense''', '''final_layer_norm''': '''encoder.layers.*.final_layer_norm''', '''encoder.layer_norm''': '''encoder.layer_norm''', '''w2v_model.layer_norm''': '''feature_projection.layer_norm''', '''quantizer.weight_proj''': '''quantizer.weight_proj''', '''quantizer.vars''': '''quantizer.codevectors''', '''project_q''': '''project_q''', '''final_proj''': '''project_hid''', '''w2v_encoder.proj''': '''ctc_proj''', '''mask_emb''': '''masked_spec_embed''', } lowerCamelCase_ = [ '''ctc_proj''', '''quantizer.weight_proj''', '''quantizer.codevectors''', '''project_q''', '''project_hid''', ] def __lowercase ( __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase ) -> Dict: '''simple docstring''' for attribute in key.split("." ): if is_finetuned: if attribute in ["quantizer", "project_q", "project_hid"]: # those layers are only relevant for pretraining and should be dropped return if attribute == "ctc_proj": # we should rename `ctc_proj` to `lm_head` for fine-tuned phoneme models _A = 'lm_head' _A = getattr(lowerCamelCase__ , lowerCamelCase__ ) if weight_type is not None: _A = getattr(lowerCamelCase__ , lowerCamelCase__ ).shape else: _A = hf_pointer.shape assert hf_shape == value.shape, ( F'''Shape of hf {key + '.' + weight_type if weight_type is not None else ''} is {hf_shape}, but should be''' F''' {value.shape} for {full_name}''' ) if weight_type == "weight": _A = value elif weight_type == "weight_g": _A = value elif weight_type == "weight_v": _A = value elif weight_type == "bias": _A = value else: _A = value logger.info(F'''{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}.''' ) def __lowercase ( __lowercase , __lowercase , __lowercase ) -> Optional[int]: '''simple docstring''' _A = [] _A = fairseq_model.state_dict() _A = hf_model.unispeech.feature_extractor for name, value in fairseq_dict.items(): _A = False if "conv_layers" in name: load_conv_layer( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , hf_model.config.feat_extract_norm == "group" , ) _A = True else: for key, mapped_key in MAPPING.items(): _A = 'unispeech.' + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key if key in name or key.split("w2v_model." )[-1] == name.split("." )[0]: _A = True if "*" in mapped_key: _A = name.split(lowerCamelCase__ )[0].split("." )[-2] _A = mapped_key.replace("*" , lowerCamelCase__ ) if "weight_g" in name: _A = 'weight_g' elif "weight_v" in name: _A = 'weight_v' elif "bias" in name: _A = 'bias' elif "weight" in name: # TODO: don't match quantizer.weight_proj _A = 'weight' else: _A = None set_recursively(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) continue if not is_used: unused_weights.append(lowerCamelCase__ ) logger.warning(F'''Unused weights: {unused_weights}''' ) def __lowercase ( __lowercase , __lowercase , __lowercase , __lowercase , __lowercase ) -> Optional[int]: '''simple docstring''' _A = full_name.split("conv_layers." )[-1] _A = name.split("." ) _A = int(items[0] ) _A = int(items[1] ) if type_id == 0: if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, ( F'''{full_name} has size {value.shape}, but''' F''' {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.''' ) _A = value logger.info(F'''Feat extract conv layer {layer_id} was initialized from {full_name}.''' ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, ( F'''{full_name} has size {value.shape}, but''' F''' {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.''' ) _A = value logger.info(F'''Feat extract conv layer {layer_id} was initialized from {full_name}.''' ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, ( F'''{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was''' " found." ) _A = value logger.info(F'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.''' ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, ( F'''{full_name} has size {value.shape}, but''' F''' {feature_extractor[layer_id].layer_norm.weight.data.shape} was found.''' ) _A = value logger.info(F'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.''' ) else: unused_weights.append(lowerCamelCase__ ) @torch.no_grad() def __lowercase ( __lowercase , __lowercase , __lowercase=None , __lowercase=None , __lowercase=True ) -> int: '''simple docstring''' if config_path is not None: _A = UniSpeechConfig.from_pretrained(lowerCamelCase__ ) else: _A = UniSpeechConfig() if is_finetuned: if dict_path: _A = Dictionary.load_from_json(lowerCamelCase__ ) # important change bos & pad token id since CTC symbol is <pad> and # not <s> as in fairseq _A = target_dict.pad_index _A = target_dict.bos_index _A = target_dict.eos_index _A = len(target_dict.symbols ) _A = os.path.join(lowerCamelCase__ , "vocab.json" ) if not os.path.isdir(lowerCamelCase__ ): logger.error("--pytorch_dump_folder_path ({}) should be a directory".format(lowerCamelCase__ ) ) return os.makedirs(lowerCamelCase__ , exist_ok=lowerCamelCase__ ) _A = target_dict.indices # fairseq has the <pad> and <s> switched _A = 42 _A = 43 with open(lowerCamelCase__ , "w" , encoding="utf-8" ) as vocab_handle: json.dump(lowerCamelCase__ , lowerCamelCase__ ) _A = WavaVecaPhonemeCTCTokenizer( lowerCamelCase__ , unk_token=target_dict.unk_word , pad_token=target_dict.pad_word , bos_token=target_dict.bos_word , eos_token=target_dict.eos_word , word_delimiter_token="|" , do_lower_case=lowerCamelCase__ , ) _A = True if config.feat_extract_norm == 'layer' else False _A = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=1_6000 , padding_value=0 , do_normalize=lowerCamelCase__ , return_attention_mask=lowerCamelCase__ , ) _A = WavaVecaProcessor(feature_extractor=lowerCamelCase__ , tokenizer=lowerCamelCase__ ) processor.save_pretrained(lowerCamelCase__ ) _A = UniSpeechForCTC(lowerCamelCase__ ) else: _A = UniSpeechForPreTraining(lowerCamelCase__ ) if is_finetuned: _A = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={"data": "/".join(dict_path.split("/" )[:-1] ), "w2v_path": checkpoint_path} ) else: _A = fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path] ) _A = model[0].eval() recursively_load_weights(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) hf_unispeech.save_pretrained(lowerCamelCase__ ) if __name__ == "__main__": lowerCamelCase_ = argparse.ArgumentParser() parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') parser.add_argument('''--checkpoint_path''', default=None, type=str, help='''Path to fairseq checkpoint''') parser.add_argument('''--dict_path''', default=None, type=str, help='''Path to dict of fine-tuned model''') parser.add_argument('''--config_path''', default=None, type=str, help='''Path to hf config.json of model to convert''') parser.add_argument( '''--not_finetuned''', action='''store_true''', help='''Whether the model to convert is a fine-tuned model or not''' ) lowerCamelCase_ = parser.parse_args() convert_unispeech_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned )
79
# This is the module that test_patching.py uses to test patch_submodule() import os # noqa: this is just for tests import os as renamed_os # noqa: this is just for tests from os import path # noqa: this is just for tests from os import path as renamed_path # noqa: this is just for tests from os.path import join # noqa: this is just for tests from os.path import join as renamed_join # noqa: this is just for tests a =open # noqa: we just need to have a builtin inside this module to test it properly
73
0
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 : str = logging.getLogger(__name__) __A : Any = {'facebook/bart-base': BartForConditionalGeneration} __A : List[Any] = {'facebook/bart-base': BartTokenizer} def __UpperCamelCase ( ) ->int: """simple docstring""" lowerCamelCase_ =argparse.ArgumentParser(description="""Export Bart model + Beam Search to ONNX graph.""" ) parser.add_argument( """--validation_file""" , type=lowerCamelCase__ , default=lowerCamelCase__ , help="""A csv or a json file containing the validation data.""" ) parser.add_argument( """--max_length""" , type=lowerCamelCase__ , default=5 , help="""The maximum total input sequence length after tokenization.""" , ) parser.add_argument( """--num_beams""" , type=lowerCamelCase__ , default=lowerCamelCase__ , 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=lowerCamelCase__ , help="""Path to pretrained model or model identifier from huggingface.co/models.""" , required=lowerCamelCase__ , ) parser.add_argument( """--config_name""" , type=lowerCamelCase__ , default=lowerCamelCase__ , help="""Pretrained config name or path if not the same as model_name""" , ) parser.add_argument( """--device""" , type=lowerCamelCase__ , default="""cpu""" , help="""Device where the model will be run""" , ) parser.add_argument("""--output_file_path""" , type=lowerCamelCase__ , default=lowerCamelCase__ , help="""Where to store the final ONNX file.""" ) lowerCamelCase_ =parser.parse_args() return args def __UpperCamelCase ( _A : Optional[Any] , _A : Dict="cpu" ) ->Union[str, Any]: """simple docstring""" lowerCamelCase_ =model_dict[model_name].from_pretrained(lowerCamelCase__ ).to(lowerCamelCase__ ) lowerCamelCase_ =tokenizer_dict[model_name].from_pretrained(lowerCamelCase__ ) if model_name in ["facebook/bart-base"]: lowerCamelCase_ =0 lowerCamelCase_ =None lowerCamelCase_ =0 return huggingface_model, tokenizer def __UpperCamelCase ( _A : List[Any] , _A : Tuple , _A : Optional[int] , _A : Dict , _A : int ) ->str: """simple docstring""" model.eval() lowerCamelCase_ =None lowerCamelCase_ =torch.jit.script(BARTBeamSearchGenerator(lowerCamelCase__ ) ) with torch.no_grad(): lowerCamelCase_ ='My friends are cool but they eat too many carbs.' lowerCamelCase_ =tokenizer([ARTICLE_TO_SUMMARIZE] , max_length=1024 , return_tensors="""pt""" ).to(model.device ) lowerCamelCase_ =model.generate( inputs["""input_ids"""] , attention_mask=inputs["""attention_mask"""] , num_beams=lowerCamelCase__ , max_length=lowerCamelCase__ , early_stopping=lowerCamelCase__ , decoder_start_token_id=model.config.decoder_start_token_id , ) torch.onnx.export( lowerCamelCase__ , ( inputs["""input_ids"""], inputs["""attention_mask"""], num_beams, max_length, model.config.decoder_start_token_id, ) , lowerCamelCase__ , 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=lowerCamelCase__ , ) logger.info("""Model exported to {}""".format(lowerCamelCase__ ) ) lowerCamelCase_ =remove_dup_initializers(os.path.abspath(lowerCamelCase__ ) ) logger.info("""Deduplicated and optimized model written to {}""".format(lowerCamelCase__ ) ) lowerCamelCase_ =onnxruntime.InferenceSession(lowerCamelCase__ ) lowerCamelCase_ =ort_sess.run( lowerCamelCase__ , { """input_ids""": inputs["""input_ids"""].cpu().numpy(), """attention_mask""": inputs["""attention_mask"""].cpu().numpy(), """num_beams""": np.array(lowerCamelCase__ ), """max_length""": np.array(lowerCamelCase__ ), """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 __UpperCamelCase ( ) ->Union[str, Any]: """simple docstring""" lowerCamelCase_ =parse_args() lowerCamelCase_ =5 lowerCamelCase_ =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() lowerCamelCase_ =torch.device(args.device ) lowerCamelCase_ =load_model_tokenizer(args.model_name_or_path , lowerCamelCase__ ) if model.config.decoder_start_token_id is None: raise ValueError("""Make sure that `config.decoder_start_token_id` is correctly defined""" ) model.to(lowerCamelCase__ ) if args.max_length: lowerCamelCase_ =args.max_length if args.num_beams: lowerCamelCase_ =args.num_beams if args.output_file_path: lowerCamelCase_ =args.output_file_path else: lowerCamelCase_ ='BART.onnx' logger.info("""Exporting model to ONNX""" ) export_and_validate_model(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) if __name__ == "__main__": main()
154
# Function to print upper half of diamond (pyramid) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> str: for i in range(0 , lowerCamelCase__ ): for _ in range(0 , n - i - 1 ): # printing spaces print(' ' , end='' ) for _ in range(0 , i + 1 ): # printing stars print('* ' , end='' ) print() def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Tuple: for i in range(lowerCamelCase__ , 0 , -1 ): for _ in range(lowerCamelCase__ , 0 , -1 ): # printing stars print('* ' , end='' ) print() for _ in range(n - i + 1 , 0 , -1 ): # printing spaces print(' ' , end='' ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Any: if n <= 0: print(' ... .... nothing printing :(' ) return floyd(lowerCamelCase__ ) # upper half reverse_floyd(lowerCamelCase__ ) # lower half if __name__ == "__main__": print(r"""| /\ | |- | |- |--| |\ /| |-""") print(r"""|/ \| |- |_ |_ |__| | \/ | |_""") a =1 while K: a =int(input("""enter the number and , and see the magic : """)) print() pretty_print(user_number) a =int(input("""press 0 to exit... and 1 to continue...""")) print("""Good Bye...""")
73
0
"""simple docstring""" import math_equivalence # From: git+https://github.com/hendrycks/math.git import datasets lowerCAmelCase__ = '''\ @article{hendrycksmath2021, title={Measuring Mathematical Problem Solving With the MATH Dataset}, author={Dan Hendrycks and Collin Burns and Saurav Kadavath and Akul Arora and Steven Basart and Eric Tang and Dawn Song and Jacob Steinhardt}, journal={arXiv preprint arXiv:2103.03874}, year={2021} } ''' lowerCAmelCase__ = '''\ This metric is used to assess performance on the Mathematics Aptitude Test of Heuristics (MATH) dataset. It first canonicalizes the inputs (e.g., converting \"1/2\" to \"\\frac{1}{2}\") and then computes accuracy. ''' lowerCAmelCase__ = R''' Calculates accuracy after canonicalizing inputs. Args: predictions: list of predictions to score. Each prediction is a string that contains natural language and LaTex. references: list of reference for each prediction. Each reference is a string that contains natural language and LaTex. Returns: accuracy: accuracy after canonicalizing inputs (e.g., converting \"1/2\" to \"\\frac{1}{2}\") Examples: >>> metric = datasets.load_metric(\"competition_math\") >>> results = metric.compute(references=[\"\\frac{1}{2}\"], predictions=[\"1/2\"]) >>> print(results) {\'accuracy\': 1.0} ''' @datasets.utils.file_utils.add_end_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION) class __snake_case ( datasets.Metric): def SCREAMING_SNAKE_CASE ( self : List[Any] ): """simple docstring""" return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Value('''string''' ), '''references''': datasets.Value('''string''' ), } ) , homepage='''https://github.com/hendrycks/math''' , codebase_urls=['''https://github.com/hendrycks/math'''] , ) def SCREAMING_SNAKE_CASE ( self : List[Any] , __lowerCAmelCase : List[Any] , __lowerCAmelCase : Tuple ): """simple docstring""" _lowerCamelCase : str = 0.0 for i, j in zip(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): n_correct += 1.0 if math_equivalence.is_equiv(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else 0.0 _lowerCamelCase : Tuple = n_correct / len(SCREAMING_SNAKE_CASE__ ) return { "accuracy": accuracy, }
72
import re import warnings from contextlib import contextmanager from ...processing_utils import ProcessorMixin class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : Any = ['''image_processor''', '''tokenizer'''] _UpperCAmelCase : List[Any] = '''AutoImageProcessor''' _UpperCAmelCase : Dict = '''AutoTokenizer''' def __init__( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : Optional[int]=None ,SCREAMING_SNAKE_CASE__ : List[Any]=None ,**SCREAMING_SNAKE_CASE__ : Union[str, Any]): __lowerCamelCase : List[str] = None if "feature_extractor" in kwargs: warnings.warn( 'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`' ' instead.' ,SCREAMING_SNAKE_CASE__ ,) __lowerCamelCase : Union[str, Any] = kwargs.pop('feature_extractor') __lowerCamelCase : Dict = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('You need to specify an `image_processor`.') if tokenizer is None: raise ValueError('You need to specify a `tokenizer`.') super().__init__(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Dict = self.image_processor __lowerCamelCase : Optional[int] = False def __call__( self : int ,*SCREAMING_SNAKE_CASE__ : Union[str, Any] ,**SCREAMING_SNAKE_CASE__ : Union[str, Any]): # For backward compatibility if self._in_target_context_manager: return self.current_processor(*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[int] = kwargs.pop('images' ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Union[str, Any] = kwargs.pop('text' ,SCREAMING_SNAKE_CASE__) if len(SCREAMING_SNAKE_CASE__) > 0: __lowerCamelCase : int = args[0] __lowerCamelCase : List[str] = args[1:] if images is None and text is None: raise ValueError('You need to specify either an `images` or `text` input to process.') if images is not None: __lowerCamelCase : Optional[int] = self.image_processor(SCREAMING_SNAKE_CASE__ ,*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) if text is not None: __lowerCamelCase : List[Any] = self.tokenizer(SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) if text is None: return inputs elif images is None: return encodings else: __lowerCamelCase : Optional[Any] = encodings['input_ids'] return inputs def lowerCAmelCase ( self : int ,*SCREAMING_SNAKE_CASE__ : Union[str, Any] ,**SCREAMING_SNAKE_CASE__ : Dict): return self.tokenizer.batch_decode(*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Optional[Any] ,*SCREAMING_SNAKE_CASE__ : List[Any] ,**SCREAMING_SNAKE_CASE__ : Any): return self.tokenizer.decode(*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) @contextmanager def lowerCAmelCase ( self : Tuple): warnings.warn( '`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your ' 'labels by using the argument `text` of the regular `__call__` method (either in the same call as ' 'your images inputs, or in a separate call.') __lowerCamelCase : List[Any] = True __lowerCamelCase : str = self.tokenizer yield __lowerCamelCase : Tuple = self.image_processor __lowerCamelCase : Tuple = False def lowerCAmelCase ( self : Any ,SCREAMING_SNAKE_CASE__ : str ,SCREAMING_SNAKE_CASE__ : int=False ,SCREAMING_SNAKE_CASE__ : List[Any]=None): if added_vocab is None: __lowerCamelCase : str = self.tokenizer.get_added_vocab() __lowerCamelCase : Union[str, Any] = {} while tokens: __lowerCamelCase : Tuple = re.search(R'<s_(.*?)>' ,SCREAMING_SNAKE_CASE__ ,re.IGNORECASE) if start_token is None: break __lowerCamelCase : Dict = start_token.group(1) __lowerCamelCase : List[str] = re.search(RF"</s_{key}>" ,SCREAMING_SNAKE_CASE__ ,re.IGNORECASE) __lowerCamelCase : Optional[int] = start_token.group() if end_token is None: __lowerCamelCase : List[Any] = tokens.replace(SCREAMING_SNAKE_CASE__ ,'') else: __lowerCamelCase : Tuple = end_token.group() __lowerCamelCase : int = re.escape(SCREAMING_SNAKE_CASE__) __lowerCamelCase : str = re.escape(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Union[str, Any] = re.search(F"{start_token_escaped}(.*?){end_token_escaped}" ,SCREAMING_SNAKE_CASE__ ,re.IGNORECASE) if content is not None: __lowerCamelCase : List[Any] = content.group(1).strip() if r"<s_" in content and r"</s_" in content: # non-leaf node __lowerCamelCase : str = self.tokenajson(SCREAMING_SNAKE_CASE__ ,is_inner_value=SCREAMING_SNAKE_CASE__ ,added_vocab=SCREAMING_SNAKE_CASE__) if value: if len(SCREAMING_SNAKE_CASE__) == 1: __lowerCamelCase : Tuple = value[0] __lowerCamelCase : int = value else: # leaf nodes __lowerCamelCase : Tuple = [] for leaf in content.split(R'<sep/>'): __lowerCamelCase : List[Any] = leaf.strip() if leaf in added_vocab and leaf[0] == "<" and leaf[-2:] == "/>": __lowerCamelCase : str = leaf[1:-2] # for categorical special tokens output[key].append(SCREAMING_SNAKE_CASE__) if len(output[key]) == 1: __lowerCamelCase : Dict = output[key][0] __lowerCamelCase : Dict = tokens[tokens.find(SCREAMING_SNAKE_CASE__) + len(SCREAMING_SNAKE_CASE__) :].strip() if tokens[:6] == r"<sep/>": # non-leaf nodes return [output] + self.tokenajson(tokens[6:] ,is_inner_value=SCREAMING_SNAKE_CASE__ ,added_vocab=SCREAMING_SNAKE_CASE__) if len(SCREAMING_SNAKE_CASE__): return [output] if is_inner_value else output else: return [] if is_inner_value else {"text_sequence": tokens} @property def lowerCAmelCase ( self : List[str]): warnings.warn( '`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.' ,SCREAMING_SNAKE_CASE__ ,) return self.image_processor_class @property def lowerCAmelCase ( self : List[Any]): warnings.warn( '`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.' ,SCREAMING_SNAKE_CASE__ ,) return self.image_processor
73
0
'''simple docstring''' import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging __snake_case = logging.get_logger(__name__) __snake_case = { '''google/pix2struct-textcaps-base''': ( '''https://huggingface.co/google/pix2struct-textcaps-base/resolve/main/config.json''' ), } class lowercase ( A__ ): """simple docstring""" _a = '''pix2struct_text_model''' _a = ['''past_key_values'''] _a = { '''hidden_size''': '''hidden_size''', '''num_attention_heads''': '''num_heads''', '''num_hidden_layers''': '''num_layers''', } def __init__( self , UpperCamelCase_=50244 , UpperCamelCase_=768 , UpperCamelCase_=64 , UpperCamelCase_=2048 , UpperCamelCase_=12 , UpperCamelCase_=12 , UpperCamelCase_=32 , UpperCamelCase_=128 , UpperCamelCase_=0.1 , UpperCamelCase_=1e-6 , UpperCamelCase_=1.0 , UpperCamelCase_="gelu_new" , UpperCamelCase_=0 , UpperCamelCase_=False , UpperCamelCase_=0 , UpperCamelCase_=1 , UpperCamelCase_=False , UpperCamelCase_=True , **UpperCamelCase_ , ): '''simple docstring''' UpperCamelCase__ :Optional[int] = vocab_size UpperCamelCase__ :int = hidden_size UpperCamelCase__ :str = d_kv UpperCamelCase__ :List[Any] = d_ff UpperCamelCase__ :List[Any] = num_layers UpperCamelCase__ :str = num_heads UpperCamelCase__ :Dict = relative_attention_num_buckets UpperCamelCase__ :List[str] = relative_attention_max_distance UpperCamelCase__ :Union[str, Any] = dropout_rate UpperCamelCase__ :Optional[int] = layer_norm_epsilon UpperCamelCase__ :Dict = initializer_factor UpperCamelCase__ :Any = use_cache UpperCamelCase__ :int = eos_token_id UpperCamelCase__ :Dict = decoder_start_token_id # for backwards compatibility UpperCamelCase__ :Dict = dense_act_fn super().__init__( pad_token_id=SCREAMING_SNAKE_CASE__ , eos_token_id=SCREAMING_SNAKE_CASE__ , decoder_start_token_id=SCREAMING_SNAKE_CASE__ , tie_word_embeddings=SCREAMING_SNAKE_CASE__ , is_decoder=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) @classmethod def lowerCAmelCase__ ( cls , UpperCamelCase_ , **UpperCamelCase_ ): '''simple docstring''' cls._set_token_in_kwargs(SCREAMING_SNAKE_CASE__ ) UpperCamelCase__ :str = cls.get_config_dict(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) # get the text config dict if we are loading from Pix2StructConfig if config_dict.get('''model_type''' ) == "pix2struct": UpperCamelCase__ :Dict = 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(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) class lowercase ( A__ ): """simple docstring""" _a = '''pix2struct_vision_model''' def __init__( self , UpperCamelCase_=768 , UpperCamelCase_=768 , UpperCamelCase_=2048 , UpperCamelCase_=64 , UpperCamelCase_=12 , UpperCamelCase_=12 , UpperCamelCase_="gelu_new" , UpperCamelCase_=1e-6 , UpperCamelCase_=0.0 , UpperCamelCase_=0.0 , UpperCamelCase_=1e-10 , UpperCamelCase_=1.0 , UpperCamelCase_=4096 , UpperCamelCase_=32 , UpperCamelCase_=128 , **UpperCamelCase_ , ): '''simple docstring''' super().__init__(**SCREAMING_SNAKE_CASE__ ) UpperCamelCase__ :Tuple = hidden_size UpperCamelCase__ :List[str] = patch_embed_hidden_size UpperCamelCase__ :Dict = d_ff UpperCamelCase__ :Optional[Any] = dropout_rate UpperCamelCase__ :str = num_hidden_layers UpperCamelCase__ :Dict = num_attention_heads UpperCamelCase__ :Optional[Any] = initializer_range UpperCamelCase__ :List[Any] = initializer_factor UpperCamelCase__ :List[str] = attention_dropout UpperCamelCase__ :str = layer_norm_eps UpperCamelCase__ :Any = dense_act_fn UpperCamelCase__ :int = seq_len UpperCamelCase__ :Tuple = relative_attention_num_buckets UpperCamelCase__ :int = relative_attention_max_distance UpperCamelCase__ :List[Any] = d_kv @classmethod def lowerCAmelCase__ ( cls , UpperCamelCase_ , **UpperCamelCase_ ): '''simple docstring''' cls._set_token_in_kwargs(SCREAMING_SNAKE_CASE__ ) UpperCamelCase__ :Optional[Any] = cls.get_config_dict(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) # get the vision config dict if we are loading from Pix2StructConfig if config_dict.get('''model_type''' ) == "pix2struct": UpperCamelCase__ :Dict = 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(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) class lowercase ( A__ ): """simple docstring""" _a = '''pix2struct''' _a = True def __init__( self , UpperCamelCase_=None , UpperCamelCase_=None , UpperCamelCase_=1.0 , UpperCamelCase_=0.02 , UpperCamelCase_=False , UpperCamelCase_=False , UpperCamelCase_=True , **UpperCamelCase_ , ): '''simple docstring''' super().__init__(tie_word_embeddings=SCREAMING_SNAKE_CASE__ , is_encoder_decoder=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) if text_config is None: UpperCamelCase__ :Any = {} logger.info('''text_config is None. Initializing the Pix2StructTextConfig with default values.''' ) if vision_config is None: UpperCamelCase__ :str = {} logger.info('''vision_config is None. Initializing the Pix2StructVisionConfig with default values.''' ) UpperCamelCase__ :Union[str, Any] = PixaStructTextConfig(**SCREAMING_SNAKE_CASE__ ) UpperCamelCase__ :Optional[Any] = PixaStructVisionConfig(**SCREAMING_SNAKE_CASE__ ) UpperCamelCase__ :Optional[int] = self.text_config.decoder_start_token_id UpperCamelCase__ :Any = self.text_config.pad_token_id UpperCamelCase__ :Optional[int] = self.text_config.eos_token_id UpperCamelCase__ :Dict = initializer_factor UpperCamelCase__ :Any = initializer_range UpperCamelCase__ :Tuple = self.initializer_range UpperCamelCase__ :Tuple = self.initializer_range UpperCamelCase__ :str = is_vqa @classmethod def lowerCAmelCase__ ( cls , UpperCamelCase_ , UpperCamelCase_ , **UpperCamelCase_ ): '''simple docstring''' return cls(text_config=text_config.to_dict() , vision_config=vision_config.to_dict() , **SCREAMING_SNAKE_CASE__ ) def lowerCAmelCase__ ( self ): '''simple docstring''' UpperCamelCase__ :Union[str, Any] = copy.deepcopy(self.__dict__ ) UpperCamelCase__ :Union[str, Any] = self.text_config.to_dict() UpperCamelCase__ :Tuple = self.vision_config.to_dict() UpperCamelCase__ :str = self.__class__.model_type return output
97
def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> int: __lowerCamelCase : Optional[int] = 0 __lowerCamelCase : Dict = len(lowerCamelCase__ ) - 1 while left <= right: # avoid divided by 0 during interpolation if sorted_collection[left] == sorted_collection[right]: if sorted_collection[left] == item: return left else: return None __lowerCamelCase : str = left + ((item - sorted_collection[left]) * (right - left)) // ( sorted_collection[right] - sorted_collection[left] ) # out of range check if point < 0 or point >= len(lowerCamelCase__ ): return None __lowerCamelCase : Tuple = sorted_collection[point] if current_item == item: return point else: if point < left: __lowerCamelCase : List[Any] = left __lowerCamelCase : Tuple = point elif point > right: __lowerCamelCase : Dict = right __lowerCamelCase : str = point else: if item < current_item: __lowerCamelCase : Dict = point - 1 else: __lowerCamelCase : Dict = point + 1 return None def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> Any: # avoid divided by 0 during interpolation if sorted_collection[left] == sorted_collection[right]: if sorted_collection[left] == item: return left else: return None __lowerCamelCase : Optional[int] = left + ((item - sorted_collection[left]) * (right - left)) // ( sorted_collection[right] - sorted_collection[left] ) # out of range check if point < 0 or point >= len(lowerCamelCase__ ): return None if sorted_collection[point] == item: return point elif point < left: return interpolation_search_by_recursion(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) elif point > right: return interpolation_search_by_recursion(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) else: if sorted_collection[point] > item: return interpolation_search_by_recursion( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , point - 1 ) else: return interpolation_search_by_recursion( lowerCamelCase__ , lowerCamelCase__ , point + 1 , lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Optional[Any]: if collection != sorted(lowerCamelCase__ ): raise ValueError('Collection must be ascending sorted' ) return True if __name__ == "__main__": import sys a =0 if debug == 1: a =[10, 30, 40, 45, 50, 66, 77, 93] try: __assert_sorted(collection) except ValueError: sys.exit("""Sequence must be ascending sorted to apply interpolation search""") a =67 a =interpolation_search(collection, target) if result is not None: print(F"""{target} found at positions: {result}""") else: print("""Not found""")
73
0
import logging from transformers import PretrainedConfig lowerCAmelCase_ = logging.getLogger(__name__) lowerCAmelCase_ = { '''bertabs-finetuned-cnndm''': '''https://huggingface.co/remi/bertabs-finetuned-cnndm-extractive-abstractive-summarization/resolve/main/config.json''', } class __lowerCAmelCase ( _a ): lowerCamelCase_ : int = '''bertabs''' def __init__(self , __magic_name__=3_0522 , __magic_name__=512 , __magic_name__=6 , __magic_name__=512 , __magic_name__=8 , __magic_name__=512 , __magic_name__=0.2 , __magic_name__=6 , __magic_name__=768 , __magic_name__=8 , __magic_name__=2048 , __magic_name__=0.2 , **__magic_name__ , ) -> str: '''simple docstring''' super().__init__(**SCREAMING_SNAKE_CASE__ ) snake_case_ : str = vocab_size snake_case_ : Optional[Any] = max_pos snake_case_ : List[Any] = enc_layers snake_case_ : int = enc_hidden_size snake_case_ : Tuple = enc_heads snake_case_ : Union[str, Any] = enc_ff_size snake_case_ : Union[str, Any] = enc_dropout snake_case_ : Dict = dec_layers snake_case_ : Union[str, Any] = dec_hidden_size snake_case_ : Optional[Any] = dec_heads snake_case_ : List[Any] = dec_ff_size snake_case_ : Dict = dec_dropout
279
import json import os import subprocess import unittest from ast import literal_eval import pytest from parameterized import parameterized, parameterized_class from . import is_sagemaker_available if is_sagemaker_available(): from sagemaker import Session, TrainingJobAnalytics from sagemaker.huggingface import HuggingFace @pytest.mark.skipif( literal_eval(os.getenv('''TEST_SAGEMAKER''' , '''False''' ) ) is not True , reason='''Skipping test because should only be run when releasing minor transformers version''' , ) @pytest.mark.usefixtures('''sm_env''' ) @parameterized_class( [ { '''framework''': '''pytorch''', '''script''': '''run_glue_model_parallelism.py''', '''model_name_or_path''': '''roberta-large''', '''instance_type''': '''ml.p3dn.24xlarge''', '''results''': {'''train_runtime''': 1_600, '''eval_accuracy''': 0.3, '''eval_loss''': 1.2}, }, { '''framework''': '''pytorch''', '''script''': '''run_glue.py''', '''model_name_or_path''': '''roberta-large''', '''instance_type''': '''ml.p3dn.24xlarge''', '''results''': {'''train_runtime''': 1_600, '''eval_accuracy''': 0.3, '''eval_loss''': 1.2}, }, ] ) class A_ ( unittest.TestCase ): def lowerCAmelCase ( self : Union[str, Any]): if self.framework == "pytorch": subprocess.run( F"cp ./examples/pytorch/text-classification/run_glue.py {self.env.test_path}/run_glue.py".split() ,encoding='utf-8' ,check=SCREAMING_SNAKE_CASE__ ,) assert hasattr(self ,'env') def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : int): # configuration for running training on smdistributed Model Parallel __lowerCamelCase : Any = { 'enabled': True, 'processes_per_host': 8, } __lowerCamelCase : List[Any] = { 'enabled': True, 'parameters': { 'microbatches': 4, 'placement_strategy': 'spread', 'pipeline': 'interleaved', 'optimize': 'speed', 'partitions': 4, 'ddp': True, }, } __lowerCamelCase : str = {'smdistributed': {'modelparallel': smp_options}, 'mpi': mpi_options} __lowerCamelCase : List[str] = 'trainer' if self.script == 'run_glue.py' else 'smtrainer' # creates estimator return HuggingFace( entry_point=self.script ,source_dir=self.env.test_path ,role=self.env.role ,image_uri=self.env.image_uri ,base_job_name=F"{self.env.base_job_name}-{instance_count}-smp-{name_extension}" ,instance_count=SCREAMING_SNAKE_CASE__ ,instance_type=self.instance_type ,debugger_hook_config=SCREAMING_SNAKE_CASE__ ,hyperparameters={ **self.env.hyperparameters, 'model_name_or_path': self.model_name_or_path, 'max_steps': 5_0_0, } ,metric_definitions=self.env.metric_definitions ,distribution=SCREAMING_SNAKE_CASE__ ,py_version='py36' ,) def lowerCAmelCase ( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : Any): TrainingJobAnalytics(SCREAMING_SNAKE_CASE__).export_csv(F"{self.env.test_path}/{job_name}_metrics.csv") @parameterized.expand([(1,)]) def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : Optional[Any]): # create estimator __lowerCamelCase : str = self.create_estimator(SCREAMING_SNAKE_CASE__) # run training estimator.fit() # result dataframe __lowerCamelCase : List[str] = TrainingJobAnalytics(estimator.latest_training_job.name).dataframe() # extract kpis __lowerCamelCase : Optional[int] = list(result_metrics_df[result_metrics_df.metric_name == 'eval_accuracy']['value']) __lowerCamelCase : Any = list(result_metrics_df[result_metrics_df.metric_name == 'eval_loss']['value']) # get train time from SageMaker job, this includes starting, preprocessing, stopping __lowerCamelCase : str = ( Session().describe_training_job(estimator.latest_training_job.name).get('TrainingTimeInSeconds' ,9_9_9_9_9_9) ) # assert kpis assert train_runtime <= self.results["train_runtime"] assert all(t >= self.results['eval_accuracy'] for t in eval_accuracy) assert all(t <= self.results['eval_loss'] for t in eval_loss) # dump tests result into json file to share in PR with open(F"{estimator.latest_training_job.name}.json" ,'w') as outfile: json.dump({'train_time': train_runtime, 'eval_accuracy': eval_accuracy, 'eval_loss': eval_loss} ,SCREAMING_SNAKE_CASE__)
73
0
'''simple docstring''' from __future__ import annotations from collections.abc import Callable from typing import Any, Generic, TypeVar _UpperCAmelCase : Any = TypeVar("""T""") class a__ ( Generic[T] ): """simple docstring""" def __init__(self , __lowercase , __lowercase ): __lowerCAmelCase = None __lowerCAmelCase = len(SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase = [any_type for _ in range(self.N )] + arr __lowerCAmelCase = fnc self.build() def _snake_case (self ): for p in range(self.N - 1 , 0 , -1 ): __lowerCAmelCase = self.fn(self.st[p * 2] , self.st[p * 2 + 1] ) def _snake_case (self , __lowercase , __lowercase ): p += self.N __lowerCAmelCase = v while p > 1: __lowerCAmelCase = p // 2 __lowerCAmelCase = self.fn(self.st[p * 2] , self.st[p * 2 + 1] ) def _snake_case (self , __lowercase , __lowercase ): # noqa: E741 __lowerCAmelCase = l + self.N, r + self.N __lowerCAmelCase = None while l <= r: if l % 2 == 1: __lowerCAmelCase = self.st[l] if res is None else self.fn(SCREAMING_SNAKE_CASE__ , self.st[l] ) if r % 2 == 0: __lowerCAmelCase = self.st[r] if res is None else self.fn(SCREAMING_SNAKE_CASE__ , self.st[r] ) __lowerCAmelCase = (l + 1) // 2, (r - 1) // 2 return res if __name__ == "__main__": from functools import reduce _UpperCAmelCase : str = [1, 1_0, -2, 9, -3, 8, 4, -7, 5, 6, 1_1, -1_2] _UpperCAmelCase : Tuple = { 0: 7, 1: 2, 2: 6, 3: -1_4, 4: 5, 5: 4, 6: 7, 7: -1_0, 8: 9, 9: 1_0, 1_0: 1_2, 1_1: 1, } _UpperCAmelCase : Optional[Any] = SegmentTree(test_array, min) _UpperCAmelCase : str = SegmentTree(test_array, max) _UpperCAmelCase : Tuple = SegmentTree(test_array, lambda a, b: a + b) def __magic_name__( ): for i in range(len(lowerCamelCase__)): for j in range(lowerCamelCase__, len(lowerCamelCase__)): __lowerCAmelCase = reduce(lowerCamelCase__, test_array[i : j + 1]) __lowerCAmelCase = reduce(lowerCamelCase__, test_array[i : j + 1]) __lowerCAmelCase = reduce(lambda lowerCamelCase, lowerCamelCase: a + b, test_array[i : j + 1]) assert min_range == min_segment_tree.query(lowerCamelCase__, lowerCamelCase__) assert max_range == max_segment_tree.query(lowerCamelCase__, lowerCamelCase__) assert sum_range == sum_segment_tree.query(lowerCamelCase__, lowerCamelCase__) test_all_segments() for index, value in test_updates.items(): _UpperCAmelCase : Union[str, Any] = value min_segment_tree.update(index, value) max_segment_tree.update(index, value) sum_segment_tree.update(index, value) test_all_segments()
174
import unittest import numpy as np from transformers import DistilBertConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask if is_flax_available(): import jax.numpy as jnp from transformers.models.distilbert.modeling_flax_distilbert import ( FlaxDistilBertForMaskedLM, FlaxDistilBertForMultipleChoice, FlaxDistilBertForQuestionAnswering, FlaxDistilBertForSequenceClassification, FlaxDistilBertForTokenClassification, FlaxDistilBertModel, ) class A_ ( unittest.TestCase ): def __init__( self : Tuple ,SCREAMING_SNAKE_CASE__ : List[str] ,SCREAMING_SNAKE_CASE__ : Any=1_3 ,SCREAMING_SNAKE_CASE__ : int=7 ,SCREAMING_SNAKE_CASE__ : str=True ,SCREAMING_SNAKE_CASE__ : Dict=True ,SCREAMING_SNAKE_CASE__ : str=True ,SCREAMING_SNAKE_CASE__ : Dict=True ,SCREAMING_SNAKE_CASE__ : List[Any]=9_9 ,SCREAMING_SNAKE_CASE__ : List[Any]=3_2 ,SCREAMING_SNAKE_CASE__ : int=5 ,SCREAMING_SNAKE_CASE__ : List[Any]=4 ,SCREAMING_SNAKE_CASE__ : Optional[Any]=3_7 ,SCREAMING_SNAKE_CASE__ : Union[str, Any]="gelu" ,SCREAMING_SNAKE_CASE__ : int=0.1 ,SCREAMING_SNAKE_CASE__ : Optional[int]=0.1 ,SCREAMING_SNAKE_CASE__ : Optional[int]=5_1_2 ,SCREAMING_SNAKE_CASE__ : Dict=1_6 ,SCREAMING_SNAKE_CASE__ : Dict=2 ,SCREAMING_SNAKE_CASE__ : Optional[int]=0.02 ,SCREAMING_SNAKE_CASE__ : Dict=4 ,): __lowerCamelCase : int = parent __lowerCamelCase : Dict = batch_size __lowerCamelCase : Union[str, Any] = seq_length __lowerCamelCase : List[Any] = is_training __lowerCamelCase : Tuple = use_attention_mask __lowerCamelCase : List[str] = use_token_type_ids __lowerCamelCase : Any = use_labels __lowerCamelCase : List[str] = vocab_size __lowerCamelCase : Any = hidden_size __lowerCamelCase : Tuple = num_hidden_layers __lowerCamelCase : Union[str, Any] = num_attention_heads __lowerCamelCase : Union[str, Any] = intermediate_size __lowerCamelCase : List[Any] = hidden_act __lowerCamelCase : int = hidden_dropout_prob __lowerCamelCase : int = attention_probs_dropout_prob __lowerCamelCase : Union[str, Any] = max_position_embeddings __lowerCamelCase : Union[str, Any] = type_vocab_size __lowerCamelCase : List[str] = type_sequence_label_size __lowerCamelCase : Tuple = initializer_range __lowerCamelCase : Optional[int] = num_choices def lowerCAmelCase ( self : Union[str, Any]): __lowerCamelCase : Dict = ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size) __lowerCamelCase : Union[str, Any] = None if self.use_attention_mask: __lowerCamelCase : Any = random_attention_mask([self.batch_size, self.seq_length]) __lowerCamelCase : str = DistilBertConfig( vocab_size=self.vocab_size ,dim=self.hidden_size ,n_layers=self.num_hidden_layers ,n_heads=self.num_attention_heads ,hidden_dim=self.intermediate_size ,hidden_act=self.hidden_act ,dropout=self.hidden_dropout_prob ,attention_dropout=self.attention_probs_dropout_prob ,max_position_embeddings=self.max_position_embeddings ,initializer_range=self.initializer_range ,tie_weights_=SCREAMING_SNAKE_CASE__ ,) return config, input_ids, attention_mask def lowerCAmelCase ( self : List[Any]): __lowerCamelCase : List[str] = self.prepare_config_and_inputs() __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : Dict = config_and_inputs __lowerCamelCase : Any = {'input_ids': input_ids, 'attention_mask': attention_mask} return config, inputs_dict @require_flax class A_ ( SCREAMING_SNAKE_CASE , unittest.TestCase ): _UpperCAmelCase : Dict = ( ( FlaxDistilBertModel, FlaxDistilBertForMaskedLM, FlaxDistilBertForMultipleChoice, FlaxDistilBertForQuestionAnswering, FlaxDistilBertForSequenceClassification, FlaxDistilBertForTokenClassification, FlaxDistilBertForQuestionAnswering, ) if is_flax_available() else () ) def lowerCAmelCase ( self : Optional[Any]): __lowerCamelCase : Tuple = FlaxDistilBertModelTester(self) @slow def lowerCAmelCase ( self : int): for model_class_name in self.all_model_classes: __lowerCamelCase : List[Any] = model_class_name.from_pretrained('distilbert-base-uncased') __lowerCamelCase : List[str] = model(np.ones((1, 1))) self.assertIsNotNone(SCREAMING_SNAKE_CASE__) @require_flax class A_ ( unittest.TestCase ): @slow def lowerCAmelCase ( self : str): __lowerCamelCase : Union[str, Any] = FlaxDistilBertModel.from_pretrained('distilbert-base-uncased') __lowerCamelCase : str = np.array([[0, 3_4_5, 2_3_2, 3_2_8, 7_4_0, 1_4_0, 1_6_9_5, 6_9, 6_0_7_8, 1_5_8_8, 2]]) __lowerCamelCase : List[Any] = np.array([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]) __lowerCamelCase : Union[str, Any] = model(SCREAMING_SNAKE_CASE__ ,attention_mask=SCREAMING_SNAKE_CASE__)[0] __lowerCamelCase : Optional[int] = (1, 1_1, 7_6_8) self.assertEqual(output.shape ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Union[str, Any] = np.array([[[-0.1639, 0.3299, 0.1648], [-0.1746, 0.3289, 0.1710], [-0.1884, 0.3357, 0.1810]]]) self.assertTrue(jnp.allclose(output[:, 1:4, 1:4] ,SCREAMING_SNAKE_CASE__ ,atol=1E-4))
73
0
import argparse import os import re snake_case_ : Optional[int] = "src/transformers" # Pattern that looks at the indentation in a line. snake_case_ : Tuple = re.compile(r"^(\s*)\S") # Pattern that matches `"key":" and puts `key` in group 0. snake_case_ : Union[str, Any] = re.compile(r"^\s*\"([^\"]+)\":") # Pattern that matches `_import_structure["key"]` and puts `key` in group 0. snake_case_ : List[Any] = re.compile(r"^\s*_import_structure\[\"([^\"]+)\"\]") # Pattern that matches `"key",` and puts `key` in group 0. snake_case_ : Optional[Any] = re.compile(r"^\s*\"([^\"]+)\",\s*$") # Pattern that matches any `[stuff]` and puts `stuff` in group 0. snake_case_ : int = re.compile(r"\[([^\]]+)\]") def A (__A : Union[str, Any] ) -> Union[str, Any]: """simple docstring""" UpperCAmelCase_ = _re_indent.search(lowerCamelCase__ ) return "" if search is None else search.groups()[0] def A (__A : int , __A : str="" , __A : Optional[int]=None , __A : Union[str, Any]=None ) -> Any: """simple docstring""" UpperCAmelCase_ = 0 UpperCAmelCase_ = code.split('''\n''' ) if start_prompt is not None: while not lines[index].startswith(lowerCamelCase__ ): index += 1 UpperCAmelCase_ = ['\n'.join(lines[:index] )] else: UpperCAmelCase_ = [] # We split into blocks until we get to the `end_prompt` (or the end of the block). UpperCAmelCase_ = [lines[index]] index += 1 while index < len(lowerCamelCase__ ) and (end_prompt is None or not lines[index].startswith(lowerCamelCase__ )): if len(lines[index] ) > 0 and get_indent(lines[index] ) == indent_level: if len(lowerCamelCase__ ) > 0 and get_indent(current_block[-1] ).startswith(indent_level + ''' ''' ): current_block.append(lines[index] ) blocks.append('''\n'''.join(lowerCamelCase__ ) ) if index < len(lowerCamelCase__ ) - 1: UpperCAmelCase_ = [lines[index + 1]] index += 1 else: UpperCAmelCase_ = [] else: blocks.append('''\n'''.join(lowerCamelCase__ ) ) UpperCAmelCase_ = [lines[index]] else: current_block.append(lines[index] ) index += 1 # Adds current block if it's nonempty. if len(lowerCamelCase__ ) > 0: blocks.append('''\n'''.join(lowerCamelCase__ ) ) # Add final block after end_prompt if provided. if end_prompt is not None and index < len(lowerCamelCase__ ): blocks.append('''\n'''.join(lines[index:] ) ) return blocks def A (__A : Union[str, Any] ) -> Optional[int]: """simple docstring""" def _inner(__A : int ): return key(lowerCamelCase__ ).lower().replace('''_''' , '''''' ) return _inner def A (__A : Union[str, Any] , __A : int=None ) -> Union[str, Any]: """simple docstring""" def noop(__A : Optional[Any] ): return x if key is None: UpperCAmelCase_ = noop # Constants are all uppercase, they go first. UpperCAmelCase_ = [obj for obj in objects if key(lowerCamelCase__ ).isupper()] # Classes are not all uppercase but start with a capital, they go second. UpperCAmelCase_ = [obj for obj in objects if key(lowerCamelCase__ )[0].isupper() and not key(lowerCamelCase__ ).isupper()] # Functions begin with a lowercase, they go last. UpperCAmelCase_ = [obj for obj in objects if not key(lowerCamelCase__ )[0].isupper()] UpperCAmelCase_ = ignore_underscore(lowerCamelCase__ ) return sorted(lowerCamelCase__ , key=lowerCamelCase__ ) + sorted(lowerCamelCase__ , key=lowerCamelCase__ ) + sorted(lowerCamelCase__ , key=lowerCamelCase__ ) def A (__A : Optional[int] ) -> str: """simple docstring""" def _replace(__A : Tuple ): UpperCAmelCase_ = match.groups()[0] if "," not in imports: return F"""[{imports}]""" UpperCAmelCase_ = [part.strip().replace('''"''' , '''''' ) for part in imports.split(''',''' )] # We will have a final empty element if the line finished with a comma. if len(keys[-1] ) == 0: UpperCAmelCase_ = keys[:-1] return "[" + ", ".join([F"""\"{k}\"""" for k in sort_objects(lowerCamelCase__ )] ) + "]" UpperCAmelCase_ = import_statement.split('''\n''' ) if len(lowerCamelCase__ ) > 3: # Here we have to sort internal imports that are on several lines (one per name): # key: [ # "object1", # "object2", # ... # ] # We may have to ignore one or two lines on each side. UpperCAmelCase_ = 2 if lines[1].strip() == '[' else 1 UpperCAmelCase_ = [(i, _re_strip_line.search(lowerCamelCase__ ).groups()[0]) for i, line in enumerate(lines[idx:-idx] )] UpperCAmelCase_ = sort_objects(lowerCamelCase__ , key=lambda __A : x[1] ) UpperCAmelCase_ = [lines[x[0] + idx] for x in sorted_indices] return "\n".join(lines[:idx] + sorted_lines + lines[-idx:] ) elif len(lowerCamelCase__ ) == 3: # Here we have to sort internal imports that are on one separate line: # key: [ # "object1", "object2", ... # ] if _re_bracket_content.search(lines[1] ) is not None: UpperCAmelCase_ = _re_bracket_content.sub(_replace , lines[1] ) else: UpperCAmelCase_ = [part.strip().replace('''"''' , '''''' ) for part in lines[1].split(''',''' )] # We will have a final empty element if the line finished with a comma. if len(keys[-1] ) == 0: UpperCAmelCase_ = keys[:-1] UpperCAmelCase_ = get_indent(lines[1] ) + ', '.join([F"""\"{k}\"""" for k in sort_objects(lowerCamelCase__ )] ) return "\n".join(lowerCamelCase__ ) else: # Finally we have to deal with imports fitting on one line UpperCAmelCase_ = _re_bracket_content.sub(_replace , lowerCamelCase__ ) return import_statement def A (__A : str , __A : Union[str, Any]=True ) -> Dict: """simple docstring""" with open(lowerCamelCase__ , encoding='''utf-8''' ) as f: UpperCAmelCase_ = f.read() if "_import_structure" not in code: return # Blocks of indent level 0 UpperCAmelCase_ = split_code_in_indented_blocks( lowerCamelCase__ , start_prompt='''_import_structure = {''' , end_prompt='''if TYPE_CHECKING:''' ) # We ignore block 0 (everything untils start_prompt) and the last block (everything after end_prompt). for block_idx in range(1 , len(lowerCamelCase__ ) - 1 ): # Check if the block contains some `_import_structure`s thingy to sort. UpperCAmelCase_ = main_blocks[block_idx] UpperCAmelCase_ = block.split('''\n''' ) # Get to the start of the imports. UpperCAmelCase_ = 0 while line_idx < len(lowerCamelCase__ ) and "_import_structure" not in block_lines[line_idx]: # Skip dummy import blocks if "import dummy" in block_lines[line_idx]: UpperCAmelCase_ = len(lowerCamelCase__ ) else: line_idx += 1 if line_idx >= len(lowerCamelCase__ ): continue # Ignore beginning and last line: they don't contain anything. UpperCAmelCase_ = '\n'.join(block_lines[line_idx:-1] ) UpperCAmelCase_ = get_indent(block_lines[1] ) # Slit the internal block into blocks of indent level 1. UpperCAmelCase_ = split_code_in_indented_blocks(lowerCamelCase__ , indent_level=lowerCamelCase__ ) # We have two categories of import key: list or _import_structure[key].append/extend UpperCAmelCase_ = _re_direct_key if '_import_structure = {' in block_lines[0] else _re_indirect_key # Grab the keys, but there is a trap: some lines are empty or just comments. UpperCAmelCase_ = [(pattern.search(lowerCamelCase__ ).groups()[0] if pattern.search(lowerCamelCase__ ) is not None else None) for b in internal_blocks] # We only sort the lines with a key. UpperCAmelCase_ = [(i, key) for i, key in enumerate(lowerCamelCase__ ) if key is not None] UpperCAmelCase_ = [x[0] for x in sorted(lowerCamelCase__ , key=lambda __A : x[1] )] # We reorder the blocks by leaving empty lines/comments as they were and reorder the rest. UpperCAmelCase_ = 0 UpperCAmelCase_ = [] for i in range(len(lowerCamelCase__ ) ): if keys[i] is None: reorderded_blocks.append(internal_blocks[i] ) else: UpperCAmelCase_ = sort_objects_in_import(internal_blocks[sorted_indices[count]] ) reorderded_blocks.append(lowerCamelCase__ ) count += 1 # And we put our main block back together with its first and last line. UpperCAmelCase_ = '\n'.join(block_lines[:line_idx] + reorderded_blocks + [block_lines[-1]] ) if code != "\n".join(lowerCamelCase__ ): if check_only: return True else: print(F"""Overwriting {file}.""" ) with open(lowerCamelCase__ , '''w''' , encoding='''utf-8''' ) as f: f.write('''\n'''.join(lowerCamelCase__ ) ) def A (__A : Dict=True ) -> Optional[Any]: """simple docstring""" UpperCAmelCase_ = [] for root, _, files in os.walk(lowerCamelCase__ ): if "__init__.py" in files: UpperCAmelCase_ = sort_imports(os.path.join(lowerCamelCase__ , '''__init__.py''' ) , check_only=lowerCamelCase__ ) if result: UpperCAmelCase_ = [os.path.join(lowerCamelCase__ , '''__init__.py''' )] if len(lowerCamelCase__ ) > 0: raise ValueError(F"""Would overwrite {len(lowerCamelCase__ )} files, run `make style`.""" ) if __name__ == "__main__": snake_case_ : Optional[int] = argparse.ArgumentParser() parser.add_argument("--check_only", action="store_true", help="Whether to only check or fix style.") snake_case_ : Optional[Any] = parser.parse_args() sort_imports_in_all_inits(check_only=args.check_only)
51
import csv import tweepy # Twitter API credentials a ="""""" a ="""""" a ="""""" a ="""""" def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> None: # authorize twitter, initialize tweepy __lowerCamelCase : Tuple = tweepy.OAuthHandler(lowerCamelCase__ , lowerCamelCase__ ) auth.set_access_token(lowerCamelCase__ , lowerCamelCase__ ) __lowerCamelCase : Optional[int] = tweepy.API(lowerCamelCase__ ) # initialize a list to hold all the tweepy Tweets __lowerCamelCase : str = [] # make initial request for most recent tweets (200 is the maximum allowed count) __lowerCamelCase : Union[str, Any] = api.user_timeline(screen_name=lowerCamelCase__ , count=2_0_0 ) # save most recent tweets alltweets.extend(lowerCamelCase__ ) # save the id of the oldest tweet less one __lowerCamelCase : Any = alltweets[-1].id - 1 # keep grabbing tweets until there are no tweets left to grab while len(lowerCamelCase__ ) > 0: print(F"getting tweets before {oldest}" ) # all subsequent requests use the max_id param to prevent duplicates __lowerCamelCase : str = api.user_timeline( screen_name=lowerCamelCase__ , count=2_0_0 , max_id=lowerCamelCase__ ) # save most recent tweets alltweets.extend(lowerCamelCase__ ) # update the id of the oldest tweet less one __lowerCamelCase : Optional[int] = alltweets[-1].id - 1 print(F"...{len(lowerCamelCase__ )} tweets downloaded so far" ) # transform the tweepy tweets into a 2D array that will populate the csv __lowerCamelCase : str = [[tweet.id_str, tweet.created_at, tweet.text] for tweet in alltweets] # write the csv with open(F"new_{screen_name}_tweets.csv" , 'w' ) as f: __lowerCamelCase : Any = csv.writer(lowerCamelCase__ ) writer.writerow(['id', 'created_at', 'text'] ) writer.writerows(lowerCamelCase__ ) if __name__ == "__main__": # pass in the username of the account you want to download get_all_tweets("""FirePing32""")
73
0
from pathlib import Path from typing import List from transformers import is_torch_available, is_vision_available from transformers.testing_utils import get_tests_dir, is_tool_test from transformers.tools.agent_types import AGENT_TYPE_MAPPING, AgentAudio, AgentImage, AgentText if is_torch_available(): import torch if is_vision_available(): from PIL import Image __snake_case = ["""text""", """image""", """audio"""] def _lowercase ( UpperCamelCase_ ) -> List[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE__ = [] for input_type in input_types: if input_type == "text": inputs.append('Text input' ) elif input_type == "image": inputs.append( Image.open(Path(get_tests_dir('fixtures/tests_samples/COCO' ) ) / '000000039769.png' ).resize((512, 512) ) ) elif input_type == "audio": inputs.append(torch.ones(3000 ) ) elif isinstance(lowerCamelCase__ , lowerCamelCase__ ): inputs.append(create_inputs(lowerCamelCase__ ) ) else: raise ValueError(F'Invalid type requested: {input_type}' ) return inputs def _lowercase ( UpperCamelCase_ ) -> List[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE__ = [] for output in outputs: if isinstance(lowerCamelCase__ , (str, AgentText) ): output_types.append('text' ) elif isinstance(lowerCamelCase__ , (Image.Image, AgentImage) ): output_types.append('image' ) elif isinstance(lowerCamelCase__ , (torch.Tensor, AgentAudio) ): output_types.append('audio' ) else: raise ValueError(F'Invalid output: {output}' ) return output_types @is_tool_test class lowercase__ : def A_ ( self : Union[str, Any] ): self.assertTrue(hasattr(self.tool , 'inputs' ) ) self.assertTrue(hasattr(self.tool , 'outputs' ) ) SCREAMING_SNAKE_CASE__ = self.tool.inputs for _input in inputs: if isinstance(_input , SCREAMING_SNAKE_CASE__ ): for __input in _input: self.assertTrue(__input in authorized_types ) else: self.assertTrue(_input in authorized_types ) SCREAMING_SNAKE_CASE__ = self.tool.outputs for _output in outputs: self.assertTrue(_output in authorized_types ) def A_ ( self : List[str] ): SCREAMING_SNAKE_CASE__ = create_inputs(self.tool.inputs ) SCREAMING_SNAKE_CASE__ = self.tool(*SCREAMING_SNAKE_CASE__ ) # There is a single output if len(self.tool.outputs ) == 1: SCREAMING_SNAKE_CASE__ = [outputs] self.assertListEqual(output_types(SCREAMING_SNAKE_CASE__ ) , self.tool.outputs ) def A_ ( self : Union[str, Any] ): self.assertTrue(hasattr(self.tool , 'description' ) ) self.assertTrue(hasattr(self.tool , 'default_checkpoint' ) ) self.assertTrue(self.tool.description.startswith('This is a tool that' ) ) def A_ ( self : Dict ): SCREAMING_SNAKE_CASE__ = create_inputs(self.tool.inputs ) SCREAMING_SNAKE_CASE__ = self.tool(*SCREAMING_SNAKE_CASE__ ) if not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): SCREAMING_SNAKE_CASE__ = [outputs] self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , len(self.tool.outputs ) ) for output, output_type in zip(SCREAMING_SNAKE_CASE__ , self.tool.outputs ): SCREAMING_SNAKE_CASE__ = AGENT_TYPE_MAPPING[output_type] self.assertTrue(isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) def A_ ( self : Any ): SCREAMING_SNAKE_CASE__ = create_inputs(self.tool.inputs ) SCREAMING_SNAKE_CASE__ = [] for _input, input_type in zip(SCREAMING_SNAKE_CASE__ , self.tool.inputs ): if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): _inputs.append([AGENT_TYPE_MAPPING[_input_type](_input ) for _input_type in input_type] ) else: _inputs.append(AGENT_TYPE_MAPPING[input_type](_input ) ) # Should not raise an error SCREAMING_SNAKE_CASE__ = self.tool(*SCREAMING_SNAKE_CASE__ ) if not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): SCREAMING_SNAKE_CASE__ = [outputs] self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , len(self.tool.outputs ) )
176
import numpy as np from scipy.spatial.distance import cdist from sklearn.metrics import fa_score import datasets a ="""\ @inproceedings{kakwani2020indicnlpsuite, title={{IndicNLPSuite: Monolingual Corpora, Evaluation Benchmarks and Pre-trained Multilingual Language Models for Indian Languages}}, author={Divyanshu Kakwani and Anoop Kunchukuttan and Satish Golla and Gokul N.C. and Avik Bhattacharyya and Mitesh M. Khapra and Pratyush Kumar}, year={2020}, booktitle={Findings of EMNLP}, } """ a ="""\ IndicGLUE is a natural language understanding benchmark for Indian languages. It contains a wide variety of tasks and covers 11 major Indian languages - as, bn, gu, hi, kn, ml, mr, or, pa, ta, te. """ a =""" Compute IndicGLUE evaluation metric associated to each IndicGLUE dataset. Args: predictions: list of predictions to score (as int64), except for 'cvit-mkb-clsr' where each prediction is a vector (of float32). references: list of ground truth labels corresponding to the predictions (as int64), except for 'cvit-mkb-clsr' where each reference is a vector (of float32). Returns: depending on the IndicGLUE subset, one or several of: \"accuracy\": Accuracy \"f1\": F1 score \"precision\": Precision@10 Examples: >>> indic_glue_metric = datasets.load_metric('indic_glue', 'wnli') # 'wnli' or any of [\"copa\", \"sna\", \"csqa\", \"wstp\", \"inltkh\", \"bbca\", \"iitp-mr\", \"iitp-pr\", \"actsa-sc\", \"md\"] >>> references = [0, 1] >>> predictions = [0, 1] >>> results = indic_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {'accuracy': 1.0} >>> indic_glue_metric = datasets.load_metric('indic_glue', 'wiki-ner') >>> references = [0, 1] >>> predictions = [0, 1] >>> results = indic_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {'accuracy': 1.0, 'f1': 1.0} >>> indic_glue_metric = datasets.load_metric('indic_glue', 'cvit-mkb-clsr') >>> references = [[0.5, 0.5, 0.5], [0.1, 0.2, 0.3]] >>> predictions = [[0.5, 0.5, 0.5], [0.1, 0.2, 0.3]] >>> results = indic_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {'precision@10': 1.0} """ def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> List[str]: return float((preds == labels).mean() ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> List[str]: __lowerCamelCase : Optional[Any] = simple_accuracy(lowerCamelCase__ , lowerCamelCase__ ) __lowerCamelCase : Tuple = float(fa_score(y_true=lowerCamelCase__ , y_pred=lowerCamelCase__ ) ) return { "accuracy": acc, "f1": fa, } def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> Optional[Any]: __lowerCamelCase : Any = np.array(lowerCamelCase__ ) __lowerCamelCase : List[Any] = np.array(lowerCamelCase__ ) __lowerCamelCase : Any = en_sentvecs.shape[0] # mean centering __lowerCamelCase : Union[str, Any] = en_sentvecs - np.mean(lowerCamelCase__ , axis=0 ) __lowerCamelCase : Dict = in_sentvecs - np.mean(lowerCamelCase__ , axis=0 ) __lowerCamelCase : Optional[int] = cdist(lowerCamelCase__ , lowerCamelCase__ , 'cosine' ) __lowerCamelCase : Optional[Any] = np.array(range(lowerCamelCase__ ) ) __lowerCamelCase : Dict = sim.argsort(axis=1 )[:, :1_0] __lowerCamelCase : Optional[int] = np.any(preds == actual[:, None] , axis=1 ) return float(matches.mean() ) @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class A_ ( datasets.Metric ): def lowerCAmelCase ( self : Optional[Any]): if self.config_name not in [ "wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", "cvit-mkb-clsr", "iitp-mr", "iitp-pr", "actsa-sc", "md", "wiki-ner", ]: raise KeyError( 'You should supply a configuration name selected in ' '["wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", ' '"cvit-mkb-clsr", "iitp-mr", "iitp-pr", "actsa-sc", "md", ' '"wiki-ner"]') return datasets.MetricInfo( description=_DESCRIPTION ,citation=_CITATION ,inputs_description=_KWARGS_DESCRIPTION ,features=datasets.Features( { 'predictions': datasets.Value('int64') if self.config_name != 'cvit-mkb-clsr' else datasets.Sequence(datasets.Value('float32')), 'references': datasets.Value('int64') if self.config_name != 'cvit-mkb-clsr' else datasets.Sequence(datasets.Value('float32')), }) ,codebase_urls=[] ,reference_urls=[] ,format='numpy' if self.config_name != 'cvit-mkb-clsr' else None ,) def lowerCAmelCase ( self : Any ,SCREAMING_SNAKE_CASE__ : Tuple ,SCREAMING_SNAKE_CASE__ : Optional[Any]): if self.config_name == "cvit-mkb-clsr": return {"precision@10": precision_at_aa(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__)} elif self.config_name in ["wiki-ner"]: return acc_and_fa(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) elif self.config_name in [ "wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", "iitp-mr", "iitp-pr", "actsa-sc", "md", ]: return {"accuracy": simple_accuracy(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__)} else: raise KeyError( 'You should supply a configuration name selected in ' '["wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", ' '"cvit-mkb-clsr", "iitp-mr", "iitp-pr", "actsa-sc", "md", ' '"wiki-ner"]')
73
0
from transformers import HfArgumentParser, TensorFlowBenchmark, TensorFlowBenchmarkArguments def __magic_name__ ( ): '''simple docstring''' a = HfArgumentParser(lowerCamelCase__ ) a = parser.parse_args_into_dataclasses()[0] a = TensorFlowBenchmark(args=lowerCamelCase__ ) try: a = parser.parse_args_into_dataclasses()[0] except ValueError as e: a = 'Arg --no_{0} is no longer used, please use --no-{0} instead.' a = ' '.join(str(lowerCamelCase__ ).split(" " )[:-1] ) a = '' a = eval(str(lowerCamelCase__ ).split(" " )[-1] ) a = [] for arg in depreciated_args: # arg[2:] removes '--' if arg[2:] in TensorFlowBenchmark.deprecated_args: # arg[5:] removes '--no_' full_error_msg += arg_error_msg.format(arg[5:] ) else: wrong_args.append(lowerCamelCase__ ) if len(lowerCamelCase__ ) > 0: a = full_error_msg + begin_error_msg + str(lowerCamelCase__ ) raise ValueError(lowerCamelCase__ ) benchmark.run() if __name__ == "__main__": main()
107
from __future__ import annotations from scipy.special import comb # type: ignore class A_ : def __init__( self : List[str] ,SCREAMING_SNAKE_CASE__ : list[tuple[float, float]]): __lowerCamelCase : Union[str, Any] = list_of_points # Degree determines the flexibility of the curve. # Degree = 1 will produce a straight line. __lowerCamelCase : int = len(SCREAMING_SNAKE_CASE__) - 1 def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : float): assert 0 <= t <= 1, "Time t must be between 0 and 1." __lowerCamelCase : list[float] = [] for i in range(len(self.list_of_points)): # basis function for each i output_values.append( comb(self.degree ,SCREAMING_SNAKE_CASE__) * ((1 - t) ** (self.degree - i)) * (t**i)) # the basis must sum up to 1 for it to produce a valid Bezier curve. assert round(sum(SCREAMING_SNAKE_CASE__) ,5) == 1 return output_values def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : float): assert 0 <= t <= 1, "Time t must be between 0 and 1." __lowerCamelCase : Tuple = self.basis_function(SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = 0.0 __lowerCamelCase : Optional[Any] = 0.0 for i in range(len(self.list_of_points)): # For all points, sum up the product of i-th basis function and i-th point. x += basis_function[i] * self.list_of_points[i][0] y += basis_function[i] * self.list_of_points[i][1] return (x, y) def lowerCAmelCase ( self : int ,SCREAMING_SNAKE_CASE__ : float = 0.01): from matplotlib import pyplot as plt # type: ignore __lowerCamelCase : list[float] = [] # x coordinates of points to plot __lowerCamelCase : list[float] = [] # y coordinates of points to plot __lowerCamelCase : Any = 0.0 while t <= 1: __lowerCamelCase : List[Any] = self.bezier_curve_function(SCREAMING_SNAKE_CASE__) to_plot_x.append(value[0]) to_plot_y.append(value[1]) t += step_size __lowerCamelCase : Optional[Any] = [i[0] for i in self.list_of_points] __lowerCamelCase : List[str] = [i[1] for i in self.list_of_points] plt.plot( SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,color='blue' ,label='Curve of Degree ' + str(self.degree) ,) plt.scatter(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,color='red' ,label='Control Points') plt.legend() plt.show() if __name__ == "__main__": import doctest doctest.testmod() BezierCurve([(1, 2), (3, 5)]).plot_curve() # degree 1 BezierCurve([(0, 0), (5, 5), (5, 0)]).plot_curve() # degree 2 BezierCurve([(0, 0), (5, 5), (5, 0), (2.5, -2.5)]).plot_curve() # degree 3
73
0
import os import pytest from datasets import ( get_dataset_config_info, get_dataset_config_names, get_dataset_infos, get_dataset_split_names, inspect_dataset, inspect_metric, ) UpperCamelCase = pytest.mark.integration @pytest.mark.parametrize("""path""" ,["""paws""", """csv"""] ) def __lowerCamelCase ( snake_case__ ,snake_case__ ) -> Union[str, Any]: """simple docstring""" inspect_dataset(lowerCamelCase__ ,lowerCamelCase__ ) _SCREAMING_SNAKE_CASE = path + '.py' assert script_name in os.listdir(lowerCamelCase__ ) assert "__pycache__" not in os.listdir(lowerCamelCase__ ) @pytest.mark.filterwarnings("""ignore:inspect_metric is deprecated:FutureWarning""" ) @pytest.mark.filterwarnings("""ignore:metric_module_factory is deprecated:FutureWarning""" ) @pytest.mark.parametrize("""path""" ,["""accuracy"""] ) def __lowerCamelCase ( snake_case__ ,snake_case__ ) -> int: """simple docstring""" inspect_metric(lowerCamelCase__ ,lowerCamelCase__ ) _SCREAMING_SNAKE_CASE = path + '.py' assert script_name in os.listdir(lowerCamelCase__ ) assert "__pycache__" not in os.listdir(lowerCamelCase__ ) @pytest.mark.parametrize( """path, config_name, expected_splits""" ,[ ("""squad""", """plain_text""", ["""train""", """validation"""]), ("""dalle-mini/wit""", """dalle-mini--wit""", ["""train"""]), ("""paws""", """labeled_final""", ["""train""", """test""", """validation"""]), ] ,) def __lowerCamelCase ( snake_case__ ,snake_case__ ,snake_case__ ) -> Tuple: """simple docstring""" _SCREAMING_SNAKE_CASE = get_dataset_config_info(lowerCamelCase__ ,config_name=lowerCamelCase__ ) assert info.config_name == config_name assert list(info.splits.keys() ) == expected_splits @pytest.mark.parametrize( """path, config_name, expected_exception""" ,[ ("""paws""", None, ValueError), ] ,) def __lowerCamelCase ( snake_case__ ,snake_case__ ,snake_case__ ) -> Union[str, Any]: """simple docstring""" with pytest.raises(lowerCamelCase__ ): get_dataset_config_info(lowerCamelCase__ ,config_name=lowerCamelCase__ ) @pytest.mark.parametrize( """path, expected""" ,[ ("""squad""", """plain_text"""), ("""acronym_identification""", """default"""), ("""lhoestq/squad""", """plain_text"""), ("""lhoestq/test""", """default"""), ("""lhoestq/demo1""", """lhoestq--demo1"""), ("""dalle-mini/wit""", """dalle-mini--wit"""), ] ,) def __lowerCamelCase ( snake_case__ ,snake_case__ ) -> Dict: """simple docstring""" _SCREAMING_SNAKE_CASE = get_dataset_config_names(lowerCamelCase__ ) assert expected in config_names @pytest.mark.parametrize( """path, expected_configs, expected_splits_in_first_config""" ,[ ("""squad""", ["""plain_text"""], ["""train""", """validation"""]), ("""dalle-mini/wit""", ["""dalle-mini--wit"""], ["""train"""]), ("""paws""", ["""labeled_final""", """labeled_swap""", """unlabeled_final"""], ["""train""", """test""", """validation"""]), ] ,) def __lowerCamelCase ( snake_case__ ,snake_case__ ,snake_case__ ) -> List[Any]: """simple docstring""" _SCREAMING_SNAKE_CASE = get_dataset_infos(lowerCamelCase__ ) assert list(infos.keys() ) == expected_configs _SCREAMING_SNAKE_CASE = expected_configs[0] assert expected_config in infos _SCREAMING_SNAKE_CASE = infos[expected_config] assert info.config_name == expected_config assert list(info.splits.keys() ) == expected_splits_in_first_config @pytest.mark.parametrize( """path, expected_config, expected_splits""" ,[ ("""squad""", """plain_text""", ["""train""", """validation"""]), ("""dalle-mini/wit""", """dalle-mini--wit""", ["""train"""]), ("""paws""", """labeled_final""", ["""train""", """test""", """validation"""]), ] ,) def __lowerCamelCase ( snake_case__ ,snake_case__ ,snake_case__ ) -> List[Any]: """simple docstring""" _SCREAMING_SNAKE_CASE = get_dataset_infos(lowerCamelCase__ ) assert expected_config in infos _SCREAMING_SNAKE_CASE = infos[expected_config] assert info.config_name == expected_config assert list(info.splits.keys() ) == expected_splits @pytest.mark.parametrize( """path, config_name, expected_exception""" ,[ ("""paws""", None, ValueError), ] ,) def __lowerCamelCase ( snake_case__ ,snake_case__ ,snake_case__ ) -> Optional[Any]: """simple docstring""" with pytest.raises(lowerCamelCase__ ): get_dataset_split_names(lowerCamelCase__ ,config_name=lowerCamelCase__ )
306
from __future__ import annotations import time a =list[tuple[int, int]] a =[ [0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles [0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0], [1, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0], ] a =[[-1, 0], [0, -1], [1, 0], [0, 1]] # up, left, down, right class A_ : def __init__( self : List[str] ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : Node | None): __lowerCamelCase : Tuple = pos_x __lowerCamelCase : List[str] = pos_y __lowerCamelCase : str = (pos_y, pos_x) __lowerCamelCase : str = goal_x __lowerCamelCase : int = goal_y __lowerCamelCase : List[Any] = parent class A_ : def __init__( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : tuple[int, int] ,SCREAMING_SNAKE_CASE__ : tuple[int, int]): __lowerCamelCase : Any = Node(start[1] ,start[0] ,goal[1] ,goal[0] ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = Node(goal[1] ,goal[0] ,goal[1] ,goal[0] ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Union[str, Any] = [self.start] __lowerCamelCase : List[str] = False def lowerCAmelCase ( self : List[Any]): while self.node_queue: __lowerCamelCase : Any = self.node_queue.pop(0) if current_node.pos == self.target.pos: __lowerCamelCase : Dict = True return self.retrace_path(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Tuple = self.get_successors(SCREAMING_SNAKE_CASE__) for node in successors: self.node_queue.append(SCREAMING_SNAKE_CASE__) if not self.reached: return [self.start.pos] return None def lowerCAmelCase ( self : str ,SCREAMING_SNAKE_CASE__ : Node): __lowerCamelCase : Union[str, Any] = [] for action in delta: __lowerCamelCase : Optional[Any] = parent.pos_x + action[1] __lowerCamelCase : Optional[int] = parent.pos_y + action[0] if not (0 <= pos_x <= len(grid[0]) - 1 and 0 <= pos_y <= len(SCREAMING_SNAKE_CASE__) - 1): continue if grid[pos_y][pos_x] != 0: continue successors.append( Node(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,self.target.pos_y ,self.target.pos_x ,SCREAMING_SNAKE_CASE__)) return successors def lowerCAmelCase ( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : Node | None): __lowerCamelCase : List[Any] = node __lowerCamelCase : int = [] while current_node is not None: path.append((current_node.pos_y, current_node.pos_x)) __lowerCamelCase : int = current_node.parent path.reverse() return path class A_ : def __init__( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : int): __lowerCamelCase : int = BreadthFirstSearch(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = BreadthFirstSearch(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = False def lowerCAmelCase ( self : str): while self.fwd_bfs.node_queue or self.bwd_bfs.node_queue: __lowerCamelCase : Any = self.fwd_bfs.node_queue.pop(0) __lowerCamelCase : Any = self.bwd_bfs.node_queue.pop(0) if current_bwd_node.pos == current_fwd_node.pos: __lowerCamelCase : List[str] = True return self.retrace_bidirectional_path( SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = current_bwd_node __lowerCamelCase : int = current_fwd_node __lowerCamelCase : str = { self.fwd_bfs: self.fwd_bfs.get_successors(SCREAMING_SNAKE_CASE__), self.bwd_bfs: self.bwd_bfs.get_successors(SCREAMING_SNAKE_CASE__), } for bfs in [self.fwd_bfs, self.bwd_bfs]: for node in successors[bfs]: bfs.node_queue.append(SCREAMING_SNAKE_CASE__) if not self.reached: return [self.fwd_bfs.start.pos] return None def lowerCAmelCase ( self : Dict ,SCREAMING_SNAKE_CASE__ : Node ,SCREAMING_SNAKE_CASE__ : Node): __lowerCamelCase : List[Any] = self.fwd_bfs.retrace_path(SCREAMING_SNAKE_CASE__) __lowerCamelCase : str = self.bwd_bfs.retrace_path(SCREAMING_SNAKE_CASE__) bwd_path.pop() bwd_path.reverse() __lowerCamelCase : List[Any] = fwd_path + bwd_path return path if __name__ == "__main__": # all coordinates are given in format [y,x] import doctest doctest.testmod() a =(0, 0) a =(len(grid) - 1, len(grid[0]) - 1) for elem in grid: print(elem) a =time.time() a =BreadthFirstSearch(init, goal) a =bfs.search() a =time.time() - start_bfs_time print("""Unidirectional BFS computation time : """, bfs_time) a =time.time() a =BidirectionalBreadthFirstSearch(init, goal) a =bd_bfs.search() a =time.time() - start_bd_bfs_time print("""Bidirectional BFS computation time : """, bd_bfs_time)
73
0
from functools import lru_cache def lowercase ( SCREAMING_SNAKE_CASE__ : Tuple ) -> set: _snake_case : Optional[int] = 2 _snake_case : Union[str, Any] = set() while i * i <= n: if n % i: i += 1 else: n //= i factors.add(lowerCamelCase__ ) if n > 1: factors.add(lowerCamelCase__ ) return factors @lru_cache def lowercase ( SCREAMING_SNAKE_CASE__ : str ) -> int: return len(unique_prime_factors(lowerCamelCase__ ) ) def lowercase ( SCREAMING_SNAKE_CASE__ : List[str] ) -> bool: return len(set(lowerCamelCase__ ) ) in (0, 1) def lowercase ( SCREAMING_SNAKE_CASE__ : Dict ) -> list: _snake_case : Tuple = 2 while True: # Increment each value of a generated range _snake_case : int = [base + i for i in range(lowerCamelCase__ )] # Run elements through out unique_prime_factors function # Append our target number to the end. _snake_case : int = [upf_len(lowerCamelCase__ ) for x in group] checker.append(lowerCamelCase__ ) # If all numbers in the list are equal, return the group variable. if equality(lowerCamelCase__ ): return group # Increment our base variable by 1 base += 1 def lowercase ( SCREAMING_SNAKE_CASE__ : List[str] = 4 ) -> int: _snake_case : int = run(lowerCamelCase__ ) return results[0] if len(lowerCamelCase__ ) else None if __name__ == "__main__": print(solution())
317
import qiskit def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> qiskit.result.counts.Counts: __lowerCamelCase : Optional[int] = qiskit.Aer.get_backend('aer_simulator' ) # Create a Quantum Circuit acting on the q register __lowerCamelCase : List[str] = qiskit.QuantumCircuit(lowerCamelCase__ , lowerCamelCase__ ) # Map the quantum measurement to the classical bits circuit.measure([0] , [0] ) # Execute the circuit on the simulator __lowerCamelCase : List[Any] = qiskit.execute(lowerCamelCase__ , lowerCamelCase__ , shots=1_0_0_0 ) # Return the histogram data of the results of the experiment. return job.result().get_counts(lowerCamelCase__ ) if __name__ == "__main__": print(F"""Total count for various states are: {single_qubit_measure(1, 1)}""")
73
0
'''simple docstring''' def __lowercase ( __lowercase = 10**9 ) -> int: '''simple docstring''' _A = 1 _A = 2 _A = 0 _A = 0 _A = 0 while perimeter <= max_perimeter: perimeters_sum += perimeter prev_value += 2 * value value += prev_value _A = 2 * value + 2 if i % 2 == 0 else 2 * value - 2 i += 1 return perimeters_sum if __name__ == "__main__": print(F"""{solution() = }""")
79
import os import sys a =os.path.join(os.path.dirname(__file__), """src""") sys.path.append(SRC_DIR) from transformers import ( AutoConfig, AutoModel, AutoModelForCausalLM, AutoModelForMaskedLM, AutoModelForQuestionAnswering, AutoModelForSequenceClassification, AutoTokenizer, add_start_docstrings, ) a =[ """torch""", """numpy""", """tokenizers""", """filelock""", """requests""", """tqdm""", """regex""", """sentencepiece""", """sacremoses""", """importlib_metadata""", """huggingface_hub""", ] @add_start_docstrings(AutoConfig.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> int: return AutoConfig.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ ) @add_start_docstrings(AutoTokenizer.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> Optional[Any]: return AutoTokenizer.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ ) @add_start_docstrings(AutoModel.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> List[str]: return AutoModel.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ ) @add_start_docstrings(AutoModelForCausalLM.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> Any: return AutoModelForCausalLM.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ ) @add_start_docstrings(AutoModelForMaskedLM.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> List[str]: return AutoModelForMaskedLM.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ ) @add_start_docstrings(AutoModelForSequenceClassification.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> List[str]: return AutoModelForSequenceClassification.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ ) @add_start_docstrings(AutoModelForQuestionAnswering.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> Tuple: return AutoModelForQuestionAnswering.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ )
73
0
from ...configuration_utils import PretrainedConfig from ...utils import logging __A : List[str] = logging.get_logger(__name__) __A : Union[str, Any] = { 'abeja/gpt-neox-japanese-2.7b': 'https://huggingface.co/abeja/gpt-neox-japanese-2.7b/resolve/main/config.json', } class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__): _UpperCamelCase:Dict = '''gpt_neox_japanese''' def __init__( self , _SCREAMING_SNAKE_CASE=3_2000 , _SCREAMING_SNAKE_CASE=2560 , _SCREAMING_SNAKE_CASE=32 , _SCREAMING_SNAKE_CASE=32 , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE="gelu" , _SCREAMING_SNAKE_CASE=1.0_0 , _SCREAMING_SNAKE_CASE=1_0000 , _SCREAMING_SNAKE_CASE=2048 , _SCREAMING_SNAKE_CASE=0.0_2 , _SCREAMING_SNAKE_CASE=1E-5 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=3_1996 , _SCREAMING_SNAKE_CASE=3_1999 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.0 , **_SCREAMING_SNAKE_CASE , )-> List[str]: super().__init__(bos_token_id=SCREAMING_SNAKE_CASE__ , eos_token_id=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) lowerCamelCase_ =vocab_size lowerCamelCase_ =max_position_embeddings lowerCamelCase_ =hidden_size lowerCamelCase_ =num_hidden_layers lowerCamelCase_ =num_attention_heads lowerCamelCase_ =intermediate_multiple_size lowerCamelCase_ =hidden_act lowerCamelCase_ =rotary_pct lowerCamelCase_ =rotary_emb_base lowerCamelCase_ =initializer_range lowerCamelCase_ =layer_norm_eps lowerCamelCase_ =use_cache lowerCamelCase_ =attention_dropout lowerCamelCase_ =hidden_dropout
154
from typing import Optional from urllib.parse import quote import huggingface_hub as hfh from packaging import version def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ = None ) -> str: if version.parse(hfh.__version__ ).release < version.parse('0.11.0' ).release: # old versions of hfh don't url-encode the file path __lowerCamelCase : int = quote(lowerCamelCase__ ) return hfh.hf_hub_url(lowerCamelCase__ , lowerCamelCase__ , repo_type='dataset' , revision=lowerCamelCase__ )
73
0
"""simple docstring""" from typing import Dict, List, Optional from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging lowerCAmelCase__ = logging.get_logger(__name__) lowerCAmelCase__ = { '''nielsr/canine-s''': 2048, } # Unicode defines 1,114,112 total “codepoints” lowerCAmelCase__ = 1114112 # Below: Constants defining canonical codepoints for special, pseudo-characters. # Copied from https://github.com/google-research/language/blob/master/language/canine/special_codepoints.py lowerCAmelCase__ = 0 lowerCAmelCase__ = 0xE000 lowerCAmelCase__ = 0xE001 lowerCAmelCase__ = 0xE002 lowerCAmelCase__ = 0xE003 lowerCAmelCase__ = 0xE004 # Maps special codepoints to human-readable names. lowerCAmelCase__ = { # Special symbols are represented using codepoints values that are valid, # but designated as "Private Use", meaning that they will never be assigned # characters by the Unicode Consortium, and are thus safe for use here. # # NOTE: Do *NOT* add any sort of [UNK_CHAR] here. They are explicitly # excluded and should fail with a hard error. CLS: '''[CLS]''', SEP: '''[SEP]''', BOS: '''[BOS]''', MASK: '''[MASK]''', PAD: '''[PAD]''', RESERVED: '''[RESERVED]''', } # Maps special codepoint human-readable names to their codepoint values. lowerCAmelCase__ = {name: codepoint for codepoint, name in SPECIAL_CODEPOINTS.items()} class __snake_case ( _lowercase): snake_case__ : int = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self : Union[str, Any] , __lowerCAmelCase : int=chr(SCREAMING_SNAKE_CASE__ ) , __lowerCAmelCase : Tuple=chr(SCREAMING_SNAKE_CASE__ ) , __lowerCAmelCase : str=chr(SCREAMING_SNAKE_CASE__ ) , __lowerCAmelCase : Union[str, Any]=chr(SCREAMING_SNAKE_CASE__ ) , __lowerCAmelCase : Any=chr(SCREAMING_SNAKE_CASE__ ) , __lowerCAmelCase : List[Any]=chr(SCREAMING_SNAKE_CASE__ ) , __lowerCAmelCase : Optional[int]=False , __lowerCAmelCase : Optional[int]=2_0_4_8 , **__lowerCAmelCase : int , ): """simple docstring""" _lowerCamelCase : List[Any] = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else bos_token _lowerCamelCase : int = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else eos_token _lowerCamelCase : List[str] = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else sep_token _lowerCamelCase : Optional[Any] = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else cls_token _lowerCamelCase : Tuple = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else pad_token # Mask token behave like a normal word, i.e. include the space before it _lowerCamelCase : List[Any] = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else mask_token super().__init__( bos_token=SCREAMING_SNAKE_CASE__ , eos_token=SCREAMING_SNAKE_CASE__ , sep_token=SCREAMING_SNAKE_CASE__ , cls_token=SCREAMING_SNAKE_CASE__ , pad_token=SCREAMING_SNAKE_CASE__ , mask_token=SCREAMING_SNAKE_CASE__ , add_prefix_space=SCREAMING_SNAKE_CASE__ , model_max_length=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) # Creates a mapping for looking up the IDs of special symbols. _lowerCamelCase : Dict[str, int] = {} for codepoint, name in SPECIAL_CODEPOINTS.items(): _lowerCamelCase : Union[str, Any] = codepoint # Creates a mapping for looking up the string forms of special symbol IDs. _lowerCamelCase : Dict[int, str] = { codepoint: name for name, codepoint in self._special_codepoints.items() } _lowerCamelCase : Any = UNICODE_VOCAB_SIZE _lowerCamelCase : Dict = len(self._special_codepoints ) @property def SCREAMING_SNAKE_CASE ( self : Any ): """simple docstring""" return self._unicode_vocab_size def SCREAMING_SNAKE_CASE ( self : List[Any] , __lowerCAmelCase : str ): """simple docstring""" return list(SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : Dict , __lowerCAmelCase : str ): """simple docstring""" try: return ord(SCREAMING_SNAKE_CASE__ ) except TypeError: raise ValueError(f'''invalid token: \'{token}\'''' ) def SCREAMING_SNAKE_CASE ( self : Dict , __lowerCAmelCase : int ): """simple docstring""" try: if index in SPECIAL_CODEPOINTS: return SPECIAL_CODEPOINTS[index] return chr(SCREAMING_SNAKE_CASE__ ) except TypeError: raise ValueError(f'''invalid id: {index}''' ) def SCREAMING_SNAKE_CASE ( self : Optional[int] , __lowerCAmelCase : Optional[int] ): """simple docstring""" return "".join(SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : List[Any] , __lowerCAmelCase : List[int] , __lowerCAmelCase : Optional[List[int]] = None ): """simple docstring""" _lowerCamelCase : Tuple = [self.sep_token_id] _lowerCamelCase : Optional[Any] = [self.cls_token_id] _lowerCamelCase : str = cls + token_ids_a + sep if token_ids_a is not None: result += token_ids_a + sep return result def SCREAMING_SNAKE_CASE ( self : List[str] , __lowerCAmelCase : List[int] , __lowerCAmelCase : Optional[List[int]] = None , __lowerCAmelCase : bool = False ): """simple docstring""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=SCREAMING_SNAKE_CASE__ , token_ids_a=SCREAMING_SNAKE_CASE__ , already_has_special_tokens=SCREAMING_SNAKE_CASE__ ) _lowerCamelCase : Any = [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1] if token_ids_a is not None: result += ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1] return result def SCREAMING_SNAKE_CASE ( self : Tuple , __lowerCAmelCase : List[int] , __lowerCAmelCase : Optional[List[int]] = None ): """simple docstring""" _lowerCamelCase : Tuple = [self.sep_token_id] _lowerCamelCase : Dict = [self.cls_token_id] _lowerCamelCase : Dict = len(cls + token_ids_a + sep ) * [0] if token_ids_a is not None: result += len(token_ids_a + sep ) * [1] return result def SCREAMING_SNAKE_CASE ( self : List[Any] , __lowerCAmelCase : str , __lowerCAmelCase : Optional[str] = None ): """simple docstring""" return ()
72
def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , ) -> float: __lowerCamelCase : Dict = [redshift, radiation_density, matter_density, dark_energy] if any(p < 0 for p in parameters ): raise ValueError('All input parameters must be positive' ) if any(p > 1 for p in parameters[1:4] ): raise ValueError('Relative densities cannot be greater than one' ) else: __lowerCamelCase : Dict = 1 - (matter_density + radiation_density + dark_energy) __lowerCamelCase : Union[str, Any] = ( radiation_density * (redshift + 1) ** 4 + matter_density * (redshift + 1) ** 3 + curvature * (redshift + 1) ** 2 + dark_energy ) __lowerCamelCase : List[Any] = hubble_constant * e_a ** (1 / 2) return hubble if __name__ == "__main__": import doctest # run doctest doctest.testmod() # demo LCDM approximation a =0.3 print( hubble_parameter( hubble_constant=68.3, radiation_density=1E-4, matter_density=matter_density, dark_energy=1 - matter_density, redshift=0, ) )
73
0
'''simple docstring''' import argparse import os from io import BytesIO from pathlib import Path import requests from clip_retrieval.clip_client import ClipClient from PIL import Image from tqdm import tqdm def a ( __a , __a , __a ) -> Tuple: '''simple docstring''' UpperCamelCase__ :Tuple = 1.5 UpperCamelCase__ :List[Any] = int(factor * num_class_images ) UpperCamelCase__ :Optional[int] = ClipClient( url='''https://knn.laion.ai/knn-service''' , indice_name='''laion_400m''' , num_images=lowerCamelCase__ , aesthetic_weight=0.1 ) os.makedirs(f'''{class_data_dir}/images''' , exist_ok=lowerCamelCase__ ) if len(list(Path(f'''{class_data_dir}/images''' ).iterdir() ) ) >= num_class_images: return while True: UpperCamelCase__ :Optional[Any] = client.query(text=lowerCamelCase__ ) if len(lowerCamelCase__ ) >= factor * num_class_images or num_images > 1e4: break else: UpperCamelCase__ :str = int(factor * num_images ) UpperCamelCase__ :Tuple = ClipClient( url='''https://knn.laion.ai/knn-service''' , indice_name='''laion_400m''' , num_images=lowerCamelCase__ , aesthetic_weight=0.1 , ) UpperCamelCase__ :Optional[int] = 0 UpperCamelCase__ :Tuple = 0 UpperCamelCase__ :Any = tqdm(desc='''downloading real regularization images''' , total=lowerCamelCase__ ) with open(f'''{class_data_dir}/caption.txt''' , '''w''' ) as fa, open(f'''{class_data_dir}/urls.txt''' , '''w''' ) as fa, open( f'''{class_data_dir}/images.txt''' , '''w''' ) as fa: while total < num_class_images: UpperCamelCase__ :List[Any] = class_images[count] count += 1 try: UpperCamelCase__ :Optional[Any] = requests.get(images['''url'''] ) if img.status_code == 200: UpperCamelCase__ :Dict = Image.open(BytesIO(img.content ) ) with open(f'''{class_data_dir}/images/{total}.jpg''' , '''wb''' ) as f: f.write(img.content ) fa.write(images['''caption'''] + '''\n''' ) fa.write(images['''url'''] + '''\n''' ) fa.write(f'''{class_data_dir}/images/{total}.jpg''' + '''\n''' ) total += 1 pbar.update(1 ) else: continue except Exception: continue return def a ( ) -> Optional[int]: '''simple docstring''' UpperCamelCase__ :Optional[int] = argparse.ArgumentParser('''''' , add_help=lowerCamelCase__ ) parser.add_argument('''--class_prompt''' , help='''text prompt to retrieve images''' , required=lowerCamelCase__ , type=lowerCamelCase__ ) parser.add_argument('''--class_data_dir''' , help='''path to save images''' , required=lowerCamelCase__ , type=lowerCamelCase__ ) parser.add_argument('''--num_class_images''' , help='''number of images to download''' , default=200 , type=lowerCamelCase__ ) return parser.parse_args() if __name__ == "__main__": __snake_case = parse_args() retrieve(args.class_prompt, args.class_data_dir, args.num_class_images)
97
from typing import List, Optional, Union from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : Optional[Any] = ['''image_processor''', '''tokenizer'''] _UpperCAmelCase : Union[str, Any] = '''Pix2StructImageProcessor''' _UpperCAmelCase : Any = ('''T5Tokenizer''', '''T5TokenizerFast''') def __init__( self : List[str] ,SCREAMING_SNAKE_CASE__ : str ,SCREAMING_SNAKE_CASE__ : int): __lowerCamelCase : List[Any] = False super().__init__(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) def __call__( self : str ,SCREAMING_SNAKE_CASE__ : Any=None ,SCREAMING_SNAKE_CASE__ : Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None ,SCREAMING_SNAKE_CASE__ : bool = True ,SCREAMING_SNAKE_CASE__ : Union[bool, str, PaddingStrategy] = False ,SCREAMING_SNAKE_CASE__ : Union[bool, str, TruncationStrategy] = None ,SCREAMING_SNAKE_CASE__ : Optional[int] = None ,SCREAMING_SNAKE_CASE__ : Optional[int] = 2_0_4_8 ,SCREAMING_SNAKE_CASE__ : int = 0 ,SCREAMING_SNAKE_CASE__ : Optional[int] = None ,SCREAMING_SNAKE_CASE__ : Optional[bool] = None ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = True ,SCREAMING_SNAKE_CASE__ : Optional[Union[str, TensorType]] = None ,**SCREAMING_SNAKE_CASE__ : Dict ,): if images is None and text is None: raise ValueError('You have to specify either images or text.') # Get only text if images is None and not self.image_processor.is_vqa: __lowerCamelCase : Tuple = self.tokenizer __lowerCamelCase : Dict = self.tokenizer( text=SCREAMING_SNAKE_CASE__ ,add_special_tokens=SCREAMING_SNAKE_CASE__ ,padding=SCREAMING_SNAKE_CASE__ ,truncation=SCREAMING_SNAKE_CASE__ ,max_length=SCREAMING_SNAKE_CASE__ ,stride=SCREAMING_SNAKE_CASE__ ,pad_to_multiple_of=SCREAMING_SNAKE_CASE__ ,return_attention_mask=SCREAMING_SNAKE_CASE__ ,return_overflowing_tokens=SCREAMING_SNAKE_CASE__ ,return_special_tokens_mask=SCREAMING_SNAKE_CASE__ ,return_offsets_mapping=SCREAMING_SNAKE_CASE__ ,return_token_type_ids=SCREAMING_SNAKE_CASE__ ,return_length=SCREAMING_SNAKE_CASE__ ,verbose=SCREAMING_SNAKE_CASE__ ,return_tensors=SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__ ,) return text_encoding if not self.image_processor.is_vqa: # add pixel_values __lowerCamelCase : List[Any] = self.image_processor( SCREAMING_SNAKE_CASE__ ,return_tensors=SCREAMING_SNAKE_CASE__ ,max_patches=SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) else: # add pixel_values and bbox __lowerCamelCase : List[Any] = self.image_processor( SCREAMING_SNAKE_CASE__ ,return_tensors=SCREAMING_SNAKE_CASE__ ,max_patches=SCREAMING_SNAKE_CASE__ ,header_text=SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) if text is not None and not self.image_processor.is_vqa: __lowerCamelCase : List[Any] = self.tokenizer( text=SCREAMING_SNAKE_CASE__ ,add_special_tokens=SCREAMING_SNAKE_CASE__ ,padding=SCREAMING_SNAKE_CASE__ ,truncation=SCREAMING_SNAKE_CASE__ ,max_length=SCREAMING_SNAKE_CASE__ ,stride=SCREAMING_SNAKE_CASE__ ,pad_to_multiple_of=SCREAMING_SNAKE_CASE__ ,return_attention_mask=SCREAMING_SNAKE_CASE__ ,return_overflowing_tokens=SCREAMING_SNAKE_CASE__ ,return_special_tokens_mask=SCREAMING_SNAKE_CASE__ ,return_offsets_mapping=SCREAMING_SNAKE_CASE__ ,return_token_type_ids=SCREAMING_SNAKE_CASE__ ,return_length=SCREAMING_SNAKE_CASE__ ,verbose=SCREAMING_SNAKE_CASE__ ,return_tensors=SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__ ,) if "attention_mask" in text_encoding: __lowerCamelCase : List[Any] = text_encoding.pop('attention_mask') if "input_ids" in text_encoding: __lowerCamelCase : Dict = text_encoding.pop('input_ids') else: __lowerCamelCase : Optional[int] = None if text_encoding is not None: encoding_image_processor.update(SCREAMING_SNAKE_CASE__) return encoding_image_processor def lowerCAmelCase ( self : Dict ,*SCREAMING_SNAKE_CASE__ : str ,**SCREAMING_SNAKE_CASE__ : int): return self.tokenizer.batch_decode(*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : List[str] ,*SCREAMING_SNAKE_CASE__ : int ,**SCREAMING_SNAKE_CASE__ : Dict): return self.tokenizer.decode(*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) @property def lowerCAmelCase ( self : int): __lowerCamelCase : Dict = self.tokenizer.model_input_names __lowerCamelCase : int = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
73
0
import os import textwrap import pyarrow as pa import pytest from datasets import ClassLabel, Features, Image from datasets.packaged_modules.csv.csv import Csv from ..utils import require_pil @pytest.fixture def lowerCamelCase_ ( _UpperCamelCase ) -> Optional[Any]: """simple docstring""" snake_case_ : Tuple = tmp_path / 'file.csv' snake_case_ : Optional[int] = textwrap.dedent( '''\\n header1,header2\n 1,2\n 10,20\n ''' ) with open(lowerCamelCase__ , '''w''' ) as f: f.write(lowerCamelCase__ ) return str(lowerCamelCase__ ) @pytest.fixture def lowerCamelCase_ ( _UpperCamelCase ) -> List[Any]: """simple docstring""" snake_case_ : List[Any] = tmp_path / 'malformed_file.csv' snake_case_ : Optional[int] = textwrap.dedent( '''\\n header1,header2\n 1,2\n 10,20,\n ''' ) with open(lowerCamelCase__ , '''w''' ) as f: f.write(lowerCamelCase__ ) return str(lowerCamelCase__ ) @pytest.fixture def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase ) -> Dict: """simple docstring""" snake_case_ : Tuple = tmp_path / 'csv_with_image.csv' snake_case_ : Union[str, Any] = textwrap.dedent( f'''\\n image\n {image_file}\n ''' ) with open(lowerCamelCase__ , '''w''' ) as f: f.write(lowerCamelCase__ ) return str(lowerCamelCase__ ) @pytest.fixture def lowerCamelCase_ ( _UpperCamelCase ) -> Optional[Any]: """simple docstring""" snake_case_ : Optional[int] = tmp_path / 'csv_with_label.csv' snake_case_ : Tuple = textwrap.dedent( '''\\n label\n good\n bad\n good\n ''' ) with open(lowerCamelCase__ , '''w''' ) as f: f.write(lowerCamelCase__ ) return str(lowerCamelCase__ ) @pytest.fixture def lowerCamelCase_ ( _UpperCamelCase ) -> List[str]: """simple docstring""" snake_case_ : Optional[int] = tmp_path / 'csv_with_int_list.csv' snake_case_ : Optional[Any] = textwrap.dedent( '''\\n int_list\n 1 2 3\n 4 5 6\n 7 8 9\n ''' ) with open(lowerCamelCase__ , '''w''' ) as f: f.write(lowerCamelCase__ ) return str(lowerCamelCase__ ) def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) -> str: """simple docstring""" snake_case_ : str = Csv() snake_case_ : Union[str, Any] = csv._generate_tables([[csv_file, malformed_csv_file]] ) with pytest.raises(lowerCamelCase__ , match='''Error tokenizing data''' ): for _ in generator: pass assert any( record.levelname == '''ERROR''' and '''Failed to read file''' in record.message and os.path.basename(lowerCamelCase__ ) in record.message for record in caplog.records ) @require_pil def lowerCamelCase_ ( _UpperCamelCase ) -> int: """simple docstring""" with open(lowerCamelCase__ , encoding='''utf-8''' ) as f: snake_case_ : List[Any] = f.read().splitlines()[1] snake_case_ : str = Csv(encoding='''utf-8''' , features=Features({'''image''': Image()} ) ) snake_case_ : int = csv._generate_tables([[csv_file_with_image]] ) snake_case_ : Optional[int] = pa.concat_tables([table for _, table in generator] ) assert pa_table.schema.field('''image''' ).type == Image()() snake_case_ : Union[str, Any] = pa_table.to_pydict()['image'] assert generated_content == [{"path": image_file, "bytes": None}] def lowerCamelCase_ ( _UpperCamelCase ) -> str: """simple docstring""" with open(lowerCamelCase__ , encoding='''utf-8''' ) as f: snake_case_ : Dict = f.read().splitlines()[1:] snake_case_ : Any = Csv(encoding='''utf-8''' , features=Features({'''label''': ClassLabel(names=['''good''', '''bad'''] )} ) ) snake_case_ : List[Any] = csv._generate_tables([[csv_file_with_label]] ) snake_case_ : Tuple = pa.concat_tables([table for _, table in generator] ) assert pa_table.schema.field('''label''' ).type == ClassLabel(names=['''good''', '''bad'''] )() snake_case_ : str = pa_table.to_pydict()['label'] assert generated_content == [ClassLabel(names=['''good''', '''bad'''] ).straint(lowerCamelCase__ ) for label in labels] def lowerCamelCase_ ( _UpperCamelCase ) -> Any: """simple docstring""" snake_case_ : Union[str, Any] = Csv(encoding='''utf-8''' , sep=''',''' , converters={'''int_list''': lambda _UpperCamelCase : [int(lowerCamelCase__ ) for i in x.split()]} ) snake_case_ : Dict = csv._generate_tables([[csv_file_with_int_list]] ) snake_case_ : Union[str, Any] = pa.concat_tables([table for _, table in generator] ) assert pa.types.is_list(pa_table.schema.field('''int_list''' ).type ) snake_case_ : List[str] = pa_table.to_pydict()['int_list'] assert generated_content == [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
279
from bisect import bisect from itertools import accumulate def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> Union[str, Any]: __lowerCamelCase : Optional[Any] = sorted(zip(lowerCamelCase__ , lowerCamelCase__ ) , key=lambda lowerCamelCase__ : x[0] / x[1] , reverse=lowerCamelCase__ ) __lowerCamelCase , __lowerCamelCase : Any = [i[0] for i in r], [i[1] for i in r] __lowerCamelCase : List[str] = list(accumulate(lowerCamelCase__ ) ) __lowerCamelCase : Union[str, Any] = bisect(lowerCamelCase__ , lowerCamelCase__ ) return ( 0 if k == 0 else sum(vl[:k] ) + (w - acc[k - 1]) * (vl[k]) / (wt[k]) if k != n else sum(vl[:k] ) ) if __name__ == "__main__": import doctest doctest.testmod()
73
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) _UpperCAmelCase : int = { """configuration_longformer""": [ """LONGFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP""", """LongformerConfig""", """LongformerOnnxConfig""", ], """tokenization_longformer""": ["""LongformerTokenizer"""], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCAmelCase : int = ["""LongformerTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCAmelCase : str = [ """LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST""", """LongformerForMaskedLM""", """LongformerForMultipleChoice""", """LongformerForQuestionAnswering""", """LongformerForSequenceClassification""", """LongformerForTokenClassification""", """LongformerModel""", """LongformerPreTrainedModel""", """LongformerSelfAttention""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCAmelCase : List[Any] = [ """TF_LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFLongformerForMaskedLM""", """TFLongformerForMultipleChoice""", """TFLongformerForQuestionAnswering""", """TFLongformerForSequenceClassification""", """TFLongformerForTokenClassification""", """TFLongformerModel""", """TFLongformerPreTrainedModel""", """TFLongformerSelfAttention""", ] if TYPE_CHECKING: from .configuration_longformer import ( LONGFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, LongformerConfig, LongformerOnnxConfig, ) from .tokenization_longformer import LongformerTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_longformer_fast import LongformerTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_longformer import ( LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, LongformerForMaskedLM, LongformerForMultipleChoice, LongformerForQuestionAnswering, LongformerForSequenceClassification, LongformerForTokenClassification, LongformerModel, LongformerPreTrainedModel, LongformerSelfAttention, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_longformer import ( TF_LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TFLongformerForMaskedLM, TFLongformerForMultipleChoice, TFLongformerForQuestionAnswering, TFLongformerForSequenceClassification, TFLongformerForTokenClassification, TFLongformerModel, TFLongformerPreTrainedModel, TFLongformerSelfAttention, ) else: import sys _UpperCAmelCase : int = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
174
from __future__ import annotations import math def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> list: if len(lowerCamelCase__ ) != 2 or len(a[0] ) != 2 or len(lowerCamelCase__ ) != 2 or len(b[0] ) != 2: raise Exception('Matrices are not 2x2' ) __lowerCamelCase : Optional[int] = [ [a[0][0] * b[0][0] + a[0][1] * b[1][0], a[0][0] * b[0][1] + a[0][1] * b[1][1]], [a[1][0] * b[0][0] + a[1][1] * b[1][0], a[1][0] * b[0][1] + a[1][1] * b[1][1]], ] return new_matrix def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> Optional[int]: return [ [matrix_a[row][col] + matrix_b[row][col] for col in range(len(matrix_a[row] ) )] for row in range(len(lowerCamelCase__ ) ) ] def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> List[str]: return [ [matrix_a[row][col] - matrix_b[row][col] for col in range(len(matrix_a[row] ) )] for row in range(len(lowerCamelCase__ ) ) ] def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> tuple[list, list, list, list]: if len(lowerCamelCase__ ) % 2 != 0 or len(a[0] ) % 2 != 0: raise Exception('Odd matrices are not supported!' ) __lowerCamelCase : Tuple = len(lowerCamelCase__ ) __lowerCamelCase : List[Any] = matrix_length // 2 __lowerCamelCase : Dict = [[a[i][j] for j in range(lowerCamelCase__ , lowerCamelCase__ )] for i in range(lowerCamelCase__ )] __lowerCamelCase : str = [ [a[i][j] for j in range(lowerCamelCase__ , lowerCamelCase__ )] for i in range(lowerCamelCase__ , lowerCamelCase__ ) ] __lowerCamelCase : Dict = [[a[i][j] for j in range(lowerCamelCase__ )] for i in range(lowerCamelCase__ )] __lowerCamelCase : Optional[Any] = [[a[i][j] for j in range(lowerCamelCase__ )] for i in range(lowerCamelCase__ , lowerCamelCase__ )] return top_left, top_right, bot_left, bot_right def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> tuple[int, int]: return len(lowerCamelCase__ ), len(matrix[0] ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> None: print('\n'.join(str(lowerCamelCase__ ) for line in matrix ) ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> list: if matrix_dimensions(lowerCamelCase__ ) == (2, 2): return default_matrix_multiplication(lowerCamelCase__ , lowerCamelCase__ ) __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : Optional[Any] = split_matrix(lowerCamelCase__ ) __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : Optional[Any] = split_matrix(lowerCamelCase__ ) __lowerCamelCase : str = actual_strassen(lowerCamelCase__ , matrix_subtraction(lowerCamelCase__ , lowerCamelCase__ ) ) __lowerCamelCase : List[str] = actual_strassen(matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) , lowerCamelCase__ ) __lowerCamelCase : List[Any] = actual_strassen(matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) , lowerCamelCase__ ) __lowerCamelCase : Tuple = actual_strassen(lowerCamelCase__ , matrix_subtraction(lowerCamelCase__ , lowerCamelCase__ ) ) __lowerCamelCase : Optional[int] = actual_strassen(matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) , matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) ) __lowerCamelCase : Dict = actual_strassen(matrix_subtraction(lowerCamelCase__ , lowerCamelCase__ ) , matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) ) __lowerCamelCase : Tuple = actual_strassen(matrix_subtraction(lowerCamelCase__ , lowerCamelCase__ ) , matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) ) __lowerCamelCase : Dict = matrix_addition(matrix_subtraction(matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) , lowerCamelCase__ ) , lowerCamelCase__ ) __lowerCamelCase : Tuple = matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) __lowerCamelCase : List[str] = matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) __lowerCamelCase : Any = matrix_subtraction(matrix_subtraction(matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) , lowerCamelCase__ ) , lowerCamelCase__ ) # construct the new matrix from our 4 quadrants __lowerCamelCase : List[Any] = [] for i in range(len(lowerCamelCase__ ) ): new_matrix.append(top_left[i] + top_right[i] ) for i in range(len(lowerCamelCase__ ) ): new_matrix.append(bot_left[i] + bot_right[i] ) return new_matrix def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> list: if matrix_dimensions(lowerCamelCase__ )[1] != matrix_dimensions(lowerCamelCase__ )[0]: __lowerCamelCase : Any = ( 'Unable to multiply these matrices, please check the dimensions.\n' F"Matrix A: {matrixa}\n" F"Matrix B: {matrixa}" ) raise Exception(lowerCamelCase__ ) __lowerCamelCase : str = matrix_dimensions(lowerCamelCase__ ) __lowerCamelCase : List[str] = matrix_dimensions(lowerCamelCase__ ) if dimensiona[0] == dimensiona[1] and dimensiona[0] == dimensiona[1]: return [matrixa, matrixa] __lowerCamelCase : str = max(*lowerCamelCase__ , *lowerCamelCase__ ) __lowerCamelCase : List[str] = int(math.pow(2 , math.ceil(math.loga(lowerCamelCase__ ) ) ) ) __lowerCamelCase : Any = matrixa __lowerCamelCase : int = matrixa # Adding zeros to the matrices so that the arrays dimensions are the same and also # power of 2 for i in range(0 , lowerCamelCase__ ): if i < dimensiona[0]: for _ in range(dimensiona[1] , lowerCamelCase__ ): new_matrixa[i].append(0 ) else: new_matrixa.append([0] * maxim ) if i < dimensiona[0]: for _ in range(dimensiona[1] , lowerCamelCase__ ): new_matrixa[i].append(0 ) else: new_matrixa.append([0] * maxim ) __lowerCamelCase : List[str] = actual_strassen(lowerCamelCase__ , lowerCamelCase__ ) # Removing the additional zeros for i in range(0 , lowerCamelCase__ ): if i < dimensiona[0]: for _ in range(dimensiona[1] , lowerCamelCase__ ): final_matrix[i].pop() else: final_matrix.pop() return final_matrix if __name__ == "__main__": a =[ [2, 3, 4, 5], [6, 4, 3, 1], [2, 3, 6, 7], [3, 1, 2, 4], [2, 3, 4, 5], [6, 4, 3, 1], [2, 3, 6, 7], [3, 1, 2, 4], [2, 3, 4, 5], [6, 2, 3, 1], ] a =[[0, 2, 1, 1], [16, 2, 3, 3], [2, 2, 7, 7], [13, 11, 22, 4]] print(strassen(matrixa, matrixa))
73
0
def A (__A : Tuple ) -> List[str]: """simple docstring""" UpperCAmelCase_ = len(lowerCamelCase__ ) while cur > 1: # Find the maximum number in arr UpperCAmelCase_ = arr.index(max(arr[0:cur] ) ) # Reverse from 0 to mi UpperCAmelCase_ = arr[mi::-1] + arr[mi + 1 : len(lowerCamelCase__ )] # Reverse whole list UpperCAmelCase_ = arr[cur - 1 :: -1] + arr[cur : len(lowerCamelCase__ )] cur -= 1 return arr if __name__ == "__main__": snake_case_ : Any = input("Enter numbers separated by a comma:\n").strip() snake_case_ : Optional[Any] = [int(item) for item in user_input.split(",")] print(pancake_sort(unsorted))
51
from math import isclose, sqrt def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> tuple[float, float, float]: __lowerCamelCase : Tuple = point_y / 4 / point_x __lowerCamelCase : Tuple = 2 * normal_gradient / (1 + normal_gradient * normal_gradient) __lowerCamelCase : List[Any] = (1 - normal_gradient * normal_gradient) / ( 1 + normal_gradient * normal_gradient ) __lowerCamelCase : int = (sa - ca * incoming_gradient) / (ca + sa * incoming_gradient) # to find the next point, solve the simultaeneous equations: # y^2 + 4x^2 = 100 # y - b = m * (x - a) # ==> A x^2 + B x + C = 0 __lowerCamelCase : Any = outgoing_gradient**2 + 4 __lowerCamelCase : Optional[int] = 2 * outgoing_gradient * (point_y - outgoing_gradient * point_x) __lowerCamelCase : str = (point_y - outgoing_gradient * point_x) ** 2 - 1_0_0 __lowerCamelCase : str = ( -linear_term - sqrt(linear_term**2 - 4 * quadratic_term * constant_term ) ) / (2 * quadratic_term) __lowerCamelCase : Optional[Any] = ( -linear_term + sqrt(linear_term**2 - 4 * quadratic_term * constant_term ) ) / (2 * quadratic_term) # two solutions, one of which is our input point __lowerCamelCase : Optional[Any] = x_minus if isclose(lowerCamelCase__ , lowerCamelCase__ ) else x_plus __lowerCamelCase : Tuple = point_y + outgoing_gradient * (next_x - point_x) return next_x, next_y, outgoing_gradient def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ = 1.4 , lowerCamelCase__ = -9.6 ) -> int: __lowerCamelCase : int = 0 __lowerCamelCase : float = first_x_coord __lowerCamelCase : float = first_y_coord __lowerCamelCase : float = (10.1 - point_y) / (0.0 - point_x) while not (-0.01 <= point_x <= 0.01 and point_y > 0): __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : Any = next_point(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) num_reflections += 1 return num_reflections if __name__ == "__main__": print(F"""{solution() = }""")
73
0
__snake_case = [sum(int(c, 10) ** 2 for c in i.__str__()) for i in range(10_00_00)] def _lowercase ( UpperCamelCase_ ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE__ = 0 while number: # Increased Speed Slightly by checking every 5 digits together. sum_of_digits_squared += DIGITS_SQUARED[number % 100000] number //= 100000 return sum_of_digits_squared # There are 2 Chains made, # One ends with 89 with the chain member 58 being the one which when declared first, # there will be the least number of iterations for all the members to be checked. # The other one ends with 1 and has only one element 1. # So 58 and 1 are chosen to be declared at the starting. # Changed dictionary to an array to quicken the solution __snake_case = [None] * 10_00_00_00 __snake_case = True __snake_case = False def _lowercase ( UpperCamelCase_ ) -> bool: '''simple docstring''' if CHAINS[number - 1] is not None: return CHAINS[number - 1] # type: ignore SCREAMING_SNAKE_CASE__ = chain(next_number(lowerCamelCase__ ) ) SCREAMING_SNAKE_CASE__ = number_chain while number < 10000000: SCREAMING_SNAKE_CASE__ = number_chain number *= 10 return number_chain def _lowercase ( UpperCamelCase_ = 10000000 ) -> int: '''simple docstring''' for i in range(1 , lowerCamelCase__ ): if CHAINS[i] is None: chain(i + 1 ) return CHAINS[:number].count(lowerCamelCase__ ) if __name__ == "__main__": import doctest doctest.testmod() print(F"""{solution() = }""")
176
import os import unicodedata from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging a =logging.get_logger(__name__) a ={"""vocab_file""": """spiece.model"""} a ={ """vocab_file""": { """albert-base-v1""": """https://huggingface.co/albert-base-v1/resolve/main/spiece.model""", """albert-large-v1""": """https://huggingface.co/albert-large-v1/resolve/main/spiece.model""", """albert-xlarge-v1""": """https://huggingface.co/albert-xlarge-v1/resolve/main/spiece.model""", """albert-xxlarge-v1""": """https://huggingface.co/albert-xxlarge-v1/resolve/main/spiece.model""", """albert-base-v2""": """https://huggingface.co/albert-base-v2/resolve/main/spiece.model""", """albert-large-v2""": """https://huggingface.co/albert-large-v2/resolve/main/spiece.model""", """albert-xlarge-v2""": """https://huggingface.co/albert-xlarge-v2/resolve/main/spiece.model""", """albert-xxlarge-v2""": """https://huggingface.co/albert-xxlarge-v2/resolve/main/spiece.model""", } } a ={ """albert-base-v1""": 512, """albert-large-v1""": 512, """albert-xlarge-v1""": 512, """albert-xxlarge-v1""": 512, """albert-base-v2""": 512, """albert-large-v2""": 512, """albert-xlarge-v2""": 512, """albert-xxlarge-v2""": 512, } a ="""▁""" class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : List[Any] = VOCAB_FILES_NAMES _UpperCAmelCase : List[str] = PRETRAINED_VOCAB_FILES_MAP _UpperCAmelCase : Optional[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self : str ,SCREAMING_SNAKE_CASE__ : Optional[int] ,SCREAMING_SNAKE_CASE__ : Tuple=True ,SCREAMING_SNAKE_CASE__ : str=True ,SCREAMING_SNAKE_CASE__ : List[str]=False ,SCREAMING_SNAKE_CASE__ : Any="[CLS]" ,SCREAMING_SNAKE_CASE__ : Optional[int]="[SEP]" ,SCREAMING_SNAKE_CASE__ : Optional[Any]="<unk>" ,SCREAMING_SNAKE_CASE__ : Any="[SEP]" ,SCREAMING_SNAKE_CASE__ : Optional[int]="<pad>" ,SCREAMING_SNAKE_CASE__ : Any="[CLS]" ,SCREAMING_SNAKE_CASE__ : Union[str, Any]="[MASK]" ,SCREAMING_SNAKE_CASE__ : Optional[Dict[str, Any]] = None ,**SCREAMING_SNAKE_CASE__ : Dict ,): # Mask token behave like a normal word, i.e. include the space before it and # is included in the raw text, there should be a match in a non-normalized sentence. __lowerCamelCase : Dict = ( AddedToken(SCREAMING_SNAKE_CASE__ ,lstrip=SCREAMING_SNAKE_CASE__ ,rstrip=SCREAMING_SNAKE_CASE__ ,normalized=SCREAMING_SNAKE_CASE__) if isinstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) else mask_token ) __lowerCamelCase : str = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( do_lower_case=SCREAMING_SNAKE_CASE__ ,remove_space=SCREAMING_SNAKE_CASE__ ,keep_accents=SCREAMING_SNAKE_CASE__ ,bos_token=SCREAMING_SNAKE_CASE__ ,eos_token=SCREAMING_SNAKE_CASE__ ,unk_token=SCREAMING_SNAKE_CASE__ ,sep_token=SCREAMING_SNAKE_CASE__ ,pad_token=SCREAMING_SNAKE_CASE__ ,cls_token=SCREAMING_SNAKE_CASE__ ,mask_token=SCREAMING_SNAKE_CASE__ ,sp_model_kwargs=self.sp_model_kwargs ,**SCREAMING_SNAKE_CASE__ ,) __lowerCamelCase : Any = do_lower_case __lowerCamelCase : Union[str, Any] = remove_space __lowerCamelCase : Tuple = keep_accents __lowerCamelCase : Dict = vocab_file __lowerCamelCase : str = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.Load(SCREAMING_SNAKE_CASE__) @property def lowerCAmelCase ( self : Optional[Any]): return len(self.sp_model) def lowerCAmelCase ( self : Optional[Any]): __lowerCamelCase : Optional[int] = {self.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__): i for i in range(self.vocab_size)} vocab.update(self.added_tokens_encoder) return vocab def __getstate__( self : Union[str, Any]): __lowerCamelCase : str = self.__dict__.copy() __lowerCamelCase : Tuple = None return state def __setstate__( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : str): __lowerCamelCase : List[str] = d # for backward compatibility if not hasattr(self ,'sp_model_kwargs'): __lowerCamelCase : List[str] = {} __lowerCamelCase : int = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.Load(self.vocab_file) def lowerCAmelCase ( self : Dict ,SCREAMING_SNAKE_CASE__ : List[Any]): if self.remove_space: __lowerCamelCase : Dict = ' '.join(inputs.strip().split()) else: __lowerCamelCase : Optional[Any] = inputs __lowerCamelCase : Tuple = outputs.replace('``' ,'"').replace('\'\'' ,'"') if not self.keep_accents: __lowerCamelCase : List[str] = unicodedata.normalize('NFKD' ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : str = ''.join([c for c in outputs if not unicodedata.combining(SCREAMING_SNAKE_CASE__)]) if self.do_lower_case: __lowerCamelCase : Optional[Any] = outputs.lower() return outputs def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : str): __lowerCamelCase : Tuple = self.preprocess_text(SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = self.sp_model.encode(SCREAMING_SNAKE_CASE__ ,out_type=SCREAMING_SNAKE_CASE__) __lowerCamelCase : Tuple = [] for piece in pieces: if len(SCREAMING_SNAKE_CASE__) > 1 and piece[-1] == str(',') and piece[-2].isdigit(): __lowerCamelCase : int = self.sp_model.EncodeAsPieces(piece[:-1].replace(SCREAMING_SNAKE_CASE__ ,'')) if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE: if len(cur_pieces[0]) == 1: __lowerCamelCase : Union[str, Any] = cur_pieces[1:] else: __lowerCamelCase : Dict = cur_pieces[0][1:] cur_pieces.append(piece[-1]) new_pieces.extend(SCREAMING_SNAKE_CASE__) else: new_pieces.append(SCREAMING_SNAKE_CASE__) return new_pieces def lowerCAmelCase ( self : Any ,SCREAMING_SNAKE_CASE__ : List[str]): return self.sp_model.PieceToId(SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : str ,SCREAMING_SNAKE_CASE__ : Any): return self.sp_model.IdToPiece(SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Tuple ,SCREAMING_SNAKE_CASE__ : int): __lowerCamelCase : Optional[Any] = [] __lowerCamelCase : int = '' __lowerCamelCase : Optional[int] = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(SCREAMING_SNAKE_CASE__) + token __lowerCamelCase : List[Any] = True __lowerCamelCase : Any = [] else: current_sub_tokens.append(SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = False out_string += self.sp_model.decode(SCREAMING_SNAKE_CASE__) return out_string.strip() def lowerCAmelCase ( self : Dict ,SCREAMING_SNAKE_CASE__ : List[int] ,SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None): __lowerCamelCase : Union[str, Any] = [self.sep_token_id] __lowerCamelCase : int = [self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def lowerCAmelCase ( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : List[int] ,SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ,SCREAMING_SNAKE_CASE__ : bool = False): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=SCREAMING_SNAKE_CASE__ ,token_ids_a=SCREAMING_SNAKE_CASE__ ,already_has_special_tokens=SCREAMING_SNAKE_CASE__) if token_ids_a is not None: return [1] + ([0] * len(SCREAMING_SNAKE_CASE__)) + [1] + ([0] * len(SCREAMING_SNAKE_CASE__)) + [1] return [1] + ([0] * len(SCREAMING_SNAKE_CASE__)) + [1] def lowerCAmelCase ( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : List[int] ,SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None): __lowerCamelCase : Tuple = [self.sep_token_id] __lowerCamelCase : List[Any] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep) * [0] return len(cls + token_ids_a + sep) * [0] + len(token_ids_a + sep) * [1] def lowerCAmelCase ( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : str ,SCREAMING_SNAKE_CASE__ : Optional[str] = None): if not os.path.isdir(SCREAMING_SNAKE_CASE__): logger.error(F"Vocabulary path ({save_directory}) should be a directory") return __lowerCamelCase : List[str] = os.path.join( SCREAMING_SNAKE_CASE__ ,(filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file']) if os.path.abspath(self.vocab_file) != os.path.abspath(SCREAMING_SNAKE_CASE__) and os.path.isfile(self.vocab_file): copyfile(self.vocab_file ,SCREAMING_SNAKE_CASE__) elif not os.path.isfile(self.vocab_file): with open(SCREAMING_SNAKE_CASE__ ,'wb') as fi: __lowerCamelCase : str = self.sp_model.serialized_model_proto() fi.write(SCREAMING_SNAKE_CASE__) return (out_vocab_file,)
73
0
from bisect import bisect from itertools import accumulate def __magic_name__ ( A : List[Any], A : str, A : Union[str, Any], A : Optional[Any] ): '''simple docstring''' a = sorted(zip(lowerCamelCase__, lowerCamelCase__ ), key=lambda A : x[0] / x[1], reverse=lowerCamelCase__ ) a = [i[0] for i in r], [i[1] for i in r] a = list(accumulate(lowerCamelCase__ ) ) a = bisect(lowerCamelCase__, lowerCamelCase__ ) return ( 0 if k == 0 else sum(vl[:k] ) + (w - acc[k - 1]) * (vl[k]) / (wt[k]) if k != n else sum(vl[:k] ) ) if __name__ == "__main__": import doctest doctest.testmod()
107
def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> float: if discount_rate < 0: raise ValueError('Discount rate cannot be negative' ) if not cash_flows: raise ValueError('Cash flows list cannot be empty' ) __lowerCamelCase : int = sum( cash_flow / ((1 + discount_rate) ** i) for i, cash_flow in enumerate(lowerCamelCase__ ) ) return round(lowerCamelCase__ , ndigits=2 ) if __name__ == "__main__": import doctest doctest.testmod()
73
0
import logging import torch from accelerate import Accelerator from arguments import EvaluationArguments from datasets import load_dataset from torch.utils.data import IterableDataset from torch.utils.data.dataloader import DataLoader from transformers import AutoModelForCausalLM, AutoTokenizer, HfArgumentParser, set_seed class __UpperCAmelCase (_UpperCAmelCase ): def __init__( self: str , UpperCAmelCase_: Optional[int] , UpperCAmelCase_: Optional[int] , UpperCAmelCase_: str=1_024 , UpperCAmelCase_: Union[str, Any]=1_024 , UpperCAmelCase_: Tuple=3.6 ): '''simple docstring''' _SCREAMING_SNAKE_CASE = tokenizer _SCREAMING_SNAKE_CASE = tokenizer.bos_token_id _SCREAMING_SNAKE_CASE = dataset _SCREAMING_SNAKE_CASE = seq_length _SCREAMING_SNAKE_CASE = seq_length * chars_per_token * num_of_sequences def __iter__( self: List[str] ): '''simple docstring''' _SCREAMING_SNAKE_CASE = iter(self.dataset ) _SCREAMING_SNAKE_CASE = True while more_examples: _SCREAMING_SNAKE_CASE = [], 0 while True: if buffer_len >= self.input_characters: break try: buffer.append(next(SCREAMING_SNAKE_CASE__ )["""content"""] ) buffer_len += len(buffer[-1] ) except StopIteration: _SCREAMING_SNAKE_CASE = False break _SCREAMING_SNAKE_CASE = tokenizer(SCREAMING_SNAKE_CASE__ , truncation=SCREAMING_SNAKE_CASE__ )['input_ids'] _SCREAMING_SNAKE_CASE = [] for tokenized_input in tokenized_inputs: all_token_ids.extend(tokenized_input + [self.concat_token_id] ) for i in range(0 , len(SCREAMING_SNAKE_CASE__ ) , self.seq_length ): _SCREAMING_SNAKE_CASE = all_token_ids[i : i + self.seq_length] if len(SCREAMING_SNAKE_CASE__ ) == self.seq_length: yield torch.tensor(SCREAMING_SNAKE_CASE__ ) def __lowerCamelCase ( snake_case__ ) -> int: """simple docstring""" _SCREAMING_SNAKE_CASE = {'streaming': True} _SCREAMING_SNAKE_CASE = load_dataset(args.dataset_name ,split="""train""" ,**lowerCamelCase__ ) _SCREAMING_SNAKE_CASE = ConstantLengthDataset(lowerCamelCase__ ,lowerCamelCase__ ,seq_length=args.seq_length ) _SCREAMING_SNAKE_CASE = DataLoader(lowerCamelCase__ ,batch_size=args.batch_size ) return eval_dataloader def __lowerCamelCase ( snake_case__ ) -> str: """simple docstring""" model.eval() _SCREAMING_SNAKE_CASE = [] for step, batch in enumerate(lowerCamelCase__ ): with torch.no_grad(): _SCREAMING_SNAKE_CASE = model(lowerCamelCase__ ,labels=lowerCamelCase__ ) _SCREAMING_SNAKE_CASE = outputs.loss.repeat(args.batch_size ) losses.append(accelerator.gather(lowerCamelCase__ ) ) if args.max_eval_steps > 0 and step >= args.max_eval_steps: break _SCREAMING_SNAKE_CASE = torch.mean(torch.cat(lowerCamelCase__ ) ) try: _SCREAMING_SNAKE_CASE = torch.exp(lowerCamelCase__ ) except OverflowError: _SCREAMING_SNAKE_CASE = float("""inf""" ) return loss.item(), perplexity.item() # Setup Accelerator UpperCamelCase = Accelerator() # Parse configuration UpperCamelCase = HfArgumentParser(EvaluationArguments) UpperCamelCase = parser.parse_args() set_seed(args.seed) # Logging UpperCamelCase = logging.getLogger(__name__) logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''', datefmt='''%m/%d/%Y %H:%M:%S''', level=logging.INFO ) # Load model and tokenizer UpperCamelCase = AutoModelForCausalLM.from_pretrained(args.model_ckpt) UpperCamelCase = AutoTokenizer.from_pretrained(args.model_ckpt) # Load dataset and dataloader UpperCamelCase = create_dataloader(args) # Prepare everything with our `accelerator`. UpperCamelCase , UpperCamelCase = accelerator.prepare(model, eval_dataloader) # Evaluate and save the last checkpoint logger.info('''Evaluating and saving model after training''') UpperCamelCase , UpperCamelCase = evaluate(args) logger.info(f"loss/eval: {eval_loss}, perplexity: {perplexity}")
306
import copy from typing import Dict, List, Optional from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING a ={ """facebook/mask2former-swin-small-coco-instance""": ( """https://huggingface.co/facebook/mask2former-swin-small-coco-instance/blob/main/config.json""" ) # See all Mask2Former models at https://huggingface.co/models?filter=mask2former } a =logging.get_logger(__name__) class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : Dict = '''mask2former''' _UpperCAmelCase : Dict = ['''swin'''] _UpperCAmelCase : Optional[int] = {'''hidden_size''': '''hidden_dim'''} def __init__( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : Optional[Dict] = None ,SCREAMING_SNAKE_CASE__ : int = 2_5_6 ,SCREAMING_SNAKE_CASE__ : int = 2_5_6 ,SCREAMING_SNAKE_CASE__ : int = 2_5_6 ,SCREAMING_SNAKE_CASE__ : int = 1_0_2_4 ,SCREAMING_SNAKE_CASE__ : str = "relu" ,SCREAMING_SNAKE_CASE__ : int = 6 ,SCREAMING_SNAKE_CASE__ : int = 1_0 ,SCREAMING_SNAKE_CASE__ : int = 8 ,SCREAMING_SNAKE_CASE__ : float = 0.0 ,SCREAMING_SNAKE_CASE__ : int = 2_0_4_8 ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : int = 4 ,SCREAMING_SNAKE_CASE__ : int = 2_5_5 ,SCREAMING_SNAKE_CASE__ : int = 1_0_0 ,SCREAMING_SNAKE_CASE__ : float = 0.1 ,SCREAMING_SNAKE_CASE__ : float = 2.0 ,SCREAMING_SNAKE_CASE__ : float = 5.0 ,SCREAMING_SNAKE_CASE__ : float = 5.0 ,SCREAMING_SNAKE_CASE__ : int = 1_2_5_4_4 ,SCREAMING_SNAKE_CASE__ : float = 3.0 ,SCREAMING_SNAKE_CASE__ : float = 0.75 ,SCREAMING_SNAKE_CASE__ : float = 0.02 ,SCREAMING_SNAKE_CASE__ : float = 1.0 ,SCREAMING_SNAKE_CASE__ : bool = True ,SCREAMING_SNAKE_CASE__ : List[int] = [4, 8, 1_6, 3_2] ,SCREAMING_SNAKE_CASE__ : bool = None ,**SCREAMING_SNAKE_CASE__ : Optional[Any] ,): if backbone_config is None: logger.info('`backbone_config` is `None`. Initializing the config with the default `Swin` backbone.') __lowerCamelCase : Optional[Any] = CONFIG_MAPPING['swin']( image_size=2_2_4 ,in_channels=3 ,patch_size=4 ,embed_dim=9_6 ,depths=[2, 2, 1_8, 2] ,num_heads=[3, 6, 1_2, 2_4] ,window_size=7 ,drop_path_rate=0.3 ,use_absolute_embeddings=SCREAMING_SNAKE_CASE__ ,out_features=['stage1', 'stage2', 'stage3', 'stage4'] ,) if isinstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__): __lowerCamelCase : Union[str, Any] = backbone_config.pop('model_type') __lowerCamelCase : Dict = CONFIG_MAPPING[backbone_model_type] __lowerCamelCase : int = config_class.from_dict(SCREAMING_SNAKE_CASE__) # verify that the backbone is supported if backbone_config.model_type not in self.backbones_supported: logger.warning_once( F"Backbone {backbone_config.model_type} is not a supported model and may not be compatible with Mask2Former. " F"Supported model types: {','.join(self.backbones_supported)}") __lowerCamelCase : Dict = backbone_config __lowerCamelCase : int = feature_size __lowerCamelCase : List[str] = mask_feature_size __lowerCamelCase : int = hidden_dim __lowerCamelCase : str = encoder_feedforward_dim __lowerCamelCase : Optional[int] = activation_function __lowerCamelCase : int = encoder_layers __lowerCamelCase : List[Any] = decoder_layers __lowerCamelCase : Union[str, Any] = num_attention_heads __lowerCamelCase : Tuple = dropout __lowerCamelCase : Dict = dim_feedforward __lowerCamelCase : Union[str, Any] = pre_norm __lowerCamelCase : List[str] = enforce_input_projection __lowerCamelCase : Optional[int] = common_stride __lowerCamelCase : Dict = ignore_value __lowerCamelCase : Optional[Any] = num_queries __lowerCamelCase : int = no_object_weight __lowerCamelCase : Optional[Any] = class_weight __lowerCamelCase : str = mask_weight __lowerCamelCase : List[str] = dice_weight __lowerCamelCase : Dict = train_num_points __lowerCamelCase : Optional[int] = oversample_ratio __lowerCamelCase : Optional[Any] = importance_sample_ratio __lowerCamelCase : List[Any] = init_std __lowerCamelCase : Tuple = init_xavier_std __lowerCamelCase : Union[str, Any] = use_auxiliary_loss __lowerCamelCase : List[Any] = feature_strides __lowerCamelCase : Any = output_auxiliary_logits __lowerCamelCase : List[Any] = decoder_layers super().__init__(**SCREAMING_SNAKE_CASE__) @classmethod def lowerCAmelCase ( cls : str ,SCREAMING_SNAKE_CASE__ : PretrainedConfig ,**SCREAMING_SNAKE_CASE__ : Tuple): return cls( backbone_config=SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__ ,) def lowerCAmelCase ( self : str): __lowerCamelCase : List[Any] = copy.deepcopy(self.__dict__) __lowerCamelCase : List[Any] = self.backbone_config.to_dict() __lowerCamelCase : Union[str, Any] = self.__class__.model_type return output
73
0
import os import unicodedata from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import SPIECE_UNDERLINE, logging a__ = logging.get_logger(__name__) a__ = {"""vocab_file""": """spiece.model"""} a__ = { """vocab_file""": { """TsinghuaAI/CPM-Generate""": """https://huggingface.co/TsinghuaAI/CPM-Generate/resolve/main/spiece.model""", } } class snake_case ( SCREAMING_SNAKE_CASE_ ): '''simple docstring''' def __init__( self : Any , lowerCAmelCase : Optional[Any] , lowerCAmelCase : Any=False , lowerCAmelCase : Tuple=True , lowerCAmelCase : Optional[int]=False , lowerCAmelCase : Tuple="<s>" , lowerCAmelCase : Optional[Any]="</s>" , lowerCAmelCase : Any="<unk>" , lowerCAmelCase : Union[str, Any]="<sep>" , lowerCAmelCase : Optional[int]="<pad>" , lowerCAmelCase : List[Any]="<cls>" , lowerCAmelCase : Optional[Any]="<mask>" , lowerCAmelCase : Dict=["<eop>", "<eod>"] , lowerCAmelCase : Optional[Dict[str, Any]] = None , **lowerCAmelCase : List[Any] , ) -> List[str]: """simple docstring""" _snake_case : List[Any] = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__) else mask_token _snake_case : List[str] = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( do_lower_case=SCREAMING_SNAKE_CASE__ , remove_space=SCREAMING_SNAKE_CASE__ , keep_accents=SCREAMING_SNAKE_CASE__ , bos_token=SCREAMING_SNAKE_CASE__ , eos_token=SCREAMING_SNAKE_CASE__ , unk_token=SCREAMING_SNAKE_CASE__ , sep_token=SCREAMING_SNAKE_CASE__ , pad_token=SCREAMING_SNAKE_CASE__ , cls_token=SCREAMING_SNAKE_CASE__ , mask_token=SCREAMING_SNAKE_CASE__ , additional_special_tokens=SCREAMING_SNAKE_CASE__ , sp_model_kwargs=self.sp_model_kwargs , **SCREAMING_SNAKE_CASE__ , ) _snake_case : Optional[int] = 3 _snake_case : str = do_lower_case _snake_case : Optional[int] = remove_space _snake_case : List[Any] = keep_accents _snake_case : Any = vocab_file _snake_case : Optional[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.Load(SCREAMING_SNAKE_CASE__) try: import jieba except ModuleNotFoundError as error: raise error.__class__( """You need to install jieba to use CpmTokenizer or CpmTokenizerFast. """ """See https://pypi.org/project/jieba/ for installation.""") _snake_case : Optional[int] = jieba _snake_case : str = str.maketrans(""" \n""" , """\u2582\u2583""") @property # Copied from transformers.models.xlnet.tokenization_xlnet.XLNetTokenizer.vocab_size def UpperCamelCase_ ( self : Dict) -> Optional[Any]: """simple docstring""" return len(self.sp_model) def UpperCamelCase_ ( self : Dict) -> Optional[int]: """simple docstring""" _snake_case : Dict = {self.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__): i for i in range(self.vocab_size)} vocab.update(self.added_tokens_encoder) return vocab def __getstate__( self : Optional[Any]) -> int: """simple docstring""" _snake_case : List[str] = self.__dict__.copy() _snake_case : Optional[int] = None return state def __setstate__( self : List[str] , lowerCAmelCase : Optional[int]) -> int: """simple docstring""" _snake_case : int = d # for backward compatibility if not hasattr(self , """sp_model_kwargs"""): _snake_case : List[Any] = {} _snake_case : str = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.Load(self.vocab_file) def UpperCamelCase_ ( self : int , lowerCAmelCase : int) -> Dict: """simple docstring""" if self.remove_space: _snake_case : List[Any] = ' '.join(inputs.strip().split()) else: _snake_case : Dict = inputs _snake_case : List[str] = outputs.replace("""``""" , """\"""").replace("""\'\'""" , """\"""") if not self.keep_accents: _snake_case : List[str] = unicodedata.normalize("""NFKD""" , SCREAMING_SNAKE_CASE__) _snake_case : int = ''.join([c for c in outputs if not unicodedata.combining(SCREAMING_SNAKE_CASE__)]) if self.do_lower_case: _snake_case : str = outputs.lower() return outputs def UpperCamelCase_ ( self : Optional[int] , lowerCAmelCase : str) -> str: """simple docstring""" _snake_case : Any = self.preprocess_text(SCREAMING_SNAKE_CASE__) _snake_case : List[Any] = self.sp_model.encode(SCREAMING_SNAKE_CASE__ , out_type=SCREAMING_SNAKE_CASE__) _snake_case : Any = [] for piece in pieces: if len(SCREAMING_SNAKE_CASE__) > 1 and piece[-1] == str(""",""") and piece[-2].isdigit(): _snake_case : Optional[int] = self.sp_model.EncodeAsPieces(piece[:-1].replace(SCREAMING_SNAKE_CASE__ , """""")) if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE: if len(cur_pieces[0]) == 1: _snake_case : Dict = cur_pieces[1:] else: _snake_case : Union[str, Any] = cur_pieces[0][1:] cur_pieces.append(piece[-1]) new_pieces.extend(SCREAMING_SNAKE_CASE__) else: new_pieces.append(SCREAMING_SNAKE_CASE__) return new_pieces def UpperCamelCase_ ( self : Optional[int] , lowerCAmelCase : Union[str, Any]) -> Union[str, Any]: """simple docstring""" return self.sp_model.PieceToId(SCREAMING_SNAKE_CASE__) def UpperCamelCase_ ( self : str , lowerCAmelCase : str) -> Optional[Any]: """simple docstring""" return self.sp_model.IdToPiece(SCREAMING_SNAKE_CASE__) def UpperCamelCase_ ( self : Dict , lowerCAmelCase : Optional[Any]) -> List[Any]: """simple docstring""" _snake_case : Optional[int] = ''.join(SCREAMING_SNAKE_CASE__).replace(SCREAMING_SNAKE_CASE__ , """ """).strip() return out_string def UpperCamelCase_ ( self : str , lowerCAmelCase : List[int] , lowerCAmelCase : Optional[List[int]] = None) -> List[str]: """simple docstring""" _snake_case : List[str] = [self.sep_token_id] _snake_case : List[Any] = [self.cls_token_id] if token_ids_a is None: return token_ids_a + sep + cls return token_ids_a + sep + token_ids_a + sep + cls def UpperCamelCase_ ( self : str , lowerCAmelCase : List[int] , lowerCAmelCase : Optional[List[int]] = None , lowerCAmelCase : bool = False) -> Optional[Any]: """simple docstring""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=SCREAMING_SNAKE_CASE__ , token_ids_a=SCREAMING_SNAKE_CASE__ , already_has_special_tokens=SCREAMING_SNAKE_CASE__) if token_ids_a is not None: return ([0] * len(SCREAMING_SNAKE_CASE__)) + [1] + ([0] * len(SCREAMING_SNAKE_CASE__)) + [1, 1] return ([0] * len(SCREAMING_SNAKE_CASE__)) + [1, 1] def UpperCamelCase_ ( self : List[str] , lowerCAmelCase : List[int] , lowerCAmelCase : Optional[List[int]] = None) -> str: """simple docstring""" _snake_case : Any = [self.sep_token_id] _snake_case : Tuple = [2] if token_ids_a is None: return len(token_ids_a + sep) * [0] + cls_segment_id return len(token_ids_a + sep) * [0] + len(token_ids_a + sep) * [1] + cls_segment_id def UpperCamelCase_ ( self : Optional[int] , lowerCAmelCase : str , lowerCAmelCase : Optional[str] = None) -> List[str]: """simple docstring""" if not os.path.isdir(SCREAMING_SNAKE_CASE__): logger.error(F'''Vocabulary path ({save_directory}) should be a directory''') return _snake_case : Any = os.path.join( SCREAMING_SNAKE_CASE__ , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""]) if os.path.abspath(self.vocab_file) != os.path.abspath(SCREAMING_SNAKE_CASE__) and os.path.isfile(self.vocab_file): copyfile(self.vocab_file , SCREAMING_SNAKE_CASE__) elif not os.path.isfile(self.vocab_file): with open(SCREAMING_SNAKE_CASE__ , """wb""") as fi: _snake_case : Dict = self.sp_model.serialized_model_proto() fi.write(SCREAMING_SNAKE_CASE__) return (out_vocab_file,) def UpperCamelCase_ ( self : List[Any] , *lowerCAmelCase : Any , **lowerCAmelCase : List[Any]) -> str: """simple docstring""" _snake_case : List[Any] = super()._decode(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__) _snake_case : Optional[int] = text.replace(""" """ , """""").replace("""\u2582""" , """ """).replace("""\u2583""" , """\n""") return text
317
import string # frequency taken from https://en.wikipedia.org/wiki/Letter_frequency a ={ """E""": 12.70, """T""": 9.06, """A""": 8.17, """O""": 7.51, """I""": 6.97, """N""": 6.75, """S""": 6.33, """H""": 6.09, """R""": 5.99, """D""": 4.25, """L""": 4.03, """C""": 2.78, """U""": 2.76, """M""": 2.41, """W""": 2.36, """F""": 2.23, """G""": 2.02, """Y""": 1.97, """P""": 1.93, """B""": 1.29, """V""": 0.98, """K""": 0.77, """J""": 0.15, """X""": 0.15, """Q""": 0.10, """Z""": 0.07, } a ="""ETAOINSHRDLCUMWFGYPBVKJXQZ""" a ="""ABCDEFGHIJKLMNOPQRSTUVWXYZ""" def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> dict[str, int]: __lowerCamelCase : Tuple = {letter: 0 for letter in string.ascii_uppercase} for letter in message.upper(): if letter in LETTERS: letter_count[letter] += 1 return letter_count def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> str: return x[0] def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> str: __lowerCamelCase : List[str] = get_letter_count(lowerCamelCase__ ) __lowerCamelCase : dict[int, list[str]] = { freq: [] for letter, freq in letter_to_freq.items() } for letter in LETTERS: freq_to_letter[letter_to_freq[letter]].append(lowerCamelCase__ ) __lowerCamelCase : dict[int, str] = {} for freq in freq_to_letter: freq_to_letter[freq].sort(key=ETAOIN.find , reverse=lowerCamelCase__ ) __lowerCamelCase : Optional[Any] = ''.join(freq_to_letter[freq] ) __lowerCamelCase : int = list(freq_to_letter_str.items() ) freq_pairs.sort(key=lowerCamelCase__ , reverse=lowerCamelCase__ ) __lowerCamelCase : list[str] = [freq_pair[1] for freq_pair in freq_pairs] return "".join(lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> int: __lowerCamelCase : str = get_frequency_order(lowerCamelCase__ ) __lowerCamelCase : Optional[Any] = 0 for common_letter in ETAOIN[:6]: if common_letter in freq_order[:6]: match_score += 1 for uncommon_letter in ETAOIN[-6:]: if uncommon_letter in freq_order[-6:]: match_score += 1 return match_score if __name__ == "__main__": import doctest doctest.testmod()
73
0
'''simple docstring''' import os import tempfile import unittest import uuid from pathlib import Path from transformers.testing_utils import get_tests_dir, require_soundfile, require_torch, require_vision from transformers.tools.agent_types import AgentAudio, AgentImage, AgentText from transformers.utils import is_soundfile_availble, is_torch_available, is_vision_available if is_torch_available(): import torch if is_soundfile_availble(): import soundfile as sf if is_vision_available(): from PIL import Image def __lowercase ( __lowercase="" ) -> str: '''simple docstring''' _A = tempfile.mkdtemp() return os.path.join(lowerCamelCase__ , str(uuid.uuida() ) + suffix ) @require_soundfile @require_torch class _UpperCAmelCase ( unittest.TestCase ): """simple docstring""" def lowerCAmelCase ( self : Optional[Any] ): '''simple docstring''' _A = torch.rand(12 , dtype=torch.floataa ) - 0.5 _A = AgentAudio(SCREAMING_SNAKE_CASE__ ) _A = str(agent_type.to_string() ) # Ensure that the tensor and the agent_type's tensor are the same self.assertTrue(torch.allclose(SCREAMING_SNAKE_CASE__ , agent_type.to_raw() , atol=1E-4 ) ) del agent_type # Ensure the path remains even after the object deletion self.assertTrue(os.path.exists(SCREAMING_SNAKE_CASE__ ) ) # Ensure that the file contains the same value as the original tensor _A = sf.read(SCREAMING_SNAKE_CASE__ ) self.assertTrue(torch.allclose(SCREAMING_SNAKE_CASE__ , torch.tensor(SCREAMING_SNAKE_CASE__ ) , atol=1E-4 ) ) def lowerCAmelCase ( self : List[Any] ): '''simple docstring''' _A = torch.rand(12 , dtype=torch.floataa ) - 0.5 _A = get_new_path(suffix=".wav" ) sf.write(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , 16000 ) _A = AgentAudio(SCREAMING_SNAKE_CASE__ ) self.assertTrue(torch.allclose(SCREAMING_SNAKE_CASE__ , agent_type.to_raw() , atol=1E-4 ) ) self.assertEqual(agent_type.to_string() , SCREAMING_SNAKE_CASE__ ) @require_vision @require_torch class _UpperCAmelCase ( unittest.TestCase ): """simple docstring""" def lowerCAmelCase ( self : Union[str, Any] ): '''simple docstring''' _A = torch.randint(0 , 256 , (64, 64, 3) ) _A = AgentImage(SCREAMING_SNAKE_CASE__ ) _A = str(agent_type.to_string() ) # Ensure that the tensor and the agent_type's tensor are the same self.assertTrue(torch.allclose(SCREAMING_SNAKE_CASE__ , agent_type._tensor , atol=1E-4 ) ) self.assertIsInstance(agent_type.to_raw() , Image.Image ) # Ensure the path remains even after the object deletion del agent_type self.assertTrue(os.path.exists(SCREAMING_SNAKE_CASE__ ) ) def lowerCAmelCase ( self : Any ): '''simple docstring''' _A = Path(get_tests_dir("fixtures/tests_samples/COCO" ) ) / '000000039769.png' _A = Image.open(SCREAMING_SNAKE_CASE__ ) _A = AgentImage(SCREAMING_SNAKE_CASE__ ) self.assertTrue(path.samefile(agent_type.to_string() ) ) self.assertTrue(image == agent_type.to_raw() ) # Ensure the path remains even after the object deletion del agent_type self.assertTrue(os.path.exists(SCREAMING_SNAKE_CASE__ ) ) def lowerCAmelCase ( self : Any ): '''simple docstring''' _A = Path(get_tests_dir("fixtures/tests_samples/COCO" ) ) / '000000039769.png' _A = Image.open(SCREAMING_SNAKE_CASE__ ) _A = AgentImage(SCREAMING_SNAKE_CASE__ ) self.assertFalse(path.samefile(agent_type.to_string() ) ) self.assertTrue(image == agent_type.to_raw() ) # Ensure the path remains even after the object deletion del agent_type self.assertTrue(os.path.exists(SCREAMING_SNAKE_CASE__ ) ) class _UpperCAmelCase ( unittest.TestCase ): """simple docstring""" def lowerCAmelCase ( self : str ): '''simple docstring''' _A = 'Hey!' _A = AgentText(SCREAMING_SNAKE_CASE__ ) self.assertEqual(SCREAMING_SNAKE_CASE__ , agent_type.to_string() ) self.assertEqual(SCREAMING_SNAKE_CASE__ , agent_type.to_raw() ) self.assertEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
79
# This is the module that test_patching.py uses to test patch_submodule() import os # noqa: this is just for tests import os as renamed_os # noqa: this is just for tests from os import path # noqa: this is just for tests from os import path as renamed_path # noqa: this is just for tests from os.path import join # noqa: this is just for tests from os.path import join as renamed_join # noqa: this is just for tests a =open # noqa: we just need to have a builtin inside this module to test it properly
73
0
import logging from transformers.configuration_utils import PretrainedConfig __A : int = logging.getLogger(__name__) class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__): _UpperCamelCase:List[Any] = '''masked_bert''' def __init__( self , _SCREAMING_SNAKE_CASE=3_0522 , _SCREAMING_SNAKE_CASE=768 , _SCREAMING_SNAKE_CASE=12 , _SCREAMING_SNAKE_CASE=12 , _SCREAMING_SNAKE_CASE=3072 , _SCREAMING_SNAKE_CASE="gelu" , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=512 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=0.0_2 , _SCREAMING_SNAKE_CASE=1E-12 , _SCREAMING_SNAKE_CASE=0 , _SCREAMING_SNAKE_CASE="topK" , _SCREAMING_SNAKE_CASE="constant" , _SCREAMING_SNAKE_CASE=0.0 , **_SCREAMING_SNAKE_CASE , )-> List[str]: super().__init__(pad_token_id=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) lowerCamelCase_ =vocab_size lowerCamelCase_ =hidden_size lowerCamelCase_ =num_hidden_layers lowerCamelCase_ =num_attention_heads lowerCamelCase_ =hidden_act lowerCamelCase_ =intermediate_size lowerCamelCase_ =hidden_dropout_prob lowerCamelCase_ =attention_probs_dropout_prob lowerCamelCase_ =max_position_embeddings lowerCamelCase_ =type_vocab_size lowerCamelCase_ =initializer_range lowerCamelCase_ =layer_norm_eps lowerCamelCase_ =pruning_method lowerCamelCase_ =mask_init lowerCamelCase_ =mask_scale
154
# Function to print upper half of diamond (pyramid) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> str: for i in range(0 , lowerCamelCase__ ): for _ in range(0 , n - i - 1 ): # printing spaces print(' ' , end='' ) for _ in range(0 , i + 1 ): # printing stars print('* ' , end='' ) print() def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Tuple: for i in range(lowerCamelCase__ , 0 , -1 ): for _ in range(lowerCamelCase__ , 0 , -1 ): # printing stars print('* ' , end='' ) print() for _ in range(n - i + 1 , 0 , -1 ): # printing spaces print(' ' , end='' ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Any: if n <= 0: print(' ... .... nothing printing :(' ) return floyd(lowerCamelCase__ ) # upper half reverse_floyd(lowerCamelCase__ ) # lower half if __name__ == "__main__": print(r"""| /\ | |- | |- |--| |\ /| |-""") print(r"""|/ \| |- |_ |_ |__| | \/ | |_""") a =1 while K: a =int(input("""enter the number and , and see the magic : """)) print() pretty_print(user_number) a =int(input("""press 0 to exit... and 1 to continue...""")) print("""Good Bye...""")
73
0
"""simple docstring""" import io import os import unicodedata from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging lowerCAmelCase__ = logging.get_logger(__name__) lowerCAmelCase__ = '''▁''' lowerCAmelCase__ = {'''vocab_file''': '''vocab.txt''', '''sentencepiece_model_ckpt''': '''sentencepiece.bpe.model'''} lowerCAmelCase__ = { '''sentencepiece_model_file''': '''sentencepiece.bpe.model''', '''vocab_file''': '''vocab.txt''', } lowerCAmelCase__ = { '''vocab_file''': { '''ernie-m-base''': '''https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/vocab.txt''', '''ernie-m-large''': '''https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/vocab.txt''', }, '''sentencepiece_model_file''': { '''ernie-m-base''': '''https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/sentencepiece.bpe.model''', '''ernie-m-large''': '''https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/sentencepiece.bpe.model''', }, } lowerCAmelCase__ = { '''ernie-m-base''': 514, '''ernie-m-large''': 514, } lowerCAmelCase__ = { '''ernie-m-base''': {'''do_lower_case''': False}, '''ernie-m-large''': {'''do_lower_case''': False}, } class __snake_case ( _lowercase): snake_case__ : List[str] = ["input_ids"] snake_case__ : Dict = VOCAB_FILES_NAMES snake_case__ : Any = PRETRAINED_INIT_CONFIGURATION snake_case__ : Optional[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES snake_case__ : Optional[int] = PRETRAINED_VOCAB_FILES_MAP snake_case__ : List[Any] = RESOURCE_FILES_NAMES def __init__( self : Dict , __lowerCAmelCase : List[str] , __lowerCAmelCase : Union[str, Any]=None , __lowerCAmelCase : int=False , __lowerCAmelCase : Union[str, Any]="utf8" , __lowerCAmelCase : List[Any]="[UNK]" , __lowerCAmelCase : Any="[SEP]" , __lowerCAmelCase : Optional[Any]="[PAD]" , __lowerCAmelCase : List[Any]="[CLS]" , __lowerCAmelCase : Optional[Any]="[MASK]" , __lowerCAmelCase : Optional[Dict[str, Any]] = None , **__lowerCAmelCase : List[Any] , ): """simple docstring""" _lowerCamelCase : Any = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( do_lower_case=SCREAMING_SNAKE_CASE__ , unk_token=SCREAMING_SNAKE_CASE__ , sep_token=SCREAMING_SNAKE_CASE__ , pad_token=SCREAMING_SNAKE_CASE__ , cls_token=SCREAMING_SNAKE_CASE__ , mask_token=SCREAMING_SNAKE_CASE__ , vocab_file=SCREAMING_SNAKE_CASE__ , encoding=SCREAMING_SNAKE_CASE__ , sp_model_kwargs=self.sp_model_kwargs , **SCREAMING_SNAKE_CASE__ , ) _lowerCamelCase : Tuple = do_lower_case _lowerCamelCase : Any = sentencepiece_model_ckpt _lowerCamelCase : Any = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(SCREAMING_SNAKE_CASE__ ) # to mimic paddlenlp.transformers.ernie_m.tokenizer.ErnieMTokenizer functioning if vocab_file is not None: _lowerCamelCase : Union[str, Any] = self.load_vocab(filepath=SCREAMING_SNAKE_CASE__ ) else: _lowerCamelCase : List[Any] = {self.sp_model.id_to_piece(SCREAMING_SNAKE_CASE__ ): id for id in range(self.sp_model.get_piece_size() )} _lowerCamelCase : Any = {v: k for k, v in self.vocab.items()} def SCREAMING_SNAKE_CASE ( self : Union[str, Any] , __lowerCAmelCase : List[str] ): """simple docstring""" if text is None: return None _lowerCamelCase : Optional[int] = self.tokenize(SCREAMING_SNAKE_CASE__ ) _lowerCamelCase : Optional[Any] = '', [] for i, ch in enumerate(SCREAMING_SNAKE_CASE__ ): if ch in self.SP_CHAR_MAPPING: _lowerCamelCase : Union[str, Any] = self.SP_CHAR_MAPPING.get(SCREAMING_SNAKE_CASE__ ) else: _lowerCamelCase : Optional[int] = unicodedata.normalize('''NFKC''' , SCREAMING_SNAKE_CASE__ ) if self.is_whitespace(SCREAMING_SNAKE_CASE__ ): continue normalized_text += ch char_mapping.extend([i] * len(SCREAMING_SNAKE_CASE__ ) ) _lowerCamelCase : int = normalized_text, [], 0 if self.do_lower_case: _lowerCamelCase : Optional[Any] = text.lower() for token in split_tokens: if token[:1] == "▁": _lowerCamelCase : Any = token[1:] _lowerCamelCase : Union[str, Any] = text[offset:].index(SCREAMING_SNAKE_CASE__ ) + offset _lowerCamelCase : Tuple = start + len(SCREAMING_SNAKE_CASE__ ) token_mapping.append((char_mapping[start], char_mapping[end - 1] + 1) ) _lowerCamelCase : List[Any] = end return token_mapping @property def SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" return len(self.vocab ) def SCREAMING_SNAKE_CASE ( self : Any ): """simple docstring""" return dict(self.vocab , **self.added_tokens_encoder ) def __getstate__( self : int ): """simple docstring""" _lowerCamelCase : List[str] = self.__dict__.copy() _lowerCamelCase : List[str] = None return state def __setstate__( self : Any , __lowerCAmelCase : List[Any] ): """simple docstring""" _lowerCamelCase : int = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): _lowerCamelCase : int = {} _lowerCamelCase : Optional[int] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.sentencepiece_model_ckpt ) def SCREAMING_SNAKE_CASE ( self : Optional[int] , __lowerCAmelCase : List[Any] ): """simple docstring""" return "".join((self.SP_CHAR_MAPPING.get(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) for c in text) ) def SCREAMING_SNAKE_CASE ( self : List[str] , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : Optional[Any]=False , __lowerCAmelCase : Dict=6_4 , __lowerCAmelCase : Optional[Any]=0.1 ): """simple docstring""" if self.sp_model_kwargs.get('''enable_sampling''' ) is True: _lowerCamelCase : Optional[int] = True if self.sp_model_kwargs.get('''alpha''' ) is not None: _lowerCamelCase : Any = self.sp_model_kwargs.get('''alpha''' ) if self.sp_model_kwargs.get('''nbest_size''' ) is not None: _lowerCamelCase : Tuple = self.sp_model_kwargs.get('''nbest_size''' ) if not enable_sampling: _lowerCamelCase : Dict = self.sp_model.EncodeAsPieces(SCREAMING_SNAKE_CASE__ ) else: _lowerCamelCase : Optional[int] = self.sp_model.SampleEncodeAsPieces(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) _lowerCamelCase : Optional[Any] = [] for pi, piece in enumerate(SCREAMING_SNAKE_CASE__ ): if piece == SPIECE_UNDERLINE: if not pieces[pi + 1].startswith(SCREAMING_SNAKE_CASE__ ) and pi != 0: new_pieces.append(SCREAMING_SNAKE_CASE__ ) continue else: continue _lowerCamelCase : List[Any] = 0 for i, chunk in enumerate(SCREAMING_SNAKE_CASE__ ): if chunk == SPIECE_UNDERLINE: continue if self.is_ch_char(SCREAMING_SNAKE_CASE__ ) or self.is_punct(SCREAMING_SNAKE_CASE__ ): if i > lst_i and piece[lst_i:i] != SPIECE_UNDERLINE: new_pieces.append(piece[lst_i:i] ) new_pieces.append(SCREAMING_SNAKE_CASE__ ) _lowerCamelCase : Optional[int] = i + 1 elif chunk.isdigit() and i > 0 and not piece[i - 1].isdigit(): if i > lst_i and piece[lst_i:i] != SPIECE_UNDERLINE: new_pieces.append(piece[lst_i:i] ) _lowerCamelCase : Any = i elif not chunk.isdigit() and i > 0 and piece[i - 1].isdigit(): if i > lst_i and piece[lst_i:i] != SPIECE_UNDERLINE: new_pieces.append(piece[lst_i:i] ) _lowerCamelCase : Dict = i if len(SCREAMING_SNAKE_CASE__ ) > lst_i: new_pieces.append(piece[lst_i:] ) return new_pieces def SCREAMING_SNAKE_CASE ( self : Tuple , __lowerCAmelCase : int ): """simple docstring""" _lowerCamelCase : List[str] = ''.join(SCREAMING_SNAKE_CASE__ ).replace(SCREAMING_SNAKE_CASE__ , ''' ''' ).strip() return out_string def SCREAMING_SNAKE_CASE ( self : int , __lowerCAmelCase : int ): """simple docstring""" _lowerCamelCase : str = self.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ ) _lowerCamelCase : str = ''.join(SCREAMING_SNAKE_CASE__ ).replace(SCREAMING_SNAKE_CASE__ , ''' ''' ).strip() return out_string def SCREAMING_SNAKE_CASE ( self : Optional[Any] , __lowerCAmelCase : List[Any] ): """simple docstring""" return self.vocab.get(SCREAMING_SNAKE_CASE__ , self.vocab.get(self.unk_token ) ) def SCREAMING_SNAKE_CASE ( self : str , __lowerCAmelCase : List[str] ): """simple docstring""" return self.reverse_vocab.get(SCREAMING_SNAKE_CASE__ , self.unk_token ) def SCREAMING_SNAKE_CASE ( self : Dict , __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : Optional[Any]=None ): """simple docstring""" if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] _lowerCamelCase : Dict = [self.cls_token_id] _lowerCamelCase : Dict = [self.sep_token_id] return _cls + token_ids_a + _sep + _sep + token_ids_a + _sep def SCREAMING_SNAKE_CASE ( self : List[str] , __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : int=None ): """simple docstring""" if offset_mapping_a is None: return [(0, 0)] + offset_mapping_a + [(0, 0)] return [(0, 0)] + offset_mapping_a + [(0, 0), (0, 0)] + offset_mapping_a + [(0, 0)] def SCREAMING_SNAKE_CASE ( self : Optional[Any] , __lowerCAmelCase : Dict , __lowerCAmelCase : Union[str, Any]=None , __lowerCAmelCase : List[Any]=False ): """simple docstring""" if already_has_special_tokens: if token_ids_a is not None: raise ValueError( '''You should not supply a second sequence if the provided sequence of ''' '''ids is already formatted with special tokens for the model.''' ) return [1 if x in [self.sep_token_id, self.cls_token_id] else 0 for x in token_ids_a] if token_ids_a is not None: return [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1, 1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1] return [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1] def SCREAMING_SNAKE_CASE ( self : Any , __lowerCAmelCase : List[int] , __lowerCAmelCase : Optional[List[int]] = None ): """simple docstring""" if token_ids_a is None: # [CLS] X [SEP] return (len(SCREAMING_SNAKE_CASE__ ) + 2) * [0] # [CLS] A [SEP] [SEP] B [SEP] return [0] * (len(SCREAMING_SNAKE_CASE__ ) + 1) + [1] * (len(SCREAMING_SNAKE_CASE__ ) + 3) def SCREAMING_SNAKE_CASE ( self : Tuple , __lowerCAmelCase : Optional[Any] ): """simple docstring""" if "\u4e00" <= char <= "\u9fff": return True return False def SCREAMING_SNAKE_CASE ( self : List[Any] , __lowerCAmelCase : Optional[int] ): """simple docstring""" if ("a" <= char <= "z") or ("A" <= char <= "Z"): return True return False def SCREAMING_SNAKE_CASE ( self : Optional[Any] , __lowerCAmelCase : Any ): """simple docstring""" if char in ",;:.?!~,;:。?!《》【】": return True return False def SCREAMING_SNAKE_CASE ( self : Any , __lowerCAmelCase : str ): """simple docstring""" if char == " " or char == "\t" or char == "\n" or char == "\r": return True if len(SCREAMING_SNAKE_CASE__ ) == 1: _lowerCamelCase : int = unicodedata.category(SCREAMING_SNAKE_CASE__ ) if cat == "Zs": return True return False def SCREAMING_SNAKE_CASE ( self : str , __lowerCAmelCase : Union[str, Any] ): """simple docstring""" _lowerCamelCase : Any = {} with io.open(SCREAMING_SNAKE_CASE__ , '''r''' , encoding='''utf-8''' ) as f: for index, line in enumerate(SCREAMING_SNAKE_CASE__ ): _lowerCamelCase : int = line.rstrip('''\n''' ) _lowerCamelCase : str = int(SCREAMING_SNAKE_CASE__ ) return token_to_idx def SCREAMING_SNAKE_CASE ( self : str , __lowerCAmelCase : str , __lowerCAmelCase : Optional[str] = None ): """simple docstring""" _lowerCamelCase : List[Any] = 0 if os.path.isdir(SCREAMING_SNAKE_CASE__ ): _lowerCamelCase : Union[str, Any] = os.path.join( SCREAMING_SNAKE_CASE__ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) else: _lowerCamelCase : str = (filename_prefix + '-' if filename_prefix else '') + save_directory with open(SCREAMING_SNAKE_CASE__ , '''w''' , encoding='''utf-8''' ) as writer: for token, token_index in sorted(self.vocab.items() , key=lambda __lowerCAmelCase : kv[1] ): if index != token_index: logger.warning( f'''Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive.''' ''' Please check that the vocabulary is not corrupted!''' ) _lowerCamelCase : Dict = token_index writer.write(token + '''\n''' ) index += 1 _lowerCamelCase : Any = os.path.join(SCREAMING_SNAKE_CASE__ , '''sentencepiece.bpe.model''' ) with open(SCREAMING_SNAKE_CASE__ , '''wb''' ) as fi: _lowerCamelCase : Dict = self.sp_model.serialized_model_proto() fi.write(SCREAMING_SNAKE_CASE__ ) return (vocab_file,)
72
import re import warnings from contextlib import contextmanager from ...processing_utils import ProcessorMixin class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : Any = ['''image_processor''', '''tokenizer'''] _UpperCAmelCase : List[Any] = '''AutoImageProcessor''' _UpperCAmelCase : Dict = '''AutoTokenizer''' def __init__( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : Optional[int]=None ,SCREAMING_SNAKE_CASE__ : List[Any]=None ,**SCREAMING_SNAKE_CASE__ : Union[str, Any]): __lowerCamelCase : List[str] = None if "feature_extractor" in kwargs: warnings.warn( 'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`' ' instead.' ,SCREAMING_SNAKE_CASE__ ,) __lowerCamelCase : Union[str, Any] = kwargs.pop('feature_extractor') __lowerCamelCase : Dict = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('You need to specify an `image_processor`.') if tokenizer is None: raise ValueError('You need to specify a `tokenizer`.') super().__init__(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Dict = self.image_processor __lowerCamelCase : Optional[int] = False def __call__( self : int ,*SCREAMING_SNAKE_CASE__ : Union[str, Any] ,**SCREAMING_SNAKE_CASE__ : Union[str, Any]): # For backward compatibility if self._in_target_context_manager: return self.current_processor(*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[int] = kwargs.pop('images' ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Union[str, Any] = kwargs.pop('text' ,SCREAMING_SNAKE_CASE__) if len(SCREAMING_SNAKE_CASE__) > 0: __lowerCamelCase : int = args[0] __lowerCamelCase : List[str] = args[1:] if images is None and text is None: raise ValueError('You need to specify either an `images` or `text` input to process.') if images is not None: __lowerCamelCase : Optional[int] = self.image_processor(SCREAMING_SNAKE_CASE__ ,*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) if text is not None: __lowerCamelCase : List[Any] = self.tokenizer(SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) if text is None: return inputs elif images is None: return encodings else: __lowerCamelCase : Optional[Any] = encodings['input_ids'] return inputs def lowerCAmelCase ( self : int ,*SCREAMING_SNAKE_CASE__ : Union[str, Any] ,**SCREAMING_SNAKE_CASE__ : Dict): return self.tokenizer.batch_decode(*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Optional[Any] ,*SCREAMING_SNAKE_CASE__ : List[Any] ,**SCREAMING_SNAKE_CASE__ : Any): return self.tokenizer.decode(*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) @contextmanager def lowerCAmelCase ( self : Tuple): warnings.warn( '`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your ' 'labels by using the argument `text` of the regular `__call__` method (either in the same call as ' 'your images inputs, or in a separate call.') __lowerCamelCase : List[Any] = True __lowerCamelCase : str = self.tokenizer yield __lowerCamelCase : Tuple = self.image_processor __lowerCamelCase : Tuple = False def lowerCAmelCase ( self : Any ,SCREAMING_SNAKE_CASE__ : str ,SCREAMING_SNAKE_CASE__ : int=False ,SCREAMING_SNAKE_CASE__ : List[Any]=None): if added_vocab is None: __lowerCamelCase : str = self.tokenizer.get_added_vocab() __lowerCamelCase : Union[str, Any] = {} while tokens: __lowerCamelCase : Tuple = re.search(R'<s_(.*?)>' ,SCREAMING_SNAKE_CASE__ ,re.IGNORECASE) if start_token is None: break __lowerCamelCase : Dict = start_token.group(1) __lowerCamelCase : List[str] = re.search(RF"</s_{key}>" ,SCREAMING_SNAKE_CASE__ ,re.IGNORECASE) __lowerCamelCase : Optional[int] = start_token.group() if end_token is None: __lowerCamelCase : List[Any] = tokens.replace(SCREAMING_SNAKE_CASE__ ,'') else: __lowerCamelCase : Tuple = end_token.group() __lowerCamelCase : int = re.escape(SCREAMING_SNAKE_CASE__) __lowerCamelCase : str = re.escape(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Union[str, Any] = re.search(F"{start_token_escaped}(.*?){end_token_escaped}" ,SCREAMING_SNAKE_CASE__ ,re.IGNORECASE) if content is not None: __lowerCamelCase : List[Any] = content.group(1).strip() if r"<s_" in content and r"</s_" in content: # non-leaf node __lowerCamelCase : str = self.tokenajson(SCREAMING_SNAKE_CASE__ ,is_inner_value=SCREAMING_SNAKE_CASE__ ,added_vocab=SCREAMING_SNAKE_CASE__) if value: if len(SCREAMING_SNAKE_CASE__) == 1: __lowerCamelCase : Tuple = value[0] __lowerCamelCase : int = value else: # leaf nodes __lowerCamelCase : Tuple = [] for leaf in content.split(R'<sep/>'): __lowerCamelCase : List[Any] = leaf.strip() if leaf in added_vocab and leaf[0] == "<" and leaf[-2:] == "/>": __lowerCamelCase : str = leaf[1:-2] # for categorical special tokens output[key].append(SCREAMING_SNAKE_CASE__) if len(output[key]) == 1: __lowerCamelCase : Dict = output[key][0] __lowerCamelCase : Dict = tokens[tokens.find(SCREAMING_SNAKE_CASE__) + len(SCREAMING_SNAKE_CASE__) :].strip() if tokens[:6] == r"<sep/>": # non-leaf nodes return [output] + self.tokenajson(tokens[6:] ,is_inner_value=SCREAMING_SNAKE_CASE__ ,added_vocab=SCREAMING_SNAKE_CASE__) if len(SCREAMING_SNAKE_CASE__): return [output] if is_inner_value else output else: return [] if is_inner_value else {"text_sequence": tokens} @property def lowerCAmelCase ( self : List[str]): warnings.warn( '`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.' ,SCREAMING_SNAKE_CASE__ ,) return self.image_processor_class @property def lowerCAmelCase ( self : List[Any]): warnings.warn( '`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.' ,SCREAMING_SNAKE_CASE__ ,) return self.image_processor
73
0
'''simple docstring''' import argparse import json from typing import List from ltp import LTP from transformers import BertTokenizer def a ( __a ) -> Any: '''simple docstring''' if ( (cp >= 0X4e00 and cp <= 0X9fff) or (cp >= 0X3400 and cp <= 0X4dbf) # or (cp >= 0X2_0000 and cp <= 0X2_a6df) # or (cp >= 0X2_a700 and cp <= 0X2_b73f) # or (cp >= 0X2_b740 and cp <= 0X2_b81f) # or (cp >= 0X2_b820 and cp <= 0X2_ceaf) # or (cp >= 0Xf900 and cp <= 0Xfaff) or (cp >= 0X2_f800 and cp <= 0X2_fa1f) # ): # return True return False def a ( __a ) -> Optional[int]: '''simple docstring''' for char in word: UpperCamelCase__ :int = ord(lowerCamelCase__ ) if not _is_chinese_char(lowerCamelCase__ ): return 0 return 1 def a ( __a ) -> str: '''simple docstring''' UpperCamelCase__ :Any = set() for token in tokens: UpperCamelCase__ :Tuple = len(lowerCamelCase__ ) > 1 and is_chinese(lowerCamelCase__ ) if chinese_word: word_set.add(lowerCamelCase__ ) UpperCamelCase__ :List[Any] = list(lowerCamelCase__ ) return word_list def a ( __a , __a ) -> List[Any]: '''simple docstring''' if not chinese_word_set: return bert_tokens UpperCamelCase__ :List[str] = max([len(lowerCamelCase__ ) for w in chinese_word_set] ) UpperCamelCase__ :Dict = bert_tokens UpperCamelCase__ :Optional[Any] = 0, len(lowerCamelCase__ ) while start < end: UpperCamelCase__ :Tuple = True if is_chinese(bert_word[start] ): UpperCamelCase__ :List[str] = min(end - start , lowerCamelCase__ ) for i in range(lowerCamelCase__ , 1 , -1 ): UpperCamelCase__ :Dict = ''.join(bert_word[start : start + i] ) if whole_word in chinese_word_set: for j in range(start + 1 , start + i ): UpperCamelCase__ :List[str] = '##' + bert_word[j] UpperCamelCase__ :Optional[Any] = start + i UpperCamelCase__ :Union[str, Any] = False break if single_word: start += 1 return bert_word def a ( __a , __a , __a ) -> str: '''simple docstring''' UpperCamelCase__ :int = [] for i in range(0 , len(lowerCamelCase__ ) , 100 ): UpperCamelCase__ :int = ltp_tokenizer.seg(lines[i : i + 100] )[0] UpperCamelCase__ :Optional[int] = [get_chinese_word(lowerCamelCase__ ) for r in res] ltp_res.extend(lowerCamelCase__ ) assert len(lowerCamelCase__ ) == len(lowerCamelCase__ ) UpperCamelCase__ :Tuple = [] for i in range(0 , len(lowerCamelCase__ ) , 100 ): UpperCamelCase__ :List[str] = bert_tokenizer(lines[i : i + 100] , add_special_tokens=lowerCamelCase__ , truncation=lowerCamelCase__ , max_length=512 ) bert_res.extend(res['''input_ids'''] ) assert len(lowerCamelCase__ ) == len(lowerCamelCase__ ) UpperCamelCase__ :Tuple = [] for input_ids, chinese_word in zip(lowerCamelCase__ , lowerCamelCase__ ): UpperCamelCase__ :List[Any] = [] for id in input_ids: UpperCamelCase__ :List[Any] = bert_tokenizer._convert_id_to_token(lowerCamelCase__ ) input_tokens.append(lowerCamelCase__ ) UpperCamelCase__ :List[Any] = add_sub_symbol(lowerCamelCase__ , lowerCamelCase__ ) UpperCamelCase__ :Dict = [] # We only save pos of chinese subwords start with ##, which mean is part of a whole word. for i, token in enumerate(lowerCamelCase__ ): if token[:2] == "##": UpperCamelCase__ :List[str] = token[2:] # save chinese tokens' pos if len(lowerCamelCase__ ) == 1 and _is_chinese_char(ord(lowerCamelCase__ ) ): ref_id.append(lowerCamelCase__ ) ref_ids.append(lowerCamelCase__ ) assert len(lowerCamelCase__ ) == len(lowerCamelCase__ ) return ref_ids def a ( __a ) -> Dict: '''simple docstring''' with open(args.file_name , '''r''' , encoding='''utf-8''' ) as f: UpperCamelCase__ :Any = f.readlines() UpperCamelCase__ :str = [line.strip() for line in data if len(lowerCamelCase__ ) > 0 and not line.isspace()] # avoid delimiter like '\u2029' UpperCamelCase__ :Any = LTP(args.ltp ) # faster in GPU device UpperCamelCase__ :List[str] = BertTokenizer.from_pretrained(args.bert ) UpperCamelCase__ :List[str] = prepare_ref(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) with open(args.save_path , '''w''' , encoding='''utf-8''' ) as f: UpperCamelCase__ :List[str] = [json.dumps(lowerCamelCase__ ) + '\n' for ref in ref_ids] f.writelines(lowerCamelCase__ ) if __name__ == "__main__": __snake_case = argparse.ArgumentParser(description='''prepare_chinese_ref''') parser.add_argument( '''--file_name''', type=str, default='''./resources/chinese-demo.txt''', help='''file need process, same as training data in lm''', ) parser.add_argument( '''--ltp''', type=str, default='''./resources/ltp''', help='''resources for LTP tokenizer, usually a path''' ) parser.add_argument('''--bert''', type=str, default='''./resources/robert''', help='''resources for Bert tokenizer''') parser.add_argument('''--save_path''', type=str, default='''./resources/ref.txt''', help='''path to save res''') __snake_case = parser.parse_args() main(args)
97
def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> int: __lowerCamelCase : Optional[int] = 0 __lowerCamelCase : Dict = len(lowerCamelCase__ ) - 1 while left <= right: # avoid divided by 0 during interpolation if sorted_collection[left] == sorted_collection[right]: if sorted_collection[left] == item: return left else: return None __lowerCamelCase : str = left + ((item - sorted_collection[left]) * (right - left)) // ( sorted_collection[right] - sorted_collection[left] ) # out of range check if point < 0 or point >= len(lowerCamelCase__ ): return None __lowerCamelCase : Tuple = sorted_collection[point] if current_item == item: return point else: if point < left: __lowerCamelCase : List[Any] = left __lowerCamelCase : Tuple = point elif point > right: __lowerCamelCase : Dict = right __lowerCamelCase : str = point else: if item < current_item: __lowerCamelCase : Dict = point - 1 else: __lowerCamelCase : Dict = point + 1 return None def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> Any: # avoid divided by 0 during interpolation if sorted_collection[left] == sorted_collection[right]: if sorted_collection[left] == item: return left else: return None __lowerCamelCase : Optional[int] = left + ((item - sorted_collection[left]) * (right - left)) // ( sorted_collection[right] - sorted_collection[left] ) # out of range check if point < 0 or point >= len(lowerCamelCase__ ): return None if sorted_collection[point] == item: return point elif point < left: return interpolation_search_by_recursion(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) elif point > right: return interpolation_search_by_recursion(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) else: if sorted_collection[point] > item: return interpolation_search_by_recursion( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , point - 1 ) else: return interpolation_search_by_recursion( lowerCamelCase__ , lowerCamelCase__ , point + 1 , lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Optional[Any]: if collection != sorted(lowerCamelCase__ ): raise ValueError('Collection must be ascending sorted' ) return True if __name__ == "__main__": import sys a =0 if debug == 1: a =[10, 30, 40, 45, 50, 66, 77, 93] try: __assert_sorted(collection) except ValueError: sys.exit("""Sequence must be ascending sorted to apply interpolation search""") a =67 a =interpolation_search(collection, target) if result is not None: print(F"""{target} found at positions: {result}""") else: print("""Not found""")
73
0
import copy import os import tempfile from unittest import TestCase from unittest.mock import patch import numpy as np import pyarrow as pa import pyarrow.parquet as pq import pytest from datasets.arrow_writer import ArrowWriter, OptimizedTypedSequence, ParquetWriter, TypedSequence from datasets.features import ArrayaD, ClassLabel, Features, Image, Value from datasets.features.features import ArrayaDExtensionType, cast_to_python_objects from datasets.keyhash import DuplicatedKeysError, InvalidKeyError from .utils import require_pil class __lowerCAmelCase ( _a ): def lowerCamelCase (self ) -> List[str]: '''simple docstring''' snake_case_ : Dict = pa.array(TypedSequence([1, 2, 3] ) ) self.assertEqual(arr.type , pa.intaa() ) def lowerCamelCase (self ) -> Union[str, Any]: '''simple docstring''' with self.assertRaises(SCREAMING_SNAKE_CASE__ ): snake_case_ : List[str] = pa.array(TypedSequence([1, 2, 3] ) , type=pa.intaa() ) def lowerCamelCase (self ) -> List[Any]: '''simple docstring''' with self.assertRaises(SCREAMING_SNAKE_CASE__ ): snake_case_ : Dict = pa.array(TypedSequence([1, 2, 3] , try_type=Value('''bool''' ) , type=Value('''int64''' ) ) ) def lowerCamelCase (self ) -> Optional[int]: '''simple docstring''' snake_case_ : int = pa.array(TypedSequence([1, 2, 3] , type=Value('''int32''' ) ) ) self.assertEqual(arr.type , pa.intaa() ) def lowerCamelCase (self ) -> Optional[Any]: '''simple docstring''' with self.assertRaises((TypeError, pa.lib.ArrowInvalid) ): snake_case_ : List[Any] = pa.array(TypedSequence(['''foo''', '''bar'''] , type=Value('''int64''' ) ) ) def lowerCamelCase (self ) -> Optional[int]: '''simple docstring''' snake_case_ : int = pa.array(TypedSequence([1, 2, 3] , try_type=Value('''int32''' ) ) ) self.assertEqual(arr.type , pa.intaa() ) def lowerCamelCase (self ) -> Union[str, Any]: '''simple docstring''' snake_case_ : str = pa.array(TypedSequence(['''foo''', '''bar'''] , try_type=Value('''int64''' ) ) ) self.assertEqual(arr.type , pa.string() ) def lowerCamelCase (self ) -> int: '''simple docstring''' snake_case_ : Dict = pa.array(TypedSequence([[[1, 2, 3]]] , type=ArrayaD((1, 3) , '''int64''' ) ) ) self.assertEqual(arr.type , ArrayaDExtensionType((1, 3) , '''int64''' ) ) def lowerCamelCase (self ) -> Union[str, Any]: '''simple docstring''' with self.assertRaises((TypeError, pa.lib.ArrowInvalid) ): snake_case_ : List[str] = pa.array(TypedSequence(['''foo''', '''bar'''] , type=ArrayaD((1, 3) , '''int64''' ) ) ) def lowerCamelCase (self ) -> int: '''simple docstring''' snake_case_ : int = pa.array(TypedSequence([[[1, 2, 3]]] , try_type=ArrayaD((1, 3) , '''int64''' ) ) ) self.assertEqual(arr.type , ArrayaDExtensionType((1, 3) , '''int64''' ) ) def lowerCamelCase (self ) -> Optional[int]: '''simple docstring''' snake_case_ : Dict = pa.array(TypedSequence(['''foo''', '''bar'''] , try_type=ArrayaD((1, 3) , '''int64''' ) ) ) self.assertEqual(arr.type , pa.string() ) @require_pil def lowerCamelCase (self ) -> str: '''simple docstring''' import PIL.Image snake_case_ : List[str] = PIL.Image.fromarray(np.arange(10 , dtype=np.uinta ).reshape(2 , 5 ) ) with patch( '''datasets.arrow_writer.cast_to_python_objects''' , side_effect=SCREAMING_SNAKE_CASE__ ) as mock_cast_to_python_objects: snake_case_ : Optional[Any] = pa.array(TypedSequence([{'''path''': None, '''bytes''': B'''image_bytes'''}, pil_image] , type=Image() ) ) snake_case_ : Any = mock_cast_to_python_objects.call_args_list[-1] self.assertIn('''optimize_list_casting''' , SCREAMING_SNAKE_CASE__ ) self.assertFalse(kwargs['''optimize_list_casting'''] ) def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase ) -> Tuple: """simple docstring""" snake_case_ : List[Any] = pa.BufferReader(lowerCamelCase__ ) if isinstance(lowerCamelCase__ , pa.Buffer ) else pa.memory_map(lowerCamelCase__ ) snake_case_ : List[str] = pa.ipc.open_stream(lowerCamelCase__ ) snake_case_ : pa.Table = f.read_all() assert len(pa_table.to_batches() ) == expected_num_chunks assert pa_table.to_pydict() == {"col_1": ["foo", "bar"], "col_2": [1, 2]} del pa_table @pytest.mark.parametrize('''writer_batch_size''' , [None, 1, 10] ) @pytest.mark.parametrize( '''fields''' , [None, {'''col_1''': pa.string(), '''col_2''': pa.intaa()}, {'''col_1''': pa.string(), '''col_2''': pa.intaa()}] ) def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase ) -> Union[str, Any]: """simple docstring""" snake_case_ : int = pa.BufferOutputStream() snake_case_ : Union[str, Any] = pa.schema(lowerCamelCase__ ) if fields else None with ArrowWriter(stream=lowerCamelCase__ , schema=lowerCamelCase__ , writer_batch_size=lowerCamelCase__ ) as writer: writer.write({'''col_1''': '''foo''', '''col_2''': 1} ) writer.write({'''col_1''': '''bar''', '''col_2''': 2} ) snake_case_ : str = writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: snake_case_ : List[str] = {'col_1': pa.string(), 'col_2': pa.intaa()} assert writer._schema == pa.schema(lowerCamelCase__ , metadata=writer._schema.metadata ) _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) def lowerCamelCase_ ( ) -> Dict: """simple docstring""" snake_case_ : str = pa.BufferOutputStream() snake_case_ : Dict = Features({'''labels''': ClassLabel(names=['''neg''', '''pos'''] )} ) with ArrowWriter(stream=lowerCamelCase__ , features=lowerCamelCase__ ) as writer: writer.write({'''labels''': 0} ) writer.write({'''labels''': 1} ) snake_case_ : List[str] = writer.finalize() assert num_examples == 2 assert num_bytes > 0 assert writer._schema == features.arrow_schema assert writer._schema.metadata == features.arrow_schema.metadata snake_case_ : Tuple = pa.BufferReader(output.getvalue() ) snake_case_ : Optional[Any] = pa.ipc.open_stream(lowerCamelCase__ ) snake_case_ : pa.Table = f.read_all() snake_case_ : List[Any] = pa_table.schema assert pa_table.num_rows == 2 assert schema == features.arrow_schema assert schema.metadata == features.arrow_schema.metadata assert features == Features.from_arrow_schema(lowerCamelCase__ ) @pytest.mark.parametrize('''writer_batch_size''' , [None, 1, 10] ) def lowerCamelCase_ ( _UpperCamelCase ) -> Union[str, Any]: """simple docstring""" snake_case_ : Any = pa.BufferOutputStream() with ArrowWriter( stream=lowerCamelCase__ , writer_batch_size=lowerCamelCase__ , hash_salt='''split_name''' , check_duplicates=lowerCamelCase__ , ) as writer: with pytest.raises(lowerCamelCase__ ): writer.write({'''col_1''': '''foo''', '''col_2''': 1} , key=[1, 2] ) snake_case_ : int = writer.finalize() @pytest.mark.parametrize('''writer_batch_size''' , [None, 2, 10] ) def lowerCamelCase_ ( _UpperCamelCase ) -> List[str]: """simple docstring""" snake_case_ : Optional[int] = pa.BufferOutputStream() with ArrowWriter( stream=lowerCamelCase__ , writer_batch_size=lowerCamelCase__ , hash_salt='''split_name''' , check_duplicates=lowerCamelCase__ , ) as writer: with pytest.raises(lowerCamelCase__ ): writer.write({'''col_1''': '''foo''', '''col_2''': 1} , key=10 ) writer.write({'''col_1''': '''bar''', '''col_2''': 2} , key=10 ) snake_case_ : str = writer.finalize() @pytest.mark.parametrize('''writer_batch_size''' , [None, 2, 10] ) def lowerCamelCase_ ( _UpperCamelCase ) -> Dict: """simple docstring""" snake_case_ : str = pa.BufferOutputStream() with ArrowWriter( stream=lowerCamelCase__ , writer_batch_size=lowerCamelCase__ , hash_salt='''split_name''' , check_duplicates=lowerCamelCase__ , ) as writer: writer.write({'''col_1''': '''foo''', '''col_2''': 1} , key=1 ) writer.write({'''col_1''': '''bar''', '''col_2''': 2} , key=2 ) snake_case_ : int = writer.finalize() assert num_examples == 2 assert num_bytes > 0 _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) @pytest.mark.parametrize('''writer_batch_size''' , [None, 1, 10] ) @pytest.mark.parametrize( '''fields''' , [None, {'''col_1''': pa.string(), '''col_2''': pa.intaa()}, {'''col_1''': pa.string(), '''col_2''': pa.intaa()}] ) def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase ) -> Any: """simple docstring""" snake_case_ : Any = pa.BufferOutputStream() snake_case_ : Dict = pa.schema(lowerCamelCase__ ) if fields else None with ArrowWriter(stream=lowerCamelCase__ , schema=lowerCamelCase__ , writer_batch_size=lowerCamelCase__ ) as writer: writer.write_batch({'''col_1''': ['''foo''', '''bar'''], '''col_2''': [1, 2]} ) writer.write_batch({'''col_1''': [], '''col_2''': []} ) snake_case_ : Optional[Any] = writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: snake_case_ : str = {'col_1': pa.string(), 'col_2': pa.intaa()} assert writer._schema == pa.schema(lowerCamelCase__ , metadata=writer._schema.metadata ) _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) @pytest.mark.parametrize('''writer_batch_size''' , [None, 1, 10] ) @pytest.mark.parametrize( '''fields''' , [None, {'''col_1''': pa.string(), '''col_2''': pa.intaa()}, {'''col_1''': pa.string(), '''col_2''': pa.intaa()}] ) def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase ) -> Optional[Any]: """simple docstring""" snake_case_ : int = pa.BufferOutputStream() snake_case_ : Dict = pa.schema(lowerCamelCase__ ) if fields else None with ArrowWriter(stream=lowerCamelCase__ , schema=lowerCamelCase__ , writer_batch_size=lowerCamelCase__ ) as writer: writer.write_table(pa.Table.from_pydict({'''col_1''': ['''foo''', '''bar'''], '''col_2''': [1, 2]} ) ) snake_case_ : Union[str, Any] = writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: snake_case_ : Union[str, Any] = {'col_1': pa.string(), 'col_2': pa.intaa()} assert writer._schema == pa.schema(lowerCamelCase__ , metadata=writer._schema.metadata ) _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) @pytest.mark.parametrize('''writer_batch_size''' , [None, 1, 10] ) @pytest.mark.parametrize( '''fields''' , [None, {'''col_1''': pa.string(), '''col_2''': pa.intaa()}, {'''col_1''': pa.string(), '''col_2''': pa.intaa()}] ) def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase ) -> Any: """simple docstring""" snake_case_ : Dict = pa.BufferOutputStream() snake_case_ : Any = pa.schema(lowerCamelCase__ ) if fields else None with ArrowWriter(stream=lowerCamelCase__ , schema=lowerCamelCase__ , writer_batch_size=lowerCamelCase__ ) as writer: writer.write_row(pa.Table.from_pydict({'''col_1''': ['''foo'''], '''col_2''': [1]} ) ) writer.write_row(pa.Table.from_pydict({'''col_1''': ['''bar'''], '''col_2''': [2]} ) ) snake_case_ : int = writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: snake_case_ : List[str] = {'col_1': pa.string(), 'col_2': pa.intaa()} assert writer._schema == pa.schema(lowerCamelCase__ , metadata=writer._schema.metadata ) _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) def lowerCamelCase_ ( ) -> Optional[int]: """simple docstring""" with tempfile.TemporaryDirectory() as tmp_dir: snake_case_ : str = {'col_1': pa.string(), 'col_2': pa.intaa()} snake_case_ : Optional[int] = os.path.join(lowerCamelCase__ , '''test.arrow''' ) with ArrowWriter(path=lowerCamelCase__ , schema=pa.schema(lowerCamelCase__ ) ) as writer: writer.write_batch({'''col_1''': ['''foo''', '''bar'''], '''col_2''': [1, 2]} ) snake_case_ : Union[str, Any] = writer.finalize() assert num_examples == 2 assert num_bytes > 0 assert writer._schema == pa.schema(lowerCamelCase__ , metadata=writer._schema.metadata ) _check_output(lowerCamelCase__ , 1 ) def lowerCamelCase_ ( _UpperCamelCase ) -> Optional[Any]: """simple docstring""" if pa.types.is_list(lowerCamelCase__ ): return get_base_dtype(arr_type.value_type ) else: return arr_type def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase ) -> Dict: """simple docstring""" if isinstance(lst[0] , lowerCamelCase__ ): change_first_primitive_element_in_list(lst[0] , lowerCamelCase__ ) else: snake_case_ : List[str] = value @pytest.mark.parametrize('''optimized_int_type, expected_dtype''' , [(None, pa.intaa()), (Value('''int32''' ), pa.intaa())] ) @pytest.mark.parametrize('''sequence''' , [[1, 2, 3], [[1, 2, 3]], [[[1, 2, 3]]]] ) def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) -> Union[str, Any]: """simple docstring""" snake_case_ : Any = pa.array(TypedSequence(lowerCamelCase__ , optimized_int_type=lowerCamelCase__ ) ) assert get_base_dtype(arr.type ) == expected_dtype @pytest.mark.parametrize( '''col, expected_dtype''' , [ ('''attention_mask''', pa.inta()), ('''special_tokens_mask''', pa.inta()), ('''token_type_ids''', pa.inta()), ('''input_ids''', pa.intaa()), ('''other''', pa.intaa()), ] , ) @pytest.mark.parametrize('''sequence''' , [[1, 2, 3], [[1, 2, 3]], [[[1, 2, 3]]]] ) def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) -> List[Any]: """simple docstring""" snake_case_ : Any = pa.array(OptimizedTypedSequence(lowerCamelCase__ , col=lowerCamelCase__ ) ) assert get_base_dtype(arr.type ) == expected_dtype # not in range if col != "other": # avoids errors due to in-place modifications snake_case_ : List[str] = copy.deepcopy(lowerCamelCase__ ) snake_case_ : List[Any] = np.iinfo(expected_dtype.to_pandas_dtype() ).max + 1 change_first_primitive_element_in_list(lowerCamelCase__ , lowerCamelCase__ ) snake_case_ : str = pa.array(OptimizedTypedSequence(lowerCamelCase__ , col=lowerCamelCase__ ) ) assert get_base_dtype(arr.type ) == pa.intaa() @pytest.mark.parametrize('''raise_exception''' , [False, True] ) def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase ) -> Tuple: """simple docstring""" snake_case_ : List[str] = str(tmp_path / '''dataset-train.arrow''' ) try: with ArrowWriter(path=lowerCamelCase__ ) as writer: if raise_exception: raise pa.lib.ArrowInvalid() else: writer.stream.close() except pa.lib.ArrowInvalid: pass finally: assert writer.stream.closed def lowerCamelCase_ ( _UpperCamelCase ) -> Optional[int]: """simple docstring""" snake_case_ : Optional[int] = 'mock://dataset-train.arrow' with ArrowWriter(path=lowerCamelCase__ , storage_options=mockfs.storage_options ) as writer: assert isinstance(writer._fs , type(lowerCamelCase__ ) ) assert writer._fs.storage_options == mockfs.storage_options writer.write({'''col_1''': '''foo''', '''col_2''': 1} ) writer.write({'''col_1''': '''bar''', '''col_2''': 2} ) snake_case_ : Dict = writer.finalize() assert num_examples == 2 assert num_bytes > 0 assert mockfs.exists(lowerCamelCase__ ) def lowerCamelCase_ ( ) -> Optional[Any]: """simple docstring""" snake_case_ : Optional[Any] = pa.BufferOutputStream() with ParquetWriter(stream=lowerCamelCase__ ) as writer: writer.write({'''col_1''': '''foo''', '''col_2''': 1} ) writer.write({'''col_1''': '''bar''', '''col_2''': 2} ) snake_case_ : List[Any] = writer.finalize() assert num_examples == 2 assert num_bytes > 0 snake_case_ : Tuple = pa.BufferReader(output.getvalue() ) snake_case_ : pa.Table = pq.read_table(lowerCamelCase__ ) assert pa_table.to_pydict() == {"col_1": ["foo", "bar"], "col_2": [1, 2]} @require_pil @pytest.mark.parametrize('''embed_local_files''' , [False, True] ) def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase ) -> List[str]: """simple docstring""" import PIL.Image snake_case_ : Dict = str(tmp_path / '''test_image_rgb.jpg''' ) PIL.Image.fromarray(np.zeros((5, 5) , dtype=np.uinta ) ).save(lowerCamelCase__ , format='''png''' ) snake_case_ : Union[str, Any] = pa.BufferOutputStream() with ParquetWriter( stream=lowerCamelCase__ , features=Features({'''image''': Image()} ) , embed_local_files=lowerCamelCase__ ) as writer: writer.write({'''image''': image_path} ) writer.finalize() snake_case_ : Dict = pa.BufferReader(output.getvalue() ) snake_case_ : pa.Table = pq.read_table(lowerCamelCase__ ) snake_case_ : Any = pa_table.to_pydict() if embed_local_files: assert isinstance(out['''image'''][0]['''path'''] , lowerCamelCase__ ) with open(lowerCamelCase__ , '''rb''' ) as f: assert out["image"][0]["bytes"] == f.read() else: assert out["image"][0]["path"] == image_path assert out["image"][0]["bytes"] is None def lowerCamelCase_ ( ) -> Optional[Any]: """simple docstring""" snake_case_ : List[str] = pa.schema([pa.field('''col_1''' , pa.string() , nullable=lowerCamelCase__ )] ) snake_case_ : List[str] = pa.BufferOutputStream() with ArrowWriter(stream=lowerCamelCase__ ) as writer: writer._build_writer(inferred_schema=lowerCamelCase__ ) assert writer._schema == pa.schema([pa.field('''col_1''' , pa.string() )] )
279
import json import os import subprocess import unittest from ast import literal_eval import pytest from parameterized import parameterized, parameterized_class from . import is_sagemaker_available if is_sagemaker_available(): from sagemaker import Session, TrainingJobAnalytics from sagemaker.huggingface import HuggingFace @pytest.mark.skipif( literal_eval(os.getenv('''TEST_SAGEMAKER''' , '''False''' ) ) is not True , reason='''Skipping test because should only be run when releasing minor transformers version''' , ) @pytest.mark.usefixtures('''sm_env''' ) @parameterized_class( [ { '''framework''': '''pytorch''', '''script''': '''run_glue_model_parallelism.py''', '''model_name_or_path''': '''roberta-large''', '''instance_type''': '''ml.p3dn.24xlarge''', '''results''': {'''train_runtime''': 1_600, '''eval_accuracy''': 0.3, '''eval_loss''': 1.2}, }, { '''framework''': '''pytorch''', '''script''': '''run_glue.py''', '''model_name_or_path''': '''roberta-large''', '''instance_type''': '''ml.p3dn.24xlarge''', '''results''': {'''train_runtime''': 1_600, '''eval_accuracy''': 0.3, '''eval_loss''': 1.2}, }, ] ) class A_ ( unittest.TestCase ): def lowerCAmelCase ( self : Union[str, Any]): if self.framework == "pytorch": subprocess.run( F"cp ./examples/pytorch/text-classification/run_glue.py {self.env.test_path}/run_glue.py".split() ,encoding='utf-8' ,check=SCREAMING_SNAKE_CASE__ ,) assert hasattr(self ,'env') def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : int): # configuration for running training on smdistributed Model Parallel __lowerCamelCase : Any = { 'enabled': True, 'processes_per_host': 8, } __lowerCamelCase : List[Any] = { 'enabled': True, 'parameters': { 'microbatches': 4, 'placement_strategy': 'spread', 'pipeline': 'interleaved', 'optimize': 'speed', 'partitions': 4, 'ddp': True, }, } __lowerCamelCase : str = {'smdistributed': {'modelparallel': smp_options}, 'mpi': mpi_options} __lowerCamelCase : List[str] = 'trainer' if self.script == 'run_glue.py' else 'smtrainer' # creates estimator return HuggingFace( entry_point=self.script ,source_dir=self.env.test_path ,role=self.env.role ,image_uri=self.env.image_uri ,base_job_name=F"{self.env.base_job_name}-{instance_count}-smp-{name_extension}" ,instance_count=SCREAMING_SNAKE_CASE__ ,instance_type=self.instance_type ,debugger_hook_config=SCREAMING_SNAKE_CASE__ ,hyperparameters={ **self.env.hyperparameters, 'model_name_or_path': self.model_name_or_path, 'max_steps': 5_0_0, } ,metric_definitions=self.env.metric_definitions ,distribution=SCREAMING_SNAKE_CASE__ ,py_version='py36' ,) def lowerCAmelCase ( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : Any): TrainingJobAnalytics(SCREAMING_SNAKE_CASE__).export_csv(F"{self.env.test_path}/{job_name}_metrics.csv") @parameterized.expand([(1,)]) def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : Optional[Any]): # create estimator __lowerCamelCase : str = self.create_estimator(SCREAMING_SNAKE_CASE__) # run training estimator.fit() # result dataframe __lowerCamelCase : List[str] = TrainingJobAnalytics(estimator.latest_training_job.name).dataframe() # extract kpis __lowerCamelCase : Optional[int] = list(result_metrics_df[result_metrics_df.metric_name == 'eval_accuracy']['value']) __lowerCamelCase : Any = list(result_metrics_df[result_metrics_df.metric_name == 'eval_loss']['value']) # get train time from SageMaker job, this includes starting, preprocessing, stopping __lowerCamelCase : str = ( Session().describe_training_job(estimator.latest_training_job.name).get('TrainingTimeInSeconds' ,9_9_9_9_9_9) ) # assert kpis assert train_runtime <= self.results["train_runtime"] assert all(t >= self.results['eval_accuracy'] for t in eval_accuracy) assert all(t <= self.results['eval_loss'] for t in eval_loss) # dump tests result into json file to share in PR with open(F"{estimator.latest_training_job.name}.json" ,'w') as outfile: json.dump({'train_time': train_runtime, 'eval_accuracy': eval_accuracy, 'eval_loss': eval_loss} ,SCREAMING_SNAKE_CASE__)
73
0
'''simple docstring''' import unittest from transformers import MraConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask if is_torch_available(): import torch from transformers import ( MraForMaskedLM, MraForMultipleChoice, MraForQuestionAnswering, MraForSequenceClassification, MraForTokenClassification, MraModel, ) from transformers.models.mra.modeling_mra import MRA_PRETRAINED_MODEL_ARCHIVE_LIST class a__ : """simple docstring""" def __init__(self , __lowercase , __lowercase=2 , __lowercase=8 , __lowercase=True , __lowercase=True , __lowercase=True , __lowercase=True , __lowercase=99 , __lowercase=16 , __lowercase=5 , __lowercase=2 , __lowercase=36 , __lowercase="gelu" , __lowercase=0.0 , __lowercase=0.0 , __lowercase=5_12 , __lowercase=16 , __lowercase=2 , __lowercase=0.0_2 , __lowercase=3 , __lowercase=4 , __lowercase=None , ): __lowerCAmelCase = parent __lowerCAmelCase = batch_size __lowerCAmelCase = seq_length __lowerCAmelCase = is_training __lowerCAmelCase = use_input_mask __lowerCAmelCase = use_token_type_ids __lowerCAmelCase = use_labels __lowerCAmelCase = vocab_size __lowerCAmelCase = hidden_size __lowerCAmelCase = num_hidden_layers __lowerCAmelCase = num_attention_heads __lowerCAmelCase = intermediate_size __lowerCAmelCase = hidden_act __lowerCAmelCase = hidden_dropout_prob __lowerCAmelCase = attention_probs_dropout_prob __lowerCAmelCase = max_position_embeddings __lowerCAmelCase = type_vocab_size __lowerCAmelCase = type_sequence_label_size __lowerCAmelCase = initializer_range __lowerCAmelCase = num_labels __lowerCAmelCase = num_choices __lowerCAmelCase = scope def _snake_case (self ): __lowerCAmelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __lowerCAmelCase = None if self.use_input_mask: __lowerCAmelCase = random_attention_mask([self.batch_size, self.seq_length] ) __lowerCAmelCase = None if self.use_token_type_ids: __lowerCAmelCase = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __lowerCAmelCase = None __lowerCAmelCase = None __lowerCAmelCase = None if self.use_labels: __lowerCAmelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __lowerCAmelCase = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __lowerCAmelCase = ids_tensor([self.batch_size] , self.num_choices ) __lowerCAmelCase = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def _snake_case (self ): return MraConfig( 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=SCREAMING_SNAKE_CASE__ , initializer_range=self.initializer_range , ) def _snake_case (self ): __lowerCAmelCase = self.get_config() __lowerCAmelCase = 3_00 return config def _snake_case (self ): ( __lowerCAmelCase ) = self.prepare_config_and_inputs() __lowerCAmelCase = True __lowerCAmelCase = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) __lowerCAmelCase = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels, encoder_hidden_states, encoder_attention_mask, ) def _snake_case (self , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase ): __lowerCAmelCase = MraModel(config=SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() __lowerCAmelCase = model(SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase = model(SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase = model(SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _snake_case (self , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , ): __lowerCAmelCase = True __lowerCAmelCase = MraModel(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() __lowerCAmelCase = model( SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ , encoder_hidden_states=SCREAMING_SNAKE_CASE__ , encoder_attention_mask=SCREAMING_SNAKE_CASE__ , ) __lowerCAmelCase = model( SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ , encoder_hidden_states=SCREAMING_SNAKE_CASE__ , ) __lowerCAmelCase = model(SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _snake_case (self , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase ): __lowerCAmelCase = MraForMaskedLM(config=SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() __lowerCAmelCase = model(SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ , labels=SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def _snake_case (self , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase ): __lowerCAmelCase = MraForQuestionAnswering(config=SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() __lowerCAmelCase = model( SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ , start_positions=SCREAMING_SNAKE_CASE__ , end_positions=SCREAMING_SNAKE_CASE__ , ) 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 _snake_case (self , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase ): __lowerCAmelCase = self.num_labels __lowerCAmelCase = MraForSequenceClassification(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() __lowerCAmelCase = model(SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ , labels=SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _snake_case (self , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase ): __lowerCAmelCase = self.num_labels __lowerCAmelCase = MraForTokenClassification(config=SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() __lowerCAmelCase = model(SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ , labels=SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def _snake_case (self , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase ): __lowerCAmelCase = self.num_choices __lowerCAmelCase = MraForMultipleChoice(config=SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() __lowerCAmelCase = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __lowerCAmelCase = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __lowerCAmelCase = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __lowerCAmelCase = model( SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ , labels=SCREAMING_SNAKE_CASE__ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def _snake_case (self ): __lowerCAmelCase = self.prepare_config_and_inputs() ( __lowerCAmelCase ) = config_and_inputs __lowerCAmelCase = {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class a__ ( __A , unittest.TestCase ): """simple docstring""" __UpperCamelCase : str = ( ( MraModel, MraForMaskedLM, MraForMultipleChoice, MraForQuestionAnswering, MraForSequenceClassification, MraForTokenClassification, ) if is_torch_available() else () ) __UpperCamelCase : Optional[int] = False __UpperCamelCase : int = False __UpperCamelCase : Union[str, Any] = False __UpperCamelCase : Any = False __UpperCamelCase : Tuple = () def _snake_case (self ): __lowerCAmelCase = MraModelTester(self ) __lowerCAmelCase = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE__ , hidden_size=37 ) def _snake_case (self ): self.config_tester.run_common_tests() def _snake_case (self ): __lowerCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE__ ) def _snake_case (self ): __lowerCAmelCase = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: __lowerCAmelCase = type self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE__ ) def _snake_case (self ): __lowerCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*SCREAMING_SNAKE_CASE__ ) def _snake_case (self ): __lowerCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*SCREAMING_SNAKE_CASE__ ) def _snake_case (self ): __lowerCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*SCREAMING_SNAKE_CASE__ ) def _snake_case (self ): __lowerCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*SCREAMING_SNAKE_CASE__ ) def _snake_case (self ): __lowerCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*SCREAMING_SNAKE_CASE__ ) @slow def _snake_case (self ): for model_name in MRA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __lowerCAmelCase = MraModel.from_pretrained(SCREAMING_SNAKE_CASE__ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) @unittest.skip(reason='''MRA does not output attentions''' ) def _snake_case (self ): return @require_torch class a__ ( unittest.TestCase ): """simple docstring""" @slow def _snake_case (self ): __lowerCAmelCase = MraModel.from_pretrained('''uw-madison/mra-base-512-4''' ) __lowerCAmelCase = torch.arange(2_56 ).unsqueeze(0 ) with torch.no_grad(): __lowerCAmelCase = model(SCREAMING_SNAKE_CASE__ )[0] __lowerCAmelCase = torch.Size((1, 2_56, 7_68) ) self.assertEqual(output.shape , SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase = torch.tensor( [[[-0.0_1_4_0, 0.0_8_3_0, -0.0_3_8_1], [0.1_5_4_6, 0.1_4_0_2, 0.0_2_2_0], [0.1_1_6_2, 0.0_8_5_1, 0.0_1_6_5]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE__ , atol=1e-4 ) ) @slow def _snake_case (self ): __lowerCAmelCase = MraForMaskedLM.from_pretrained('''uw-madison/mra-base-512-4''' ) __lowerCAmelCase = torch.arange(2_56 ).unsqueeze(0 ) with torch.no_grad(): __lowerCAmelCase = model(SCREAMING_SNAKE_CASE__ )[0] __lowerCAmelCase = 5_02_65 __lowerCAmelCase = torch.Size((1, 2_56, vocab_size) ) self.assertEqual(output.shape , SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase = torch.tensor( [[[9.2_5_9_5, -3.6_0_3_8, 1_1.8_8_1_9], [9.3_8_6_9, -3.2_6_9_3, 1_1.0_9_5_6], [1_1.8_5_2_4, -3.4_9_3_8, 1_3.1_2_1_0]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE__ , atol=1e-4 ) ) @slow def _snake_case (self ): __lowerCAmelCase = MraForMaskedLM.from_pretrained('''uw-madison/mra-base-4096-8-d3''' ) __lowerCAmelCase = torch.arange(40_96 ).unsqueeze(0 ) with torch.no_grad(): __lowerCAmelCase = model(SCREAMING_SNAKE_CASE__ )[0] __lowerCAmelCase = 5_02_65 __lowerCAmelCase = torch.Size((1, 40_96, vocab_size) ) self.assertEqual(output.shape , SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase = torch.tensor( [[[5.4_7_8_9, -2.3_5_6_4, 7.5_0_6_4], [7.9_0_6_7, -1.3_3_6_9, 9.9_6_6_8], [9.0_7_1_2, -1.8_1_0_6, 7.0_3_8_0]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE__ , atol=1e-4 ) )
174
import unittest import numpy as np from transformers import DistilBertConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask if is_flax_available(): import jax.numpy as jnp from transformers.models.distilbert.modeling_flax_distilbert import ( FlaxDistilBertForMaskedLM, FlaxDistilBertForMultipleChoice, FlaxDistilBertForQuestionAnswering, FlaxDistilBertForSequenceClassification, FlaxDistilBertForTokenClassification, FlaxDistilBertModel, ) class A_ ( unittest.TestCase ): def __init__( self : Tuple ,SCREAMING_SNAKE_CASE__ : List[str] ,SCREAMING_SNAKE_CASE__ : Any=1_3 ,SCREAMING_SNAKE_CASE__ : int=7 ,SCREAMING_SNAKE_CASE__ : str=True ,SCREAMING_SNAKE_CASE__ : Dict=True ,SCREAMING_SNAKE_CASE__ : str=True ,SCREAMING_SNAKE_CASE__ : Dict=True ,SCREAMING_SNAKE_CASE__ : List[Any]=9_9 ,SCREAMING_SNAKE_CASE__ : List[Any]=3_2 ,SCREAMING_SNAKE_CASE__ : int=5 ,SCREAMING_SNAKE_CASE__ : List[Any]=4 ,SCREAMING_SNAKE_CASE__ : Optional[Any]=3_7 ,SCREAMING_SNAKE_CASE__ : Union[str, Any]="gelu" ,SCREAMING_SNAKE_CASE__ : int=0.1 ,SCREAMING_SNAKE_CASE__ : Optional[int]=0.1 ,SCREAMING_SNAKE_CASE__ : Optional[int]=5_1_2 ,SCREAMING_SNAKE_CASE__ : Dict=1_6 ,SCREAMING_SNAKE_CASE__ : Dict=2 ,SCREAMING_SNAKE_CASE__ : Optional[int]=0.02 ,SCREAMING_SNAKE_CASE__ : Dict=4 ,): __lowerCamelCase : int = parent __lowerCamelCase : Dict = batch_size __lowerCamelCase : Union[str, Any] = seq_length __lowerCamelCase : List[Any] = is_training __lowerCamelCase : Tuple = use_attention_mask __lowerCamelCase : List[str] = use_token_type_ids __lowerCamelCase : Any = use_labels __lowerCamelCase : List[str] = vocab_size __lowerCamelCase : Any = hidden_size __lowerCamelCase : Tuple = num_hidden_layers __lowerCamelCase : Union[str, Any] = num_attention_heads __lowerCamelCase : Union[str, Any] = intermediate_size __lowerCamelCase : List[Any] = hidden_act __lowerCamelCase : int = hidden_dropout_prob __lowerCamelCase : int = attention_probs_dropout_prob __lowerCamelCase : Union[str, Any] = max_position_embeddings __lowerCamelCase : Union[str, Any] = type_vocab_size __lowerCamelCase : List[str] = type_sequence_label_size __lowerCamelCase : Tuple = initializer_range __lowerCamelCase : Optional[int] = num_choices def lowerCAmelCase ( self : Union[str, Any]): __lowerCamelCase : Dict = ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size) __lowerCamelCase : Union[str, Any] = None if self.use_attention_mask: __lowerCamelCase : Any = random_attention_mask([self.batch_size, self.seq_length]) __lowerCamelCase : str = DistilBertConfig( vocab_size=self.vocab_size ,dim=self.hidden_size ,n_layers=self.num_hidden_layers ,n_heads=self.num_attention_heads ,hidden_dim=self.intermediate_size ,hidden_act=self.hidden_act ,dropout=self.hidden_dropout_prob ,attention_dropout=self.attention_probs_dropout_prob ,max_position_embeddings=self.max_position_embeddings ,initializer_range=self.initializer_range ,tie_weights_=SCREAMING_SNAKE_CASE__ ,) return config, input_ids, attention_mask def lowerCAmelCase ( self : List[Any]): __lowerCamelCase : List[str] = self.prepare_config_and_inputs() __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : Dict = config_and_inputs __lowerCamelCase : Any = {'input_ids': input_ids, 'attention_mask': attention_mask} return config, inputs_dict @require_flax class A_ ( SCREAMING_SNAKE_CASE , unittest.TestCase ): _UpperCAmelCase : Dict = ( ( FlaxDistilBertModel, FlaxDistilBertForMaskedLM, FlaxDistilBertForMultipleChoice, FlaxDistilBertForQuestionAnswering, FlaxDistilBertForSequenceClassification, FlaxDistilBertForTokenClassification, FlaxDistilBertForQuestionAnswering, ) if is_flax_available() else () ) def lowerCAmelCase ( self : Optional[Any]): __lowerCamelCase : Tuple = FlaxDistilBertModelTester(self) @slow def lowerCAmelCase ( self : int): for model_class_name in self.all_model_classes: __lowerCamelCase : List[Any] = model_class_name.from_pretrained('distilbert-base-uncased') __lowerCamelCase : List[str] = model(np.ones((1, 1))) self.assertIsNotNone(SCREAMING_SNAKE_CASE__) @require_flax class A_ ( unittest.TestCase ): @slow def lowerCAmelCase ( self : str): __lowerCamelCase : Union[str, Any] = FlaxDistilBertModel.from_pretrained('distilbert-base-uncased') __lowerCamelCase : str = np.array([[0, 3_4_5, 2_3_2, 3_2_8, 7_4_0, 1_4_0, 1_6_9_5, 6_9, 6_0_7_8, 1_5_8_8, 2]]) __lowerCamelCase : List[Any] = np.array([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]) __lowerCamelCase : Union[str, Any] = model(SCREAMING_SNAKE_CASE__ ,attention_mask=SCREAMING_SNAKE_CASE__)[0] __lowerCamelCase : Optional[int] = (1, 1_1, 7_6_8) self.assertEqual(output.shape ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Union[str, Any] = np.array([[[-0.1639, 0.3299, 0.1648], [-0.1746, 0.3289, 0.1710], [-0.1884, 0.3357, 0.1810]]]) self.assertTrue(jnp.allclose(output[:, 1:4, 1:4] ,SCREAMING_SNAKE_CASE__ ,atol=1E-4))
73
0
import inspect from typing import Callable, List, Optional, Union import torch from transformers import ( CLIPImageProcessor, CLIPTextModel, CLIPTokenizer, WhisperForConditionalGeneration, WhisperProcessor, ) from diffusers import ( AutoencoderKL, DDIMScheduler, DiffusionPipeline, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionModel, ) from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import StableDiffusionPipelineOutput from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker from diffusers.utils import logging snake_case_ : Any = logging.get_logger(__name__) # pylint: disable=invalid-name class __snake_case ( a ): def __init__( self : Any , _snake_case : WhisperForConditionalGeneration , _snake_case : WhisperProcessor , _snake_case : AutoencoderKL , _snake_case : CLIPTextModel , _snake_case : CLIPTokenizer , _snake_case : UNetaDConditionModel , _snake_case : Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler] , _snake_case : StableDiffusionSafetyChecker , _snake_case : CLIPImageProcessor , ): """simple docstring""" super().__init__() if safety_checker is None: logger.warning( F"""You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure""" ''' that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered''' ''' results in services or applications open to the public. Both the diffusers team and Hugging Face''' ''' strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling''' ''' it only for use-cases that involve analyzing network behavior or auditing its results. For more''' ''' information, please have a look at https://github.com/huggingface/diffusers/pull/254 .''') self.register_modules( speech_model=SCREAMING_SNAKE_CASE__ , speech_processor=SCREAMING_SNAKE_CASE__ , vae=SCREAMING_SNAKE_CASE__ , text_encoder=SCREAMING_SNAKE_CASE__ , tokenizer=SCREAMING_SNAKE_CASE__ , unet=SCREAMING_SNAKE_CASE__ , scheduler=SCREAMING_SNAKE_CASE__ , feature_extractor=SCREAMING_SNAKE_CASE__ , ) def lowerCamelCase ( self : Any , _snake_case : Optional[Union[str, int]] = "auto"): """simple docstring""" if slice_size == "auto": UpperCAmelCase_ = self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(SCREAMING_SNAKE_CASE__) def lowerCamelCase ( self : str): """simple docstring""" self.enable_attention_slicing(SCREAMING_SNAKE_CASE__) @torch.no_grad() def __call__( self : List[Any] , _snake_case : List[Any] , _snake_case : Dict=16000 , _snake_case : int = 512 , _snake_case : int = 512 , _snake_case : int = 50 , _snake_case : float = 7.5 , _snake_case : Optional[Union[str, List[str]]] = None , _snake_case : Optional[int] = 1 , _snake_case : float = 0.0 , _snake_case : Optional[torch.Generator] = None , _snake_case : Optional[torch.FloatTensor] = None , _snake_case : Optional[str] = "pil" , _snake_case : bool = True , _snake_case : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , _snake_case : int = 1 , **_snake_case : Any , ): """simple docstring""" UpperCAmelCase_ = self.speech_processor.feature_extractor( SCREAMING_SNAKE_CASE__ , return_tensors='''pt''' , sampling_rate=SCREAMING_SNAKE_CASE__).input_features.to(self.device) UpperCAmelCase_ = self.speech_model.generate(SCREAMING_SNAKE_CASE__ , max_length=480000) UpperCAmelCase_ = self.speech_processor.tokenizer.batch_decode(SCREAMING_SNAKE_CASE__ , skip_special_tokens=SCREAMING_SNAKE_CASE__ , normalize=SCREAMING_SNAKE_CASE__)[ 0 ] if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__): UpperCAmelCase_ = 1 elif isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__): UpperCAmelCase_ = len(SCREAMING_SNAKE_CASE__) else: raise ValueError(F"""`prompt` has to be of type `str` or `list` but is {type(SCREAMING_SNAKE_CASE__)}""") if height % 8 != 0 or width % 8 != 0: raise ValueError(F"""`height` and `width` have to be divisible by 8 but are {height} and {width}.""") if (callback_steps is None) or ( callback_steps is not None and (not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__) or callback_steps <= 0) ): raise ValueError( F"""`callback_steps` has to be a positive integer but is {callback_steps} of type""" F""" {type(SCREAMING_SNAKE_CASE__)}.""") # get prompt text embeddings UpperCAmelCase_ = self.tokenizer( SCREAMING_SNAKE_CASE__ , padding='''max_length''' , max_length=self.tokenizer.model_max_length , return_tensors='''pt''' , ) UpperCAmelCase_ = text_inputs.input_ids if text_input_ids.shape[-1] > self.tokenizer.model_max_length: UpperCAmelCase_ = self.tokenizer.batch_decode(text_input_ids[:, self.tokenizer.model_max_length :]) logger.warning( '''The following part of your input was truncated because CLIP can only handle sequences up to''' F""" {self.tokenizer.model_max_length} tokens: {removed_text}""") UpperCAmelCase_ = text_input_ids[:, : self.tokenizer.model_max_length] UpperCAmelCase_ = self.text_encoder(text_input_ids.to(self.device))[0] # duplicate text embeddings for each generation per prompt, using mps friendly method UpperCAmelCase_ = text_embeddings.shape UpperCAmelCase_ = text_embeddings.repeat(1 , SCREAMING_SNAKE_CASE__ , 1) UpperCAmelCase_ = text_embeddings.view(bs_embed * num_images_per_prompt , SCREAMING_SNAKE_CASE__ , -1) # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2) # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1` # corresponds to doing no classifier free guidance. UpperCAmelCase_ = guidance_scale > 1.0 # get unconditional embeddings for classifier free guidance if do_classifier_free_guidance: UpperCAmelCase_ = 42 if negative_prompt is None: UpperCAmelCase_ = [''] * batch_size elif type(SCREAMING_SNAKE_CASE__) is not type(SCREAMING_SNAKE_CASE__): raise TypeError( F"""`negative_prompt` should be the same type to `prompt`, but got {type(SCREAMING_SNAKE_CASE__)} !=""" F""" {type(SCREAMING_SNAKE_CASE__)}.""") elif isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__): UpperCAmelCase_ = [negative_prompt] elif batch_size != len(SCREAMING_SNAKE_CASE__): raise ValueError( F"""`negative_prompt`: {negative_prompt} has batch size {len(SCREAMING_SNAKE_CASE__)}, but `prompt`:""" F""" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches""" ''' the batch size of `prompt`.''') else: UpperCAmelCase_ = negative_prompt UpperCAmelCase_ = text_input_ids.shape[-1] UpperCAmelCase_ = self.tokenizer( SCREAMING_SNAKE_CASE__ , padding='''max_length''' , max_length=SCREAMING_SNAKE_CASE__ , truncation=SCREAMING_SNAKE_CASE__ , return_tensors='''pt''' , ) UpperCAmelCase_ = self.text_encoder(uncond_input.input_ids.to(self.device))[0] # duplicate unconditional embeddings for each generation per prompt, using mps friendly method UpperCAmelCase_ = uncond_embeddings.shape[1] UpperCAmelCase_ = uncond_embeddings.repeat(1 , SCREAMING_SNAKE_CASE__ , 1) UpperCAmelCase_ = uncond_embeddings.view(batch_size * num_images_per_prompt , SCREAMING_SNAKE_CASE__ , -1) # For classifier free guidance, we need to do two forward passes. # Here we concatenate the unconditional and text embeddings into a single batch # to avoid doing two forward passes UpperCAmelCase_ = torch.cat([uncond_embeddings, text_embeddings]) # get the initial random noise unless the user supplied it # Unlike in other pipelines, latents need to be generated in the target device # for 1-to-1 results reproducibility with the CompVis implementation. # However this currently doesn't work in `mps`. UpperCAmelCase_ = (batch_size * num_images_per_prompt, self.unet.config.in_channels, height // 8, width // 8) UpperCAmelCase_ = text_embeddings.dtype if latents is None: if self.device.type == "mps": # randn does not exist on mps UpperCAmelCase_ = torch.randn(SCREAMING_SNAKE_CASE__ , generator=SCREAMING_SNAKE_CASE__ , device='''cpu''' , dtype=SCREAMING_SNAKE_CASE__).to( self.device) else: UpperCAmelCase_ = torch.randn(SCREAMING_SNAKE_CASE__ , generator=SCREAMING_SNAKE_CASE__ , device=self.device , dtype=SCREAMING_SNAKE_CASE__) else: if latents.shape != latents_shape: raise ValueError(F"""Unexpected latents shape, got {latents.shape}, expected {latents_shape}""") UpperCAmelCase_ = latents.to(self.device) # set timesteps self.scheduler.set_timesteps(SCREAMING_SNAKE_CASE__) # Some schedulers like PNDM have timesteps as arrays # It's more optimized to move all timesteps to correct device beforehand UpperCAmelCase_ = self.scheduler.timesteps.to(self.device) # scale the initial noise by the standard deviation required by the scheduler UpperCAmelCase_ = latents * self.scheduler.init_noise_sigma # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 # and should be between [0, 1] UpperCAmelCase_ = 'eta' in set(inspect.signature(self.scheduler.step).parameters.keys()) UpperCAmelCase_ = {} if accepts_eta: UpperCAmelCase_ = eta for i, t in enumerate(self.progress_bar(SCREAMING_SNAKE_CASE__)): # expand the latents if we are doing classifier free guidance UpperCAmelCase_ = torch.cat([latents] * 2) if do_classifier_free_guidance else latents UpperCAmelCase_ = self.scheduler.scale_model_input(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__) # predict the noise residual UpperCAmelCase_ = self.unet(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , encoder_hidden_states=SCREAMING_SNAKE_CASE__).sample # perform guidance if do_classifier_free_guidance: UpperCAmelCase_ = noise_pred.chunk(2) UpperCAmelCase_ = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) # compute the previous noisy sample x_t -> x_t-1 UpperCAmelCase_ = self.scheduler.step(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__).prev_sample # call the callback, if provided if callback is not None and i % callback_steps == 0: callback(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__) UpperCAmelCase_ = 1 / 0.1_8_2_1_5 * latents UpperCAmelCase_ = self.vae.decode(SCREAMING_SNAKE_CASE__).sample UpperCAmelCase_ = (image / 2 + 0.5).clamp(0 , 1) # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16 UpperCAmelCase_ = image.cpu().permute(0 , 2 , 3 , 1).float().numpy() if output_type == "pil": UpperCAmelCase_ = self.numpy_to_pil(SCREAMING_SNAKE_CASE__) if not return_dict: return image return StableDiffusionPipelineOutput(images=SCREAMING_SNAKE_CASE__ , nsfw_content_detected=SCREAMING_SNAKE_CASE__)
51
import csv import tweepy # Twitter API credentials a ="""""" a ="""""" a ="""""" a ="""""" def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> None: # authorize twitter, initialize tweepy __lowerCamelCase : Tuple = tweepy.OAuthHandler(lowerCamelCase__ , lowerCamelCase__ ) auth.set_access_token(lowerCamelCase__ , lowerCamelCase__ ) __lowerCamelCase : Optional[int] = tweepy.API(lowerCamelCase__ ) # initialize a list to hold all the tweepy Tweets __lowerCamelCase : str = [] # make initial request for most recent tweets (200 is the maximum allowed count) __lowerCamelCase : Union[str, Any] = api.user_timeline(screen_name=lowerCamelCase__ , count=2_0_0 ) # save most recent tweets alltweets.extend(lowerCamelCase__ ) # save the id of the oldest tweet less one __lowerCamelCase : Any = alltweets[-1].id - 1 # keep grabbing tweets until there are no tweets left to grab while len(lowerCamelCase__ ) > 0: print(F"getting tweets before {oldest}" ) # all subsequent requests use the max_id param to prevent duplicates __lowerCamelCase : str = api.user_timeline( screen_name=lowerCamelCase__ , count=2_0_0 , max_id=lowerCamelCase__ ) # save most recent tweets alltweets.extend(lowerCamelCase__ ) # update the id of the oldest tweet less one __lowerCamelCase : Optional[int] = alltweets[-1].id - 1 print(F"...{len(lowerCamelCase__ )} tweets downloaded so far" ) # transform the tweepy tweets into a 2D array that will populate the csv __lowerCamelCase : str = [[tweet.id_str, tweet.created_at, tweet.text] for tweet in alltweets] # write the csv with open(F"new_{screen_name}_tweets.csv" , 'w' ) as f: __lowerCamelCase : Any = csv.writer(lowerCamelCase__ ) writer.writerow(['id', 'created_at', 'text'] ) writer.writerows(lowerCamelCase__ ) if __name__ == "__main__": # pass in the username of the account you want to download get_all_tweets("""FirePing32""")
73
0
import csv from collections import defaultdict from dataclasses import dataclass, field from typing import List, Optional import matplotlib.pyplot as plt import numpy as np from matplotlib.ticker import ScalarFormatter from transformers import HfArgumentParser def _lowercase ( UpperCamelCase_=None , UpperCamelCase_=None ) -> Any: '''simple docstring''' return field(default_factory=lambda: default , metadata=lowerCamelCase__ ) @dataclass class lowercase__ : A__ : str =field( metadata={"""help""": """The csv file to plot."""} , ) A__ : bool =field( default=_UpperCAmelCase , metadata={"""help""": """Whether to plot along batch size or sequence length. Defaults to sequence length."""} , ) A__ : bool =field( default=_UpperCAmelCase , metadata={"""help""": """Whether the csv file has time results or memory results. Defaults to memory results."""} , ) A__ : bool =field( default=_UpperCAmelCase , metadata={"""help""": """Disable logarithmic scale when plotting"""} , ) A__ : bool =field( default=_UpperCAmelCase , metadata={ """help""": """Whether the csv file has training results or inference results. Defaults to inference results.""" } , ) A__ : Optional[str] =field( default=_UpperCAmelCase , metadata={"""help""": """Filename under which the plot will be saved. If unused no plot is saved."""} , ) A__ : Optional[List[str]] =list_field( default=_UpperCAmelCase , metadata={"""help""": """List of model names that are used instead of the ones in the csv file."""} ) def _lowercase ( UpperCamelCase_ ) -> Any: '''simple docstring''' try: int(lowerCamelCase__ ) return True except ValueError: return False def _lowercase ( UpperCamelCase_ ) -> List[Any]: '''simple docstring''' try: float(lowerCamelCase__ ) return True except ValueError: return False class lowercase__ : def __init__( self : Optional[int] , UpperCAmelCase_ : Dict ): SCREAMING_SNAKE_CASE__ = args SCREAMING_SNAKE_CASE__ = defaultdict(lambda: {"bsz": [], "seq_len": [], "result": {}} ) with open(self.args.csv_file , newline='' ) as csv_file: SCREAMING_SNAKE_CASE__ = csv.DictReader(SCREAMING_SNAKE_CASE__ ) for row in reader: SCREAMING_SNAKE_CASE__ = row['model'] self.result_dict[model_name]["bsz"].append(int(row['batch_size'] ) ) self.result_dict[model_name]["seq_len"].append(int(row['sequence_length'] ) ) if can_convert_to_int(row['result'] ): # value is not None SCREAMING_SNAKE_CASE__ = int(row['result'] ) elif can_convert_to_float(row['result'] ): # value is not None SCREAMING_SNAKE_CASE__ = float(row['result'] ) def A_ ( self : List[str] ): SCREAMING_SNAKE_CASE__ = plt.subplots() SCREAMING_SNAKE_CASE__ = 'Time usage' if self.args.is_time else 'Memory usage' SCREAMING_SNAKE_CASE__ = title_str + ' for training' if self.args.is_train else title_str + ' for inference' if not self.args.no_log_scale: # set logarithm scales ax.set_xscale('log' ) ax.set_yscale('log' ) for axis in [ax.xaxis, ax.yaxis]: axis.set_major_formatter(ScalarFormatter() ) for model_name_idx, model_name in enumerate(self.result_dict.keys() ): SCREAMING_SNAKE_CASE__ = sorted(set(self.result_dict[model_name]['bsz'] ) ) SCREAMING_SNAKE_CASE__ = sorted(set(self.result_dict[model_name]['seq_len'] ) ) SCREAMING_SNAKE_CASE__ = self.result_dict[model_name]['result'] (SCREAMING_SNAKE_CASE__) = ( (batch_sizes, sequence_lengths) if self.args.plot_along_batch else (sequence_lengths, batch_sizes) ) SCREAMING_SNAKE_CASE__ = ( model_name if self.args.short_model_names is None else self.args.short_model_names[model_name_idx] ) for inner_loop_value in inner_loop_array: if self.args.plot_along_batch: SCREAMING_SNAKE_CASE__ = np.asarray( [results[(x, inner_loop_value)] for x in x_axis_array if (x, inner_loop_value) in results] , dtype=SCREAMING_SNAKE_CASE__ , ) else: SCREAMING_SNAKE_CASE__ = np.asarray( [results[(inner_loop_value, x)] for x in x_axis_array if (inner_loop_value, x) in results] , dtype=np.floataa , ) (SCREAMING_SNAKE_CASE__) = ( ('batch_size', 'len') if self.args.plot_along_batch else ('in #tokens', 'bsz') ) SCREAMING_SNAKE_CASE__ = np.asarray(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )[: len(SCREAMING_SNAKE_CASE__ )] plt.scatter( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , label=F'{label_model_name} - {inner_loop_label}: {inner_loop_value}' ) plt.plot(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , '--' ) title_str += F' {label_model_name} vs.' SCREAMING_SNAKE_CASE__ = title_str[:-4] SCREAMING_SNAKE_CASE__ = 'Time in s' if self.args.is_time else 'Memory in MB' # plot plt.title(SCREAMING_SNAKE_CASE__ ) plt.xlabel(SCREAMING_SNAKE_CASE__ ) plt.ylabel(SCREAMING_SNAKE_CASE__ ) plt.legend() if self.args.figure_png_file is not None: plt.savefig(self.args.figure_png_file ) else: plt.show() def _lowercase ( ) -> Dict: '''simple docstring''' SCREAMING_SNAKE_CASE__ = HfArgumentParser(lowerCamelCase__ ) SCREAMING_SNAKE_CASE__ = parser.parse_args_into_dataclasses()[0] SCREAMING_SNAKE_CASE__ = Plot(args=lowerCamelCase__ ) plot.plot() if __name__ == "__main__": main()
176
import numpy as np from scipy.spatial.distance import cdist from sklearn.metrics import fa_score import datasets a ="""\ @inproceedings{kakwani2020indicnlpsuite, title={{IndicNLPSuite: Monolingual Corpora, Evaluation Benchmarks and Pre-trained Multilingual Language Models for Indian Languages}}, author={Divyanshu Kakwani and Anoop Kunchukuttan and Satish Golla and Gokul N.C. and Avik Bhattacharyya and Mitesh M. Khapra and Pratyush Kumar}, year={2020}, booktitle={Findings of EMNLP}, } """ a ="""\ IndicGLUE is a natural language understanding benchmark for Indian languages. It contains a wide variety of tasks and covers 11 major Indian languages - as, bn, gu, hi, kn, ml, mr, or, pa, ta, te. """ a =""" Compute IndicGLUE evaluation metric associated to each IndicGLUE dataset. Args: predictions: list of predictions to score (as int64), except for 'cvit-mkb-clsr' where each prediction is a vector (of float32). references: list of ground truth labels corresponding to the predictions (as int64), except for 'cvit-mkb-clsr' where each reference is a vector (of float32). Returns: depending on the IndicGLUE subset, one or several of: \"accuracy\": Accuracy \"f1\": F1 score \"precision\": Precision@10 Examples: >>> indic_glue_metric = datasets.load_metric('indic_glue', 'wnli') # 'wnli' or any of [\"copa\", \"sna\", \"csqa\", \"wstp\", \"inltkh\", \"bbca\", \"iitp-mr\", \"iitp-pr\", \"actsa-sc\", \"md\"] >>> references = [0, 1] >>> predictions = [0, 1] >>> results = indic_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {'accuracy': 1.0} >>> indic_glue_metric = datasets.load_metric('indic_glue', 'wiki-ner') >>> references = [0, 1] >>> predictions = [0, 1] >>> results = indic_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {'accuracy': 1.0, 'f1': 1.0} >>> indic_glue_metric = datasets.load_metric('indic_glue', 'cvit-mkb-clsr') >>> references = [[0.5, 0.5, 0.5], [0.1, 0.2, 0.3]] >>> predictions = [[0.5, 0.5, 0.5], [0.1, 0.2, 0.3]] >>> results = indic_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {'precision@10': 1.0} """ def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> List[str]: return float((preds == labels).mean() ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> List[str]: __lowerCamelCase : Optional[Any] = simple_accuracy(lowerCamelCase__ , lowerCamelCase__ ) __lowerCamelCase : Tuple = float(fa_score(y_true=lowerCamelCase__ , y_pred=lowerCamelCase__ ) ) return { "accuracy": acc, "f1": fa, } def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> Optional[Any]: __lowerCamelCase : Any = np.array(lowerCamelCase__ ) __lowerCamelCase : List[Any] = np.array(lowerCamelCase__ ) __lowerCamelCase : Any = en_sentvecs.shape[0] # mean centering __lowerCamelCase : Union[str, Any] = en_sentvecs - np.mean(lowerCamelCase__ , axis=0 ) __lowerCamelCase : Dict = in_sentvecs - np.mean(lowerCamelCase__ , axis=0 ) __lowerCamelCase : Optional[int] = cdist(lowerCamelCase__ , lowerCamelCase__ , 'cosine' ) __lowerCamelCase : Optional[Any] = np.array(range(lowerCamelCase__ ) ) __lowerCamelCase : Dict = sim.argsort(axis=1 )[:, :1_0] __lowerCamelCase : Optional[int] = np.any(preds == actual[:, None] , axis=1 ) return float(matches.mean() ) @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class A_ ( datasets.Metric ): def lowerCAmelCase ( self : Optional[Any]): if self.config_name not in [ "wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", "cvit-mkb-clsr", "iitp-mr", "iitp-pr", "actsa-sc", "md", "wiki-ner", ]: raise KeyError( 'You should supply a configuration name selected in ' '["wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", ' '"cvit-mkb-clsr", "iitp-mr", "iitp-pr", "actsa-sc", "md", ' '"wiki-ner"]') return datasets.MetricInfo( description=_DESCRIPTION ,citation=_CITATION ,inputs_description=_KWARGS_DESCRIPTION ,features=datasets.Features( { 'predictions': datasets.Value('int64') if self.config_name != 'cvit-mkb-clsr' else datasets.Sequence(datasets.Value('float32')), 'references': datasets.Value('int64') if self.config_name != 'cvit-mkb-clsr' else datasets.Sequence(datasets.Value('float32')), }) ,codebase_urls=[] ,reference_urls=[] ,format='numpy' if self.config_name != 'cvit-mkb-clsr' else None ,) def lowerCAmelCase ( self : Any ,SCREAMING_SNAKE_CASE__ : Tuple ,SCREAMING_SNAKE_CASE__ : Optional[Any]): if self.config_name == "cvit-mkb-clsr": return {"precision@10": precision_at_aa(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__)} elif self.config_name in ["wiki-ner"]: return acc_and_fa(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) elif self.config_name in [ "wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", "iitp-mr", "iitp-pr", "actsa-sc", "md", ]: return {"accuracy": simple_accuracy(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__)} else: raise KeyError( 'You should supply a configuration name selected in ' '["wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", ' '"cvit-mkb-clsr", "iitp-mr", "iitp-pr", "actsa-sc", "md", ' '"wiki-ner"]')
73
0
import numpy as np from scipy.spatial.distance import cdist from sklearn.metrics import fa_score import datasets __lowerCAmelCase : str = '\\n @inproceedings{kakwani2020indicnlpsuite,\n title={{IndicNLPSuite: Monolingual Corpora, Evaluation Benchmarks and Pre-trained Multilingual Language Models for Indian Languages}},\n author={Divyanshu Kakwani and Anoop Kunchukuttan and Satish Golla and Gokul N.C. and Avik Bhattacharyya and Mitesh M. Khapra and Pratyush Kumar},\n year={2020},\n booktitle={Findings of EMNLP},\n}\n' __lowerCAmelCase : Any = '\\n IndicGLUE is a natural language understanding benchmark for Indian languages. It contains a wide\n variety of tasks and covers 11 major Indian languages - as, bn, gu, hi, kn, ml, mr, or, pa, ta, te.\n' __lowerCAmelCase : Union[str, Any] = '\nCompute IndicGLUE evaluation metric associated to each IndicGLUE dataset.\nArgs:\n predictions: list of predictions to score (as int64),\n except for \'cvit-mkb-clsr\' where each prediction is a vector (of float32).\n references: list of ground truth labels corresponding to the predictions (as int64),\n except for \'cvit-mkb-clsr\' where each reference is a vector (of float32).\nReturns: depending on the IndicGLUE subset, one or several of:\n \"accuracy\": Accuracy\n \"f1\": F1 score\n \"precision\": Precision@10\nExamples:\n\n >>> indic_glue_metric = datasets.load_metric(\'indic_glue\', \'wnli\') # \'wnli\' or any of [\"copa\", \"sna\", \"csqa\", \"wstp\", \"inltkh\", \"bbca\", \"iitp-mr\", \"iitp-pr\", \"actsa-sc\", \"md\"]\n >>> references = [0, 1]\n >>> predictions = [0, 1]\n >>> results = indic_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'accuracy\': 1.0}\n\n >>> indic_glue_metric = datasets.load_metric(\'indic_glue\', \'wiki-ner\')\n >>> references = [0, 1]\n >>> predictions = [0, 1]\n >>> results = indic_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'accuracy\': 1.0, \'f1\': 1.0}\n\n >>> indic_glue_metric = datasets.load_metric(\'indic_glue\', \'cvit-mkb-clsr\')\n >>> references = [[0.5, 0.5, 0.5], [0.1, 0.2, 0.3]]\n >>> predictions = [[0.5, 0.5, 0.5], [0.1, 0.2, 0.3]]\n >>> results = indic_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'precision@10\': 1.0}\n\n' def __magic_name__ ( A : Optional[Any], A : List[Any] ): '''simple docstring''' return float((preds == labels).mean() ) def __magic_name__ ( A : Tuple, A : Optional[int] ): '''simple docstring''' a = simple_accuracy(lowerCamelCase__, lowerCamelCase__ ) a = float(fa_score(y_true=lowerCamelCase__, y_pred=lowerCamelCase__ ) ) return { "accuracy": acc, "f1": fa, } def __magic_name__ ( A : Tuple, A : Any ): '''simple docstring''' a = np.array(lowerCamelCase__ ) a = np.array(lowerCamelCase__ ) a = en_sentvecs.shape[0] # mean centering a = en_sentvecs - np.mean(lowerCamelCase__, axis=0 ) a = in_sentvecs - np.mean(lowerCamelCase__, axis=0 ) a = cdist(lowerCamelCase__, lowerCamelCase__, "cosine" ) a = np.array(range(lowerCamelCase__ ) ) a = sim.argsort(axis=1 )[:, :10] a = np.any(preds == actual[:, None], axis=1 ) return float(matches.mean() ) @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class snake_case__ (datasets.Metric ): """simple docstring""" def __UpperCAmelCase ( self : Optional[Any] ) -> int: if self.config_name not in [ "wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", "cvit-mkb-clsr", "iitp-mr", "iitp-pr", "actsa-sc", "md", "wiki-ner", ]: raise KeyError( "You should supply a configuration name selected in " "[\"wnli\", \"copa\", \"sna\", \"csqa\", \"wstp\", \"inltkh\", \"bbca\", " "\"cvit-mkb-clsr\", \"iitp-mr\", \"iitp-pr\", \"actsa-sc\", \"md\", " "\"wiki-ner\"]" ) return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "predictions": datasets.Value("int64" ) if self.config_name != "cvit-mkb-clsr" else datasets.Sequence(datasets.Value("float32" ) ), "references": datasets.Value("int64" ) if self.config_name != "cvit-mkb-clsr" else datasets.Sequence(datasets.Value("float32" ) ), } ) , codebase_urls=[] , reference_urls=[] , format="numpy" if self.config_name != "cvit-mkb-clsr" else None , ) def __UpperCAmelCase ( self : Any , __lowerCamelCase : Tuple , __lowerCamelCase : Optional[Any] ) -> Union[str, Any]: if self.config_name == "cvit-mkb-clsr": return {"precision@10": precision_at_aa(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )} elif self.config_name in ["wiki-ner"]: return acc_and_fa(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) elif self.config_name in [ "wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", "iitp-mr", "iitp-pr", "actsa-sc", "md", ]: return {"accuracy": simple_accuracy(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )} else: raise KeyError( "You should supply a configuration name selected in " "[\"wnli\", \"copa\", \"sna\", \"csqa\", \"wstp\", \"inltkh\", \"bbca\", " "\"cvit-mkb-clsr\", \"iitp-mr\", \"iitp-pr\", \"actsa-sc\", \"md\", " "\"wiki-ner\"]" )
107
from __future__ import annotations from scipy.special import comb # type: ignore class A_ : def __init__( self : List[str] ,SCREAMING_SNAKE_CASE__ : list[tuple[float, float]]): __lowerCamelCase : Union[str, Any] = list_of_points # Degree determines the flexibility of the curve. # Degree = 1 will produce a straight line. __lowerCamelCase : int = len(SCREAMING_SNAKE_CASE__) - 1 def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : float): assert 0 <= t <= 1, "Time t must be between 0 and 1." __lowerCamelCase : list[float] = [] for i in range(len(self.list_of_points)): # basis function for each i output_values.append( comb(self.degree ,SCREAMING_SNAKE_CASE__) * ((1 - t) ** (self.degree - i)) * (t**i)) # the basis must sum up to 1 for it to produce a valid Bezier curve. assert round(sum(SCREAMING_SNAKE_CASE__) ,5) == 1 return output_values def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : float): assert 0 <= t <= 1, "Time t must be between 0 and 1." __lowerCamelCase : Tuple = self.basis_function(SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = 0.0 __lowerCamelCase : Optional[Any] = 0.0 for i in range(len(self.list_of_points)): # For all points, sum up the product of i-th basis function and i-th point. x += basis_function[i] * self.list_of_points[i][0] y += basis_function[i] * self.list_of_points[i][1] return (x, y) def lowerCAmelCase ( self : int ,SCREAMING_SNAKE_CASE__ : float = 0.01): from matplotlib import pyplot as plt # type: ignore __lowerCamelCase : list[float] = [] # x coordinates of points to plot __lowerCamelCase : list[float] = [] # y coordinates of points to plot __lowerCamelCase : Any = 0.0 while t <= 1: __lowerCamelCase : List[Any] = self.bezier_curve_function(SCREAMING_SNAKE_CASE__) to_plot_x.append(value[0]) to_plot_y.append(value[1]) t += step_size __lowerCamelCase : Optional[Any] = [i[0] for i in self.list_of_points] __lowerCamelCase : List[str] = [i[1] for i in self.list_of_points] plt.plot( SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,color='blue' ,label='Curve of Degree ' + str(self.degree) ,) plt.scatter(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,color='red' ,label='Control Points') plt.legend() plt.show() if __name__ == "__main__": import doctest doctest.testmod() BezierCurve([(1, 2), (3, 5)]).plot_curve() # degree 1 BezierCurve([(0, 0), (5, 5), (5, 0)]).plot_curve() # degree 2 BezierCurve([(0, 0), (5, 5), (5, 0), (2.5, -2.5)]).plot_curve() # degree 3
73
0
from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCamelCase = logging.get_logger(__name__) UpperCamelCase = { '''transfo-xl-wt103''': '''https://huggingface.co/transfo-xl-wt103/resolve/main/config.json''', } class __UpperCAmelCase (_UpperCAmelCase ): __snake_case : Any = '''transfo-xl''' __snake_case : Union[str, Any] = ['''mems'''] __snake_case : List[Any] = { '''n_token''': '''vocab_size''', '''hidden_size''': '''d_model''', '''num_attention_heads''': '''n_head''', '''num_hidden_layers''': '''n_layer''', } def __init__( self: List[Any] , UpperCAmelCase_: Optional[int]=267_735 , UpperCAmelCase_: List[Any]=[20_000, 40_000, 200_000] , UpperCAmelCase_: List[Any]=1_024 , UpperCAmelCase_: Optional[int]=1_024 , UpperCAmelCase_: int=16 , UpperCAmelCase_: List[str]=64 , UpperCAmelCase_: Any=4_096 , UpperCAmelCase_: int=4 , UpperCAmelCase_: List[Any]=False , UpperCAmelCase_: List[str]=18 , UpperCAmelCase_: Any=1_600 , UpperCAmelCase_: List[Any]=1_000 , UpperCAmelCase_: Optional[Any]=True , UpperCAmelCase_: Union[str, Any]=True , UpperCAmelCase_: Tuple=0 , UpperCAmelCase_: str=-1 , UpperCAmelCase_: Union[str, Any]=True , UpperCAmelCase_: int=0.1 , UpperCAmelCase_: Union[str, Any]=0.0 , UpperCAmelCase_: List[Any]=True , UpperCAmelCase_: Optional[Any]="normal" , UpperCAmelCase_: List[Any]=0.01 , UpperCAmelCase_: Dict=0.01 , UpperCAmelCase_: List[Any]=0.02 , UpperCAmelCase_: Dict=1E-5 , UpperCAmelCase_: List[str]=0 , **UpperCAmelCase_: List[Any] , ): '''simple docstring''' _SCREAMING_SNAKE_CASE = vocab_size _SCREAMING_SNAKE_CASE = [] self.cutoffs.extend(SCREAMING_SNAKE_CASE__ ) if proj_share_all_but_first: _SCREAMING_SNAKE_CASE = [False] + [True] * len(self.cutoffs ) else: _SCREAMING_SNAKE_CASE = [False] + [False] * len(self.cutoffs ) _SCREAMING_SNAKE_CASE = d_model _SCREAMING_SNAKE_CASE = d_embed _SCREAMING_SNAKE_CASE = d_head _SCREAMING_SNAKE_CASE = d_inner _SCREAMING_SNAKE_CASE = div_val _SCREAMING_SNAKE_CASE = pre_lnorm _SCREAMING_SNAKE_CASE = n_layer _SCREAMING_SNAKE_CASE = n_head _SCREAMING_SNAKE_CASE = mem_len _SCREAMING_SNAKE_CASE = same_length _SCREAMING_SNAKE_CASE = attn_type _SCREAMING_SNAKE_CASE = clamp_len _SCREAMING_SNAKE_CASE = sample_softmax _SCREAMING_SNAKE_CASE = adaptive _SCREAMING_SNAKE_CASE = dropout _SCREAMING_SNAKE_CASE = dropatt _SCREAMING_SNAKE_CASE = untie_r _SCREAMING_SNAKE_CASE = init _SCREAMING_SNAKE_CASE = init_range _SCREAMING_SNAKE_CASE = proj_init_std _SCREAMING_SNAKE_CASE = init_std _SCREAMING_SNAKE_CASE = layer_norm_epsilon super().__init__(eos_token_id=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) @property def UpperCamelCase ( self: List[Any] ): '''simple docstring''' logger.info(F'The model {self.model_type} is one of the few models that has no sequence length limit.' ) return -1 @max_position_embeddings.setter def UpperCamelCase ( self: str , UpperCAmelCase_: Dict ): '''simple docstring''' raise NotImplementedError( F'The model {self.model_type} is one of the few models that has no sequence length limit.' )
306
from __future__ import annotations import time a =list[tuple[int, int]] a =[ [0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles [0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0], [1, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0], ] a =[[-1, 0], [0, -1], [1, 0], [0, 1]] # up, left, down, right class A_ : def __init__( self : List[str] ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : Node | None): __lowerCamelCase : Tuple = pos_x __lowerCamelCase : List[str] = pos_y __lowerCamelCase : str = (pos_y, pos_x) __lowerCamelCase : str = goal_x __lowerCamelCase : int = goal_y __lowerCamelCase : List[Any] = parent class A_ : def __init__( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : tuple[int, int] ,SCREAMING_SNAKE_CASE__ : tuple[int, int]): __lowerCamelCase : Any = Node(start[1] ,start[0] ,goal[1] ,goal[0] ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = Node(goal[1] ,goal[0] ,goal[1] ,goal[0] ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Union[str, Any] = [self.start] __lowerCamelCase : List[str] = False def lowerCAmelCase ( self : List[Any]): while self.node_queue: __lowerCamelCase : Any = self.node_queue.pop(0) if current_node.pos == self.target.pos: __lowerCamelCase : Dict = True return self.retrace_path(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Tuple = self.get_successors(SCREAMING_SNAKE_CASE__) for node in successors: self.node_queue.append(SCREAMING_SNAKE_CASE__) if not self.reached: return [self.start.pos] return None def lowerCAmelCase ( self : str ,SCREAMING_SNAKE_CASE__ : Node): __lowerCamelCase : Union[str, Any] = [] for action in delta: __lowerCamelCase : Optional[Any] = parent.pos_x + action[1] __lowerCamelCase : Optional[int] = parent.pos_y + action[0] if not (0 <= pos_x <= len(grid[0]) - 1 and 0 <= pos_y <= len(SCREAMING_SNAKE_CASE__) - 1): continue if grid[pos_y][pos_x] != 0: continue successors.append( Node(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,self.target.pos_y ,self.target.pos_x ,SCREAMING_SNAKE_CASE__)) return successors def lowerCAmelCase ( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : Node | None): __lowerCamelCase : List[Any] = node __lowerCamelCase : int = [] while current_node is not None: path.append((current_node.pos_y, current_node.pos_x)) __lowerCamelCase : int = current_node.parent path.reverse() return path class A_ : def __init__( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : int): __lowerCamelCase : int = BreadthFirstSearch(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = BreadthFirstSearch(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = False def lowerCAmelCase ( self : str): while self.fwd_bfs.node_queue or self.bwd_bfs.node_queue: __lowerCamelCase : Any = self.fwd_bfs.node_queue.pop(0) __lowerCamelCase : Any = self.bwd_bfs.node_queue.pop(0) if current_bwd_node.pos == current_fwd_node.pos: __lowerCamelCase : List[str] = True return self.retrace_bidirectional_path( SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = current_bwd_node __lowerCamelCase : int = current_fwd_node __lowerCamelCase : str = { self.fwd_bfs: self.fwd_bfs.get_successors(SCREAMING_SNAKE_CASE__), self.bwd_bfs: self.bwd_bfs.get_successors(SCREAMING_SNAKE_CASE__), } for bfs in [self.fwd_bfs, self.bwd_bfs]: for node in successors[bfs]: bfs.node_queue.append(SCREAMING_SNAKE_CASE__) if not self.reached: return [self.fwd_bfs.start.pos] return None def lowerCAmelCase ( self : Dict ,SCREAMING_SNAKE_CASE__ : Node ,SCREAMING_SNAKE_CASE__ : Node): __lowerCamelCase : List[Any] = self.fwd_bfs.retrace_path(SCREAMING_SNAKE_CASE__) __lowerCamelCase : str = self.bwd_bfs.retrace_path(SCREAMING_SNAKE_CASE__) bwd_path.pop() bwd_path.reverse() __lowerCamelCase : List[Any] = fwd_path + bwd_path return path if __name__ == "__main__": # all coordinates are given in format [y,x] import doctest doctest.testmod() a =(0, 0) a =(len(grid) - 1, len(grid[0]) - 1) for elem in grid: print(elem) a =time.time() a =BreadthFirstSearch(init, goal) a =bfs.search() a =time.time() - start_bfs_time print("""Unidirectional BFS computation time : """, bfs_time) a =time.time() a =BidirectionalBreadthFirstSearch(init, goal) a =bd_bfs.search() a =time.time() - start_bd_bfs_time print("""Bidirectional BFS computation time : """, bd_bfs_time)
73
0
import argparse import json import numpy import torch from transformers.models.xlm.tokenization_xlm import VOCAB_FILES_NAMES from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging logging.set_verbosity_info() def lowercase ( SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Any ) -> Any: # Load checkpoint _snake_case : Union[str, Any] = torch.load(lowerCamelCase__ , map_location="""cpu""" ) _snake_case : Dict = chkpt['model'] # We have the base model one level deeper than the original XLM repository _snake_case : Any = {} for k, v in state_dict.items(): if "pred_layer" in k: _snake_case : int = v else: _snake_case : List[Any] = v _snake_case : Any = chkpt['params'] _snake_case : List[Any] = {n: v for n, v in config.items() if not isinstance(lowerCamelCase__ , (torch.FloatTensor, numpy.ndarray) )} _snake_case : Union[str, Any] = chkpt['dico_word2id'] _snake_case : Union[str, Any] = {s + '</w>' if s.find("""@@""" ) == -1 and i > 13 else s.replace("""@@""" , """""" ): i for s, i in vocab.items()} # Save pytorch-model _snake_case : Tuple = pytorch_dump_folder_path + '/' + WEIGHTS_NAME _snake_case : List[Any] = pytorch_dump_folder_path + '/' + CONFIG_NAME _snake_case : List[str] = pytorch_dump_folder_path + '/' + VOCAB_FILES_NAMES['vocab_file'] print(F'''Save PyTorch model to {pytorch_weights_dump_path}''' ) torch.save(lowerCamelCase__ , lowerCamelCase__ ) print(F'''Save configuration file to {pytorch_config_dump_path}''' ) with open(lowerCamelCase__ , """w""" , encoding="""utf-8""" ) as f: f.write(json.dumps(lowerCamelCase__ , indent=2 ) + """\n""" ) print(F'''Save vocab file to {pytorch_config_dump_path}''' ) with open(lowerCamelCase__ , """w""" , encoding="""utf-8""" ) as f: f.write(json.dumps(lowerCamelCase__ , indent=2 ) + """\n""" ) if __name__ == "__main__": a__ = argparse.ArgumentParser() # Required parameters parser.add_argument( """--xlm_checkpoint_path""", default=None, type=str, required=True, help="""Path the official PyTorch dump.""" ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model.""" ) a__ = parser.parse_args() convert_xlm_checkpoint_to_pytorch(args.xlm_checkpoint_path, args.pytorch_dump_folder_path)
317
import qiskit def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> qiskit.result.counts.Counts: __lowerCamelCase : Optional[int] = qiskit.Aer.get_backend('aer_simulator' ) # Create a Quantum Circuit acting on the q register __lowerCamelCase : List[str] = qiskit.QuantumCircuit(lowerCamelCase__ , lowerCamelCase__ ) # Map the quantum measurement to the classical bits circuit.measure([0] , [0] ) # Execute the circuit on the simulator __lowerCamelCase : List[Any] = qiskit.execute(lowerCamelCase__ , lowerCamelCase__ , shots=1_0_0_0 ) # Return the histogram data of the results of the experiment. return job.result().get_counts(lowerCamelCase__ ) if __name__ == "__main__": print(F"""Total count for various states are: {single_qubit_measure(1, 1)}""")
73
0
'''simple docstring''' from math import isclose, sqrt def __lowercase ( __lowercase , __lowercase , __lowercase ) -> tuple[float, float, float]: '''simple docstring''' _A = point_y / 4 / point_x _A = 2 * normal_gradient / (1 + normal_gradient * normal_gradient) _A = (1 - normal_gradient * normal_gradient) / ( 1 + normal_gradient * normal_gradient ) _A = (sa - ca * incoming_gradient) / (ca + sa * incoming_gradient) # to find the next point, solve the simultaeneous equations: # y^2 + 4x^2 = 100 # y - b = m * (x - a) # ==> A x^2 + B x + C = 0 _A = outgoing_gradient**2 + 4 _A = 2 * outgoing_gradient * (point_y - outgoing_gradient * point_x) _A = (point_y - outgoing_gradient * point_x) ** 2 - 100 _A = ( -linear_term - sqrt(linear_term**2 - 4 * quadratic_term * constant_term ) ) / (2 * quadratic_term) _A = ( -linear_term + sqrt(linear_term**2 - 4 * quadratic_term * constant_term ) ) / (2 * quadratic_term) # two solutions, one of which is our input point _A = x_minus if isclose(lowerCamelCase__ , lowerCamelCase__ ) else x_plus _A = point_y + outgoing_gradient * (next_x - point_x) return next_x, next_y, outgoing_gradient def __lowercase ( __lowercase = 1.4 , __lowercase = -9.6 ) -> int: '''simple docstring''' _A = 0 _A = first_x_coord _A = first_y_coord _A = (10.1 - point_y) / (0.0 - point_x) while not (-0.01 <= point_x <= 0.01 and point_y > 0): _A = next_point(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) num_reflections += 1 return num_reflections if __name__ == "__main__": print(F"""{solution() = }""")
79
import os import sys a =os.path.join(os.path.dirname(__file__), """src""") sys.path.append(SRC_DIR) from transformers import ( AutoConfig, AutoModel, AutoModelForCausalLM, AutoModelForMaskedLM, AutoModelForQuestionAnswering, AutoModelForSequenceClassification, AutoTokenizer, add_start_docstrings, ) a =[ """torch""", """numpy""", """tokenizers""", """filelock""", """requests""", """tqdm""", """regex""", """sentencepiece""", """sacremoses""", """importlib_metadata""", """huggingface_hub""", ] @add_start_docstrings(AutoConfig.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> int: return AutoConfig.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ ) @add_start_docstrings(AutoTokenizer.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> Optional[Any]: return AutoTokenizer.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ ) @add_start_docstrings(AutoModel.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> List[str]: return AutoModel.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ ) @add_start_docstrings(AutoModelForCausalLM.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> Any: return AutoModelForCausalLM.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ ) @add_start_docstrings(AutoModelForMaskedLM.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> List[str]: return AutoModelForMaskedLM.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ ) @add_start_docstrings(AutoModelForSequenceClassification.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> List[str]: return AutoModelForSequenceClassification.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ ) @add_start_docstrings(AutoModelForQuestionAnswering.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> Tuple: return AutoModelForQuestionAnswering.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ )
73
0
from manim import * class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__): def _snake_case ( self )-> Union[str, Any]: lowerCamelCase_ =Rectangle(height=0.5 , width=0.5 ) lowerCamelCase_ =Rectangle(height=0.2_5 , width=0.2_5 ) lowerCamelCase_ =Rectangle(height=0.4_6 , width=0.4_6 ).set_stroke(width=0 ) lowerCamelCase_ =[mem.copy() for i in range(6 )] lowerCamelCase_ =[mem.copy() for i in range(6 )] lowerCamelCase_ =VGroup(*SCREAMING_SNAKE_CASE__ ).arrange(SCREAMING_SNAKE_CASE__ , buff=0 ) lowerCamelCase_ =VGroup(*SCREAMING_SNAKE_CASE__ ).arrange(SCREAMING_SNAKE_CASE__ , buff=0 ) lowerCamelCase_ =VGroup(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ).arrange(SCREAMING_SNAKE_CASE__ , buff=0 ) lowerCamelCase_ =Text("""CPU""" , font_size=24 ) lowerCamelCase_ =Group(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ).arrange(SCREAMING_SNAKE_CASE__ , buff=0.5 , aligned_edge=SCREAMING_SNAKE_CASE__ ) cpu.move_to([-2.5, -0.5, 0] ) self.add(SCREAMING_SNAKE_CASE__ ) lowerCamelCase_ =[mem.copy() for i in range(4 )] lowerCamelCase_ =VGroup(*SCREAMING_SNAKE_CASE__ ).arrange(SCREAMING_SNAKE_CASE__ , buff=0 ) lowerCamelCase_ =Text("""GPU""" , font_size=24 ) lowerCamelCase_ =Group(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ).arrange(SCREAMING_SNAKE_CASE__ , buff=0.5 , aligned_edge=SCREAMING_SNAKE_CASE__ ) gpu.move_to([-1, -1, 0] ) self.add(SCREAMING_SNAKE_CASE__ ) lowerCamelCase_ =[mem.copy() for i in range(6 )] lowerCamelCase_ =VGroup(*SCREAMING_SNAKE_CASE__ ).arrange(SCREAMING_SNAKE_CASE__ , buff=0 ) lowerCamelCase_ =Text("""Model""" , font_size=24 ) lowerCamelCase_ =Group(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ).arrange(SCREAMING_SNAKE_CASE__ , buff=0.5 , aligned_edge=SCREAMING_SNAKE_CASE__ ) model.move_to([3, -1.0, 0] ) self.add(SCREAMING_SNAKE_CASE__ ) lowerCamelCase_ =[] lowerCamelCase_ =[] lowerCamelCase_ =[] for i, rect in enumerate(SCREAMING_SNAKE_CASE__ ): rect.set_stroke(SCREAMING_SNAKE_CASE__ ) lowerCamelCase_ =Rectangle(height=0.4_6 / 4 , width=0.4_6 / 3 ).set_stroke(width=0.0 ).set_fill(SCREAMING_SNAKE_CASE__ , opacity=0.7 ) if i == 0: cpu_target.next_to(cpu_left_col_base[0].get_corner(DOWN + LEFT ) , buff=0.0_2 , direction=SCREAMING_SNAKE_CASE__ ) cpu_target.set_x(cpu_target.get_x() + 0.1 ) elif i == 3: cpu_target.next_to(model_cpu_arr[0] , direction=SCREAMING_SNAKE_CASE__ , buff=0.0 ) else: cpu_target.next_to(model_cpu_arr[i - 1] , direction=SCREAMING_SNAKE_CASE__ , buff=0.0 ) self.add(SCREAMING_SNAKE_CASE__ ) model_cpu_arr.append(SCREAMING_SNAKE_CASE__ ) self.add(*SCREAMING_SNAKE_CASE__ , *SCREAMING_SNAKE_CASE__ , *SCREAMING_SNAKE_CASE__ ) lowerCamelCase_ =[mem.copy() for i in range(6 )] lowerCamelCase_ =VGroup(*SCREAMING_SNAKE_CASE__ ).arrange(SCREAMING_SNAKE_CASE__ , buff=0 ) lowerCamelCase_ =Text("""Loaded Checkpoint""" , font_size=24 ) lowerCamelCase_ =Group(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ).arrange(SCREAMING_SNAKE_CASE__ , buff=0.5 , aligned_edge=SCREAMING_SNAKE_CASE__ ) checkpoint.move_to([3, 0.5, 0] ) self.add(SCREAMING_SNAKE_CASE__ ) lowerCamelCase_ =[] lowerCamelCase_ =[] for i, rect in enumerate(SCREAMING_SNAKE_CASE__ ): lowerCamelCase_ =fill.copy().set_fill(SCREAMING_SNAKE_CASE__ , opacity=0.7 ) target.move_to(SCREAMING_SNAKE_CASE__ ) ckpt_arr.append(SCREAMING_SNAKE_CASE__ ) lowerCamelCase_ =target.copy() if i < 5: cpu_target.move_to(cpu_left_col_base[i + 1] ) else: cpu_target.move_to(cpu_right_col_base[i - 5] ) ckpt_cpu_arr.append(SCREAMING_SNAKE_CASE__ ) self.add(*SCREAMING_SNAKE_CASE__ , *SCREAMING_SNAKE_CASE__ ) lowerCamelCase_ =Square(side_length=2.2 ) key.move_to([-5, 2, 0] ) lowerCamelCase_ =MarkupText( f'<b>Key:</b>\n\n<span fgcolor=\'{YELLOW}\'>●</span> Empty Model' , font_size=18 , ) key_text.move_to([-5, 2.4, 0] ) self.add(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) lowerCamelCase_ =MarkupText( f'<span fgcolor=\'{BLUE}\'>●</span> Checkpoint' , font_size=18 , ) blue_text.next_to(SCREAMING_SNAKE_CASE__ , DOWN * 2.4 , aligned_edge=key_text.get_left() ) self.add(SCREAMING_SNAKE_CASE__ ) lowerCamelCase_ =MarkupText( f'Based on the passed in configuration, weights are stored in\na variety of np.memmaps on disk or to a particular device.' , font_size=24 , ) step_a.move_to([2, 2, 0] ) lowerCamelCase_ =[meta_mem.copy() for i in range(6 )] lowerCamelCase_ =[meta_mem.copy() for i in range(6 )] lowerCamelCase_ =VGroup(*SCREAMING_SNAKE_CASE__ ).arrange(SCREAMING_SNAKE_CASE__ , buff=0 ) lowerCamelCase_ =VGroup(*SCREAMING_SNAKE_CASE__ ).arrange(SCREAMING_SNAKE_CASE__ , buff=0 ) lowerCamelCase_ =VGroup(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ).arrange(SCREAMING_SNAKE_CASE__ , buff=0 ) lowerCamelCase_ =Text("""Disk""" , font_size=24 ) lowerCamelCase_ =Group(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ).arrange(SCREAMING_SNAKE_CASE__ , buff=0.5 , aligned_edge=SCREAMING_SNAKE_CASE__ ) disk.move_to([-4.0, -1.2_5, 0] ) self.play(Write(SCREAMING_SNAKE_CASE__ , run_time=3 ) , Write(SCREAMING_SNAKE_CASE__ , run_time=1 ) , Create(SCREAMING_SNAKE_CASE__ , run_time=1 ) ) lowerCamelCase_ =[] for i, rect in enumerate(SCREAMING_SNAKE_CASE__ ): lowerCamelCase_ =rect.copy() target.generate_target() target.target.move_to(disk_left_col_base[i] ).scale(0.5 ) animations.append(MoveToTarget(SCREAMING_SNAKE_CASE__ , run_time=1.5 ) ) self.play(*SCREAMING_SNAKE_CASE__ ) self.play(FadeOut(SCREAMING_SNAKE_CASE__ ) ) lowerCamelCase_ =MarkupText(f'Then, the checkpoint is removed from memory\nthrough garbage collection.' , font_size=24 ) step_a.move_to([2, 2, 0] ) self.play(Write(SCREAMING_SNAKE_CASE__ , run_time=3 ) ) self.play( FadeOut(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , *SCREAMING_SNAKE_CASE__ , *SCREAMING_SNAKE_CASE__ ) , ) self.wait()
154
from typing import Optional from urllib.parse import quote import huggingface_hub as hfh from packaging import version def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ = None ) -> str: if version.parse(hfh.__version__ ).release < version.parse('0.11.0' ).release: # old versions of hfh don't url-encode the file path __lowerCamelCase : int = quote(lowerCamelCase__ ) return hfh.hf_hub_url(lowerCamelCase__ , lowerCamelCase__ , repo_type='dataset' , revision=lowerCamelCase__ )
73
0
"""simple docstring""" from __future__ import annotations from collections.abc import Iterator from typing import Generic, TypeVar lowerCAmelCase__ = TypeVar('''T''') class __snake_case ( Generic[T]): def __init__( self : List[str] , __lowerCAmelCase : T ): """simple docstring""" _lowerCamelCase : List[Any] = data _lowerCamelCase : Node[T] | None = None def __str__( self : Any ): """simple docstring""" return f'''{self.data}''' class __snake_case ( Generic[T]): def __init__( self : Optional[Any] ): """simple docstring""" _lowerCamelCase : Node[T] | None = None def __iter__( self : int ): """simple docstring""" _lowerCamelCase : List[str] = self.top while node: yield node.data _lowerCamelCase : Optional[int] = node.next def __str__( self : List[Any] ): """simple docstring""" return "->".join([str(SCREAMING_SNAKE_CASE__ ) for item in self] ) def __len__( self : List[str] ): """simple docstring""" return len(tuple(iter(self ) ) ) def SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" return self.top is None def SCREAMING_SNAKE_CASE ( self : Optional[int] , __lowerCAmelCase : T ): """simple docstring""" _lowerCamelCase : Dict = Node(SCREAMING_SNAKE_CASE__ ) if not self.is_empty(): _lowerCamelCase : int = self.top _lowerCamelCase : Union[str, Any] = node def SCREAMING_SNAKE_CASE ( self : Tuple ): """simple docstring""" if self.is_empty(): raise IndexError('''pop from empty stack''' ) assert isinstance(self.top , SCREAMING_SNAKE_CASE__ ) _lowerCamelCase : List[str] = self.top _lowerCamelCase : List[str] = self.top.next return pop_node.data def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" if self.is_empty(): raise IndexError('''peek from empty stack''' ) assert self.top is not None return self.top.data def SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" _lowerCamelCase : Optional[int] = None if __name__ == "__main__": from doctest import testmod testmod()
72
def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , ) -> float: __lowerCamelCase : Dict = [redshift, radiation_density, matter_density, dark_energy] if any(p < 0 for p in parameters ): raise ValueError('All input parameters must be positive' ) if any(p > 1 for p in parameters[1:4] ): raise ValueError('Relative densities cannot be greater than one' ) else: __lowerCamelCase : Dict = 1 - (matter_density + radiation_density + dark_energy) __lowerCamelCase : Union[str, Any] = ( radiation_density * (redshift + 1) ** 4 + matter_density * (redshift + 1) ** 3 + curvature * (redshift + 1) ** 2 + dark_energy ) __lowerCamelCase : List[Any] = hubble_constant * e_a ** (1 / 2) return hubble if __name__ == "__main__": import doctest # run doctest doctest.testmod() # demo LCDM approximation a =0.3 print( hubble_parameter( hubble_constant=68.3, radiation_density=1E-4, matter_density=matter_density, dark_energy=1 - matter_density, redshift=0, ) )
73
0
'''simple docstring''' def a ( __a ) -> list[int]: '''simple docstring''' UpperCamelCase__ :str = len(lowerCamelCase__ ) for i in range(lowerCamelCase__ ): for j in range(i + 1 , lowerCamelCase__ ): if numbers[j] < numbers[i]: UpperCamelCase__ :str = numbers[j], numbers[i] return numbers if __name__ == "__main__": __snake_case = input('''Enter numbers separated by a comma:\n''').strip() __snake_case = [int(item) for item in user_input.split(''',''')] print(exchange_sort(unsorted))
97
from typing import List, Optional, Union from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : Optional[Any] = ['''image_processor''', '''tokenizer'''] _UpperCAmelCase : Union[str, Any] = '''Pix2StructImageProcessor''' _UpperCAmelCase : Any = ('''T5Tokenizer''', '''T5TokenizerFast''') def __init__( self : List[str] ,SCREAMING_SNAKE_CASE__ : str ,SCREAMING_SNAKE_CASE__ : int): __lowerCamelCase : List[Any] = False super().__init__(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) def __call__( self : str ,SCREAMING_SNAKE_CASE__ : Any=None ,SCREAMING_SNAKE_CASE__ : Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None ,SCREAMING_SNAKE_CASE__ : bool = True ,SCREAMING_SNAKE_CASE__ : Union[bool, str, PaddingStrategy] = False ,SCREAMING_SNAKE_CASE__ : Union[bool, str, TruncationStrategy] = None ,SCREAMING_SNAKE_CASE__ : Optional[int] = None ,SCREAMING_SNAKE_CASE__ : Optional[int] = 2_0_4_8 ,SCREAMING_SNAKE_CASE__ : int = 0 ,SCREAMING_SNAKE_CASE__ : Optional[int] = None ,SCREAMING_SNAKE_CASE__ : Optional[bool] = None ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = True ,SCREAMING_SNAKE_CASE__ : Optional[Union[str, TensorType]] = None ,**SCREAMING_SNAKE_CASE__ : Dict ,): if images is None and text is None: raise ValueError('You have to specify either images or text.') # Get only text if images is None and not self.image_processor.is_vqa: __lowerCamelCase : Tuple = self.tokenizer __lowerCamelCase : Dict = self.tokenizer( text=SCREAMING_SNAKE_CASE__ ,add_special_tokens=SCREAMING_SNAKE_CASE__ ,padding=SCREAMING_SNAKE_CASE__ ,truncation=SCREAMING_SNAKE_CASE__ ,max_length=SCREAMING_SNAKE_CASE__ ,stride=SCREAMING_SNAKE_CASE__ ,pad_to_multiple_of=SCREAMING_SNAKE_CASE__ ,return_attention_mask=SCREAMING_SNAKE_CASE__ ,return_overflowing_tokens=SCREAMING_SNAKE_CASE__ ,return_special_tokens_mask=SCREAMING_SNAKE_CASE__ ,return_offsets_mapping=SCREAMING_SNAKE_CASE__ ,return_token_type_ids=SCREAMING_SNAKE_CASE__ ,return_length=SCREAMING_SNAKE_CASE__ ,verbose=SCREAMING_SNAKE_CASE__ ,return_tensors=SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__ ,) return text_encoding if not self.image_processor.is_vqa: # add pixel_values __lowerCamelCase : List[Any] = self.image_processor( SCREAMING_SNAKE_CASE__ ,return_tensors=SCREAMING_SNAKE_CASE__ ,max_patches=SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) else: # add pixel_values and bbox __lowerCamelCase : List[Any] = self.image_processor( SCREAMING_SNAKE_CASE__ ,return_tensors=SCREAMING_SNAKE_CASE__ ,max_patches=SCREAMING_SNAKE_CASE__ ,header_text=SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) if text is not None and not self.image_processor.is_vqa: __lowerCamelCase : List[Any] = self.tokenizer( text=SCREAMING_SNAKE_CASE__ ,add_special_tokens=SCREAMING_SNAKE_CASE__ ,padding=SCREAMING_SNAKE_CASE__ ,truncation=SCREAMING_SNAKE_CASE__ ,max_length=SCREAMING_SNAKE_CASE__ ,stride=SCREAMING_SNAKE_CASE__ ,pad_to_multiple_of=SCREAMING_SNAKE_CASE__ ,return_attention_mask=SCREAMING_SNAKE_CASE__ ,return_overflowing_tokens=SCREAMING_SNAKE_CASE__ ,return_special_tokens_mask=SCREAMING_SNAKE_CASE__ ,return_offsets_mapping=SCREAMING_SNAKE_CASE__ ,return_token_type_ids=SCREAMING_SNAKE_CASE__ ,return_length=SCREAMING_SNAKE_CASE__ ,verbose=SCREAMING_SNAKE_CASE__ ,return_tensors=SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__ ,) if "attention_mask" in text_encoding: __lowerCamelCase : List[Any] = text_encoding.pop('attention_mask') if "input_ids" in text_encoding: __lowerCamelCase : Dict = text_encoding.pop('input_ids') else: __lowerCamelCase : Optional[int] = None if text_encoding is not None: encoding_image_processor.update(SCREAMING_SNAKE_CASE__) return encoding_image_processor def lowerCAmelCase ( self : Dict ,*SCREAMING_SNAKE_CASE__ : str ,**SCREAMING_SNAKE_CASE__ : int): return self.tokenizer.batch_decode(*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : List[str] ,*SCREAMING_SNAKE_CASE__ : int ,**SCREAMING_SNAKE_CASE__ : Dict): return self.tokenizer.decode(*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) @property def lowerCAmelCase ( self : int): __lowerCamelCase : Dict = self.tokenizer.model_input_names __lowerCamelCase : int = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
73
0
import copy from typing import TYPE_CHECKING, Any, Mapping, Optional, OrderedDict from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ..auto.configuration_auto import AutoConfig if TYPE_CHECKING: from ... import PreTrainedTokenizerBase, TensorType lowerCAmelCase_ = logging.get_logger(__name__) class __lowerCAmelCase ( _a ): lowerCamelCase_ : Tuple = '''vision-encoder-decoder''' lowerCamelCase_ : Union[str, Any] = True def __init__(self , **__magic_name__ ) -> str: '''simple docstring''' super().__init__(**SCREAMING_SNAKE_CASE__ ) if "encoder" not in kwargs or "decoder" not in kwargs: raise ValueError( F'''A configuraton of type {self.model_type} cannot be instantiated because ''' F'''not both `encoder` and `decoder` sub-configurations are passed, but only {kwargs}''' ) snake_case_ : Optional[int] = kwargs.pop('''encoder''' ) snake_case_ : List[str] = encoder_config.pop('''model_type''' ) snake_case_ : Union[str, Any] = kwargs.pop('''decoder''' ) snake_case_ : Optional[Any] = decoder_config.pop('''model_type''' ) snake_case_ : str = AutoConfig.for_model(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) snake_case_ : Tuple = AutoConfig.for_model(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) snake_case_ : Optional[Any] = True @classmethod def lowerCamelCase (cls , __magic_name__ , __magic_name__ , **__magic_name__ ) -> Optional[int]: '''simple docstring''' logger.info('''Setting `config.is_decoder=True` and `config.add_cross_attention=True` for decoder_config''' ) snake_case_ : List[str] = True snake_case_ : Tuple = True return cls(encoder=encoder_config.to_dict() , decoder=decoder_config.to_dict() , **SCREAMING_SNAKE_CASE__ ) def lowerCamelCase (self ) -> str: '''simple docstring''' snake_case_ : str = copy.deepcopy(self.__dict__ ) snake_case_ : Optional[Any] = self.encoder.to_dict() snake_case_ : Optional[Any] = self.decoder.to_dict() snake_case_ : Tuple = self.__class__.model_type return output class __lowerCAmelCase ( _a ): lowerCamelCase_ : List[Any] = version.parse('''1.11''' ) @property def lowerCamelCase (self ) -> Tuple: '''simple docstring''' return OrderedDict( [ ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}), ] ) @property def lowerCamelCase (self ) -> Dict: '''simple docstring''' return 1e-4 @property def lowerCamelCase (self ) -> List[str]: '''simple docstring''' return OrderedDict({'''last_hidden_state''': {0: '''batch''', 1: '''encoder_sequence'''}} ) class __lowerCAmelCase ( _a ): @property def lowerCamelCase (self ) -> str: '''simple docstring''' snake_case_ : Union[str, Any] = OrderedDict() snake_case_ : List[str] = {0: 'batch', 1: 'past_decoder_sequence + sequence'} snake_case_ : Tuple = {0: 'batch', 1: 'past_decoder_sequence + sequence'} snake_case_ : Tuple = {0: 'batch', 1: 'encoder_sequence'} return common_inputs def lowerCamelCase (self , __magic_name__ , __magic_name__ = -1 , __magic_name__ = -1 , __magic_name__ = False , __magic_name__ = None , ) -> Dict: '''simple docstring''' import torch snake_case_ : int = OrderedDict() snake_case_ : Any = super().generate_dummy_inputs( SCREAMING_SNAKE_CASE__ , batch_size=SCREAMING_SNAKE_CASE__ , seq_length=SCREAMING_SNAKE_CASE__ , is_pair=SCREAMING_SNAKE_CASE__ , framework=SCREAMING_SNAKE_CASE__ ) snake_case_ : Any = dummy_input['input_ids'].shape snake_case_ : Optional[Any] = (batch, encoder_sequence, self._config.encoder_hidden_size) snake_case_ : str = dummy_input.pop('''input_ids''' ) snake_case_ : Any = dummy_input.pop('''attention_mask''' ) snake_case_ : Dict = torch.zeros(SCREAMING_SNAKE_CASE__ ) return common_inputs class __lowerCAmelCase ( _a ): @property def lowerCamelCase (self ) -> Any: '''simple docstring''' pass def lowerCamelCase (self , __magic_name__ ) -> Any: '''simple docstring''' return VisionEncoderDecoderEncoderOnnxConfig(SCREAMING_SNAKE_CASE__ ) def lowerCamelCase (self , __magic_name__ , __magic_name__ , __magic_name__ = "default" ) -> str: '''simple docstring''' snake_case_ : Optional[Any] = encoder_config.hidden_size return VisionEncoderDecoderDecoderOnnxConfig(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
279
from bisect import bisect from itertools import accumulate def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> Union[str, Any]: __lowerCamelCase : Optional[Any] = sorted(zip(lowerCamelCase__ , lowerCamelCase__ ) , key=lambda lowerCamelCase__ : x[0] / x[1] , reverse=lowerCamelCase__ ) __lowerCamelCase , __lowerCamelCase : Any = [i[0] for i in r], [i[1] for i in r] __lowerCamelCase : List[str] = list(accumulate(lowerCamelCase__ ) ) __lowerCamelCase : Union[str, Any] = bisect(lowerCamelCase__ , lowerCamelCase__ ) return ( 0 if k == 0 else sum(vl[:k] ) + (w - acc[k - 1]) * (vl[k]) / (wt[k]) if k != n else sum(vl[:k] ) ) if __name__ == "__main__": import doctest doctest.testmod()
73
0
'''simple docstring''' from ..utils import DummyObject, requires_backends class a__ ( metaclass=__A ): """simple docstring""" __UpperCamelCase : List[str] = ['''keras_nlp'''] def __init__(self , *__lowercase , **__lowercase ): requires_backends(self , ['''keras_nlp'''] )
174
from __future__ import annotations import math def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> list: if len(lowerCamelCase__ ) != 2 or len(a[0] ) != 2 or len(lowerCamelCase__ ) != 2 or len(b[0] ) != 2: raise Exception('Matrices are not 2x2' ) __lowerCamelCase : Optional[int] = [ [a[0][0] * b[0][0] + a[0][1] * b[1][0], a[0][0] * b[0][1] + a[0][1] * b[1][1]], [a[1][0] * b[0][0] + a[1][1] * b[1][0], a[1][0] * b[0][1] + a[1][1] * b[1][1]], ] return new_matrix def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> Optional[int]: return [ [matrix_a[row][col] + matrix_b[row][col] for col in range(len(matrix_a[row] ) )] for row in range(len(lowerCamelCase__ ) ) ] def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> List[str]: return [ [matrix_a[row][col] - matrix_b[row][col] for col in range(len(matrix_a[row] ) )] for row in range(len(lowerCamelCase__ ) ) ] def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> tuple[list, list, list, list]: if len(lowerCamelCase__ ) % 2 != 0 or len(a[0] ) % 2 != 0: raise Exception('Odd matrices are not supported!' ) __lowerCamelCase : Tuple = len(lowerCamelCase__ ) __lowerCamelCase : List[Any] = matrix_length // 2 __lowerCamelCase : Dict = [[a[i][j] for j in range(lowerCamelCase__ , lowerCamelCase__ )] for i in range(lowerCamelCase__ )] __lowerCamelCase : str = [ [a[i][j] for j in range(lowerCamelCase__ , lowerCamelCase__ )] for i in range(lowerCamelCase__ , lowerCamelCase__ ) ] __lowerCamelCase : Dict = [[a[i][j] for j in range(lowerCamelCase__ )] for i in range(lowerCamelCase__ )] __lowerCamelCase : Optional[Any] = [[a[i][j] for j in range(lowerCamelCase__ )] for i in range(lowerCamelCase__ , lowerCamelCase__ )] return top_left, top_right, bot_left, bot_right def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> tuple[int, int]: return len(lowerCamelCase__ ), len(matrix[0] ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> None: print('\n'.join(str(lowerCamelCase__ ) for line in matrix ) ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> list: if matrix_dimensions(lowerCamelCase__ ) == (2, 2): return default_matrix_multiplication(lowerCamelCase__ , lowerCamelCase__ ) __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : Optional[Any] = split_matrix(lowerCamelCase__ ) __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : Optional[Any] = split_matrix(lowerCamelCase__ ) __lowerCamelCase : str = actual_strassen(lowerCamelCase__ , matrix_subtraction(lowerCamelCase__ , lowerCamelCase__ ) ) __lowerCamelCase : List[str] = actual_strassen(matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) , lowerCamelCase__ ) __lowerCamelCase : List[Any] = actual_strassen(matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) , lowerCamelCase__ ) __lowerCamelCase : Tuple = actual_strassen(lowerCamelCase__ , matrix_subtraction(lowerCamelCase__ , lowerCamelCase__ ) ) __lowerCamelCase : Optional[int] = actual_strassen(matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) , matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) ) __lowerCamelCase : Dict = actual_strassen(matrix_subtraction(lowerCamelCase__ , lowerCamelCase__ ) , matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) ) __lowerCamelCase : Tuple = actual_strassen(matrix_subtraction(lowerCamelCase__ , lowerCamelCase__ ) , matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) ) __lowerCamelCase : Dict = matrix_addition(matrix_subtraction(matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) , lowerCamelCase__ ) , lowerCamelCase__ ) __lowerCamelCase : Tuple = matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) __lowerCamelCase : List[str] = matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) __lowerCamelCase : Any = matrix_subtraction(matrix_subtraction(matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) , lowerCamelCase__ ) , lowerCamelCase__ ) # construct the new matrix from our 4 quadrants __lowerCamelCase : List[Any] = [] for i in range(len(lowerCamelCase__ ) ): new_matrix.append(top_left[i] + top_right[i] ) for i in range(len(lowerCamelCase__ ) ): new_matrix.append(bot_left[i] + bot_right[i] ) return new_matrix def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> list: if matrix_dimensions(lowerCamelCase__ )[1] != matrix_dimensions(lowerCamelCase__ )[0]: __lowerCamelCase : Any = ( 'Unable to multiply these matrices, please check the dimensions.\n' F"Matrix A: {matrixa}\n" F"Matrix B: {matrixa}" ) raise Exception(lowerCamelCase__ ) __lowerCamelCase : str = matrix_dimensions(lowerCamelCase__ ) __lowerCamelCase : List[str] = matrix_dimensions(lowerCamelCase__ ) if dimensiona[0] == dimensiona[1] and dimensiona[0] == dimensiona[1]: return [matrixa, matrixa] __lowerCamelCase : str = max(*lowerCamelCase__ , *lowerCamelCase__ ) __lowerCamelCase : List[str] = int(math.pow(2 , math.ceil(math.loga(lowerCamelCase__ ) ) ) ) __lowerCamelCase : Any = matrixa __lowerCamelCase : int = matrixa # Adding zeros to the matrices so that the arrays dimensions are the same and also # power of 2 for i in range(0 , lowerCamelCase__ ): if i < dimensiona[0]: for _ in range(dimensiona[1] , lowerCamelCase__ ): new_matrixa[i].append(0 ) else: new_matrixa.append([0] * maxim ) if i < dimensiona[0]: for _ in range(dimensiona[1] , lowerCamelCase__ ): new_matrixa[i].append(0 ) else: new_matrixa.append([0] * maxim ) __lowerCamelCase : List[str] = actual_strassen(lowerCamelCase__ , lowerCamelCase__ ) # Removing the additional zeros for i in range(0 , lowerCamelCase__ ): if i < dimensiona[0]: for _ in range(dimensiona[1] , lowerCamelCase__ ): final_matrix[i].pop() else: final_matrix.pop() return final_matrix if __name__ == "__main__": a =[ [2, 3, 4, 5], [6, 4, 3, 1], [2, 3, 6, 7], [3, 1, 2, 4], [2, 3, 4, 5], [6, 4, 3, 1], [2, 3, 6, 7], [3, 1, 2, 4], [2, 3, 4, 5], [6, 2, 3, 1], ] a =[[0, 2, 1, 1], [16, 2, 3, 3], [2, 2, 7, 7], [13, 11, 22, 4]] print(strassen(matrixa, matrixa))
73
0
from typing import Any import numpy as np def A (__A : int ) -> bool: """simple docstring""" return np.array_equal(lowerCamelCase__ , matrix.conjugate().T ) def A (__A : Union[str, Any] , __A : Any ) -> Any: """simple docstring""" UpperCAmelCase_ = v.conjugate().T UpperCAmelCase_ = v_star.dot(lowerCamelCase__ ) assert isinstance(lowerCamelCase__ , np.ndarray ) return (v_star_dot.dot(lowerCamelCase__ )) / (v_star.dot(lowerCamelCase__ )) def A () -> None: """simple docstring""" UpperCAmelCase_ = np.array([[2, 2 + 1j, 4], [2 - 1j, 3, 1j], [4, -1j, 1]] ) UpperCAmelCase_ = np.array([[1], [2], [3]] ) assert is_hermitian(lowerCamelCase__ ), F"""{a} is not hermitian.""" print(rayleigh_quotient(lowerCamelCase__ , lowerCamelCase__ ) ) UpperCAmelCase_ = np.array([[1, 2, 4], [2, 3, -1], [4, -1, 1]] ) assert is_hermitian(lowerCamelCase__ ), F"""{a} is not hermitian.""" assert rayleigh_quotient(lowerCamelCase__ , lowerCamelCase__ ) == float(3 ) if __name__ == "__main__": import doctest doctest.testmod() tests()
51
from math import isclose, sqrt def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> tuple[float, float, float]: __lowerCamelCase : Tuple = point_y / 4 / point_x __lowerCamelCase : Tuple = 2 * normal_gradient / (1 + normal_gradient * normal_gradient) __lowerCamelCase : List[Any] = (1 - normal_gradient * normal_gradient) / ( 1 + normal_gradient * normal_gradient ) __lowerCamelCase : int = (sa - ca * incoming_gradient) / (ca + sa * incoming_gradient) # to find the next point, solve the simultaeneous equations: # y^2 + 4x^2 = 100 # y - b = m * (x - a) # ==> A x^2 + B x + C = 0 __lowerCamelCase : Any = outgoing_gradient**2 + 4 __lowerCamelCase : Optional[int] = 2 * outgoing_gradient * (point_y - outgoing_gradient * point_x) __lowerCamelCase : str = (point_y - outgoing_gradient * point_x) ** 2 - 1_0_0 __lowerCamelCase : str = ( -linear_term - sqrt(linear_term**2 - 4 * quadratic_term * constant_term ) ) / (2 * quadratic_term) __lowerCamelCase : Optional[Any] = ( -linear_term + sqrt(linear_term**2 - 4 * quadratic_term * constant_term ) ) / (2 * quadratic_term) # two solutions, one of which is our input point __lowerCamelCase : Optional[Any] = x_minus if isclose(lowerCamelCase__ , lowerCamelCase__ ) else x_plus __lowerCamelCase : Tuple = point_y + outgoing_gradient * (next_x - point_x) return next_x, next_y, outgoing_gradient def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ = 1.4 , lowerCamelCase__ = -9.6 ) -> int: __lowerCamelCase : int = 0 __lowerCamelCase : float = first_x_coord __lowerCamelCase : float = first_y_coord __lowerCamelCase : float = (10.1 - point_y) / (0.0 - point_x) while not (-0.01 <= point_x <= 0.01 and point_y > 0): __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : Any = next_point(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) num_reflections += 1 return num_reflections if __name__ == "__main__": print(F"""{solution() = }""")
73
0
import argparse import os import pickle import sys import torch from transformers import TransfoXLConfig, TransfoXLLMHeadModel, load_tf_weights_in_transfo_xl from transformers.models.transfo_xl import tokenization_transfo_xl as data_utils from transformers.models.transfo_xl.tokenization_transfo_xl import CORPUS_NAME, VOCAB_FILES_NAMES from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging logging.set_verbosity_info() # We do this to be able to load python 2 datasets pickles # See e.g. https://stackoverflow.com/questions/2121874/python-pickling-after-changing-a-modules-directory/2121918#2121918 __snake_case = data_utils.TransfoXLTokenizer __snake_case = data_utils.TransfoXLCorpus __snake_case = data_utils __snake_case = data_utils def _lowercase ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) -> Union[str, Any]: '''simple docstring''' if transfo_xl_dataset_file: # Convert a pre-processed corpus (see original TensorFlow repo) with open(lowerCamelCase__ , 'rb' ) as fp: SCREAMING_SNAKE_CASE__ = pickle.load(lowerCamelCase__ , encoding='latin1' ) # Save vocabulary and dataset cache as Dictionaries (should be better than pickles for the long-term) SCREAMING_SNAKE_CASE__ = pytorch_dump_folder_path + '/' + VOCAB_FILES_NAMES['pretrained_vocab_file'] print(F'Save vocabulary to {pytorch_vocab_dump_path}' ) SCREAMING_SNAKE_CASE__ = corpus.vocab.__dict__ torch.save(lowerCamelCase__ , lowerCamelCase__ ) SCREAMING_SNAKE_CASE__ = corpus.__dict__ corpus_dict_no_vocab.pop('vocab' , lowerCamelCase__ ) SCREAMING_SNAKE_CASE__ = pytorch_dump_folder_path + '/' + CORPUS_NAME print(F'Save dataset to {pytorch_dataset_dump_path}' ) torch.save(lowerCamelCase__ , lowerCamelCase__ ) if tf_checkpoint_path: # Convert a pre-trained TensorFlow model SCREAMING_SNAKE_CASE__ = os.path.abspath(lowerCamelCase__ ) SCREAMING_SNAKE_CASE__ = os.path.abspath(lowerCamelCase__ ) print(F'Converting Transformer XL checkpoint from {tf_path} with config at {config_path}.' ) # Initialise PyTorch model if transfo_xl_config_file == "": SCREAMING_SNAKE_CASE__ = TransfoXLConfig() else: SCREAMING_SNAKE_CASE__ = TransfoXLConfig.from_json_file(lowerCamelCase__ ) print(F'Building PyTorch model from configuration: {config}' ) SCREAMING_SNAKE_CASE__ = TransfoXLLMHeadModel(lowerCamelCase__ ) SCREAMING_SNAKE_CASE__ = load_tf_weights_in_transfo_xl(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) # Save pytorch-model SCREAMING_SNAKE_CASE__ = os.path.join(lowerCamelCase__ , lowerCamelCase__ ) SCREAMING_SNAKE_CASE__ = os.path.join(lowerCamelCase__ , lowerCamelCase__ ) print(F'Save PyTorch model to {os.path.abspath(lowerCamelCase__ )}' ) torch.save(model.state_dict() , lowerCamelCase__ ) print(F'Save configuration file to {os.path.abspath(lowerCamelCase__ )}' ) with open(lowerCamelCase__ , 'w' , encoding='utf-8' ) as f: f.write(config.to_json_string() ) if __name__ == "__main__": __snake_case = argparse.ArgumentParser() parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, required=True, help="""Path to the folder to store the PyTorch model or dataset/vocab.""", ) parser.add_argument( """--tf_checkpoint_path""", default="""""", type=str, help="""An optional path to a TensorFlow checkpoint path to be converted.""", ) parser.add_argument( """--transfo_xl_config_file""", default="""""", type=str, help=( """An optional config json file corresponding to the pre-trained BERT model. \n""" """This specifies the model architecture.""" ), ) parser.add_argument( """--transfo_xl_dataset_file""", default="""""", type=str, help="""An optional dataset file to be converted in a vocabulary.""", ) __snake_case = parser.parse_args() convert_transfo_xl_checkpoint_to_pytorch( args.tf_checkpoint_path, args.transfo_xl_config_file, args.pytorch_dump_folder_path, args.transfo_xl_dataset_file, )
176
import os import unicodedata from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging a =logging.get_logger(__name__) a ={"""vocab_file""": """spiece.model"""} a ={ """vocab_file""": { """albert-base-v1""": """https://huggingface.co/albert-base-v1/resolve/main/spiece.model""", """albert-large-v1""": """https://huggingface.co/albert-large-v1/resolve/main/spiece.model""", """albert-xlarge-v1""": """https://huggingface.co/albert-xlarge-v1/resolve/main/spiece.model""", """albert-xxlarge-v1""": """https://huggingface.co/albert-xxlarge-v1/resolve/main/spiece.model""", """albert-base-v2""": """https://huggingface.co/albert-base-v2/resolve/main/spiece.model""", """albert-large-v2""": """https://huggingface.co/albert-large-v2/resolve/main/spiece.model""", """albert-xlarge-v2""": """https://huggingface.co/albert-xlarge-v2/resolve/main/spiece.model""", """albert-xxlarge-v2""": """https://huggingface.co/albert-xxlarge-v2/resolve/main/spiece.model""", } } a ={ """albert-base-v1""": 512, """albert-large-v1""": 512, """albert-xlarge-v1""": 512, """albert-xxlarge-v1""": 512, """albert-base-v2""": 512, """albert-large-v2""": 512, """albert-xlarge-v2""": 512, """albert-xxlarge-v2""": 512, } a ="""▁""" class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : List[Any] = VOCAB_FILES_NAMES _UpperCAmelCase : List[str] = PRETRAINED_VOCAB_FILES_MAP _UpperCAmelCase : Optional[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self : str ,SCREAMING_SNAKE_CASE__ : Optional[int] ,SCREAMING_SNAKE_CASE__ : Tuple=True ,SCREAMING_SNAKE_CASE__ : str=True ,SCREAMING_SNAKE_CASE__ : List[str]=False ,SCREAMING_SNAKE_CASE__ : Any="[CLS]" ,SCREAMING_SNAKE_CASE__ : Optional[int]="[SEP]" ,SCREAMING_SNAKE_CASE__ : Optional[Any]="<unk>" ,SCREAMING_SNAKE_CASE__ : Any="[SEP]" ,SCREAMING_SNAKE_CASE__ : Optional[int]="<pad>" ,SCREAMING_SNAKE_CASE__ : Any="[CLS]" ,SCREAMING_SNAKE_CASE__ : Union[str, Any]="[MASK]" ,SCREAMING_SNAKE_CASE__ : Optional[Dict[str, Any]] = None ,**SCREAMING_SNAKE_CASE__ : Dict ,): # Mask token behave like a normal word, i.e. include the space before it and # is included in the raw text, there should be a match in a non-normalized sentence. __lowerCamelCase : Dict = ( AddedToken(SCREAMING_SNAKE_CASE__ ,lstrip=SCREAMING_SNAKE_CASE__ ,rstrip=SCREAMING_SNAKE_CASE__ ,normalized=SCREAMING_SNAKE_CASE__) if isinstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) else mask_token ) __lowerCamelCase : str = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( do_lower_case=SCREAMING_SNAKE_CASE__ ,remove_space=SCREAMING_SNAKE_CASE__ ,keep_accents=SCREAMING_SNAKE_CASE__ ,bos_token=SCREAMING_SNAKE_CASE__ ,eos_token=SCREAMING_SNAKE_CASE__ ,unk_token=SCREAMING_SNAKE_CASE__ ,sep_token=SCREAMING_SNAKE_CASE__ ,pad_token=SCREAMING_SNAKE_CASE__ ,cls_token=SCREAMING_SNAKE_CASE__ ,mask_token=SCREAMING_SNAKE_CASE__ ,sp_model_kwargs=self.sp_model_kwargs ,**SCREAMING_SNAKE_CASE__ ,) __lowerCamelCase : Any = do_lower_case __lowerCamelCase : Union[str, Any] = remove_space __lowerCamelCase : Tuple = keep_accents __lowerCamelCase : Dict = vocab_file __lowerCamelCase : str = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.Load(SCREAMING_SNAKE_CASE__) @property def lowerCAmelCase ( self : Optional[Any]): return len(self.sp_model) def lowerCAmelCase ( self : Optional[Any]): __lowerCamelCase : Optional[int] = {self.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__): i for i in range(self.vocab_size)} vocab.update(self.added_tokens_encoder) return vocab def __getstate__( self : Union[str, Any]): __lowerCamelCase : str = self.__dict__.copy() __lowerCamelCase : Tuple = None return state def __setstate__( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : str): __lowerCamelCase : List[str] = d # for backward compatibility if not hasattr(self ,'sp_model_kwargs'): __lowerCamelCase : List[str] = {} __lowerCamelCase : int = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.Load(self.vocab_file) def lowerCAmelCase ( self : Dict ,SCREAMING_SNAKE_CASE__ : List[Any]): if self.remove_space: __lowerCamelCase : Dict = ' '.join(inputs.strip().split()) else: __lowerCamelCase : Optional[Any] = inputs __lowerCamelCase : Tuple = outputs.replace('``' ,'"').replace('\'\'' ,'"') if not self.keep_accents: __lowerCamelCase : List[str] = unicodedata.normalize('NFKD' ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : str = ''.join([c for c in outputs if not unicodedata.combining(SCREAMING_SNAKE_CASE__)]) if self.do_lower_case: __lowerCamelCase : Optional[Any] = outputs.lower() return outputs def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : str): __lowerCamelCase : Tuple = self.preprocess_text(SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = self.sp_model.encode(SCREAMING_SNAKE_CASE__ ,out_type=SCREAMING_SNAKE_CASE__) __lowerCamelCase : Tuple = [] for piece in pieces: if len(SCREAMING_SNAKE_CASE__) > 1 and piece[-1] == str(',') and piece[-2].isdigit(): __lowerCamelCase : int = self.sp_model.EncodeAsPieces(piece[:-1].replace(SCREAMING_SNAKE_CASE__ ,'')) if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE: if len(cur_pieces[0]) == 1: __lowerCamelCase : Union[str, Any] = cur_pieces[1:] else: __lowerCamelCase : Dict = cur_pieces[0][1:] cur_pieces.append(piece[-1]) new_pieces.extend(SCREAMING_SNAKE_CASE__) else: new_pieces.append(SCREAMING_SNAKE_CASE__) return new_pieces def lowerCAmelCase ( self : Any ,SCREAMING_SNAKE_CASE__ : List[str]): return self.sp_model.PieceToId(SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : str ,SCREAMING_SNAKE_CASE__ : Any): return self.sp_model.IdToPiece(SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Tuple ,SCREAMING_SNAKE_CASE__ : int): __lowerCamelCase : Optional[Any] = [] __lowerCamelCase : int = '' __lowerCamelCase : Optional[int] = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(SCREAMING_SNAKE_CASE__) + token __lowerCamelCase : List[Any] = True __lowerCamelCase : Any = [] else: current_sub_tokens.append(SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = False out_string += self.sp_model.decode(SCREAMING_SNAKE_CASE__) return out_string.strip() def lowerCAmelCase ( self : Dict ,SCREAMING_SNAKE_CASE__ : List[int] ,SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None): __lowerCamelCase : Union[str, Any] = [self.sep_token_id] __lowerCamelCase : int = [self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def lowerCAmelCase ( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : List[int] ,SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ,SCREAMING_SNAKE_CASE__ : bool = False): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=SCREAMING_SNAKE_CASE__ ,token_ids_a=SCREAMING_SNAKE_CASE__ ,already_has_special_tokens=SCREAMING_SNAKE_CASE__) if token_ids_a is not None: return [1] + ([0] * len(SCREAMING_SNAKE_CASE__)) + [1] + ([0] * len(SCREAMING_SNAKE_CASE__)) + [1] return [1] + ([0] * len(SCREAMING_SNAKE_CASE__)) + [1] def lowerCAmelCase ( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : List[int] ,SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None): __lowerCamelCase : Tuple = [self.sep_token_id] __lowerCamelCase : List[Any] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep) * [0] return len(cls + token_ids_a + sep) * [0] + len(token_ids_a + sep) * [1] def lowerCAmelCase ( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : str ,SCREAMING_SNAKE_CASE__ : Optional[str] = None): if not os.path.isdir(SCREAMING_SNAKE_CASE__): logger.error(F"Vocabulary path ({save_directory}) should be a directory") return __lowerCamelCase : List[str] = os.path.join( SCREAMING_SNAKE_CASE__ ,(filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file']) if os.path.abspath(self.vocab_file) != os.path.abspath(SCREAMING_SNAKE_CASE__) and os.path.isfile(self.vocab_file): copyfile(self.vocab_file ,SCREAMING_SNAKE_CASE__) elif not os.path.isfile(self.vocab_file): with open(SCREAMING_SNAKE_CASE__ ,'wb') as fi: __lowerCamelCase : str = self.sp_model.serialized_model_proto() fi.write(SCREAMING_SNAKE_CASE__) return (out_vocab_file,)
73
0
import copy from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ..auto import CONFIG_MAPPING __lowerCAmelCase : List[Any] = logging.get_logger(__name__) __lowerCAmelCase : int = { 'microsoft/conditional-detr-resnet-50': ( 'https://huggingface.co/microsoft/conditional-detr-resnet-50/resolve/main/config.json' ), } class snake_case__ (_UpperCamelCase ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = '''conditional_detr''' SCREAMING_SNAKE_CASE_ : int = ['''past_key_values'''] SCREAMING_SNAKE_CASE_ : Optional[int] = { '''hidden_size''': '''d_model''', '''num_attention_heads''': '''encoder_attention_heads''', } def __init__( self : Dict , __lowerCamelCase : int=True , __lowerCamelCase : List[str]=None , __lowerCamelCase : List[str]=3 , __lowerCamelCase : int=3_00 , __lowerCamelCase : str=6 , __lowerCamelCase : Dict=20_48 , __lowerCamelCase : Union[str, Any]=8 , __lowerCamelCase : int=6 , __lowerCamelCase : Optional[int]=20_48 , __lowerCamelCase : List[Any]=8 , __lowerCamelCase : int=0.0 , __lowerCamelCase : Tuple=0.0 , __lowerCamelCase : Union[str, Any]=True , __lowerCamelCase : Optional[Any]="relu" , __lowerCamelCase : List[Any]=2_56 , __lowerCamelCase : List[Any]=0.1 , __lowerCamelCase : Any=0.0 , __lowerCamelCase : List[Any]=0.0 , __lowerCamelCase : str=0.02 , __lowerCamelCase : Tuple=1.0 , __lowerCamelCase : str=False , __lowerCamelCase : Dict="sine" , __lowerCamelCase : int="resnet50" , __lowerCamelCase : Union[str, Any]=True , __lowerCamelCase : str=False , __lowerCamelCase : Tuple=2 , __lowerCamelCase : Optional[int]=5 , __lowerCamelCase : int=2 , __lowerCamelCase : List[str]=1 , __lowerCamelCase : int=1 , __lowerCamelCase : str=2 , __lowerCamelCase : Optional[int]=5 , __lowerCamelCase : int=2 , __lowerCamelCase : Dict=0.25 , **__lowerCamelCase : Union[str, Any] , ) -> str: if backbone_config is not None and use_timm_backbone: raise ValueError("You can\'t specify both `backbone_config` and `use_timm_backbone`." ) if not use_timm_backbone: if backbone_config is None: logger.info("`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone." ) a = CONFIG_MAPPING['resnet'](out_features=["stage4"] ) elif isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): a = backbone_config.get("model_type" ) a = CONFIG_MAPPING[backbone_model_type] a = config_class.from_dict(SCREAMING_SNAKE_CASE__ ) a = use_timm_backbone a = backbone_config a = num_channels a = num_queries a = d_model a = encoder_ffn_dim a = encoder_layers a = encoder_attention_heads a = decoder_ffn_dim a = decoder_layers a = decoder_attention_heads a = dropout a = attention_dropout a = activation_dropout a = activation_function a = init_std a = init_xavier_std a = encoder_layerdrop a = decoder_layerdrop a = encoder_layers a = auxiliary_loss a = position_embedding_type a = backbone a = use_pretrained_backbone a = dilation # Hungarian matcher a = class_cost a = bbox_cost a = giou_cost # Loss coefficients a = mask_loss_coefficient a = dice_loss_coefficient a = cls_loss_coefficient a = bbox_loss_coefficient a = giou_loss_coefficient a = focal_alpha super().__init__(is_encoder_decoder=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) @property def __UpperCAmelCase ( self : Union[str, Any] ) -> Any: return self.encoder_attention_heads @property def __UpperCAmelCase ( self : int ) -> Tuple: return self.d_model def __UpperCAmelCase ( self : str ) -> Optional[Any]: a = copy.deepcopy(self.__dict__ ) if self.backbone_config is not None: a = self.backbone_config.to_dict() a = self.__class__.model_type return output class snake_case__ (_UpperCamelCase ): """simple docstring""" SCREAMING_SNAKE_CASE_ : int = version.parse("""1.11""" ) @property def __UpperCAmelCase ( self : Optional[int] ) -> List[Any]: return OrderedDict( [ ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}), ("pixel_mask", {0: "batch"}), ] ) @property def __UpperCAmelCase ( self : Optional[Any] ) -> Tuple: return 1e-5 @property def __UpperCAmelCase ( self : str ) -> Union[str, Any]: return 12
107
def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> float: if discount_rate < 0: raise ValueError('Discount rate cannot be negative' ) if not cash_flows: raise ValueError('Cash flows list cannot be empty' ) __lowerCamelCase : int = sum( cash_flow / ((1 + discount_rate) ** i) for i, cash_flow in enumerate(lowerCamelCase__ ) ) return round(lowerCamelCase__ , ndigits=2 ) if __name__ == "__main__": import doctest doctest.testmod()
73
0
"""simple docstring""" import argparse from typing import Dict import tensorflow as tf import torch from tqdm import tqdm from transformers import BigBirdPegasusConfig, BigBirdPegasusForConditionalGeneration _lowercase = [ # tf -> hf ('''/''', '''.'''), ('''layer_''', '''layers.'''), ('''kernel''', '''weight'''), ('''beta''', '''bias'''), ('''gamma''', '''weight'''), ('''pegasus''', '''model'''), ] _lowercase = [ ('''.output.dense''', '''.fc2'''), ('''intermediate.LayerNorm''', '''final_layer_norm'''), ('''intermediate.dense''', '''fc1'''), ] _lowercase = ( INIT_COMMON + [ ('''attention.self.LayerNorm''', '''self_attn_layer_norm'''), ('''attention.output.dense''', '''self_attn.out_proj'''), ('''attention.self''', '''self_attn'''), ('''attention.encdec.LayerNorm''', '''encoder_attn_layer_norm'''), ('''attention.encdec_output.dense''', '''encoder_attn.out_proj'''), ('''attention.encdec''', '''encoder_attn'''), ('''key''', '''k_proj'''), ('''value''', '''v_proj'''), ('''query''', '''q_proj'''), ('''decoder.LayerNorm''', '''decoder.layernorm_embedding'''), ] + END_COMMON ) _lowercase = ( INIT_COMMON + [ ('''embeddings.word_embeddings''', '''shared.weight'''), ('''embeddings.position_embeddings''', '''embed_positions.weight'''), ('''attention.self.LayerNorm''', '''self_attn_layer_norm'''), ('''attention.output.dense''', '''self_attn.output'''), ('''attention.self''', '''self_attn.self'''), ('''encoder.LayerNorm''', '''encoder.layernorm_embedding'''), ] + END_COMMON ) _lowercase = [ '''encdec/key/bias''', '''encdec/query/bias''', '''encdec/value/bias''', '''self/key/bias''', '''self/query/bias''', '''self/value/bias''', '''encdec_output/dense/bias''', '''attention/output/dense/bias''', ] def _snake_case ( snake_case__ : Optional[Any] , snake_case__ : List[str] ): for tf_name, hf_name in patterns: A = k.replace(snake_case__ , snake_case__ ) return k def _snake_case ( snake_case__ : dict , snake_case__ : dict ): A = BigBirdPegasusConfig(**snake_case__ ) A = BigBirdPegasusForConditionalGeneration(snake_case__ ) A = torch_model.state_dict() A = {} # separating decoder weights A = {k: tf_weights[k] for k in tf_weights if k.startswith('pegasus/decoder' )} A = {k: tf_weights[k] for k in tf_weights if not k.startswith('pegasus/decoder' )} for k, v in tqdm(decoder_weights.items() , 'tf -> hf conversion' ): A = [k.endswith(snake_case__ ) for ending in KEYS_TO_IGNORE] if any(snake_case__ ): continue A = DECODER_PATTERNS A = rename_state_dict_key(snake_case__ , snake_case__ ) if new_k not in state_dict: raise ValueError(F'could not find new key {new_k} in state dict. (converted from {k})' ) if any(True if i in k else False for i in ['dense', 'query', 'key', 'value'] ): A = v.T A = torch.from_numpy(snake_case__ ) assert v.shape == state_dict[new_k].shape, F'{new_k}, {k}, {v.shape}, {state_dict[new_k].shape}' for k, v in tqdm(remaining_weights.items() , 'tf -> hf conversion' ): A = [k.endswith(snake_case__ ) for ending in KEYS_TO_IGNORE] if any(snake_case__ ): continue A = REMAINING_PATTERNS A = rename_state_dict_key(snake_case__ , snake_case__ ) if new_k not in state_dict and k != "pegasus/embeddings/position_embeddings": raise ValueError(F'could not find new key {new_k} in state dict. (converted from {k})' ) if any(True if i in k else False for i in ['dense', 'query', 'key', 'value'] ): A = v.T A = torch.from_numpy(snake_case__ ) if k != "pegasus/embeddings/position_embeddings": assert v.shape == state_dict[new_k].shape, F'{new_k}, {k}, {v.shape}, {state_dict[new_k].shape}' A = mapping['model.embed_positions.weight'] A = mapping.pop('model.embed_positions.weight' ) A , A = torch_model.load_state_dict(snake_case__ , strict=snake_case__ ) A = [ k for k in missing if k not in [ 'final_logits_bias', 'model.encoder.embed_tokens.weight', 'model.decoder.embed_tokens.weight', 'lm_head.weight', ] ] assert unexpected_missing == [], F'no matches found for the following torch keys {unexpected_missing}' assert extra == [], F'no matches found for the following tf keys {extra}' return torch_model def _snake_case ( snake_case__ : Union[str, Any] ): A = tf.train.list_variables(snake_case__ ) A = {} A = ['global_step'] for name, shape in tqdm(snake_case__ , desc='converting tf checkpoint to dict' ): A = any(pat in name for pat in ignore_name ) if skip_key: continue A = tf.train.load_variable(snake_case__ , snake_case__ ) A = array return tf_weights def _snake_case ( snake_case__ : str , snake_case__ : str , snake_case__ : dict ): A = get_tf_weights_as_numpy(snake_case__ ) A = convert_bigbird_pegasus(snake_case__ , snake_case__ ) torch_model.save_pretrained(snake_case__ ) if __name__ == "__main__": _lowercase = argparse.ArgumentParser() parser.add_argument('''--tf_ckpt_path''', type=str, help='''passed to tf.train.list_variables''') parser.add_argument('''--save_dir''', default=None, type=str, help='''Path to the output PyTorch model.''') _lowercase = parser.parse_args() _lowercase = {} convert_bigbird_pegasus_ckpt_to_pytorch(args.tf_ckpt_path, args.save_dir, config_update=config_update)
74
"""simple docstring""" import argparse import json import os 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 from accelerate.utils.deepspeed import DummyOptim, DummyScheduler _lowercase = 16 _lowercase = 32 def _snake_case ( snake_case__ : Accelerator , snake_case__ : int = 16 , snake_case__ : str = "bert-base-cased" ): A = AutoTokenizer.from_pretrained(snake_case__ ) A = load_dataset('glue' , 'mrpc' ) def tokenize_function(snake_case__ : Dict ): # max_length=None => use the model max length (it's actually the default) A = tokenizer(examples['sentence1'] , examples['sentence2'] , truncation=snake_case__ , max_length=snake_case__ ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset A = datasets.map( snake_case__ , batched=snake_case__ , remove_columns=['idx', 'sentence1', 'sentence2'] , load_from_cache_file=snake_case__ ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library A = tokenized_datasets.rename_column('label' , 'labels' ) def collate_fn(snake_case__ : int ): # On TPU it's best to pad everything to the same length or training will be very slow. if accelerator.distributed_type == DistributedType.TPU: return tokenizer.pad(snake_case__ , padding='max_length' , max_length=128 , return_tensors='pt' ) return tokenizer.pad(snake_case__ , padding='longest' , return_tensors='pt' ) # Instantiate dataloaders. A = DataLoader( tokenized_datasets['train'] , shuffle=snake_case__ , collate_fn=snake_case__ , batch_size=snake_case__ ) A = DataLoader( tokenized_datasets['validation'] , shuffle=snake_case__ , collate_fn=snake_case__ , batch_size=snake_case__ ) return train_dataloader, eval_dataloader def _snake_case ( snake_case__ : Optional[int] , snake_case__ : Optional[int] ): # Initialize accelerator A = Accelerator() # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs A = config['lr'] A = int(config['num_epochs'] ) A = int(config['seed'] ) A = int(config['batch_size'] ) A = args.model_name_or_path set_seed(snake_case__ ) A , A = get_dataloaders(snake_case__ , snake_case__ , snake_case__ ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) A = AutoModelForSequenceClassification.from_pretrained(snake_case__ , return_dict=snake_case__ ) # Instantiate optimizer A = ( AdamW if accelerator.state.deepspeed_plugin is None or 'optimizer' not in accelerator.state.deepspeed_plugin.deepspeed_config else DummyOptim ) A = optimizer_cls(params=model.parameters() , lr=snake_case__ ) if accelerator.state.deepspeed_plugin is not None: A = accelerator.state.deepspeed_plugin.deepspeed_config[ 'gradient_accumulation_steps' ] else: A = 1 A = (len(snake_case__ ) * num_epochs) // gradient_accumulation_steps # Instantiate scheduler if ( accelerator.state.deepspeed_plugin is None or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config ): A = get_linear_schedule_with_warmup( optimizer=snake_case__ , num_warmup_steps=0 , num_training_steps=snake_case__ , ) else: A = DummyScheduler(snake_case__ , total_num_steps=snake_case__ , warmup_num_steps=0 ) # 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. A , A , A , A , A = accelerator.prepare( snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ ) # We need to keep track of how many total steps we have iterated over A = 0 # We also need to keep track of the stating epoch so files are named properly A = 0 # Now we train the model A = evaluate.load('glue' , 'mrpc' ) A = 0 A = {} for epoch in range(snake_case__ , snake_case__ ): model.train() for step, batch in enumerate(snake_case__ ): A = model(**snake_case__ ) A = outputs.loss A = loss / gradient_accumulation_steps accelerator.backward(snake_case__ ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() overall_step += 1 model.eval() A = 0 for step, batch in enumerate(snake_case__ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): A = model(**snake_case__ ) A = outputs.logits.argmax(dim=-1 ) # It is slightly faster to call this once, than multiple times A , A = accelerator.gather( (predictions, batch['labels']) ) # If we are in a multiprocess environment, the last batch has duplicates if accelerator.use_distributed: if step == len(snake_case__ ) - 1: A = predictions[: len(eval_dataloader.dataset ) - samples_seen] A = references[: len(eval_dataloader.dataset ) - samples_seen] else: samples_seen += references.shape[0] metric.add_batch( predictions=snake_case__ , references=snake_case__ , ) A = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F'epoch {epoch}:' , snake_case__ ) A = eval_metric['accuracy'] if best_performance < eval_metric["accuracy"]: A = eval_metric['accuracy'] if args.performance_lower_bound is not None: assert ( args.performance_lower_bound <= best_performance ), F'Best performance metric {best_performance} is lower than the lower bound {args.performance_lower_bound}' accelerator.wait_for_everyone() if accelerator.is_main_process: with open(os.path.join(args.output_dir , 'all_results.json' ) , 'w' ) as f: json.dump(snake_case__ , snake_case__ ) def _snake_case ( ): A = argparse.ArgumentParser(description='Simple example of training script tracking peak GPU memory usage.' ) parser.add_argument( '--model_name_or_path' , type=snake_case__ , default='bert-base-cased' , help='Path to pretrained model or model identifier from huggingface.co/models.' , required=snake_case__ , ) parser.add_argument( '--output_dir' , type=snake_case__ , default='.' , help='Optional save directory where all checkpoint folders will be stored. Default is the current working directory.' , ) parser.add_argument( '--performance_lower_bound' , type=snake_case__ , default=snake_case__ , help='Optional lower bound for the performance metric. If set, the training will throw error when the performance metric drops below this value.' , ) parser.add_argument( '--num_epochs' , type=snake_case__ , default=3 , help='Number of train epochs.' , ) A = parser.parse_args() A = {'lr': 2e-5, 'num_epochs': args.num_epochs, 'seed': 42, 'batch_size': 16} training_function(snake_case__ , snake_case__ ) if __name__ == "__main__": main()
74
1
"""simple docstring""" from ..utils import DummyObject, requires_backends class lowerCAmelCase_ ( metaclass=_lowercase ): '''simple docstring''' _lowerCamelCase: List[Any] = ['''sentencepiece'''] def __init__( self : str ,*A_ : Any ,**A_ : Any ) -> Optional[Any]: requires_backends(self ,['sentencepiece'] ) class lowerCAmelCase_ ( metaclass=_lowercase ): '''simple docstring''' _lowerCamelCase: Tuple = ['''sentencepiece'''] def __init__( self : Union[str, Any] ,*A_ : Tuple ,**A_ : Tuple ) -> Optional[int]: requires_backends(self ,['sentencepiece'] ) class lowerCAmelCase_ ( metaclass=_lowercase ): '''simple docstring''' _lowerCamelCase: Tuple = ['''sentencepiece'''] def __init__( self : Dict ,*A_ : List[str] ,**A_ : int ) -> List[Any]: requires_backends(self ,['sentencepiece'] ) class lowerCAmelCase_ ( metaclass=_lowercase ): '''simple docstring''' _lowerCamelCase: Optional[int] = ['''sentencepiece'''] def __init__( self : Any ,*A_ : Any ,**A_ : Optional[int] ) -> Optional[int]: requires_backends(self ,['sentencepiece'] ) class lowerCAmelCase_ ( metaclass=_lowercase ): '''simple docstring''' _lowerCamelCase: str = ['''sentencepiece'''] def __init__( self : Optional[int] ,*A_ : Any ,**A_ : Any ) -> int: requires_backends(self ,['sentencepiece'] ) class lowerCAmelCase_ ( metaclass=_lowercase ): '''simple docstring''' _lowerCamelCase: Union[str, Any] = ['''sentencepiece'''] def __init__( self : str ,*A_ : List[str] ,**A_ : str ) -> Optional[int]: requires_backends(self ,['sentencepiece'] ) class lowerCAmelCase_ ( metaclass=_lowercase ): '''simple docstring''' _lowerCamelCase: List[Any] = ['''sentencepiece'''] def __init__( self : int ,*A_ : Any ,**A_ : str ) -> str: requires_backends(self ,['sentencepiece'] ) class lowerCAmelCase_ ( metaclass=_lowercase ): '''simple docstring''' _lowerCamelCase: Any = ['''sentencepiece'''] def __init__( self : Optional[Any] ,*A_ : Union[str, Any] ,**A_ : str ) -> int: requires_backends(self ,['sentencepiece'] ) class lowerCAmelCase_ ( metaclass=_lowercase ): '''simple docstring''' _lowerCamelCase: Optional[int] = ['''sentencepiece'''] def __init__( self : Optional[int] ,*A_ : int ,**A_ : Optional[Any] ) -> List[Any]: requires_backends(self ,['sentencepiece'] ) class lowerCAmelCase_ ( metaclass=_lowercase ): '''simple docstring''' _lowerCamelCase: List[str] = ['''sentencepiece'''] def __init__( self : str ,*A_ : List[str] ,**A_ : Dict ) -> Union[str, Any]: requires_backends(self ,['sentencepiece'] ) class lowerCAmelCase_ ( metaclass=_lowercase ): '''simple docstring''' _lowerCamelCase: str = ['''sentencepiece'''] def __init__( self : List[Any] ,*A_ : Tuple ,**A_ : Any ) -> List[Any]: requires_backends(self ,['sentencepiece'] ) class lowerCAmelCase_ ( metaclass=_lowercase ): '''simple docstring''' _lowerCamelCase: Optional[Any] = ['''sentencepiece'''] def __init__( self : int ,*A_ : Any ,**A_ : int ) -> Optional[Any]: requires_backends(self ,['sentencepiece'] ) class lowerCAmelCase_ ( metaclass=_lowercase ): '''simple docstring''' _lowerCamelCase: Union[str, Any] = ['''sentencepiece'''] def __init__( self : str ,*A_ : Union[str, Any] ,**A_ : Union[str, Any] ) -> Optional[int]: requires_backends(self ,['sentencepiece'] ) class lowerCAmelCase_ ( metaclass=_lowercase ): '''simple docstring''' _lowerCamelCase: Optional[int] = ['''sentencepiece'''] def __init__( self : List[str] ,*A_ : Optional[Any] ,**A_ : Tuple ) -> Tuple: requires_backends(self ,['sentencepiece'] ) class lowerCAmelCase_ ( metaclass=_lowercase ): '''simple docstring''' _lowerCamelCase: int = ['''sentencepiece'''] def __init__( self : Tuple ,*A_ : Optional[int] ,**A_ : Optional[int] ) -> int: requires_backends(self ,['sentencepiece'] ) class lowerCAmelCase_ ( metaclass=_lowercase ): '''simple docstring''' _lowerCamelCase: Dict = ['''sentencepiece'''] def __init__( self : int ,*A_ : Any ,**A_ : int ) -> str: requires_backends(self ,['sentencepiece'] ) class lowerCAmelCase_ ( metaclass=_lowercase ): '''simple docstring''' _lowerCamelCase: int = ['''sentencepiece'''] def __init__( self : Dict ,*A_ : Tuple ,**A_ : List[Any] ) -> Optional[Any]: requires_backends(self ,['sentencepiece'] ) class lowerCAmelCase_ ( metaclass=_lowercase ): '''simple docstring''' _lowerCamelCase: Tuple = ['''sentencepiece'''] def __init__( self : Tuple ,*A_ : List[Any] ,**A_ : Tuple ) -> int: requires_backends(self ,['sentencepiece'] ) class lowerCAmelCase_ ( metaclass=_lowercase ): '''simple docstring''' _lowerCamelCase: List[Any] = ['''sentencepiece'''] def __init__( self : Optional[Any] ,*A_ : List[str] ,**A_ : List[Any] ) -> Tuple: requires_backends(self ,['sentencepiece'] ) class lowerCAmelCase_ ( metaclass=_lowercase ): '''simple docstring''' _lowerCamelCase: Tuple = ['''sentencepiece'''] def __init__( self : Any ,*A_ : Optional[int] ,**A_ : Union[str, Any] ) -> Tuple: requires_backends(self ,['sentencepiece'] ) class lowerCAmelCase_ ( metaclass=_lowercase ): '''simple docstring''' _lowerCamelCase: List[str] = ['''sentencepiece'''] def __init__( self : str ,*A_ : List[Any] ,**A_ : Dict ) -> Optional[Any]: requires_backends(self ,['sentencepiece'] ) class lowerCAmelCase_ ( metaclass=_lowercase ): '''simple docstring''' _lowerCamelCase: List[Any] = ['''sentencepiece'''] def __init__( self : int ,*A_ : Union[str, Any] ,**A_ : str ) -> Tuple: requires_backends(self ,['sentencepiece'] ) class lowerCAmelCase_ ( metaclass=_lowercase ): '''simple docstring''' _lowerCamelCase: str = ['''sentencepiece'''] def __init__( self : str ,*A_ : int ,**A_ : Tuple ) -> Any: requires_backends(self ,['sentencepiece'] ) class lowerCAmelCase_ ( metaclass=_lowercase ): '''simple docstring''' _lowerCamelCase: Tuple = ['''sentencepiece'''] def __init__( self : List[str] ,*A_ : List[str] ,**A_ : Tuple ) -> str: requires_backends(self ,['sentencepiece'] ) class lowerCAmelCase_ ( metaclass=_lowercase ): '''simple docstring''' _lowerCamelCase: List[str] = ['''sentencepiece'''] def __init__( self : List[str] ,*A_ : List[str] ,**A_ : Optional[Any] ) -> Union[str, Any]: requires_backends(self ,['sentencepiece'] ) class lowerCAmelCase_ ( metaclass=_lowercase ): '''simple docstring''' _lowerCamelCase: Optional[Any] = ['''sentencepiece'''] def __init__( self : Any ,*A_ : List[Any] ,**A_ : Union[str, Any] ) -> Union[str, Any]: requires_backends(self ,['sentencepiece'] ) class lowerCAmelCase_ ( metaclass=_lowercase ): '''simple docstring''' _lowerCamelCase: Union[str, Any] = ['''sentencepiece'''] def __init__( self : Dict ,*A_ : List[str] ,**A_ : Any ) -> Optional[Any]: requires_backends(self ,['sentencepiece'] ) class lowerCAmelCase_ ( metaclass=_lowercase ): '''simple docstring''' _lowerCamelCase: Dict = ['''sentencepiece'''] def __init__( self : Dict ,*A_ : int ,**A_ : Optional[int] ) -> Dict: requires_backends(self ,['sentencepiece'] ) class lowerCAmelCase_ ( metaclass=_lowercase ): '''simple docstring''' _lowerCamelCase: str = ['''sentencepiece'''] def __init__( self : List[Any] ,*A_ : Union[str, Any] ,**A_ : Union[str, Any] ) -> List[Any]: requires_backends(self ,['sentencepiece'] ) class lowerCAmelCase_ ( metaclass=_lowercase ): '''simple docstring''' _lowerCamelCase: str = ['''sentencepiece'''] def __init__( self : Any ,*A_ : Union[str, Any] ,**A_ : Any ) -> List[Any]: requires_backends(self ,['sentencepiece'] ) class lowerCAmelCase_ ( metaclass=_lowercase ): '''simple docstring''' _lowerCamelCase: Dict = ['''sentencepiece'''] def __init__( self : Optional[int] ,*A_ : int ,**A_ : Union[str, Any] ) -> Tuple: requires_backends(self ,['sentencepiece'] )
74
"""simple docstring""" 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 lowerCAmelCase_ : '''simple docstring''' def __init__( self : Optional[Any] ,A_ : str ,A_ : Dict=13 ,A_ : str=7 ,A_ : str=True ,A_ : Any=True ,A_ : Optional[Any]=True ,A_ : Any=True ,A_ : Optional[Any]=True ,A_ : Any=False ,A_ : str=False ,A_ : Tuple=False ,A_ : str=2 ,A_ : Optional[int]=99 ,A_ : Union[str, Any]=0 ,A_ : Optional[Any]=32 ,A_ : Optional[int]=5 ,A_ : Optional[int]=4 ,A_ : Union[str, Any]=0.1 ,A_ : List[str]=0.1 ,A_ : Union[str, Any]=512 ,A_ : Union[str, Any]=2 ,A_ : Any=0.02 ,A_ : List[str]=2 ,A_ : int=4 ,A_ : int="last" ,A_ : Dict=True ,A_ : Union[str, Any]=None ,A_ : Any=0 ,) -> List[Any]: A = parent A = batch_size A = seq_length A = is_training A = use_input_lengths A = use_token_type_ids A = use_labels A = gelu_activation A = sinusoidal_embeddings A = causal A = asm A = n_langs A = vocab_size A = n_special A = hidden_size A = num_hidden_layers A = num_attention_heads A = hidden_dropout_prob A = attention_probs_dropout_prob A = max_position_embeddings A = type_sequence_label_size A = initializer_range A = num_labels A = num_choices A = summary_type A = use_proj A = scope A = bos_token_id def _SCREAMING_SNAKE_CASE ( self : Dict ) -> Union[str, Any]: A = ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size ) A = random_attention_mask([self.batch_size, self.seq_length] ) A = None if self.use_input_lengths: A = ( ids_tensor([self.batch_size] ,vocab_size=2 ) + self.seq_length - 2 ) # small variation of seq_length A = None if self.use_token_type_ids: A = ids_tensor([self.batch_size, self.seq_length] ,self.n_langs ) A = None A = None A = None if self.use_labels: A = ids_tensor([self.batch_size] ,self.type_sequence_label_size ) A = ids_tensor([self.batch_size, self.seq_length] ,self.num_labels ) A = ids_tensor([self.batch_size] ,2 ).float() A = ids_tensor([self.batch_size] ,self.num_choices ) A = 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 : Optional[int] ) -> Dict: 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 : List[Any] ,A_ : Any ,A_ : int ,A_ : Dict ,A_ : str ,A_ : Optional[Any] ,A_ : List[str] ,A_ : Union[str, Any] ,A_ : int ,A_ : str ,) -> Any: A = XLMModel(config=A_ ) model.to(A_ ) model.eval() A = model(A_ ,lengths=A_ ,langs=A_ ) A = model(A_ ,langs=A_ ) A = model(A_ ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) def _SCREAMING_SNAKE_CASE ( self : List[str] ,A_ : Any ,A_ : str ,A_ : Optional[int] ,A_ : Union[str, Any] ,A_ : Optional[int] ,A_ : str ,A_ : Any ,A_ : str ,A_ : Dict ,) -> Dict: A = XLMWithLMHeadModel(A_ ) model.to(A_ ) model.eval() A = 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 : Union[str, Any] ,A_ : List[str] ,A_ : Union[str, Any] ,A_ : Union[str, Any] ,A_ : List[str] ,A_ : Any ,A_ : Optional[int] ,A_ : Optional[int] ,A_ : Optional[int] ,A_ : Optional[Any] ,) -> int: A = XLMForQuestionAnsweringSimple(A_ ) model.to(A_ ) model.eval() A = model(A_ ) A = model(A_ ,start_positions=A_ ,end_positions=A_ ) A = 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 : Any ,A_ : Tuple ,A_ : Optional[int] ,A_ : Any ,A_ : List[Any] ,A_ : int ,A_ : Tuple ,A_ : Tuple ,A_ : List[str] ,A_ : Optional[int] ,) -> List[Any]: A = XLMForQuestionAnswering(A_ ) model.to(A_ ) model.eval() A = model(A_ ) A = model( A_ ,start_positions=A_ ,end_positions=A_ ,cls_index=A_ ,is_impossible=A_ ,p_mask=A_ ,) A = model( A_ ,start_positions=A_ ,end_positions=A_ ,cls_index=A_ ,is_impossible=A_ ,) ((A) , ) = result_with_labels.to_tuple() A = model(A_ ,start_positions=A_ ,end_positions=A_ ) ((A) , ) = 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 : List[Any] ,A_ : Tuple ,A_ : int ,A_ : Optional[int] ,A_ : List[str] ,A_ : str ,A_ : Optional[Any] ,A_ : Optional[int] ,A_ : Optional[Any] ,A_ : List[Any] ,) -> Optional[int]: A = XLMForSequenceClassification(A_ ) model.to(A_ ) model.eval() A = model(A_ ) A = 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 : int ,A_ : List[Any] ,A_ : str ,A_ : Optional[Any] ,A_ : List[Any] ,A_ : Optional[int] ,A_ : Tuple ,A_ : Union[str, Any] ,A_ : Optional[int] ,A_ : Optional[int] ,) -> List[str]: A = self.num_labels A = XLMForTokenClassification(A_ ) model.to(A_ ) model.eval() A = 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 : Dict ,A_ : Optional[int] ,A_ : Union[str, Any] ,A_ : List[str] ,A_ : Optional[int] ,A_ : List[str] ,A_ : Optional[Any] ,A_ : Union[str, Any] ,A_ : Dict ,A_ : List[Any] ,) -> List[str]: A = self.num_choices A = XLMForMultipleChoice(config=A_ ) model.to(A_ ) model.eval() A = input_ids.unsqueeze(1 ).expand(-1 ,self.num_choices ,-1 ).contiguous() A = token_type_ids.unsqueeze(1 ).expand(-1 ,self.num_choices ,-1 ).contiguous() A = input_mask.unsqueeze(1 ).expand(-1 ,self.num_choices ,-1 ).contiguous() A = 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 : Dict ) -> int: A = self.prepare_config_and_inputs() ( ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ) = config_and_inputs A = {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'lengths': input_lengths} return config, inputs_dict @require_torch class lowerCAmelCase_ ( _lowercase , _lowercase , _lowercase , unittest.TestCase ): '''simple docstring''' _lowerCamelCase: Union[str, Any] = ( ( XLMModel, XLMWithLMHeadModel, XLMForQuestionAnswering, XLMForSequenceClassification, XLMForQuestionAnsweringSimple, XLMForTokenClassification, XLMForMultipleChoice, ) if is_torch_available() else () ) _lowerCamelCase: str = ( (XLMWithLMHeadModel,) if is_torch_available() else () ) # TODO (PVP): Check other models whether language generation is also applicable _lowerCamelCase: Optional[int] = ( { '''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 : Any ,A_ : Optional[int] ,A_ : Union[str, Any] ,A_ : Union[str, Any] ,A_ : Any ,A_ : Any ) -> Any: 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 : int ,A_ : str ,A_ : Optional[int] ,A_ : List[Any]=False ) -> int: A = super()._prepare_for_class(A_ ,A_ ,return_labels=A_ ) if return_labels: if model_class.__name__ == "XLMForQuestionAnswering": A = torch.zeros( self.model_tester.batch_size ,dtype=torch.long ,device=A_ ) A = torch.zeros( self.model_tester.batch_size ,dtype=torch.long ,device=A_ ) return inputs_dict def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Optional[Any]: A = XLMModelTester(self ) A = ConfigTester(self ,config_class=A_ ,emb_dim=37 ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> str: self.config_tester.run_common_tests() def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Any: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_model(*A_ ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> List[Any]: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_lm_head(*A_ ) def _SCREAMING_SNAKE_CASE ( self : Any ) -> Tuple: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_simple_qa(*A_ ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> List[Any]: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_qa(*A_ ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Any: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_sequence_classif(*A_ ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Optional[Any]: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_token_classif(*A_ ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Any: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_for_multiple_choice(*A_ ) def _SCREAMING_SNAKE_CASE ( self : Tuple ,A_ : Union[str, Any] ,A_ : Any ,A_ : str ,A_ : Tuple ,A_ : Any ,A_ : Any=False ,A_ : Any=1 ) -> List[Any]: 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 A = min_length + idx + 1 A = min_length + idx + 1 A = ( 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 : Dict ,A_ : Optional[int] ,A_ : str ,A_ : Optional[int] ,A_ : int ,A_ : Any ,A_ : str=False ,A_ : Any=1 ) -> Tuple: 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 A = min_length + idx + 1 A = (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 : List[Any] ) -> Optional[Any]: for model_name in XLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: A = XLMModel.from_pretrained(A_ ) self.assertIsNotNone(A_ ) @require_torch class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' @slow def _SCREAMING_SNAKE_CASE ( self : Dict ) -> str: A = XLMWithLMHeadModel.from_pretrained('xlm-mlm-en-2048' ) model.to(A_ ) A = torch.tensor([[14, 447]] ,dtype=torch.long ,device=A_ ) # the president A = [ 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 A = model.generate(A_ ,do_sample=A_ ) self.assertListEqual(output_ids[0].cpu().numpy().tolist() ,A_ )
74
1
"""simple docstring""" # Function to print upper half of diamond (pyramid) def _snake_case ( snake_case__ : Dict ): for i in range(0 , snake_case__ ): for _ in range(0 , n - i - 1 ): # printing spaces print(' ' , end='' ) for _ in range(0 , i + 1 ): # printing stars print('* ' , end='' ) print() def _snake_case ( snake_case__ : Tuple ): for i in range(snake_case__ , 0 , -1 ): for _ in range(snake_case__ , 0 , -1 ): # printing stars print('* ' , end='' ) print() for _ in range(n - i + 1 , 0 , -1 ): # printing spaces print(' ' , end='' ) def _snake_case ( snake_case__ : Dict ): if n <= 0: print(' ... .... nothing printing :(' ) return floyd(snake_case__ ) # upper half reverse_floyd(snake_case__ ) # lower half if __name__ == "__main__": print(r'''| /\ | |- | |- |--| |\ /| |-''') print(r'''|/ \| |- |_ |_ |__| | \/ | |_''') _lowercase = 1 while K: _lowercase = int(input('''enter the number and , and see the magic : ''')) print() pretty_print(user_number) _lowercase = int(input('''press 0 to exit... and 1 to continue...''')) print('''Good Bye...''')
74
"""simple docstring""" from dataclasses import dataclass, field from typing import Tuple from ..utils import cached_property, is_tf_available, logging, requires_backends from .benchmark_args_utils import BenchmarkArguments if is_tf_available(): import tensorflow as tf _lowercase = logging.get_logger(__name__) @dataclass class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: Optional[int] = [ '''no_inference''', '''no_cuda''', '''no_tpu''', '''no_speed''', '''no_memory''', '''no_env_print''', '''no_multi_process''', ] def __init__( self : int ,**A_ : Any ) -> Any: for deprecated_arg in self.deprecated_args: if deprecated_arg in kwargs: A = deprecated_arg[3:] A = not kwargs.pop(A_ ) logger.warning( F'{deprecated_arg} is depreciated. Please use --no-{positive_arg} or' F' {positive_arg}={kwargs[positive_arg]}' ) A = kwargs.pop('tpu_name' ,self.tpu_name ) A = kwargs.pop('device_idx' ,self.device_idx ) A = kwargs.pop('eager_mode' ,self.eager_mode ) A = kwargs.pop('use_xla' ,self.use_xla ) super().__init__(**A_ ) _lowerCamelCase: str = field( default=_lowercase , metadata={'''help''': '''Name of TPU'''} , ) _lowerCamelCase: int = field( default=0 , metadata={'''help''': '''CPU / GPU device index. Defaults to 0.'''} , ) _lowerCamelCase: bool = field(default=_lowercase , metadata={'''help''': '''Benchmark models in eager model.'''} ) _lowerCamelCase: bool = field( default=_lowercase , metadata={ '''help''': '''Benchmark models using XLA JIT compilation. Note that `eager_model` has to be set to `False`.''' } , ) @cached_property def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Tuple["tf.distribute.cluster_resolver.TPUClusterResolver"]: requires_backends(self ,['tf'] ) A = None if self.tpu: try: if self.tpu_name: A = tf.distribute.cluster_resolver.TPUClusterResolver(self.tpu_name ) else: A = tf.distribute.cluster_resolver.TPUClusterResolver() except ValueError: A = None return tpu @cached_property def _SCREAMING_SNAKE_CASE ( self : Tuple ) -> Tuple["tf.distribute.Strategy", "tf.distribute.cluster_resolver.TPUClusterResolver"]: requires_backends(self ,['tf'] ) if self.is_tpu: tf.config.experimental_connect_to_cluster(self._setup_tpu ) tf.tpu.experimental.initialize_tpu_system(self._setup_tpu ) A = tf.distribute.TPUStrategy(self._setup_tpu ) else: # currently no multi gpu is allowed if self.is_gpu: # TODO: Currently only single GPU is supported tf.config.set_visible_devices(self.gpu_list[self.device_idx] ,'GPU' ) A = tf.distribute.OneDeviceStrategy(device=F'/gpu:{self.device_idx}' ) else: tf.config.set_visible_devices([] ,'GPU' ) # disable GPU A = tf.distribute.OneDeviceStrategy(device=F'/cpu:{self.device_idx}' ) return strategy @property def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> bool: requires_backends(self ,['tf'] ) return self._setup_tpu is not None @property def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> "tf.distribute.Strategy": requires_backends(self ,['tf'] ) return self._setup_strategy @property def _SCREAMING_SNAKE_CASE ( self : int ) -> str: requires_backends(self ,['tf'] ) return tf.config.list_physical_devices('GPU' ) @property def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> int: requires_backends(self ,['tf'] ) if self.cuda: return len(self.gpu_list ) return 0 @property def _SCREAMING_SNAKE_CASE ( self : str ) -> bool: return self.n_gpu > 0
74
1
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging _lowercase = logging.get_logger(__name__) _lowercase = { '''google/switch-base-8''': '''https://huggingface.co/google/switch-base-8/blob/main/config.json''', } class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: Tuple = '''switch_transformers''' _lowerCamelCase: int = ['''past_key_values'''] _lowerCamelCase: int = {'''hidden_size''': '''d_model''', '''num_attention_heads''': '''num_heads''', '''num_hidden_layers''': '''num_layers'''} def __init__( self : Optional[int] ,A_ : Optional[int]=3_2128 ,A_ : Optional[Any]=768 ,A_ : Any=64 ,A_ : Tuple=2048 ,A_ : List[str]=64 ,A_ : str=12 ,A_ : Optional[int]=3 ,A_ : Union[str, Any]=12 ,A_ : Optional[int]=3 ,A_ : Any=12 ,A_ : Union[str, Any]=8 ,A_ : List[str]=False ,A_ : List[str]=0.01 ,A_ : List[str]="float32" ,A_ : Tuple=False ,A_ : Dict=32 ,A_ : List[str]=128 ,A_ : Tuple=0.1 ,A_ : List[Any]=1e-6 ,A_ : List[str]=0.0_01 ,A_ : Tuple=0.0_01 ,A_ : Dict=1.0 ,A_ : int="relu" ,A_ : List[Any]=True ,A_ : Dict=False ,A_ : List[Any]=True ,A_ : int=0 ,A_ : Optional[Any]=1 ,**A_ : str ,) -> Dict: A = vocab_size A = d_model A = d_kv A = d_ff A = num_sparse_encoder_layers A = num_layers A = ( num_decoder_layers if num_decoder_layers is not None else self.num_layers ) # default = symmetry A = num_sparse_decoder_layers # This tells us, each how many encoder layer we'll have to set a sparse layer. if self.num_sparse_encoder_layers > 0: A = self.num_layers // self.num_sparse_encoder_layers else: A = self.num_layers # HACK: this will create 0 sparse layers # This tells us, each how many encoder layer we'll have to set a sparse layer. if self.num_sparse_decoder_layers > 0: A = self.num_decoder_layers // self.num_sparse_decoder_layers else: A = self.num_decoder_layers # HACK: this will create 0 sparse layers A = num_heads A = num_experts A = expert_capacity A = router_bias A = router_jitter_noise if router_dtype not in ["float32", "float16", "bfloat16"]: raise ValueError(F'`router_dtype` must be one of \'float32\', \'float16\' or \'bfloat16\', got {router_dtype}' ) A = router_dtype A = router_ignore_padding_tokens A = relative_attention_num_buckets A = relative_attention_max_distance A = dropout_rate A = layer_norm_epsilon A = initializer_factor A = feed_forward_proj A = use_cache A = add_router_probs A = router_z_loss_coef A = router_aux_loss_coef A = self.feed_forward_proj.split('-' ) A = act_info[-1] A = act_info[0] == 'gated' if len(A_ ) > 1 and act_info[0] != "gated" or len(A_ ) > 2: raise ValueError( F'`feed_forward_proj`: {feed_forward_proj} is not a valid activation function of the dense layer.' 'Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. ' '\'gated-gelu\' or \'relu\'' ) # for backwards compatibility if feed_forward_proj == "gated-gelu": A = 'gelu_new' super().__init__( pad_token_id=A_ ,eos_token_id=A_ ,is_encoder_decoder=A_ ,**A_ ,)
74
"""simple docstring""" import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..bit import BitConfig _lowercase = logging.get_logger(__name__) _lowercase = { '''Intel/dpt-large''': '''https://huggingface.co/Intel/dpt-large/resolve/main/config.json''', # See all DPT models at https://huggingface.co/models?filter=dpt } class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: Tuple = '''dpt''' def __init__( self : str ,A_ : Tuple=768 ,A_ : int=12 ,A_ : Optional[int]=12 ,A_ : Optional[int]=3072 ,A_ : List[str]="gelu" ,A_ : str=0.0 ,A_ : int=0.0 ,A_ : str=0.02 ,A_ : str=1e-12 ,A_ : str=384 ,A_ : Dict=16 ,A_ : Union[str, Any]=3 ,A_ : Dict=False ,A_ : Any=True ,A_ : Optional[int]=[2, 5, 8, 11] ,A_ : Optional[Any]="project" ,A_ : Tuple=[4, 2, 1, 0.5] ,A_ : int=[96, 192, 384, 768] ,A_ : int=256 ,A_ : str=-1 ,A_ : Optional[int]=False ,A_ : Optional[int]=True ,A_ : Union[str, Any]=0.4 ,A_ : Union[str, Any]=255 ,A_ : Union[str, Any]=0.1 ,A_ : List[str]=[1, 1024, 24, 24] ,A_ : List[str]=[0, 1] ,A_ : List[Any]=None ,**A_ : Tuple ,) -> Union[str, Any]: super().__init__(**A_ ) A = hidden_size A = is_hybrid if self.is_hybrid: if backbone_config is None: logger.info('Initializing the config with a `BiT` backbone.' ) A = { 'global_padding': 'same', 'layer_type': 'bottleneck', 'depths': [3, 4, 9], 'out_features': ['stage1', 'stage2', 'stage3'], 'embedding_dynamic_padding': True, } A = BitConfig(**A_ ) elif isinstance(A_ ,A_ ): logger.info('Initializing the config with a `BiT` backbone.' ) A = BitConfig(**A_ ) elif isinstance(A_ ,A_ ): A = backbone_config else: raise ValueError( F'backbone_config must be a dictionary or a `PretrainedConfig`, got {backbone_config.__class__}.' ) A = backbone_featmap_shape A = neck_ignore_stages if readout_type != "project": raise ValueError('Readout type must be \'project\' when using `DPT-hybrid` mode.' ) else: A = None A = None A = [] A = num_hidden_layers A = num_attention_heads A = intermediate_size A = hidden_act A = hidden_dropout_prob A = attention_probs_dropout_prob A = initializer_range A = layer_norm_eps A = image_size A = patch_size A = num_channels A = qkv_bias A = backbone_out_indices if readout_type not in ["ignore", "add", "project"]: raise ValueError('Readout_type must be one of [\'ignore\', \'add\', \'project\']' ) A = readout_type A = reassemble_factors A = neck_hidden_sizes A = fusion_hidden_size A = head_in_index A = use_batch_norm_in_fusion_residual # auxiliary head attributes (semantic segmentation) A = use_auxiliary_head A = auxiliary_loss_weight A = semantic_loss_ignore_index A = semantic_classifier_dropout def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> str: A = copy.deepcopy(self.__dict__ ) if output["backbone_config"] is not None: A = self.backbone_config.to_dict() A = self.__class__.model_type return output
74
1
"""simple docstring""" import unittest from transformers.models.xlm_prophetnet.tokenization_xlm_prophetnet import SPIECE_UNDERLINE, XLMProphetNetTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin _lowercase = get_tests_dir('''fixtures/test_sentencepiece.model''') @require_sentencepiece class lowerCAmelCase_ ( _lowercase , unittest.TestCase ): '''simple docstring''' _lowerCamelCase: List[Any] = XLMProphetNetTokenizer _lowerCamelCase: Optional[Any] = False _lowerCamelCase: Union[str, Any] = True def _SCREAMING_SNAKE_CASE ( self : str ) -> Union[str, Any]: super().setUp() # We have a SentencePiece fixture for testing A = XLMProphetNetTokenizer(A_ ,keep_accents=A_ ) tokenizer.save_pretrained(self.tmpdirname ) def _SCREAMING_SNAKE_CASE ( self : int ) -> List[str]: A = '[PAD]' A = 0 self.assertEqual(self.get_tokenizer()._convert_token_to_id(A_ ) ,A_ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(A_ ) ,A_ ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Optional[Any]: A = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] ,'[PAD]' ) self.assertEqual(vocab_keys[1] ,'[CLS]' ) self.assertEqual(vocab_keys[-1] ,'j' ) self.assertEqual(len(A_ ) ,1012 ) def _SCREAMING_SNAKE_CASE ( self : Dict ) -> int: self.assertEqual(self.get_tokenizer().vocab_size ,1012 ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Optional[Any]: A = XLMProphetNetTokenizer(A_ ,keep_accents=A_ ) A = tokenizer.tokenize('This is a test' ) self.assertListEqual(A_ ,['▁This', '▁is', '▁a', '▁t', 'est'] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(A_ ) ,[value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]] ,) A = tokenizer.tokenize('I was born in 92000, and this is falsé.' ) self.assertListEqual( A_ ,[ SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '9', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', 'é', '.', ] ,) A = tokenizer.convert_tokens_to_ids(A_ ) self.assertListEqual( A_ ,[ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, -9, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, -9, 4] ] ,) A = tokenizer.convert_ids_to_tokens(A_ ) self.assertListEqual( A_ ,[ SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '[UNK]', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', '[UNK]', '.', ] ,) @cached_property def _SCREAMING_SNAKE_CASE ( self : Any ) -> List[Any]: return XLMProphetNetTokenizer.from_pretrained('microsoft/xprophetnet-large-wiki100-cased' ) @slow def _SCREAMING_SNAKE_CASE ( self : str ) -> Any: A = 'Hello World!' A = [3_5389, 6672, 49, 2] self.assertListEqual(A_ ,self.big_tokenizer.encode(A_ ) ) @slow def _SCREAMING_SNAKE_CASE ( self : Tuple ) -> Optional[int]: # fmt: off A = {'input_ids': [[1_1073, 8_2783, 18, 26, 8_2783, 549, 5_1540, 248, 1_7209, 1301, 217, 20, 21_5186, 1325, 147, 1_7209, 1301, 217, 20, 5_6370, 53, 12_2020, 20, 1_6477, 27, 8_7355, 4548, 20, 4728, 7_8392, 17, 15_9969, 18, 26, 2_4491, 629, 15, 538, 2_2704, 5439, 15, 2788, 2_4491, 9885, 15, 4_3534, 605, 15, 814, 1_8403, 3_3200, 29, 15, 4_3534, 2_4458, 1_2410, 111, 2_4966, 8_3669, 9637, 14_4068, 26, 850, 2_2346, 27, 147, 2_4966, 8_3669, 8_3490, 26, 3_9113, 735, 27, 689, 656, 2800, 1339, 4600, 53, 12_2020, 11_5785, 34, 816, 1339, 4_6887, 18, 147, 5_3905, 1951, 4_2238, 4_1170, 1_7732, 834, 436, 15, 2_7523, 9_8733, 217, 147, 5542, 4981, 930, 1_7347, 16, 2], [2_0091, 629, 94, 8_2786, 58, 490, 20, 1528, 84, 5_3905, 344, 8_0592, 11_0128, 1_8822, 5267, 1306, 62, 15_2537, 308, 7997, 401, 12_4427, 549, 3_5442, 225, 109, 1_5055, 2_5748, 147, 7119, 4_3712, 34, 767, 13_5366, 18, 16, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [592, 6_3784, 11_9466, 17, 14_7808, 8_8214, 18, 656, 81, 32, 3296, 1_0280, 16, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=A_ ,model_name='microsoft/xprophetnet-large-wiki100-cased' ,revision='1acad1643ddd54a44df6a1b797ada8373685d90e' ,)
74
"""simple docstring""" from __future__ import annotations import math _lowercase = '''2020.9.26''' _lowercase = '''xcodz-dot, cclaus, dhruvmanila''' def _snake_case ( snake_case__ : float , snake_case__ : float , snake_case__ : float , snake_case__ : float , snake_case__ : float ): if not all(isinstance(snake_case__ , (float, int) ) for val in locals().values() ): A = F'Input values must either be float or int: {list(locals().values() )}' raise TypeError(snake_case__ ) A = ((x * distance) / (z + distance)) * scale A = ((y * distance) / (z + distance)) * scale return projected_x, projected_y def _snake_case ( snake_case__ : float , snake_case__ : float , snake_case__ : float , snake_case__ : str , snake_case__ : float ): if not isinstance(snake_case__ , snake_case__ ): raise TypeError('Axis must be a str' ) A = locals() del input_variables["axis"] if not all(isinstance(snake_case__ , (float, int) ) for val in input_variables.values() ): A = ( 'Input values except axis must either be float or int: ' F'{list(input_variables.values() )}' ) raise TypeError(snake_case__ ) A = (angle % 360) / 450 * 180 / math.pi if axis == "z": A = x * math.cos(snake_case__ ) - y * math.sin(snake_case__ ) A = y * math.cos(snake_case__ ) + x * math.sin(snake_case__ ) A = z elif axis == "x": A = y * math.cos(snake_case__ ) - z * math.sin(snake_case__ ) A = z * math.cos(snake_case__ ) + y * math.sin(snake_case__ ) A = x elif axis == "y": A = x * math.cos(snake_case__ ) - z * math.sin(snake_case__ ) A = z * math.cos(snake_case__ ) + x * math.sin(snake_case__ ) A = y else: raise ValueError('not a valid axis, choose one of \'x\', \'y\', \'z\'' ) return new_x, new_y, new_z if __name__ == "__main__": import doctest doctest.testmod() print(F"""{convert_to_ad(1.0, 2.0, 3.0, 10.0, 10.0) = }""") print(F"""{rotate(1.0, 2.0, 3.0, 'y', 90.0) = }""")
74
1
"""simple docstring""" import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import BertTokenizer, BertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import AlignProcessor, EfficientNetImageProcessor @require_vision class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : str ) -> Tuple: A = tempfile.mkdtemp() A = [ '[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing', ',', 'low', 'lowest', ] A = 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] ) ) A = { 'do_resize': True, 'size': 20, 'do_center_crop': True, 'crop_size': 18, 'do_normalize': True, 'image_mean': [0.48_14_54_66, 0.4_57_82_75, 0.40_82_10_73], 'image_std': [0.26_86_29_54, 0.26_13_02_58, 0.27_57_77_11], } A = os.path.join(self.tmpdirname ,A_ ) with open(self.image_processor_file ,'w' ,encoding='utf-8' ) as fp: json.dump(A_ ,A_ ) def _SCREAMING_SNAKE_CASE ( self : Any ,**A_ : Optional[int] ) -> Dict: return BertTokenizer.from_pretrained(self.tmpdirname ,**A_ ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ,**A_ : Any ) -> int: return BertTokenizerFast.from_pretrained(self.tmpdirname ,**A_ ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ,**A_ : Tuple ) -> int: return EfficientNetImageProcessor.from_pretrained(self.tmpdirname ,**A_ ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Optional[Any]: shutil.rmtree(self.tmpdirname ) def _SCREAMING_SNAKE_CASE ( self : str ) -> Optional[int]: A = [np.random.randint(255 ,size=(3, 30, 400) ,dtype=np.uinta )] A = [Image.fromarray(np.moveaxis(A_ ,0 ,-1 ) ) for x in image_inputs] return image_inputs def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Tuple: A = self.get_tokenizer() A = self.get_rust_tokenizer() A = self.get_image_processor() A = AlignProcessor(tokenizer=A_ ,image_processor=A_ ) processor_slow.save_pretrained(self.tmpdirname ) A = AlignProcessor.from_pretrained(self.tmpdirname ,use_fast=A_ ) A = AlignProcessor(tokenizer=A_ ,image_processor=A_ ) processor_fast.save_pretrained(self.tmpdirname ) A = AlignProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor_slow.tokenizer.get_vocab() ,tokenizer_slow.get_vocab() ) self.assertEqual(processor_fast.tokenizer.get_vocab() ,tokenizer_fast.get_vocab() ) self.assertEqual(tokenizer_slow.get_vocab() ,tokenizer_fast.get_vocab() ) self.assertIsInstance(processor_slow.tokenizer ,A_ ) self.assertIsInstance(processor_fast.tokenizer ,A_ ) self.assertEqual(processor_slow.image_processor.to_json_string() ,image_processor.to_json_string() ) self.assertEqual(processor_fast.image_processor.to_json_string() ,image_processor.to_json_string() ) self.assertIsInstance(processor_slow.image_processor ,A_ ) self.assertIsInstance(processor_fast.image_processor ,A_ ) def _SCREAMING_SNAKE_CASE ( self : int ) -> Union[str, Any]: A = AlignProcessor(tokenizer=self.get_tokenizer() ,image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) A = self.get_tokenizer(bos_token='(BOS)' ,eos_token='(EOS)' ) A = self.get_image_processor(do_normalize=A_ ,padding_value=1.0 ) A = AlignProcessor.from_pretrained( self.tmpdirname ,bos_token='(BOS)' ,eos_token='(EOS)' ,do_normalize=A_ ,padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() ,tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer ,A_ ) self.assertEqual(processor.image_processor.to_json_string() ,image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor ,A_ ) def _SCREAMING_SNAKE_CASE ( self : Dict ) -> str: A = self.get_image_processor() A = self.get_tokenizer() A = AlignProcessor(tokenizer=A_ ,image_processor=A_ ) A = self.prepare_image_inputs() A = image_processor(A_ ,return_tensors='np' ) A = processor(images=A_ ,return_tensors='np' ) for key in input_image_proc.keys(): self.assertAlmostEqual(input_image_proc[key].sum() ,input_processor[key].sum() ,delta=1e-2 ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Tuple: A = self.get_image_processor() A = self.get_tokenizer() A = AlignProcessor(tokenizer=A_ ,image_processor=A_ ) A = 'lower newer' A = processor(text=A_ ) A = tokenizer(A_ ,padding='max_length' ,max_length=64 ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] ,encoded_processor[key] ) def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> Optional[Any]: A = self.get_image_processor() A = self.get_tokenizer() A = AlignProcessor(tokenizer=A_ ,image_processor=A_ ) A = 'lower newer' A = self.prepare_image_inputs() A = processor(text=A_ ,images=A_ ) self.assertListEqual(list(inputs.keys() ) ,['input_ids', 'token_type_ids', 'attention_mask', 'pixel_values'] ) # test if it raises when no input is passed with pytest.raises(A_ ): processor() def _SCREAMING_SNAKE_CASE ( self : Dict ) -> Optional[Any]: A = self.get_image_processor() A = self.get_tokenizer() A = AlignProcessor(tokenizer=A_ ,image_processor=A_ ) A = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] A = processor.batch_decode(A_ ) A = tokenizer.batch_decode(A_ ) self.assertListEqual(A_ ,A_ ) def _SCREAMING_SNAKE_CASE ( self : str ) -> List[str]: A = self.get_image_processor() A = self.get_tokenizer() A = AlignProcessor(tokenizer=A_ ,image_processor=A_ ) A = 'lower newer' A = self.prepare_image_inputs() A = processor(text=A_ ,images=A_ ) self.assertListEqual(list(inputs.keys() ) ,processor.model_input_names )
74
"""simple docstring""" class lowerCAmelCase_ : '''simple docstring''' def __init__( self : int ,A_ : int ) -> Union[str, Any]: A = n A = [None] * self.n A = 0 # index of the first element A = 0 A = 0 def __len__( self : int ) -> int: return self.size def _SCREAMING_SNAKE_CASE ( self : Any ) -> bool: return self.size == 0 def _SCREAMING_SNAKE_CASE ( self : Dict ) -> Tuple: return False if self.is_empty() else self.array[self.front] def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : List[Any] ) -> int: if self.size >= self.n: raise Exception('QUEUE IS FULL' ) A = data A = (self.rear + 1) % self.n self.size += 1 return self def _SCREAMING_SNAKE_CASE ( self : int ) -> List[Any]: if self.size == 0: raise Exception('UNDERFLOW' ) A = self.array[self.front] A = None A = (self.front + 1) % self.n self.size -= 1 return temp
74
1
"""simple docstring""" import os import random import sys from . import cryptomath_module as cryptomath from . import rabin_miller _lowercase = 3 def _snake_case ( snake_case__ : int ): print('Generating primitive root of p' ) while True: A = random.randrange(3 , snake_case__ ) if pow(snake_case__ , 2 , snake_case__ ) == 1: continue if pow(snake_case__ , snake_case__ , snake_case__ ) == 1: continue return g def _snake_case ( snake_case__ : int ): print('Generating prime p...' ) A = rabin_miller.generate_large_prime(snake_case__ ) # select large prime number. A = primitive_root(snake_case__ ) # one primitive root on modulo p. A = random.randrange(3 , snake_case__ ) # private_key -> have to be greater than 2 for safety. A = cryptomath.find_mod_inverse(pow(snake_case__ , snake_case__ , snake_case__ ) , snake_case__ ) A = (key_size, e_a, e_a, p) A = (key_size, d) return public_key, private_key def _snake_case ( snake_case__ : str , snake_case__ : int ): if os.path.exists(F'{name}_pubkey.txt' ) or os.path.exists(F'{name}_privkey.txt' ): print('\nWARNING:' ) print( F'"{name}_pubkey.txt" or "{name}_privkey.txt" already exists. \n' 'Use a different name or delete these files and re-run this program.' ) sys.exit() A , A = generate_key(snake_case__ ) print(F'\nWriting public key to file {name}_pubkey.txt...' ) with open(F'{name}_pubkey.txt' , 'w' ) as fo: fo.write(F'{public_key[0]},{public_key[1]},{public_key[2]},{public_key[3]}' ) print(F'Writing private key to file {name}_privkey.txt...' ) with open(F'{name}_privkey.txt' , 'w' ) as fo: fo.write(F'{private_key[0]},{private_key[1]}' ) def _snake_case ( ): print('Making key files...' ) make_key_files('elgamal' , 2048 ) print('Key files generation successful' ) if __name__ == "__main__": main()
74
"""simple docstring""" import warnings from ...utils import logging from .image_processing_yolos import YolosImageProcessor _lowercase = logging.get_logger(__name__) class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' def __init__( self : Union[str, Any] ,*A_ : List[str] ,**A_ : int ) -> None: warnings.warn( 'The class YolosFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please' ' use YolosImageProcessor instead.' ,A_ ,) super().__init__(*A_ ,**A_ )
74
1
"""simple docstring""" import re def _snake_case ( snake_case__ : str ): A = re.compile( r'^(?:0|94|\+94|0{2}94)' r'7(0|1|2|4|5|6|7|8)' r'(-| |)' r'\d{7}$' ) return bool(re.search(snake_case__ , snake_case__ ) ) if __name__ == "__main__": _lowercase = '''0094702343221''' print(is_sri_lankan_phone_number(phone))
74
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging _lowercase = logging.get_logger(__name__) _lowercase = { '''bigcode/gpt_bigcode-santacoder''': '''https://huggingface.co/bigcode/gpt_bigcode-santacoder/resolve/main/config.json''', } class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: List[str] = '''gpt_bigcode''' _lowerCamelCase: List[Any] = ['''past_key_values'''] _lowerCamelCase: int = { '''hidden_size''': '''n_embd''', '''max_position_embeddings''': '''n_positions''', '''num_attention_heads''': '''n_head''', '''num_hidden_layers''': '''n_layer''', } def __init__( self : Optional[int] ,A_ : Dict=5_0257 ,A_ : Union[str, Any]=1024 ,A_ : str=768 ,A_ : Any=12 ,A_ : Any=12 ,A_ : Optional[int]=None ,A_ : Any="gelu_pytorch_tanh" ,A_ : List[str]=0.1 ,A_ : Optional[int]=0.1 ,A_ : List[str]=0.1 ,A_ : Tuple=1e-5 ,A_ : Optional[int]=0.02 ,A_ : List[str]=True ,A_ : Optional[Any]=True ,A_ : List[Any]=5_0256 ,A_ : Union[str, Any]=5_0256 ,A_ : int=True ,A_ : Optional[Any]=True ,A_ : Dict=True ,**A_ : Union[str, Any] ,) -> Union[str, Any]: A = vocab_size A = n_positions A = n_embd A = n_layer A = n_head A = n_inner A = activation_function A = resid_pdrop A = embd_pdrop A = attn_pdrop A = layer_norm_epsilon A = initializer_range A = scale_attn_weights A = use_cache A = attention_softmax_in_fpaa A = scale_attention_softmax_in_fpaa A = multi_query A = bos_token_id A = eos_token_id super().__init__(bos_token_id=A_ ,eos_token_id=A_ ,**A_ )
74
1
"""simple docstring""" def _snake_case ( snake_case__ : int , snake_case__ : int ): return number | (1 << position) def _snake_case ( snake_case__ : int , snake_case__ : int ): return number & ~(1 << position) def _snake_case ( snake_case__ : int , snake_case__ : int ): return number ^ (1 << position) def _snake_case ( snake_case__ : int , snake_case__ : int ): return ((number >> position) & 1) == 1 def _snake_case ( snake_case__ : int , snake_case__ : int ): return int((number & (1 << position)) != 0 ) if __name__ == "__main__": import doctest doctest.testmod()
74
"""simple docstring""" import math import os import re import sys import unittest from pathlib import Path from typing import Tuple from unittest.mock import patch from parameterized import parameterized from transformers.testing_utils import ( CaptureStderr, ExtendSysPath, TestCasePlus, execute_subprocess_async, get_gpu_count, get_torch_dist_unique_port, require_apex, require_bitsandbytes, require_fairscale, require_torch, require_torch_gpu, require_torch_multi_gpu, require_torch_non_multi_gpu, slow, ) from transformers.trainer_callback import TrainerState from transformers.trainer_utils import set_seed _lowercase = os.path.abspath(os.path.dirname(__file__)) with ExtendSysPath(F"""{bindir}/../../examples/pytorch/translation"""): from run_translation import main # noqa set_seed(42) _lowercase = '''sshleifer/student_marian_en_ro_6_1''' _lowercase = '''sshleifer/tiny-mbart''' @require_torch class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : Any ,A_ : Union[str, Any]=False ,A_ : Optional[int]=None ,A_ : List[str]=True ,A_ : Tuple=True ,A_ : Union[str, Any]=True ,A_ : List[str]=True ,) -> Tuple: A = self.run_trainer( eval_steps=1 ,max_len=12 ,model_name=A_ ,num_train_epochs=1 ,distributed=A_ ,extra_args_str=A_ ,predict_with_generate=A_ ,do_train=A_ ,do_eval=A_ ,do_predict=A_ ,) A = TrainerState.load_from_json(os.path.join(A_ ,'trainer_state.json' ) ).log_history if not do_eval: return A = [log for log in logs if 'eval_loss' in log.keys()] A = eval_metrics[0] if predict_with_generate: assert "eval_bleu" in first_step_stats A = eval_metrics[-1] assert isinstance(last_step_stats['eval_bleu'] ,A_ ) assert not math.isnan(float(last_step_stats['eval_loss'] ) ), "eval_loss must not be `nan`" @require_torch_non_multi_gpu def _SCREAMING_SNAKE_CASE ( self : str ) -> Dict: self.run_seqaseq_quick() @require_torch_multi_gpu def _SCREAMING_SNAKE_CASE ( self : int ) -> int: self.run_seqaseq_quick(distributed=A_ ) @require_torch_multi_gpu def _SCREAMING_SNAKE_CASE ( self : str ) -> List[Any]: self.run_seqaseq_quick(distributed=A_ ) @unittest.skip('Requires an update of the env running those tests' ) @require_torch_multi_gpu @require_fairscale def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Dict: self.run_seqaseq_quick(distributed=A_ ,extra_args_str='--sharded_ddp simple' ) @unittest.skip('Requires an update of the env running those tests' ) @require_torch_multi_gpu @require_fairscale def _SCREAMING_SNAKE_CASE ( self : Any ) -> int: self.run_seqaseq_quick(distributed=A_ ,extra_args_str='--sharded_ddp simple --fp16' ) @unittest.skip('Requires an update of the env running those tests' ) @require_torch_multi_gpu @require_fairscale def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> List[Any]: self.run_seqaseq_quick(distributed=A_ ,extra_args_str='--sharded_ddp zero_dp_2' ,predict_with_generate=A_ ) @unittest.skip('Requires an update of the env running those tests' ) @require_torch_multi_gpu @require_fairscale def _SCREAMING_SNAKE_CASE ( self : Dict ) -> Dict: self.run_seqaseq_quick( distributed=A_ ,extra_args_str='--sharded_ddp zero_dp_2 --fp16' ,predict_with_generate=A_ ) @require_apex @require_torch_gpu def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> Optional[Any]: # XXX: apex breaks the trainer if it's run twice e.g. run_seq2seq.main() from the same # program and it breaks other tests that run from the same pytest worker, therefore until this is # sorted out it must be run only in an external program, that is distributed=True in this # test and only under one or more gpus - if we want cpu will need to make a special test # # specifically to the problem traced it to self.optimizer.step() - if it's run 2nd time via # 2nd main() call it botches the future eval. # self.run_seqaseq_quick(distributed=A_ ,extra_args_str='--fp16 --fp16_backend=apex' ) # test 2nd time - was getting eval_loss': nan' # to reproduce the problem set distributed=False self.run_seqaseq_quick(distributed=A_ ,extra_args_str='--fp16 --fp16_backend=apex' ) @parameterized.expand(['base', 'low', 'high', 'mixed'] ) @require_torch_multi_gpu def _SCREAMING_SNAKE_CASE ( self : str ,A_ : Dict ) -> List[str]: # as each sub-test is slow-ish split into multiple sub-tests to avoid CI timeout A = { # test with the default log_level - should be info and thus log info once 'base': {'extra_args_str': '', 'n_matches': 1}, # test with low log_level and log_level_replica - should be noisy on all processes # now the info string should appear twice on 2 processes 'low': {'extra_args_str': '--log_level debug --log_level_replica debug', 'n_matches': 2}, # test with high log_level and low log_level_replica # now the info string should appear once only on the replica 'high': {'extra_args_str': '--log_level error --log_level_replica debug', 'n_matches': 1}, # test with high log_level and log_level_replica - should be quiet on all processes 'mixed': {'extra_args_str': '--log_level error --log_level_replica error', 'n_matches': 0}, } A = experiments[experiment_id] A = {'distributed': True, 'predict_with_generate': False, 'do_eval': False, 'do_predict': False} A = 'Running training' with CaptureStderr() as cl: self.run_seqaseq_quick(**A_ ,extra_args_str=data['extra_args_str'] ) A = len(re.findall(A_ ,cl.err ) ) self.assertEqual(A_ ,data['n_matches'] ) @slow def _SCREAMING_SNAKE_CASE ( self : Tuple ) -> str: A = self.run_trainer( eval_steps=2 ,max_len=128 ,model_name=A_ ,learning_rate=3e-4 ,num_train_epochs=10 ,distributed=A_ ,) # Check metrics A = TrainerState.load_from_json(os.path.join(A_ ,'trainer_state.json' ) ).log_history A = [log for log in logs if 'eval_loss' in log.keys()] A = eval_metrics[0] A = eval_metrics[-1] assert first_step_stats["eval_loss"] > last_step_stats["eval_loss"], "model learned nothing" assert isinstance(last_step_stats['eval_bleu'] ,A_ ) # test if do_predict saves generations and metrics A = os.listdir(A_ ) A = {os.path.basename(A_ ) for p in contents} assert "generated_predictions.txt" in contents assert "predict_results.json" in contents @slow @require_bitsandbytes def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Optional[int]: from transformers.training_args import OptimizerNames def train_and_return_metrics(A_ : str ) -> Tuple[int, float]: A = '--skip_memory_metrics 0' A = self.run_trainer( max_len=128 ,model_name=A_ ,learning_rate=3e-4 ,num_train_epochs=1 ,optim=A_ ,distributed=A_ ,extra_args_str=A_ ,do_eval=A_ ,do_predict=A_ ,n_gpus_to_use=1 ,) # Check metrics A = TrainerState.load_from_json(Path(A_ ,'trainer_state.json' ) ).log_history A = int(logs[0]['train_mem_gpu_peaked_delta'] / 2**20 ) A = int(logs[0]['train_mem_gpu_alloc_delta'] / 2**20 ) A = logs[0]['train_loss'] return gpu_peak_mem_mb, gpu_alloc_mem_mb, loss A , A , A = train_and_return_metrics(OptimizerNames.ADAMW_TORCH.value ) A , A , A = train_and_return_metrics(OptimizerNames.ADAMW_BNB.value ) A = gpu_alloc_mem_orig - gpu_alloc_mem_bnb A = gpu_peak_mem_orig + gpu_alloc_mem_orig A = gpu_peak_mem_bnb + gpu_alloc_mem_bnb A = gpu_total_mem_orig - gpu_total_mem_bnb # sshleifer/student_marian_en_ro_6_1 has 54M parameter, 29M of which is `nn.Embedding` which # doesn't get quantized and remains in fp32. Therefore we only have 25M parameters quantized # in 2 bytes and the diff in optim memory usage is derived as so: # # - normal 25*8=~200MB (8 bytes per param) # - bnb 25*2= ~50MB (2 bytes per param) # # Thus we should expect ~150MB total memory saved. # # Peak memory should be the same - the total should be different by about that same margin # # After leaving a small margin to accommodate for differences between gpus let's check # that we have at least 120MB in savings A = 120 # uncomment the following if this test starts failing - requires py38 for a new print feature # gpu_peak_mem_diff = gpu_peak_mem_orig - gpu_peak_mem_bnb # print(f"{gpu_alloc_mem_orig=}MB {gpu_peak_mem_orig=}MB {gpu_alloc_mem_orig+gpu_peak_mem_orig=}MB") # print(f" {gpu_alloc_mem_bnb=}MB {gpu_peak_mem_bnb=}MB {gpu_alloc_mem_bnb+gpu_peak_mem_bnb=}MB") # print(f"{gpu_alloc_mem_diff=}MB") # print(f"{gpu_peak_mem_diff=}MB") # print(f"{gpu_total_mem_orig=}MB, {gpu_total_mem_bnb=}MB") # print(f"{gpu_total_mem_diff=}MB, {gpu_total_mem_diff=}MB") self.assertGreater( A_ ,A_ ,'should use ~150MB less alloc gpu memory with BNB, compared to without it for this model but got' F' a difference of {gpu_alloc_mem_diff}MB, with gpu_alloc_mem_orig={gpu_alloc_mem_orig}MB and' F' gpu_alloc_mem_bnb={gpu_alloc_mem_bnb}MB' ,) self.assertGreater( A_ ,A_ ,'should use ~150MB less total gpu memory with BNB, compared to without it for this model but got' F' a difference of {gpu_total_mem_diff}MB, with gpu_total_mem_orig={gpu_total_mem_orig}MB and' F' gpu_total_mem_bnb={gpu_total_mem_bnb}MB' ,) self.assertEqual( A_ ,A_ ,F'loss should be the same, but got loss_orig={loss_orig}, loss_bnb={loss_bnb}' ) def _SCREAMING_SNAKE_CASE ( self : List[str] ,A_ : int ,A_ : str ,A_ : int ,A_ : float = 3e-3 ,A_ : str = "adafactor" ,A_ : bool = False ,A_ : str = None ,A_ : int = 0 ,A_ : bool = True ,A_ : bool = True ,A_ : bool = True ,A_ : bool = True ,A_ : int = None ,) -> Dict: A = self.test_file_dir / '../fixtures/tests_samples/wmt_en_ro' A = self.get_auto_remove_tmp_dir() A = F'\n --model_name_or_path {model_name}\n --train_file {data_dir}/train.json\n --validation_file {data_dir}/val.json\n --test_file {data_dir}/test.json\n --output_dir {output_dir}\n --overwrite_output_dir\n --max_train_samples 8\n --max_source_length {max_len}\n --max_target_length {max_len}\n --do_train\n --num_train_epochs {str(A_ )}\n --per_device_train_batch_size 4\n --learning_rate {learning_rate}\n --warmup_steps 8\n --logging_steps 0\n --logging_strategy no\n --save_steps {str(A_ )}\n --group_by_length\n --label_smoothing_factor 0.1\n --target_lang ro_RO\n --source_lang en_XX\n '.split() A = F'\n --do_eval\n --per_device_eval_batch_size 4\n --max_eval_samples 8\n --val_max_target_length {max_len}\n --evaluation_strategy steps\n --eval_steps {str(A_ )}\n '.split() A = '\n --do_predict\n '.split() A = [] if do_train: args += args_train if do_eval: args += args_eval if do_predict: args += args_predict if predict_with_generate: args += "--predict_with_generate".split() if do_train: if optim == "adafactor": args += "--adafactor".split() else: args += F'--optim {optim}'.split() if extra_args_str is not None: args += extra_args_str.split() if distributed: if n_gpus_to_use is None: A = get_gpu_count() A = get_torch_dist_unique_port() A = F'\n -m torch.distributed.run\n --nproc_per_node={n_gpus_to_use}\n --master_port={master_port}\n {self.examples_dir_str}/pytorch/translation/run_translation.py\n '.split() A = [sys.executable] + distributed_args + args # keep for quick debug # print(" ".join([f"\nPYTHONPATH={self.src_dir_str}"] +cmd)); die execute_subprocess_async(A_ ,env=self.get_env() ) else: A = ['run_translation.py'] + args with patch.object(A_ ,'argv' ,A_ ): main() return output_dir
74
1
"""simple docstring""" import unittest from datasets import load_dataset from transformers import BloomTokenizerFast from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class lowerCAmelCase_ ( _lowercase , unittest.TestCase ): '''simple docstring''' _lowerCamelCase: Tuple = None _lowerCamelCase: Union[str, Any] = BloomTokenizerFast _lowerCamelCase: int = BloomTokenizerFast _lowerCamelCase: List[str] = True _lowerCamelCase: str = False _lowerCamelCase: Union[str, Any] = '''tokenizer_file''' _lowerCamelCase: Tuple = {'''bos_token''': '''<s>''', '''eos_token''': '''</s>''', '''unk_token''': '''<unk>''', '''pad_token''': '''<pad>'''} def _SCREAMING_SNAKE_CASE ( self : Any ) -> List[Any]: super().setUp() A = BloomTokenizerFast.from_pretrained('bigscience/tokenizer' ) tokenizer.save_pretrained(self.tmpdirname ) def _SCREAMING_SNAKE_CASE ( self : List[str] ,**A_ : str ) -> Dict: kwargs.update(self.special_tokens_map ) return BloomTokenizerFast.from_pretrained(self.tmpdirname ,**A_ ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> List[str]: A = self.get_rust_tokenizer() A = ['The quick brown fox</s>', 'jumps over the lazy dog</s>'] A = [[2175, 2_3714, 7_3173, 14_4252, 2], [77, 13_2619, 3478, 368, 10_9586, 3_5433, 2]] A = tokenizer.batch_encode_plus(A_ )['input_ids'] self.assertListEqual(A_ ,A_ ) A = tokenizer.batch_decode(A_ ) self.assertListEqual(A_ ,A_ ) def _SCREAMING_SNAKE_CASE ( self : Tuple ,A_ : List[Any]=6 ) -> List[str]: for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'{tokenizer.__class__.__name__} ({pretrained_name})' ): A = self.rust_tokenizer_class.from_pretrained(A_ ,**A_ ) # tokenizer_r.pad_token = None # Hotfixing padding = None # Simple input A = 'This is a simple input' A = ['This is a simple input 1', 'This is a simple input 2'] A = ('This is a simple input', 'This is a pair') A = [ ('This is a simple input 1', 'This is a simple input 2'), ('This is a simple pair 1', 'This is a simple pair 2'), ] # Simple input tests try: tokenizer_r.encode(A_ ,max_length=A_ ) tokenizer_r.encode_plus(A_ ,max_length=A_ ) tokenizer_r.batch_encode_plus(A_ ,max_length=A_ ) tokenizer_r.encode(A_ ,max_length=A_ ) tokenizer_r.batch_encode_plus(A_ ,max_length=A_ ) except ValueError: self.fail('Bloom Tokenizer should be able to deal with padding' ) A = None # Hotfixing padding = None self.assertRaises(A_ ,tokenizer_r.encode ,A_ ,max_length=A_ ,padding='max_length' ) # Simple input self.assertRaises(A_ ,tokenizer_r.encode_plus ,A_ ,max_length=A_ ,padding='max_length' ) # Simple input self.assertRaises( A_ ,tokenizer_r.batch_encode_plus ,A_ ,max_length=A_ ,padding='max_length' ,) # Pair input self.assertRaises(A_ ,tokenizer_r.encode ,A_ ,max_length=A_ ,padding='max_length' ) # Pair input self.assertRaises(A_ ,tokenizer_r.encode_plus ,A_ ,max_length=A_ ,padding='max_length' ) # Pair input self.assertRaises( A_ ,tokenizer_r.batch_encode_plus ,A_ ,max_length=A_ ,padding='max_length' ,) def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> List[str]: A = self.get_rust_tokenizer() A = load_dataset('xnli' ,'all_languages' ,split='test' ,streaming=A_ ) A = next(iter(A_ ) )['premise'] # pick up one data A = list(sample_data.values() ) A = list(map(tokenizer.encode ,A_ ) ) A = [tokenizer.decode(A_ ,clean_up_tokenization_spaces=A_ ) for x in output_tokens] self.assertListEqual(A_ ,A_ ) def _SCREAMING_SNAKE_CASE ( self : int ) -> List[Any]: # The test has to be overriden because BLOOM uses ALiBi positional embeddings that does not have # any sequence length constraints. This test of the parent class will fail since it relies on the # maximum sequence length of the positoonal embeddings. self.assertGreaterEqual(len(self.tokenizer_class.pretrained_vocab_files_map ) ,1 ) self.assertGreaterEqual(len(list(self.tokenizer_class.pretrained_vocab_files_map.values() )[0] ) ,1 )
74
"""simple docstring""" from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging _lowercase = logging.get_logger(__name__) _lowercase = { '''facebook/deit-base-distilled-patch16-224''': ( '''https://huggingface.co/facebook/deit-base-patch16-224/resolve/main/config.json''' ), # See all DeiT models at https://huggingface.co/models?filter=deit } class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: Optional[Any] = '''deit''' def __init__( self : int ,A_ : Optional[Any]=768 ,A_ : Union[str, Any]=12 ,A_ : Dict=12 ,A_ : int=3072 ,A_ : Optional[Any]="gelu" ,A_ : Dict=0.0 ,A_ : Any=0.0 ,A_ : str=0.02 ,A_ : Tuple=1e-12 ,A_ : Union[str, Any]=224 ,A_ : Optional[Any]=16 ,A_ : List[Any]=3 ,A_ : Optional[Any]=True ,A_ : Optional[int]=16 ,**A_ : Union[str, Any] ,) -> Dict: super().__init__(**A_ ) A = hidden_size A = num_hidden_layers A = num_attention_heads A = intermediate_size A = hidden_act A = hidden_dropout_prob A = attention_probs_dropout_prob A = initializer_range A = layer_norm_eps A = image_size A = patch_size A = num_channels A = qkv_bias A = encoder_stride class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: int = version.parse('''1.11''' ) @property def _SCREAMING_SNAKE_CASE ( self : Tuple ) -> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ] ) @property def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> float: return 1e-4
74
1
"""simple docstring""" import argparse import logging import pickle import random import time import numpy as np from transformers import BertTokenizer, GPTaTokenizer, RobertaTokenizer logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''', datefmt='''%m/%d/%Y %H:%M:%S''', level=logging.INFO ) _lowercase = logging.getLogger(__name__) def _snake_case ( ): A = argparse.ArgumentParser( description='Preprocess the data to avoid re-doing it several times by (tokenization + token_to_ids).' ) parser.add_argument('--file_path' , type=snake_case__ , default='data/dump.txt' , help='The path to the data.' ) parser.add_argument('--tokenizer_type' , type=snake_case__ , default='bert' , choices=['bert', 'roberta', 'gpt2'] ) parser.add_argument('--tokenizer_name' , type=snake_case__ , default='bert-base-uncased' , help='The tokenizer to use.' ) parser.add_argument('--dump_file' , type=snake_case__ , default='data/dump' , help='The dump file prefix.' ) A = parser.parse_args() logger.info(F'Loading Tokenizer ({args.tokenizer_name})' ) if args.tokenizer_type == "bert": A = BertTokenizer.from_pretrained(args.tokenizer_name ) A = tokenizer.special_tokens_map['cls_token'] # `[CLS]` A = tokenizer.special_tokens_map['sep_token'] # `[SEP]` elif args.tokenizer_type == "roberta": A = RobertaTokenizer.from_pretrained(args.tokenizer_name ) A = tokenizer.special_tokens_map['cls_token'] # `<s>` A = tokenizer.special_tokens_map['sep_token'] # `</s>` elif args.tokenizer_type == "gpt2": A = GPTaTokenizer.from_pretrained(args.tokenizer_name ) A = tokenizer.special_tokens_map['bos_token'] # `<|endoftext|>` A = tokenizer.special_tokens_map['eos_token'] # `<|endoftext|>` logger.info(F'Loading text from {args.file_path}' ) with open(args.file_path , 'r' , encoding='utf8' ) as fp: A = fp.readlines() logger.info('Start encoding' ) logger.info(F'{len(snake_case__ )} examples to process.' ) A = [] A = 0 A = 1_0000 A = time.time() for text in data: A = F'{bos} {text.strip()} {sep}' A = tokenizer.encode(snake_case__ , add_special_tokens=snake_case__ ) rslt.append(snake_case__ ) iter += 1 if iter % interval == 0: A = time.time() logger.info(F'{iter} examples processed. - {(end-start):.2f}s/{interval}expl' ) A = time.time() logger.info('Finished binarization' ) logger.info(F'{len(snake_case__ )} examples processed.' ) A = F'{args.dump_file}.{args.tokenizer_name}.pickle' A = tokenizer.vocab_size if vocab_size < (1 << 16): A = [np.uintaa(snake_case__ ) for d in rslt] else: A = [np.intaa(snake_case__ ) for d in rslt] random.shuffle(rslt_ ) logger.info(F'Dump to {dp_file}' ) with open(snake_case__ , 'wb' ) as handle: pickle.dump(rslt_ , snake_case__ , protocol=pickle.HIGHEST_PROTOCOL ) if __name__ == "__main__": main()
74
"""simple docstring""" import math from collections import defaultdict from typing import List, Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from .scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin, SchedulerOutput def _snake_case ( snake_case__ : List[Any] , snake_case__ : Optional[int]=0.999 , snake_case__ : Union[str, Any]="cosine" , ): if alpha_transform_type == "cosine": def alpha_bar_fn(snake_case__ : Union[str, Any] ): return math.cos((t + 0.008) / 1.008 * math.pi / 2 ) ** 2 elif alpha_transform_type == "exp": def alpha_bar_fn(snake_case__ : Dict ): return math.exp(t * -12.0 ) else: raise ValueError(F'Unsupported alpha_tranform_type: {alpha_transform_type}' ) A = [] for i in range(snake_case__ ): A = i / num_diffusion_timesteps A = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar_fn(snake_case__ ) / alpha_bar_fn(snake_case__ ) , snake_case__ ) ) return torch.tensor(snake_case__ , dtype=torch.floataa ) class lowerCAmelCase_ ( _lowercase , _lowercase ): '''simple docstring''' _lowerCamelCase: Optional[int] = [e.name for e in KarrasDiffusionSchedulers] _lowerCamelCase: Optional[Any] = 2 @register_to_config def __init__( self : str ,A_ : int = 1000 ,A_ : float = 0.0_00_85 ,A_ : float = 0.0_12 ,A_ : str = "linear" ,A_ : Optional[Union[np.ndarray, List[float]]] = None ,A_ : str = "epsilon" ,A_ : Optional[bool] = False ,A_ : Optional[bool] = False ,A_ : float = 1.0 ,A_ : str = "linspace" ,A_ : int = 0 ,) -> List[str]: if trained_betas is not None: A = torch.tensor(A_ ,dtype=torch.floataa ) elif beta_schedule == "linear": A = torch.linspace(A_ ,A_ ,A_ ,dtype=torch.floataa ) elif beta_schedule == "scaled_linear": # this schedule is very specific to the latent diffusion model. A = ( torch.linspace(beta_start**0.5 ,beta_end**0.5 ,A_ ,dtype=torch.floataa ) ** 2 ) elif beta_schedule == "squaredcos_cap_v2": # Glide cosine schedule A = betas_for_alpha_bar(A_ ,alpha_transform_type='cosine' ) elif beta_schedule == "exp": A = betas_for_alpha_bar(A_ ,alpha_transform_type='exp' ) else: raise NotImplementedError(F'{beta_schedule} does is not implemented for {self.__class__}' ) A = 1.0 - self.betas A = torch.cumprod(self.alphas ,dim=0 ) # set all values self.set_timesteps(A_ ,A_ ,A_ ) A = use_karras_sigmas def _SCREAMING_SNAKE_CASE ( self : int ,A_ : Tuple ,A_ : Tuple=None ) -> Tuple: if schedule_timesteps is None: A = self.timesteps A = (schedule_timesteps == timestep).nonzero() # The sigma index that is taken for the **very** first `step` # is always the second index (or the last index if there is only 1) # This way we can ensure we don't accidentally skip a sigma in # case we start in the middle of the denoising schedule (e.g. for image-to-image) if len(self._index_counter ) == 0: A = 1 if len(A_ ) > 1 else 0 else: A = timestep.cpu().item() if torch.is_tensor(A_ ) else timestep A = self._index_counter[timestep_int] return indices[pos].item() @property def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> List[Any]: # standard deviation of the initial noise distribution if self.config.timestep_spacing in ["linspace", "trailing"]: return self.sigmas.max() return (self.sigmas.max() ** 2 + 1) ** 0.5 def _SCREAMING_SNAKE_CASE ( self : List[Any] ,A_ : torch.FloatTensor ,A_ : Union[float, torch.FloatTensor] ,) -> torch.FloatTensor: A = self.index_for_timestep(A_ ) A = self.sigmas[step_index] A = sample / ((sigma**2 + 1) ** 0.5) return sample def _SCREAMING_SNAKE_CASE ( self : str ,A_ : int ,A_ : Union[str, torch.device] = None ,A_ : Optional[int] = None ,) -> Optional[Any]: A = num_inference_steps A = num_train_timesteps or self.config.num_train_timesteps # "linspace", "leading", "trailing" corresponds to annotation of Table 2. of https://arxiv.org/abs/2305.08891 if self.config.timestep_spacing == "linspace": A = np.linspace(0 ,num_train_timesteps - 1 ,A_ ,dtype=A_ )[::-1].copy() elif self.config.timestep_spacing == "leading": A = num_train_timesteps // self.num_inference_steps # creates integer timesteps by multiplying by ratio # casting to int to avoid issues when num_inference_step is power of 3 A = (np.arange(0 ,A_ ) * step_ratio).round()[::-1].copy().astype(A_ ) timesteps += self.config.steps_offset elif self.config.timestep_spacing == "trailing": A = num_train_timesteps / self.num_inference_steps # creates integer timesteps by multiplying by ratio # casting to int to avoid issues when num_inference_step is power of 3 A = (np.arange(A_ ,0 ,-step_ratio )).round().copy().astype(A_ ) timesteps -= 1 else: raise ValueError( F'{self.config.timestep_spacing} is not supported. Please make sure to choose one of \'linspace\', \'leading\' or \'trailing\'.' ) A = np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5 ) A = np.log(A_ ) A = np.interp(A_ ,np.arange(0 ,len(A_ ) ) ,A_ ) if self.config.use_karras_sigmas: A = self._convert_to_karras(in_sigmas=A_ ,num_inference_steps=self.num_inference_steps ) A = np.array([self._sigma_to_t(A_ ,A_ ) for sigma in sigmas] ) A = np.concatenate([sigmas, [0.0]] ).astype(np.floataa ) A = torch.from_numpy(A_ ).to(device=A_ ) A = torch.cat([sigmas[:1], sigmas[1:-1].repeat_interleave(2 ), sigmas[-1:]] ) A = torch.from_numpy(A_ ) A = torch.cat([timesteps[:1], timesteps[1:].repeat_interleave(2 )] ) if str(A_ ).startswith('mps' ): # mps does not support float64 A = timesteps.to(A_ ,dtype=torch.floataa ) else: A = timesteps.to(device=A_ ) # empty dt and derivative A = None A = None # for exp beta schedules, such as the one for `pipeline_shap_e.py` # we need an index counter A = defaultdict(A_ ) def _SCREAMING_SNAKE_CASE ( self : Any ,A_ : Optional[Any] ,A_ : List[str] ) -> Dict: # get log sigma A = np.log(A_ ) # get distribution A = log_sigma - log_sigmas[:, np.newaxis] # get sigmas range A = np.cumsum((dists >= 0) ,axis=0 ).argmax(axis=0 ).clip(max=log_sigmas.shape[0] - 2 ) A = low_idx + 1 A = log_sigmas[low_idx] A = log_sigmas[high_idx] # interpolate sigmas A = (low - log_sigma) / (low - high) A = np.clip(A_ ,0 ,1 ) # transform interpolation to time range A = (1 - w) * low_idx + w * high_idx A = t.reshape(sigma.shape ) return t def _SCREAMING_SNAKE_CASE ( self : List[str] ,A_ : torch.FloatTensor ,A_ : int ) -> torch.FloatTensor: A = in_sigmas[-1].item() A = in_sigmas[0].item() A = 7.0 # 7.0 is the value used in the paper A = np.linspace(0 ,1 ,A_ ) A = sigma_min ** (1 / rho) A = sigma_max ** (1 / rho) A = (max_inv_rho + ramp * (min_inv_rho - max_inv_rho)) ** rho return sigmas @property def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Dict: return self.dt is None def _SCREAMING_SNAKE_CASE ( self : Tuple ,A_ : Union[torch.FloatTensor, np.ndarray] ,A_ : Union[float, torch.FloatTensor] ,A_ : Union[torch.FloatTensor, np.ndarray] ,A_ : bool = True ,) -> Union[SchedulerOutput, Tuple]: A = self.index_for_timestep(A_ ) # advance index counter by 1 A = timestep.cpu().item() if torch.is_tensor(A_ ) else timestep self._index_counter[timestep_int] += 1 if self.state_in_first_order: A = self.sigmas[step_index] A = self.sigmas[step_index + 1] else: # 2nd order / Heun's method A = self.sigmas[step_index - 1] A = self.sigmas[step_index] # currently only gamma=0 is supported. This usually works best anyways. # We can support gamma in the future but then need to scale the timestep before # passing it to the model which requires a change in API A = 0 A = sigma * (gamma + 1) # Note: sigma_hat == sigma for now # 1. compute predicted original sample (x_0) from sigma-scaled predicted noise if self.config.prediction_type == "epsilon": A = sigma_hat if self.state_in_first_order else sigma_next A = sample - sigma_input * model_output elif self.config.prediction_type == "v_prediction": A = sigma_hat if self.state_in_first_order else sigma_next A = model_output * (-sigma_input / (sigma_input**2 + 1) ** 0.5) + ( sample / (sigma_input**2 + 1) ) elif self.config.prediction_type == "sample": A = model_output else: raise ValueError( F'prediction_type given as {self.config.prediction_type} must be one of `epsilon`, or `v_prediction`' ) if self.config.clip_sample: A = pred_original_sample.clamp( -self.config.clip_sample_range ,self.config.clip_sample_range ) if self.state_in_first_order: # 2. Convert to an ODE derivative for 1st order A = (sample - pred_original_sample) / sigma_hat # 3. delta timestep A = sigma_next - sigma_hat # store for 2nd order step A = derivative A = dt A = sample else: # 2. 2nd order / Heun's method A = (sample - pred_original_sample) / sigma_next A = (self.prev_derivative + derivative) / 2 # 3. take prev timestep & sample A = self.dt A = self.sample # free dt and derivative # Note, this puts the scheduler in "first order mode" A = None A = None A = None A = sample + derivative * dt if not return_dict: return (prev_sample,) return SchedulerOutput(prev_sample=A_ ) def _SCREAMING_SNAKE_CASE ( self : int ,A_ : torch.FloatTensor ,A_ : torch.FloatTensor ,A_ : torch.FloatTensor ,) -> torch.FloatTensor: # Make sure sigmas and timesteps have the same device and dtype as original_samples A = self.sigmas.to(device=original_samples.device ,dtype=original_samples.dtype ) if original_samples.device.type == "mps" and torch.is_floating_point(A_ ): # mps does not support float64 A = self.timesteps.to(original_samples.device ,dtype=torch.floataa ) A = timesteps.to(original_samples.device ,dtype=torch.floataa ) else: A = self.timesteps.to(original_samples.device ) A = timesteps.to(original_samples.device ) A = [self.index_for_timestep(A_ ,A_ ) for t in timesteps] A = sigmas[step_indices].flatten() while len(sigma.shape ) < len(original_samples.shape ): A = sigma.unsqueeze(-1 ) A = original_samples + noise * sigma return noisy_samples def __len__( self : Dict ) -> int: return self.config.num_train_timesteps
74
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available _lowercase = { '''configuration_biogpt''': ['''BIOGPT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''BioGptConfig'''], '''tokenization_biogpt''': ['''BioGptTokenizer'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase = [ '''BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''BioGptForCausalLM''', '''BioGptForTokenClassification''', '''BioGptForSequenceClassification''', '''BioGptModel''', '''BioGptPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_biogpt import BIOGPT_PRETRAINED_CONFIG_ARCHIVE_MAP, BioGptConfig from .tokenization_biogpt import BioGptTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_biogpt import ( BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST, BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification, BioGptModel, BioGptPreTrainedModel, ) else: import sys _lowercase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
74
"""simple docstring""" class lowerCAmelCase_ : '''simple docstring''' def __init__( self : Dict ,A_ : list[int] ) -> None: A = len(A_ ) A = [0] * len_array if len_array > 0: A = array[0] for i in range(1 ,A_ ): A = self.prefix_sum[i - 1] + array[i] def _SCREAMING_SNAKE_CASE ( self : str ,A_ : int ,A_ : int ) -> int: if start == 0: return self.prefix_sum[end] return self.prefix_sum[end] - self.prefix_sum[start - 1] def _SCREAMING_SNAKE_CASE ( self : str ,A_ : int ) -> bool: A = {0} for sum_item in self.prefix_sum: if sum_item - target_sum in sums: return True sums.add(A_ ) return False if __name__ == "__main__": import doctest doctest.testmod()
74
1
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging _lowercase = logging.get_logger(__name__) _lowercase = { '''microsoft/markuplm-base''': '''https://huggingface.co/microsoft/markuplm-base/resolve/main/config.json''', '''microsoft/markuplm-large''': '''https://huggingface.co/microsoft/markuplm-large/resolve/main/config.json''', } class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: Tuple = '''markuplm''' def __init__( self : Any ,A_ : List[Any]=3_0522 ,A_ : Tuple=768 ,A_ : Dict=12 ,A_ : Tuple=12 ,A_ : List[Any]=3072 ,A_ : Dict="gelu" ,A_ : List[str]=0.1 ,A_ : Union[str, Any]=0.1 ,A_ : List[str]=512 ,A_ : Dict=2 ,A_ : Optional[int]=0.02 ,A_ : Optional[Any]=1e-12 ,A_ : List[Any]=0 ,A_ : Optional[int]=0 ,A_ : Union[str, Any]=2 ,A_ : Optional[int]=256 ,A_ : Dict=1024 ,A_ : Optional[Any]=216 ,A_ : str=1001 ,A_ : Any=32 ,A_ : Optional[int]=50 ,A_ : Any="absolute" ,A_ : Optional[int]=True ,A_ : List[Any]=None ,**A_ : int ,) -> Dict: super().__init__( pad_token_id=A_ ,bos_token_id=A_ ,eos_token_id=A_ ,**A_ ,) A = vocab_size A = hidden_size A = num_hidden_layers A = num_attention_heads A = hidden_act A = intermediate_size A = hidden_dropout_prob A = attention_probs_dropout_prob A = max_position_embeddings A = type_vocab_size A = initializer_range A = layer_norm_eps A = position_embedding_type A = use_cache A = classifier_dropout # additional properties A = max_depth A = max_xpath_tag_unit_embeddings A = max_xpath_subs_unit_embeddings A = tag_pad_id A = subs_pad_id A = xpath_unit_hidden_size
74
"""simple docstring""" import argparse import torch from huggingface_hub import hf_hub_download from transformers import AutoTokenizer, RobertaPreLayerNormConfig, RobertaPreLayerNormForMaskedLM from transformers.utils import logging logging.set_verbosity_info() _lowercase = logging.get_logger(__name__) def _snake_case ( snake_case__ : str , snake_case__ : str ): A = RobertaPreLayerNormConfig.from_pretrained( snake_case__ , architectures=['RobertaPreLayerNormForMaskedLM'] ) # convert state_dict A = torch.load(hf_hub_download(repo_id=snake_case__ , filename='pytorch_model.bin' ) ) A = {} for tensor_key, tensor_value in original_state_dict.items(): # The transformer implementation gives the model a unique name, rather than overwiriting 'roberta' if tensor_key.startswith('roberta.' ): A = 'roberta_prelayernorm.' + tensor_key[len('roberta.' ) :] # The original implementation contains weights which are not used, remove them from the state_dict if tensor_key.endswith('.self.LayerNorm.weight' ) or tensor_key.endswith('.self.LayerNorm.bias' ): continue A = tensor_value A = RobertaPreLayerNormForMaskedLM.from_pretrained( pretrained_model_name_or_path=snake_case__ , config=snake_case__ , state_dict=snake_case__ ) model.save_pretrained(snake_case__ ) # convert tokenizer A = AutoTokenizer.from_pretrained(snake_case__ ) tokenizer.save_pretrained(snake_case__ ) if __name__ == "__main__": _lowercase = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--checkpoint-repo''', default=None, type=str, required=True, help='''Path the official PyTorch dump, e.g. \'andreasmadsen/efficient_mlm_m0.40\'.''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) _lowercase = parser.parse_args() convert_roberta_prelayernorm_checkpoint_to_pytorch(args.checkpoint_repo, args.pytorch_dump_folder_path)
74
1
"""simple docstring""" import argparse import struct import unittest class lowerCAmelCase_ : '''simple docstring''' def __init__( self : Tuple ,A_ : bytes ) -> None: A = data # Initialize hash values A = [ 0X6_A_0_9_E_6_6_7, 0XB_B_6_7_A_E_8_5, 0X3_C_6_E_F_3_7_2, 0XA_5_4_F_F_5_3_A, 0X5_1_0_E_5_2_7_F, 0X9_B_0_5_6_8_8_C, 0X1_F_8_3_D_9_A_B, 0X5_B_E_0_C_D_1_9, ] # Initialize round constants A = [ 0X4_2_8_A_2_F_9_8, 0X7_1_3_7_4_4_9_1, 0XB_5_C_0_F_B_C_F, 0XE_9_B_5_D_B_A_5, 0X3_9_5_6_C_2_5_B, 0X5_9_F_1_1_1_F_1, 0X9_2_3_F_8_2_A_4, 0XA_B_1_C_5_E_D_5, 0XD_8_0_7_A_A_9_8, 0X1_2_8_3_5_B_0_1, 0X2_4_3_1_8_5_B_E, 0X5_5_0_C_7_D_C_3, 0X7_2_B_E_5_D_7_4, 0X8_0_D_E_B_1_F_E, 0X9_B_D_C_0_6_A_7, 0XC_1_9_B_F_1_7_4, 0XE_4_9_B_6_9_C_1, 0XE_F_B_E_4_7_8_6, 0X0_F_C_1_9_D_C_6, 0X2_4_0_C_A_1_C_C, 0X2_D_E_9_2_C_6_F, 0X4_A_7_4_8_4_A_A, 0X5_C_B_0_A_9_D_C, 0X7_6_F_9_8_8_D_A, 0X9_8_3_E_5_1_5_2, 0XA_8_3_1_C_6_6_D, 0XB_0_0_3_2_7_C_8, 0XB_F_5_9_7_F_C_7, 0XC_6_E_0_0_B_F_3, 0XD_5_A_7_9_1_4_7, 0X0_6_C_A_6_3_5_1, 0X1_4_2_9_2_9_6_7, 0X2_7_B_7_0_A_8_5, 0X2_E_1_B_2_1_3_8, 0X4_D_2_C_6_D_F_C, 0X5_3_3_8_0_D_1_3, 0X6_5_0_A_7_3_5_4, 0X7_6_6_A_0_A_B_B, 0X8_1_C_2_C_9_2_E, 0X9_2_7_2_2_C_8_5, 0XA_2_B_F_E_8_A_1, 0XA_8_1_A_6_6_4_B, 0XC_2_4_B_8_B_7_0, 0XC_7_6_C_5_1_A_3, 0XD_1_9_2_E_8_1_9, 0XD_6_9_9_0_6_2_4, 0XF_4_0_E_3_5_8_5, 0X1_0_6_A_A_0_7_0, 0X1_9_A_4_C_1_1_6, 0X1_E_3_7_6_C_0_8, 0X2_7_4_8_7_7_4_C, 0X3_4_B_0_B_C_B_5, 0X3_9_1_C_0_C_B_3, 0X4_E_D_8_A_A_4_A, 0X5_B_9_C_C_A_4_F, 0X6_8_2_E_6_F_F_3, 0X7_4_8_F_8_2_E_E, 0X7_8_A_5_6_3_6_F, 0X8_4_C_8_7_8_1_4, 0X8_C_C_7_0_2_0_8, 0X9_0_B_E_F_F_F_A, 0XA_4_5_0_6_C_E_B, 0XB_E_F_9_A_3_F_7, 0XC_6_7_1_7_8_F_2, ] A = self.preprocessing(self.data ) self.final_hash() @staticmethod def _SCREAMING_SNAKE_CASE ( A_ : bytes ) -> bytes: A = B'\x80' + (B'\x00' * (63 - (len(A_ ) + 8) % 64)) A = struct.pack('>Q' ,(len(A_ ) * 8) ) return data + padding + big_endian_integer def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> None: # Convert into blocks of 64 bytes A = [ self.preprocessed_data[x : x + 64] for x in range(0 ,len(self.preprocessed_data ) ,64 ) ] for block in self.blocks: # Convert the given block into a list of 4 byte integers A = list(struct.unpack('>16L' ,A_ ) ) # add 48 0-ed integers words += [0] * 48 A , A , A , A , A , A , A , A = self.hashes for index in range(0 ,64 ): if index > 15: # modify the zero-ed indexes at the end of the array A = ( self.ror(words[index - 15] ,7 ) ^ self.ror(words[index - 15] ,18 ) ^ (words[index - 15] >> 3) ) A = ( self.ror(words[index - 2] ,17 ) ^ self.ror(words[index - 2] ,19 ) ^ (words[index - 2] >> 10) ) A = ( words[index - 16] + sa + words[index - 7] + sa ) % 0X1_0_0_0_0_0_0_0_0 # Compression A = self.ror(A_ ,6 ) ^ self.ror(A_ ,11 ) ^ self.ror(A_ ,25 ) A = (e & f) ^ ((~e & 0XF_F_F_F_F_F_F_F) & g) A = ( h + sa + ch + self.round_constants[index] + words[index] ) % 0X1_0_0_0_0_0_0_0_0 A = self.ror(A_ ,2 ) ^ self.ror(A_ ,13 ) ^ self.ror(A_ ,22 ) A = (a & b) ^ (a & c) ^ (b & c) A = (sa + maj) % 0X1_0_0_0_0_0_0_0_0 A , A , A , A , A , A , A , A = ( g, f, e, ((d + tempa) % 0X1_0_0_0_0_0_0_0_0), c, b, a, ((tempa + tempa) % 0X1_0_0_0_0_0_0_0_0), ) A = [a, b, c, d, e, f, g, h] # Modify final values A = [ ((element + mutated_hash_values[index]) % 0X1_0_0_0_0_0_0_0_0) for index, element in enumerate(self.hashes ) ] A = ''.join([hex(A_ )[2:].zfill(8 ) for value in self.hashes] ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ,A_ : int ,A_ : int ) -> int: return 0XF_F_F_F_F_F_F_F & (value << (32 - rotations)) | (value >> rotations) class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> None: import hashlib A = bytes('Test String' ,'utf-8' ) self.assertEqual(SHAaaa(A_ ).hash ,hashlib.shaaaa(A_ ).hexdigest() ) def _snake_case ( ): import doctest doctest.testmod() A = argparse.ArgumentParser() parser.add_argument( '-s' , '--string' , dest='input_string' , default='Hello World!! Welcome to Cryptography' , help='Hash the string' , ) parser.add_argument( '-f' , '--file' , dest='input_file' , help='Hash contents of a file' ) A = parser.parse_args() A = args.input_string # hash input should be a bytestring if args.input_file: with open(args.input_file , 'rb' ) as f: A = f.read() else: A = bytes(snake_case__ , 'utf-8' ) print(SHAaaa(snake_case__ ).hash ) if __name__ == "__main__": main()
74
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging _lowercase = logging.get_logger(__name__) _lowercase = { '''junnyu/roformer_chinese_small''': '''https://huggingface.co/junnyu/roformer_chinese_small/resolve/main/config.json''', '''junnyu/roformer_chinese_base''': '''https://huggingface.co/junnyu/roformer_chinese_base/resolve/main/config.json''', '''junnyu/roformer_chinese_char_small''': ( '''https://huggingface.co/junnyu/roformer_chinese_char_small/resolve/main/config.json''' ), '''junnyu/roformer_chinese_char_base''': ( '''https://huggingface.co/junnyu/roformer_chinese_char_base/resolve/main/config.json''' ), '''junnyu/roformer_small_discriminator''': ( '''https://huggingface.co/junnyu/roformer_small_discriminator/resolve/main/config.json''' ), '''junnyu/roformer_small_generator''': ( '''https://huggingface.co/junnyu/roformer_small_generator/resolve/main/config.json''' ), # See all RoFormer models at https://huggingface.co/models?filter=roformer } class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: Optional[Any] = '''roformer''' def __init__( self : Tuple ,A_ : Optional[int]=5_0000 ,A_ : Tuple=None ,A_ : Optional[Any]=768 ,A_ : Dict=12 ,A_ : Optional[int]=12 ,A_ : Union[str, Any]=3072 ,A_ : Dict="gelu" ,A_ : Dict=0.1 ,A_ : List[Any]=0.1 ,A_ : List[Any]=1536 ,A_ : List[str]=2 ,A_ : Any=0.02 ,A_ : str=1e-12 ,A_ : Optional[int]=0 ,A_ : List[str]=False ,A_ : Tuple=True ,**A_ : List[str] ,) -> Dict: super().__init__(pad_token_id=A_ ,**A_ ) A = vocab_size A = hidden_size if embedding_size is None else embedding_size A = hidden_size A = num_hidden_layers A = num_attention_heads A = hidden_act A = intermediate_size A = hidden_dropout_prob A = attention_probs_dropout_prob A = max_position_embeddings A = type_vocab_size A = initializer_range A = layer_norm_eps A = rotary_value A = use_cache class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' @property def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": A = {0: 'batch', 1: 'choice', 2: 'sequence'} else: A = {0: 'batch', 1: 'sequence'} A = {0: 'batch', 1: 'sequence'} return OrderedDict( [ ('input_ids', dynamic_axis), ('attention_mask', dynamic_axis), ('token_type_ids', dynamic_axis), ] )
74
1
"""simple docstring""" import argparse import json import os import pickle import shutil import numpy as np import torch from distiller import Distiller from lm_seqs_dataset import LmSeqsDataset from transformers import ( BertConfig, BertForMaskedLM, BertTokenizer, DistilBertConfig, DistilBertForMaskedLM, DistilBertTokenizer, GPTaConfig, GPTaLMHeadModel, GPTaTokenizer, RobertaConfig, RobertaForMaskedLM, RobertaTokenizer, ) from utils import git_log, init_gpu_params, logger, set_seed _lowercase = { '''distilbert''': (DistilBertConfig, DistilBertForMaskedLM, DistilBertTokenizer), '''roberta''': (RobertaConfig, RobertaForMaskedLM, RobertaTokenizer), '''bert''': (BertConfig, BertForMaskedLM, BertTokenizer), '''gpt2''': (GPTaConfig, GPTaLMHeadModel, GPTaTokenizer), } def _snake_case ( snake_case__ : Dict ): assert (args.mlm and args.alpha_mlm > 0.0) or (not args.mlm and args.alpha_mlm == 0.0) assert (args.alpha_mlm > 0.0 and args.alpha_clm == 0.0) or (args.alpha_mlm == 0.0 and args.alpha_clm > 0.0) if args.mlm: assert os.path.isfile(args.token_counts ) assert (args.student_type in ["roberta", "distilbert"]) and (args.teacher_type in ["roberta", "bert"]) else: assert (args.student_type in ["gpt2"]) and (args.teacher_type in ["gpt2"]) assert args.teacher_type == args.student_type or ( args.student_type == "distilbert" and args.teacher_type == "bert" ) assert os.path.isfile(args.student_config ) if args.student_pretrained_weights is not None: assert os.path.isfile(args.student_pretrained_weights ) if args.freeze_token_type_embds: assert args.student_type in ["roberta"] assert args.alpha_ce >= 0.0 assert args.alpha_mlm >= 0.0 assert args.alpha_clm >= 0.0 assert args.alpha_mse >= 0.0 assert args.alpha_cos >= 0.0 assert args.alpha_ce + args.alpha_mlm + args.alpha_clm + args.alpha_mse + args.alpha_cos > 0.0 def _snake_case ( snake_case__ : Union[str, Any] , snake_case__ : Union[str, Any] ): if args.student_type == "roberta": A = False elif args.student_type == "gpt2": A = False def _snake_case ( snake_case__ : Dict , snake_case__ : Any ): if args.student_type == "roberta": A = False def _snake_case ( ): A = argparse.ArgumentParser(description='Training' ) parser.add_argument('--force' , action='store_true' , help='Overwrite dump_path if it already exists.' ) parser.add_argument( '--dump_path' , type=snake_case__ , required=snake_case__ , help='The output directory (log, checkpoints, parameters, etc.)' ) parser.add_argument( '--data_file' , type=snake_case__ , required=snake_case__ , help='The binarized file (tokenized + tokens_to_ids) and grouped by sequence.' , ) parser.add_argument( '--student_type' , type=snake_case__ , choices=['distilbert', 'roberta', 'gpt2'] , required=snake_case__ , help='The student type (DistilBERT, RoBERTa).' , ) parser.add_argument('--student_config' , type=snake_case__ , required=snake_case__ , help='Path to the student configuration.' ) parser.add_argument( '--student_pretrained_weights' , default=snake_case__ , type=snake_case__ , help='Load student initialization checkpoint.' ) parser.add_argument( '--teacher_type' , choices=['bert', 'roberta', 'gpt2'] , required=snake_case__ , help='Teacher type (BERT, RoBERTa).' ) parser.add_argument('--teacher_name' , type=snake_case__ , required=snake_case__ , help='The teacher model.' ) parser.add_argument('--temperature' , default=2.0 , type=snake_case__ , help='Temperature for the softmax temperature.' ) parser.add_argument( '--alpha_ce' , default=0.5 , type=snake_case__ , help='Linear weight for the distillation loss. Must be >=0.' ) parser.add_argument( '--alpha_mlm' , default=0.0 , type=snake_case__ , help='Linear weight for the MLM loss. Must be >=0. Should be used in conjunction with `mlm` flag.' , ) parser.add_argument('--alpha_clm' , default=0.5 , type=snake_case__ , help='Linear weight for the CLM loss. Must be >=0.' ) parser.add_argument('--alpha_mse' , default=0.0 , type=snake_case__ , help='Linear weight of the MSE loss. Must be >=0.' ) parser.add_argument( '--alpha_cos' , default=0.0 , type=snake_case__ , help='Linear weight of the cosine embedding loss. Must be >=0.' ) parser.add_argument( '--mlm' , action='store_true' , help='The LM step: MLM or CLM. If `mlm` is True, the MLM is used over CLM.' ) parser.add_argument( '--mlm_mask_prop' , default=0.15 , type=snake_case__ , help='Proportion of tokens for which we need to make a prediction.' , ) parser.add_argument('--word_mask' , default=0.8 , type=snake_case__ , help='Proportion of tokens to mask out.' ) parser.add_argument('--word_keep' , default=0.1 , type=snake_case__ , help='Proportion of tokens to keep.' ) parser.add_argument('--word_rand' , default=0.1 , type=snake_case__ , help='Proportion of tokens to randomly replace.' ) parser.add_argument( '--mlm_smoothing' , default=0.7 , type=snake_case__ , help='Smoothing parameter to emphasize more rare tokens (see XLM, similar to word2vec).' , ) parser.add_argument('--token_counts' , type=snake_case__ , help='The token counts in the data_file for MLM.' ) parser.add_argument( '--restrict_ce_to_mask' , action='store_true' , help='If true, compute the distillation loss only the [MLM] prediction distribution.' , ) parser.add_argument( '--freeze_pos_embs' , action='store_true' , help='Freeze positional embeddings during distillation. For student_type in [\'roberta\', \'gpt2\'] only.' , ) parser.add_argument( '--freeze_token_type_embds' , action='store_true' , help='Freeze token type embeddings during distillation if existent. For student_type in [\'roberta\'] only.' , ) parser.add_argument('--n_epoch' , type=snake_case__ , default=3 , help='Number of pass on the whole dataset.' ) parser.add_argument('--batch_size' , type=snake_case__ , default=5 , help='Batch size (for each process).' ) parser.add_argument( '--group_by_size' , action='store_false' , help='If true, group sequences that have similar length into the same batch. Default is true.' , ) parser.add_argument( '--gradient_accumulation_steps' , type=snake_case__ , default=50 , help='Gradient accumulation for larger training batches.' , ) parser.add_argument('--warmup_prop' , default=0.05 , type=snake_case__ , help='Linear warmup proportion.' ) parser.add_argument('--weight_decay' , default=0.0 , type=snake_case__ , help='Weight decay if we apply some.' ) parser.add_argument('--learning_rate' , default=5e-4 , type=snake_case__ , help='The initial learning rate for Adam.' ) parser.add_argument('--adam_epsilon' , default=1e-6 , type=snake_case__ , help='Epsilon for Adam optimizer.' ) parser.add_argument('--max_grad_norm' , default=5.0 , type=snake_case__ , help='Max gradient norm.' ) parser.add_argument('--initializer_range' , default=0.02 , type=snake_case__ , help='Random initialization range.' ) parser.add_argument( '--fp16' , action='store_true' , help='Whether to use 16-bit (mixed) precision (through NVIDIA apex) instead of 32-bit' , ) parser.add_argument( '--fp16_opt_level' , type=snake_case__ , default='O1' , help=( 'For fp16: Apex AMP optimization level selected in [\'O0\', \'O1\', \'O2\', and \'O3\'].' 'See details at https://nvidia.github.io/apex/amp.html' ) , ) parser.add_argument('--n_gpu' , type=snake_case__ , default=1 , help='Number of GPUs in the node.' ) parser.add_argument('--local_rank' , type=snake_case__ , default=-1 , help='Distributed training - Local rank' ) parser.add_argument('--seed' , type=snake_case__ , default=56 , help='Random seed' ) parser.add_argument('--log_interval' , type=snake_case__ , default=500 , help='Tensorboard logging interval.' ) parser.add_argument('--checkpoint_interval' , type=snake_case__ , default=4000 , help='Checkpoint interval.' ) A = parser.parse_args() sanity_checks(snake_case__ ) # ARGS # init_gpu_params(snake_case__ ) set_seed(snake_case__ ) if args.is_master: if os.path.exists(args.dump_path ): if not args.force: raise ValueError( F'Serialization dir {args.dump_path} already exists, but you have not precised wheter to overwrite' ' itUse `--force` if you want to overwrite it' ) else: shutil.rmtree(args.dump_path ) if not os.path.exists(args.dump_path ): os.makedirs(args.dump_path ) logger.info(F'Experiment will be dumped and logged in {args.dump_path}' ) # SAVE PARAMS # logger.info(F'Param: {args}' ) with open(os.path.join(args.dump_path , 'parameters.json' ) , 'w' ) as f: json.dump(vars(snake_case__ ) , snake_case__ , indent=4 ) git_log(args.dump_path ) A , A , A = MODEL_CLASSES[args.student_type] A , A , A = MODEL_CLASSES[args.teacher_type] # TOKENIZER # A = teacher_tokenizer_class.from_pretrained(args.teacher_name ) A = {} for tok_name, tok_symbol in tokenizer.special_tokens_map.items(): A = tokenizer.all_special_tokens.index(snake_case__ ) A = tokenizer.all_special_ids[idx] logger.info(F'Special tokens {special_tok_ids}' ) A = special_tok_ids A = tokenizer.max_model_input_sizes[args.teacher_name] # DATA LOADER # logger.info(F'Loading data from {args.data_file}' ) with open(args.data_file , 'rb' ) as fp: A = pickle.load(snake_case__ ) if args.mlm: logger.info(F'Loading token counts from {args.token_counts} (already pre-computed)' ) with open(args.token_counts , 'rb' ) as fp: A = pickle.load(snake_case__ ) A = np.maximum(snake_case__ , 1 ) ** -args.mlm_smoothing for idx in special_tok_ids.values(): A = 0.0 # do not predict special tokens A = torch.from_numpy(snake_case__ ) else: A = None A = LmSeqsDataset(params=snake_case__ , data=snake_case__ ) logger.info('Data loader created.' ) # STUDENT # logger.info(F'Loading student config from {args.student_config}' ) A = student_config_class.from_pretrained(args.student_config ) A = True if args.student_pretrained_weights is not None: logger.info(F'Loading pretrained weights from {args.student_pretrained_weights}' ) A = student_model_class.from_pretrained(args.student_pretrained_weights , config=snake_case__ ) else: A = student_model_class(snake_case__ ) if args.n_gpu > 0: student.to(F'cuda:{args.local_rank}' ) logger.info('Student loaded.' ) # TEACHER # A = teacher_model_class.from_pretrained(args.teacher_name , output_hidden_states=snake_case__ ) if args.n_gpu > 0: teacher.to(F'cuda:{args.local_rank}' ) logger.info(F'Teacher loaded from {args.teacher_name}.' ) # FREEZING # if args.freeze_pos_embs: freeze_pos_embeddings(snake_case__ , snake_case__ ) if args.freeze_token_type_embds: freeze_token_type_embeddings(snake_case__ , snake_case__ ) # SANITY CHECKS # assert student.config.vocab_size == teacher.config.vocab_size assert student.config.hidden_size == teacher.config.hidden_size assert student.config.max_position_embeddings == teacher.config.max_position_embeddings if args.mlm: assert token_probs.size(0 ) == stu_architecture_config.vocab_size # DISTILLER # torch.cuda.empty_cache() A = Distiller( params=snake_case__ , dataset=snake_case__ , token_probs=snake_case__ , student=snake_case__ , teacher=snake_case__ ) distiller.train() logger.info('Let\'s go get some drinks.' ) if __name__ == "__main__": main()
74
"""simple docstring""" import argparse import torch from torch import nn from transformers import MBartConfig, MBartForConditionalGeneration def _snake_case ( snake_case__ : Dict ): A = [ 'encoder.version', 'decoder.version', 'model.encoder.version', 'model.decoder.version', '_float_tensor', 'decoder.output_projection.weight', ] for k in ignore_keys: state_dict.pop(snake_case__ , snake_case__ ) def _snake_case ( snake_case__ : int ): A , A = emb.weight.shape A = nn.Linear(snake_case__ , snake_case__ , bias=snake_case__ ) A = emb.weight.data return lin_layer def _snake_case ( snake_case__ : List[str] , snake_case__ : Any="facebook/mbart-large-en-ro" , snake_case__ : Optional[int]=False , snake_case__ : List[str]=False ): A = torch.load(snake_case__ , map_location='cpu' )['model'] remove_ignore_keys_(snake_case__ ) A = state_dict['encoder.embed_tokens.weight'].shape[0] A = MBartConfig.from_pretrained(snake_case__ , vocab_size=snake_case__ ) if mbart_aa and finetuned: A = 'relu' A = state_dict['decoder.embed_tokens.weight'] A = MBartForConditionalGeneration(snake_case__ ) model.model.load_state_dict(snake_case__ ) if finetuned: A = make_linear_from_emb(model.model.shared ) return model if __name__ == "__main__": _lowercase = argparse.ArgumentParser() # Required parameters parser.add_argument( '''fairseq_path''', type=str, help='''bart.large, bart.large.cnn or a path to a model.pt on local filesystem.''' ) parser.add_argument('''pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') parser.add_argument( '''--hf_config''', default='''facebook/mbart-large-cc25''', type=str, help='''Which huggingface architecture to use: mbart-large''', ) parser.add_argument('''--mbart_50''', action='''store_true''', help='''whether the model is mMART-50 checkpoint''') parser.add_argument('''--finetuned''', action='''store_true''', help='''whether the model is a fine-tuned checkpoint''') _lowercase = parser.parse_args() _lowercase = convert_fairseq_mbart_checkpoint_from_disk( args.fairseq_path, hf_config_path=args.hf_config, finetuned=args.finetuned, mbart_aa=args.mbart_aa ) model.save_pretrained(args.pytorch_dump_folder_path)
74
1
"""simple docstring""" from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging _lowercase = logging.get_logger(__name__) _lowercase = { '''facebook/deit-base-distilled-patch16-224''': ( '''https://huggingface.co/facebook/deit-base-patch16-224/resolve/main/config.json''' ), # See all DeiT models at https://huggingface.co/models?filter=deit } class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: Optional[Any] = '''deit''' def __init__( self : int ,A_ : Optional[Any]=768 ,A_ : Union[str, Any]=12 ,A_ : Dict=12 ,A_ : int=3072 ,A_ : Optional[Any]="gelu" ,A_ : Dict=0.0 ,A_ : Any=0.0 ,A_ : str=0.02 ,A_ : Tuple=1e-12 ,A_ : Union[str, Any]=224 ,A_ : Optional[Any]=16 ,A_ : List[Any]=3 ,A_ : Optional[Any]=True ,A_ : Optional[int]=16 ,**A_ : Union[str, Any] ,) -> Dict: super().__init__(**A_ ) A = hidden_size A = num_hidden_layers A = num_attention_heads A = intermediate_size A = hidden_act A = hidden_dropout_prob A = attention_probs_dropout_prob A = initializer_range A = layer_norm_eps A = image_size A = patch_size A = num_channels A = qkv_bias A = encoder_stride class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: int = version.parse('''1.11''' ) @property def _SCREAMING_SNAKE_CASE ( self : Tuple ) -> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ] ) @property def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> float: return 1e-4
74
"""simple docstring""" import argparse import struct import unittest class lowerCAmelCase_ : '''simple docstring''' def __init__( self : Tuple ,A_ : bytes ) -> None: A = data # Initialize hash values A = [ 0X6_A_0_9_E_6_6_7, 0XB_B_6_7_A_E_8_5, 0X3_C_6_E_F_3_7_2, 0XA_5_4_F_F_5_3_A, 0X5_1_0_E_5_2_7_F, 0X9_B_0_5_6_8_8_C, 0X1_F_8_3_D_9_A_B, 0X5_B_E_0_C_D_1_9, ] # Initialize round constants A = [ 0X4_2_8_A_2_F_9_8, 0X7_1_3_7_4_4_9_1, 0XB_5_C_0_F_B_C_F, 0XE_9_B_5_D_B_A_5, 0X3_9_5_6_C_2_5_B, 0X5_9_F_1_1_1_F_1, 0X9_2_3_F_8_2_A_4, 0XA_B_1_C_5_E_D_5, 0XD_8_0_7_A_A_9_8, 0X1_2_8_3_5_B_0_1, 0X2_4_3_1_8_5_B_E, 0X5_5_0_C_7_D_C_3, 0X7_2_B_E_5_D_7_4, 0X8_0_D_E_B_1_F_E, 0X9_B_D_C_0_6_A_7, 0XC_1_9_B_F_1_7_4, 0XE_4_9_B_6_9_C_1, 0XE_F_B_E_4_7_8_6, 0X0_F_C_1_9_D_C_6, 0X2_4_0_C_A_1_C_C, 0X2_D_E_9_2_C_6_F, 0X4_A_7_4_8_4_A_A, 0X5_C_B_0_A_9_D_C, 0X7_6_F_9_8_8_D_A, 0X9_8_3_E_5_1_5_2, 0XA_8_3_1_C_6_6_D, 0XB_0_0_3_2_7_C_8, 0XB_F_5_9_7_F_C_7, 0XC_6_E_0_0_B_F_3, 0XD_5_A_7_9_1_4_7, 0X0_6_C_A_6_3_5_1, 0X1_4_2_9_2_9_6_7, 0X2_7_B_7_0_A_8_5, 0X2_E_1_B_2_1_3_8, 0X4_D_2_C_6_D_F_C, 0X5_3_3_8_0_D_1_3, 0X6_5_0_A_7_3_5_4, 0X7_6_6_A_0_A_B_B, 0X8_1_C_2_C_9_2_E, 0X9_2_7_2_2_C_8_5, 0XA_2_B_F_E_8_A_1, 0XA_8_1_A_6_6_4_B, 0XC_2_4_B_8_B_7_0, 0XC_7_6_C_5_1_A_3, 0XD_1_9_2_E_8_1_9, 0XD_6_9_9_0_6_2_4, 0XF_4_0_E_3_5_8_5, 0X1_0_6_A_A_0_7_0, 0X1_9_A_4_C_1_1_6, 0X1_E_3_7_6_C_0_8, 0X2_7_4_8_7_7_4_C, 0X3_4_B_0_B_C_B_5, 0X3_9_1_C_0_C_B_3, 0X4_E_D_8_A_A_4_A, 0X5_B_9_C_C_A_4_F, 0X6_8_2_E_6_F_F_3, 0X7_4_8_F_8_2_E_E, 0X7_8_A_5_6_3_6_F, 0X8_4_C_8_7_8_1_4, 0X8_C_C_7_0_2_0_8, 0X9_0_B_E_F_F_F_A, 0XA_4_5_0_6_C_E_B, 0XB_E_F_9_A_3_F_7, 0XC_6_7_1_7_8_F_2, ] A = self.preprocessing(self.data ) self.final_hash() @staticmethod def _SCREAMING_SNAKE_CASE ( A_ : bytes ) -> bytes: A = B'\x80' + (B'\x00' * (63 - (len(A_ ) + 8) % 64)) A = struct.pack('>Q' ,(len(A_ ) * 8) ) return data + padding + big_endian_integer def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> None: # Convert into blocks of 64 bytes A = [ self.preprocessed_data[x : x + 64] for x in range(0 ,len(self.preprocessed_data ) ,64 ) ] for block in self.blocks: # Convert the given block into a list of 4 byte integers A = list(struct.unpack('>16L' ,A_ ) ) # add 48 0-ed integers words += [0] * 48 A , A , A , A , A , A , A , A = self.hashes for index in range(0 ,64 ): if index > 15: # modify the zero-ed indexes at the end of the array A = ( self.ror(words[index - 15] ,7 ) ^ self.ror(words[index - 15] ,18 ) ^ (words[index - 15] >> 3) ) A = ( self.ror(words[index - 2] ,17 ) ^ self.ror(words[index - 2] ,19 ) ^ (words[index - 2] >> 10) ) A = ( words[index - 16] + sa + words[index - 7] + sa ) % 0X1_0_0_0_0_0_0_0_0 # Compression A = self.ror(A_ ,6 ) ^ self.ror(A_ ,11 ) ^ self.ror(A_ ,25 ) A = (e & f) ^ ((~e & 0XF_F_F_F_F_F_F_F) & g) A = ( h + sa + ch + self.round_constants[index] + words[index] ) % 0X1_0_0_0_0_0_0_0_0 A = self.ror(A_ ,2 ) ^ self.ror(A_ ,13 ) ^ self.ror(A_ ,22 ) A = (a & b) ^ (a & c) ^ (b & c) A = (sa + maj) % 0X1_0_0_0_0_0_0_0_0 A , A , A , A , A , A , A , A = ( g, f, e, ((d + tempa) % 0X1_0_0_0_0_0_0_0_0), c, b, a, ((tempa + tempa) % 0X1_0_0_0_0_0_0_0_0), ) A = [a, b, c, d, e, f, g, h] # Modify final values A = [ ((element + mutated_hash_values[index]) % 0X1_0_0_0_0_0_0_0_0) for index, element in enumerate(self.hashes ) ] A = ''.join([hex(A_ )[2:].zfill(8 ) for value in self.hashes] ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ,A_ : int ,A_ : int ) -> int: return 0XF_F_F_F_F_F_F_F & (value << (32 - rotations)) | (value >> rotations) class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> None: import hashlib A = bytes('Test String' ,'utf-8' ) self.assertEqual(SHAaaa(A_ ).hash ,hashlib.shaaaa(A_ ).hexdigest() ) def _snake_case ( ): import doctest doctest.testmod() A = argparse.ArgumentParser() parser.add_argument( '-s' , '--string' , dest='input_string' , default='Hello World!! Welcome to Cryptography' , help='Hash the string' , ) parser.add_argument( '-f' , '--file' , dest='input_file' , help='Hash contents of a file' ) A = parser.parse_args() A = args.input_string # hash input should be a bytestring if args.input_file: with open(args.input_file , 'rb' ) as f: A = f.read() else: A = bytes(snake_case__ , 'utf-8' ) print(SHAaaa(snake_case__ ).hash ) if __name__ == "__main__": main()
74
1
"""simple docstring""" # Copyright 2021 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 pathlib import Path import torch from ...utils import is_npu_available, is_xpu_available from .config_args import ClusterConfig, default_json_config_file from .config_utils import SubcommandHelpFormatter _lowercase = '''Create a default config file for Accelerate with only a few flags set.''' def _snake_case ( snake_case__ : str="no" , snake_case__ : str = default_json_config_file , snake_case__ : bool = False ): A = Path(snake_case__ ) path.parent.mkdir(parents=snake_case__ , exist_ok=snake_case__ ) if path.exists(): print( F'Configuration already exists at {save_location}, will not override. Run `accelerate config` manually or pass a different `save_location`.' ) return False A = mixed_precision.lower() if mixed_precision not in ["no", "fp16", "bf16", "fp8"]: raise ValueError( F'`mixed_precision` should be one of \'no\', \'fp16\', \'bf16\', or \'fp8\'. Received {mixed_precision}' ) A = { 'compute_environment': 'LOCAL_MACHINE', 'mixed_precision': mixed_precision, } if torch.cuda.is_available(): A = torch.cuda.device_count() A = num_gpus A = False if num_gpus > 1: A = 'MULTI_GPU' else: A = 'NO' elif is_xpu_available() and use_xpu: A = torch.xpu.device_count() A = num_xpus A = False if num_xpus > 1: A = 'MULTI_XPU' else: A = 'NO' elif is_npu_available(): A = torch.npu.device_count() A = num_npus A = False if num_npus > 1: A = 'MULTI_NPU' else: A = 'NO' else: A = 0 A = True A = 1 A = 'NO' A = ClusterConfig(**snake_case__ ) config.to_json_file(snake_case__ ) return path def _snake_case ( snake_case__ : Optional[int] , snake_case__ : Union[str, Any] ): A = parser.add_parser('default' , parents=snake_case__ , help=snake_case__ , formatter_class=snake_case__ ) parser.add_argument( '--config_file' , default=snake_case__ , help=( 'The path to use to store the config file. Will default to a file named default_config.yaml in the cache ' 'location, which is the content of the environment `HF_HOME` suffixed with \'accelerate\', or if you don\'t have ' 'such an environment variable, your cache directory (\'~/.cache\' or the content of `XDG_CACHE_HOME`) suffixed ' 'with \'huggingface\'.' ) , dest='save_location' , ) parser.add_argument( '--mixed_precision' , choices=['no', 'fp16', 'bf16'] , type=snake_case__ , help='Whether or not to use mixed precision training. ' 'Choose between FP16 and BF16 (bfloat16) training. ' 'BF16 training is only supported on Nvidia Ampere GPUs and PyTorch 1.10 or later.' , default='no' , ) parser.set_defaults(func=snake_case__ ) return parser def _snake_case ( snake_case__ : Any ): A = write_basic_config(args.mixed_precision , args.save_location ) if config_file: print(F'accelerate configuration saved at {config_file}' )
74
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) _lowercase = {'''configuration_deit''': ['''DEIT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''DeiTConfig''', '''DeiTOnnxConfig''']} try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase = ['''DeiTFeatureExtractor'''] _lowercase = ['''DeiTImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase = [ '''DEIT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''DeiTForImageClassification''', '''DeiTForImageClassificationWithTeacher''', '''DeiTForMaskedImageModeling''', '''DeiTModel''', '''DeiTPreTrainedModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase = [ '''TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFDeiTForImageClassification''', '''TFDeiTForImageClassificationWithTeacher''', '''TFDeiTForMaskedImageModeling''', '''TFDeiTModel''', '''TFDeiTPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_deit import DEIT_PRETRAINED_CONFIG_ARCHIVE_MAP, DeiTConfig, DeiTOnnxConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_deit import DeiTFeatureExtractor from .image_processing_deit import DeiTImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_deit import ( DEIT_PRETRAINED_MODEL_ARCHIVE_LIST, DeiTForImageClassification, DeiTForImageClassificationWithTeacher, DeiTForMaskedImageModeling, DeiTModel, DeiTPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_deit import ( TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST, TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher, TFDeiTForMaskedImageModeling, TFDeiTModel, TFDeiTPreTrainedModel, ) else: import sys _lowercase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
74
1
"""simple docstring""" from typing import Callable, List, Optional, Tuple, Union import torch from transformers import CLIPTextModel, CLIPTokenizer from ...configuration_utils import ConfigMixin, register_to_config from ...models import ModelMixin, TransformeraDModel, VQModel from ...schedulers import VQDiffusionScheduler from ...utils import logging from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput _lowercase = logging.get_logger(__name__) # pylint: disable=invalid-name class lowerCAmelCase_ ( _lowercase , _lowercase ): '''simple docstring''' @register_to_config def __init__( self : Optional[Any] ,A_ : bool ,A_ : Optional[int] = None ,A_ : Optional[int] = None ) -> Union[str, Any]: super().__init__() A = learnable if self.learnable: assert hidden_size is not None, "learnable=True requires `hidden_size` to be set" assert length is not None, "learnable=True requires `length` to be set" A = torch.zeros(A_ ,A_ ) else: A = None A = torch.nn.Parameter(A_ ) class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: VQModel _lowerCamelCase: CLIPTextModel _lowerCamelCase: CLIPTokenizer _lowerCamelCase: TransformeraDModel _lowerCamelCase: LearnedClassifierFreeSamplingEmbeddings _lowerCamelCase: VQDiffusionScheduler def __init__( self : int ,A_ : VQModel ,A_ : CLIPTextModel ,A_ : CLIPTokenizer ,A_ : TransformeraDModel ,A_ : VQDiffusionScheduler ,A_ : LearnedClassifierFreeSamplingEmbeddings ,) -> Optional[Any]: super().__init__() self.register_modules( vqvae=A_ ,transformer=A_ ,text_encoder=A_ ,tokenizer=A_ ,scheduler=A_ ,learned_classifier_free_sampling_embeddings=A_ ,) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ,A_ : List[Any] ,A_ : List[Any] ,A_ : Any ) -> Optional[int]: A = len(A_ ) if isinstance(A_ ,A_ ) else 1 # get prompt text embeddings A = self.tokenizer( A_ ,padding='max_length' ,max_length=self.tokenizer.model_max_length ,return_tensors='pt' ,) A = text_inputs.input_ids if text_input_ids.shape[-1] > self.tokenizer.model_max_length: A = self.tokenizer.batch_decode(text_input_ids[:, self.tokenizer.model_max_length :] ) logger.warning( 'The following part of your input was truncated because CLIP can only handle sequences up to' F' {self.tokenizer.model_max_length} tokens: {removed_text}' ) A = text_input_ids[:, : self.tokenizer.model_max_length] A = self.text_encoder(text_input_ids.to(self.device ) )[0] # NOTE: This additional step of normalizing the text embeddings is from VQ-Diffusion. # While CLIP does normalize the pooled output of the text transformer when combining # the image and text embeddings, CLIP does not directly normalize the last hidden state. # # CLIP normalizing the pooled output. # https://github.com/huggingface/transformers/blob/d92e22d1f28324f513f3080e5c47c071a3916721/src/transformers/models/clip/modeling_clip.py#L1052-L1053 A = prompt_embeds / prompt_embeds.norm(dim=-1 ,keepdim=A_ ) # duplicate text embeddings for each generation per prompt A = prompt_embeds.repeat_interleave(A_ ,dim=0 ) if do_classifier_free_guidance: if self.learned_classifier_free_sampling_embeddings.learnable: A = self.learned_classifier_free_sampling_embeddings.embeddings A = negative_prompt_embeds.unsqueeze(0 ).repeat(A_ ,1 ,1 ) else: A = [''] * batch_size A = text_input_ids.shape[-1] A = self.tokenizer( A_ ,padding='max_length' ,max_length=A_ ,truncation=A_ ,return_tensors='pt' ,) A = self.text_encoder(uncond_input.input_ids.to(self.device ) )[0] # See comment for normalizing text embeddings A = negative_prompt_embeds / negative_prompt_embeds.norm(dim=-1 ,keepdim=A_ ) # duplicate unconditional embeddings for each generation per prompt, using mps friendly method A = negative_prompt_embeds.shape[1] A = negative_prompt_embeds.repeat(1 ,A_ ,1 ) A = negative_prompt_embeds.view(batch_size * num_images_per_prompt ,A_ ,-1 ) # For classifier free guidance, we need to do two forward passes. # Here we concatenate the unconditional and text embeddings into a single batch # to avoid doing two forward passes A = torch.cat([negative_prompt_embeds, prompt_embeds] ) return prompt_embeds @torch.no_grad() def __call__( self : Optional[Any] ,A_ : Union[str, List[str]] ,A_ : int = 100 ,A_ : float = 5.0 ,A_ : float = 1.0 ,A_ : int = 1 ,A_ : Optional[Union[torch.Generator, List[torch.Generator]]] = None ,A_ : Optional[torch.FloatTensor] = None ,A_ : Optional[str] = "pil" ,A_ : bool = True ,A_ : Optional[Callable[[int, int, torch.FloatTensor], None]] = None ,A_ : int = 1 ,) -> Union[ImagePipelineOutput, Tuple]: if isinstance(A_ ,A_ ): A = 1 elif isinstance(A_ ,A_ ): A = len(A_ ) else: raise ValueError(F'`prompt` has to be of type `str` or `list` but is {type(A_ )}' ) A = batch_size * num_images_per_prompt A = guidance_scale > 1.0 A = self._encode_prompt(A_ ,A_ ,A_ ) if (callback_steps is None) or ( callback_steps is not None and (not isinstance(A_ ,A_ ) or callback_steps <= 0) ): raise ValueError( F'`callback_steps` has to be a positive integer but is {callback_steps} of type' F' {type(A_ )}.' ) # get the initial completely masked latents unless the user supplied it A = (batch_size, self.transformer.num_latent_pixels) if latents is None: A = self.transformer.num_vector_embeds - 1 A = torch.full(A_ ,A_ ).to(self.device ) else: if latents.shape != latents_shape: raise ValueError(F'Unexpected latents shape, got {latents.shape}, expected {latents_shape}' ) if (latents < 0).any() or (latents >= self.transformer.num_vector_embeds).any(): raise ValueError( 'Unexpected latents value(s). All latents be valid embedding indices i.e. in the range 0,' F' {self.transformer.num_vector_embeds - 1} (inclusive).' ) A = latents.to(self.device ) # set timesteps self.scheduler.set_timesteps(A_ ,device=self.device ) A = self.scheduler.timesteps.to(self.device ) A = latents for i, t in enumerate(self.progress_bar(A_ ) ): # expand the sample if we are doing classifier free guidance A = torch.cat([sample] * 2 ) if do_classifier_free_guidance else sample # predict the un-noised image # model_output == `log_p_x_0` A = self.transformer(A_ ,encoder_hidden_states=A_ ,timestep=A_ ).sample if do_classifier_free_guidance: A , A = model_output.chunk(2 ) A = model_output_uncond + guidance_scale * (model_output_text - model_output_uncond) model_output -= torch.logsumexp(A_ ,dim=1 ,keepdim=A_ ) A = self.truncate(A_ ,A_ ) # remove `log(0)`'s (`-inf`s) A = model_output.clamp(-70 ) # compute the previous noisy sample x_t -> x_t-1 A = self.scheduler.step(A_ ,timestep=A_ ,sample=A_ ,generator=A_ ).prev_sample # call the callback, if provided if callback is not None and i % callback_steps == 0: callback(A_ ,A_ ,A_ ) A = self.vqvae.config.vq_embed_dim A = (batch_size, self.transformer.height, self.transformer.width, embedding_channels) A = self.vqvae.quantize.get_codebook_entry(A_ ,shape=A_ ) A = self.vqvae.decode(A_ ,force_not_quantize=A_ ).sample A = (image / 2 + 0.5).clamp(0 ,1 ) A = image.cpu().permute(0 ,2 ,3 ,1 ).numpy() if output_type == "pil": A = self.numpy_to_pil(A_ ) if not return_dict: return (image,) return ImagePipelineOutput(images=A_ ) def _SCREAMING_SNAKE_CASE ( self : Any ,A_ : torch.FloatTensor ,A_ : float ) -> torch.FloatTensor: A , A = torch.sort(A_ ,1 ,descending=A_ ) A = torch.exp(A_ ) A = sorted_p_x_0.cumsum(dim=1 ) < truncation_rate # Ensure that at least the largest probability is not zeroed out A = torch.full_like(keep_mask[:, 0:1, :] ,A_ ) A = torch.cat((all_true, keep_mask) ,dim=1 ) A = keep_mask[:, :-1, :] A = keep_mask.gather(1 ,indices.argsort(1 ) ) A = log_p_x_0.clone() A = -torch.inf # -inf = log(0) return rv
74
"""simple docstring""" from __future__ import annotations import requests def _snake_case ( snake_case__ : str ): A = F'https://hacker-news.firebaseio.com/v0/item/{story_id}.json?print=pretty' return requests.get(snake_case__ ).json() def _snake_case ( snake_case__ : int = 10 ): A = 'https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty' A = requests.get(snake_case__ ).json()[:max_stories] return [get_hackernews_story(snake_case__ ) for story_id in story_ids] def _snake_case ( snake_case__ : int = 10 ): A = hackernews_top_stories(snake_case__ ) return "\n".join('* [{title}]({url})'.format(**snake_case__ ) for story in stories ) if __name__ == "__main__": print(hackernews_top_stories_as_markdown())
74
1
"""simple docstring""" from urllib.parse import quote import pytest from datasets.utils.hub import hf_hub_url @pytest.mark.parametrize('repo_id' , ['canonical_dataset_name', 'org-name/dataset-name'] ) @pytest.mark.parametrize('path' , ['filename.csv', 'filename with blanks.csv'] ) @pytest.mark.parametrize('revision' , [None, 'v2'] ) def _snake_case ( snake_case__ : Any , snake_case__ : str , snake_case__ : Dict ): A = hf_hub_url(repo_id=snake_case__ , path=snake_case__ , revision=snake_case__ ) assert url == F'https://huggingface.co/datasets/{repo_id}/resolve/{revision or "main"}/{quote(snake_case__ )}'
74
"""simple docstring""" from string import ascii_uppercase _lowercase = {char: i for i, char in enumerate(ascii_uppercase)} _lowercase = dict(enumerate(ascii_uppercase)) def _snake_case ( snake_case__ : str , snake_case__ : str ): A = len(snake_case__ ) A = 0 while True: if x == i: A = 0 if len(snake_case__ ) == len(snake_case__ ): break key += key[i] i += 1 return key def _snake_case ( snake_case__ : str , snake_case__ : str ): A = '' A = 0 for letter in message: if letter == " ": cipher_text += " " else: A = (dicta[letter] - dicta[key_new[i]]) % 26 i += 1 cipher_text += dicta[x] return cipher_text def _snake_case ( snake_case__ : str , snake_case__ : str ): A = '' A = 0 for letter in cipher_text: if letter == " ": or_txt += " " else: A = (dicta[letter] + dicta[key_new[i]] + 26) % 26 i += 1 or_txt += dicta[x] return or_txt def _snake_case ( ): A = 'THE GERMAN ATTACK' A = 'SECRET' A = generate_key(snake_case__ , snake_case__ ) A = cipher_text(snake_case__ , snake_case__ ) print(F'Encrypted Text = {s}' ) print(F'Original Text = {original_text(snake_case__ , snake_case__ )}' ) if __name__ == "__main__": import doctest doctest.testmod() main()
74
1
"""simple docstring""" import math import os import re import sys import unittest from pathlib import Path from typing import Tuple from unittest.mock import patch from parameterized import parameterized from transformers.testing_utils import ( CaptureStderr, ExtendSysPath, TestCasePlus, execute_subprocess_async, get_gpu_count, get_torch_dist_unique_port, require_apex, require_bitsandbytes, require_fairscale, require_torch, require_torch_gpu, require_torch_multi_gpu, require_torch_non_multi_gpu, slow, ) from transformers.trainer_callback import TrainerState from transformers.trainer_utils import set_seed _lowercase = os.path.abspath(os.path.dirname(__file__)) with ExtendSysPath(F"""{bindir}/../../examples/pytorch/translation"""): from run_translation import main # noqa set_seed(42) _lowercase = '''sshleifer/student_marian_en_ro_6_1''' _lowercase = '''sshleifer/tiny-mbart''' @require_torch class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : Any ,A_ : Union[str, Any]=False ,A_ : Optional[int]=None ,A_ : List[str]=True ,A_ : Tuple=True ,A_ : Union[str, Any]=True ,A_ : List[str]=True ,) -> Tuple: A = self.run_trainer( eval_steps=1 ,max_len=12 ,model_name=A_ ,num_train_epochs=1 ,distributed=A_ ,extra_args_str=A_ ,predict_with_generate=A_ ,do_train=A_ ,do_eval=A_ ,do_predict=A_ ,) A = TrainerState.load_from_json(os.path.join(A_ ,'trainer_state.json' ) ).log_history if not do_eval: return A = [log for log in logs if 'eval_loss' in log.keys()] A = eval_metrics[0] if predict_with_generate: assert "eval_bleu" in first_step_stats A = eval_metrics[-1] assert isinstance(last_step_stats['eval_bleu'] ,A_ ) assert not math.isnan(float(last_step_stats['eval_loss'] ) ), "eval_loss must not be `nan`" @require_torch_non_multi_gpu def _SCREAMING_SNAKE_CASE ( self : str ) -> Dict: self.run_seqaseq_quick() @require_torch_multi_gpu def _SCREAMING_SNAKE_CASE ( self : int ) -> int: self.run_seqaseq_quick(distributed=A_ ) @require_torch_multi_gpu def _SCREAMING_SNAKE_CASE ( self : str ) -> List[Any]: self.run_seqaseq_quick(distributed=A_ ) @unittest.skip('Requires an update of the env running those tests' ) @require_torch_multi_gpu @require_fairscale def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Dict: self.run_seqaseq_quick(distributed=A_ ,extra_args_str='--sharded_ddp simple' ) @unittest.skip('Requires an update of the env running those tests' ) @require_torch_multi_gpu @require_fairscale def _SCREAMING_SNAKE_CASE ( self : Any ) -> int: self.run_seqaseq_quick(distributed=A_ ,extra_args_str='--sharded_ddp simple --fp16' ) @unittest.skip('Requires an update of the env running those tests' ) @require_torch_multi_gpu @require_fairscale def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> List[Any]: self.run_seqaseq_quick(distributed=A_ ,extra_args_str='--sharded_ddp zero_dp_2' ,predict_with_generate=A_ ) @unittest.skip('Requires an update of the env running those tests' ) @require_torch_multi_gpu @require_fairscale def _SCREAMING_SNAKE_CASE ( self : Dict ) -> Dict: self.run_seqaseq_quick( distributed=A_ ,extra_args_str='--sharded_ddp zero_dp_2 --fp16' ,predict_with_generate=A_ ) @require_apex @require_torch_gpu def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> Optional[Any]: # XXX: apex breaks the trainer if it's run twice e.g. run_seq2seq.main() from the same # program and it breaks other tests that run from the same pytest worker, therefore until this is # sorted out it must be run only in an external program, that is distributed=True in this # test and only under one or more gpus - if we want cpu will need to make a special test # # specifically to the problem traced it to self.optimizer.step() - if it's run 2nd time via # 2nd main() call it botches the future eval. # self.run_seqaseq_quick(distributed=A_ ,extra_args_str='--fp16 --fp16_backend=apex' ) # test 2nd time - was getting eval_loss': nan' # to reproduce the problem set distributed=False self.run_seqaseq_quick(distributed=A_ ,extra_args_str='--fp16 --fp16_backend=apex' ) @parameterized.expand(['base', 'low', 'high', 'mixed'] ) @require_torch_multi_gpu def _SCREAMING_SNAKE_CASE ( self : str ,A_ : Dict ) -> List[str]: # as each sub-test is slow-ish split into multiple sub-tests to avoid CI timeout A = { # test with the default log_level - should be info and thus log info once 'base': {'extra_args_str': '', 'n_matches': 1}, # test with low log_level and log_level_replica - should be noisy on all processes # now the info string should appear twice on 2 processes 'low': {'extra_args_str': '--log_level debug --log_level_replica debug', 'n_matches': 2}, # test with high log_level and low log_level_replica # now the info string should appear once only on the replica 'high': {'extra_args_str': '--log_level error --log_level_replica debug', 'n_matches': 1}, # test with high log_level and log_level_replica - should be quiet on all processes 'mixed': {'extra_args_str': '--log_level error --log_level_replica error', 'n_matches': 0}, } A = experiments[experiment_id] A = {'distributed': True, 'predict_with_generate': False, 'do_eval': False, 'do_predict': False} A = 'Running training' with CaptureStderr() as cl: self.run_seqaseq_quick(**A_ ,extra_args_str=data['extra_args_str'] ) A = len(re.findall(A_ ,cl.err ) ) self.assertEqual(A_ ,data['n_matches'] ) @slow def _SCREAMING_SNAKE_CASE ( self : Tuple ) -> str: A = self.run_trainer( eval_steps=2 ,max_len=128 ,model_name=A_ ,learning_rate=3e-4 ,num_train_epochs=10 ,distributed=A_ ,) # Check metrics A = TrainerState.load_from_json(os.path.join(A_ ,'trainer_state.json' ) ).log_history A = [log for log in logs if 'eval_loss' in log.keys()] A = eval_metrics[0] A = eval_metrics[-1] assert first_step_stats["eval_loss"] > last_step_stats["eval_loss"], "model learned nothing" assert isinstance(last_step_stats['eval_bleu'] ,A_ ) # test if do_predict saves generations and metrics A = os.listdir(A_ ) A = {os.path.basename(A_ ) for p in contents} assert "generated_predictions.txt" in contents assert "predict_results.json" in contents @slow @require_bitsandbytes def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Optional[int]: from transformers.training_args import OptimizerNames def train_and_return_metrics(A_ : str ) -> Tuple[int, float]: A = '--skip_memory_metrics 0' A = self.run_trainer( max_len=128 ,model_name=A_ ,learning_rate=3e-4 ,num_train_epochs=1 ,optim=A_ ,distributed=A_ ,extra_args_str=A_ ,do_eval=A_ ,do_predict=A_ ,n_gpus_to_use=1 ,) # Check metrics A = TrainerState.load_from_json(Path(A_ ,'trainer_state.json' ) ).log_history A = int(logs[0]['train_mem_gpu_peaked_delta'] / 2**20 ) A = int(logs[0]['train_mem_gpu_alloc_delta'] / 2**20 ) A = logs[0]['train_loss'] return gpu_peak_mem_mb, gpu_alloc_mem_mb, loss A , A , A = train_and_return_metrics(OptimizerNames.ADAMW_TORCH.value ) A , A , A = train_and_return_metrics(OptimizerNames.ADAMW_BNB.value ) A = gpu_alloc_mem_orig - gpu_alloc_mem_bnb A = gpu_peak_mem_orig + gpu_alloc_mem_orig A = gpu_peak_mem_bnb + gpu_alloc_mem_bnb A = gpu_total_mem_orig - gpu_total_mem_bnb # sshleifer/student_marian_en_ro_6_1 has 54M parameter, 29M of which is `nn.Embedding` which # doesn't get quantized and remains in fp32. Therefore we only have 25M parameters quantized # in 2 bytes and the diff in optim memory usage is derived as so: # # - normal 25*8=~200MB (8 bytes per param) # - bnb 25*2= ~50MB (2 bytes per param) # # Thus we should expect ~150MB total memory saved. # # Peak memory should be the same - the total should be different by about that same margin # # After leaving a small margin to accommodate for differences between gpus let's check # that we have at least 120MB in savings A = 120 # uncomment the following if this test starts failing - requires py38 for a new print feature # gpu_peak_mem_diff = gpu_peak_mem_orig - gpu_peak_mem_bnb # print(f"{gpu_alloc_mem_orig=}MB {gpu_peak_mem_orig=}MB {gpu_alloc_mem_orig+gpu_peak_mem_orig=}MB") # print(f" {gpu_alloc_mem_bnb=}MB {gpu_peak_mem_bnb=}MB {gpu_alloc_mem_bnb+gpu_peak_mem_bnb=}MB") # print(f"{gpu_alloc_mem_diff=}MB") # print(f"{gpu_peak_mem_diff=}MB") # print(f"{gpu_total_mem_orig=}MB, {gpu_total_mem_bnb=}MB") # print(f"{gpu_total_mem_diff=}MB, {gpu_total_mem_diff=}MB") self.assertGreater( A_ ,A_ ,'should use ~150MB less alloc gpu memory with BNB, compared to without it for this model but got' F' a difference of {gpu_alloc_mem_diff}MB, with gpu_alloc_mem_orig={gpu_alloc_mem_orig}MB and' F' gpu_alloc_mem_bnb={gpu_alloc_mem_bnb}MB' ,) self.assertGreater( A_ ,A_ ,'should use ~150MB less total gpu memory with BNB, compared to without it for this model but got' F' a difference of {gpu_total_mem_diff}MB, with gpu_total_mem_orig={gpu_total_mem_orig}MB and' F' gpu_total_mem_bnb={gpu_total_mem_bnb}MB' ,) self.assertEqual( A_ ,A_ ,F'loss should be the same, but got loss_orig={loss_orig}, loss_bnb={loss_bnb}' ) def _SCREAMING_SNAKE_CASE ( self : List[str] ,A_ : int ,A_ : str ,A_ : int ,A_ : float = 3e-3 ,A_ : str = "adafactor" ,A_ : bool = False ,A_ : str = None ,A_ : int = 0 ,A_ : bool = True ,A_ : bool = True ,A_ : bool = True ,A_ : bool = True ,A_ : int = None ,) -> Dict: A = self.test_file_dir / '../fixtures/tests_samples/wmt_en_ro' A = self.get_auto_remove_tmp_dir() A = F'\n --model_name_or_path {model_name}\n --train_file {data_dir}/train.json\n --validation_file {data_dir}/val.json\n --test_file {data_dir}/test.json\n --output_dir {output_dir}\n --overwrite_output_dir\n --max_train_samples 8\n --max_source_length {max_len}\n --max_target_length {max_len}\n --do_train\n --num_train_epochs {str(A_ )}\n --per_device_train_batch_size 4\n --learning_rate {learning_rate}\n --warmup_steps 8\n --logging_steps 0\n --logging_strategy no\n --save_steps {str(A_ )}\n --group_by_length\n --label_smoothing_factor 0.1\n --target_lang ro_RO\n --source_lang en_XX\n '.split() A = F'\n --do_eval\n --per_device_eval_batch_size 4\n --max_eval_samples 8\n --val_max_target_length {max_len}\n --evaluation_strategy steps\n --eval_steps {str(A_ )}\n '.split() A = '\n --do_predict\n '.split() A = [] if do_train: args += args_train if do_eval: args += args_eval if do_predict: args += args_predict if predict_with_generate: args += "--predict_with_generate".split() if do_train: if optim == "adafactor": args += "--adafactor".split() else: args += F'--optim {optim}'.split() if extra_args_str is not None: args += extra_args_str.split() if distributed: if n_gpus_to_use is None: A = get_gpu_count() A = get_torch_dist_unique_port() A = F'\n -m torch.distributed.run\n --nproc_per_node={n_gpus_to_use}\n --master_port={master_port}\n {self.examples_dir_str}/pytorch/translation/run_translation.py\n '.split() A = [sys.executable] + distributed_args + args # keep for quick debug # print(" ".join([f"\nPYTHONPATH={self.src_dir_str}"] +cmd)); die execute_subprocess_async(A_ ,env=self.get_env() ) else: A = ['run_translation.py'] + args with patch.object(A_ ,'argv' ,A_ ): main() return output_dir
74
"""simple docstring""" import os import tempfile import unittest from pathlib import Path from transformers import AutoConfig, is_torch_available from transformers.testing_utils import require_torch, torch_device if is_torch_available(): from transformers import PyTorchBenchmark, PyTorchBenchmarkArguments @require_torch class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : int ,A_ : List[Any] ) -> Optional[Any]: for model_result in results.values(): for batch_size, sequence_length in zip(model_result['bs'] ,model_result['ss'] ): A = model_result['result'][batch_size][sequence_length] self.assertIsNotNone(A_ ) def _SCREAMING_SNAKE_CASE ( self : int ) -> Optional[Any]: A = 'sshleifer/tiny-gpt2' A = PyTorchBenchmarkArguments( models=[MODEL_ID] ,training=A_ ,inference=A_ ,sequence_lengths=[8] ,batch_sizes=[1] ,multi_process=A_ ,) A = PyTorchBenchmark(A_ ) A = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Optional[int]: A = 'sgugger/tiny-distilbert-classification' A = PyTorchBenchmarkArguments( models=[MODEL_ID] ,training=A_ ,inference=A_ ,sequence_lengths=[8] ,batch_sizes=[1] ,multi_process=A_ ,only_pretrain_model=A_ ,) A = PyTorchBenchmark(A_ ) A = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> List[str]: A = 'sshleifer/tiny-gpt2' A = PyTorchBenchmarkArguments( models=[MODEL_ID] ,training=A_ ,inference=A_ ,torchscript=A_ ,sequence_lengths=[8] ,batch_sizes=[1] ,multi_process=A_ ,) A = PyTorchBenchmark(A_ ) A = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) @unittest.skipIf(torch_device == 'cpu' ,'Cant do half precision' ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> List[Any]: A = 'sshleifer/tiny-gpt2' A = PyTorchBenchmarkArguments( models=[MODEL_ID] ,training=A_ ,inference=A_ ,fpaa=A_ ,sequence_lengths=[8] ,batch_sizes=[1] ,multi_process=A_ ,) A = PyTorchBenchmark(A_ ) A = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Optional[Any]: A = 'sshleifer/tiny-gpt2' A = AutoConfig.from_pretrained(A_ ) # set architectures equal to `None` A = None A = PyTorchBenchmarkArguments( models=[MODEL_ID] ,training=A_ ,inference=A_ ,sequence_lengths=[8] ,batch_sizes=[1] ,multi_process=A_ ,) A = PyTorchBenchmark(A_ ,configs=[config] ) A = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def _SCREAMING_SNAKE_CASE ( self : Tuple ) -> Optional[int]: A = 'sshleifer/tiny-gpt2' A = PyTorchBenchmarkArguments( models=[MODEL_ID] ,training=A_ ,inference=A_ ,sequence_lengths=[8] ,batch_sizes=[1] ,multi_process=A_ ,) A = PyTorchBenchmark(A_ ) A = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) @unittest.skipIf(torch_device == 'cpu' ,'Can\'t do half precision' ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> List[Any]: A = 'sshleifer/tiny-gpt2' A = PyTorchBenchmarkArguments( models=[MODEL_ID] ,training=A_ ,inference=A_ ,sequence_lengths=[8] ,batch_sizes=[1] ,fpaa=A_ ,multi_process=A_ ,) A = PyTorchBenchmark(A_ ) A = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> Optional[int]: A = 'sshleifer/tiny-gpt2' A = AutoConfig.from_pretrained(A_ ) A = PyTorchBenchmarkArguments( models=[MODEL_ID] ,training=A_ ,inference=A_ ,sequence_lengths=[8] ,batch_sizes=[1] ,multi_process=A_ ,) A = PyTorchBenchmark(A_ ,configs=[config] ) A = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def _SCREAMING_SNAKE_CASE ( self : Any ) -> List[Any]: A = 'sshleifer/tinier_bart' A = AutoConfig.from_pretrained(A_ ) A = PyTorchBenchmarkArguments( models=[MODEL_ID] ,training=A_ ,inference=A_ ,sequence_lengths=[8] ,batch_sizes=[1] ,multi_process=A_ ,) A = PyTorchBenchmark(A_ ,configs=[config] ) A = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def _SCREAMING_SNAKE_CASE ( self : Any ) -> List[str]: A = 'sshleifer/tiny-gpt2' A = AutoConfig.from_pretrained(A_ ) A = PyTorchBenchmarkArguments( models=[MODEL_ID] ,training=A_ ,inference=A_ ,sequence_lengths=[8] ,batch_sizes=[1] ,multi_process=A_ ,) A = PyTorchBenchmark(A_ ,configs=[config] ) A = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def _SCREAMING_SNAKE_CASE ( self : Any ) -> List[str]: A = 'sshleifer/tinier_bart' A = AutoConfig.from_pretrained(A_ ) A = PyTorchBenchmarkArguments( models=[MODEL_ID] ,training=A_ ,inference=A_ ,sequence_lengths=[8] ,batch_sizes=[1] ,multi_process=A_ ,) A = PyTorchBenchmark(A_ ,configs=[config] ) A = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def _SCREAMING_SNAKE_CASE ( self : Dict ) -> Dict: A = 'sshleifer/tiny-gpt2' with tempfile.TemporaryDirectory() as tmp_dir: A = PyTorchBenchmarkArguments( models=[MODEL_ID] ,training=A_ ,inference=A_ ,save_to_csv=A_ ,sequence_lengths=[8] ,batch_sizes=[1] ,inference_time_csv_file=os.path.join(A_ ,'inf_time.csv' ) ,train_memory_csv_file=os.path.join(A_ ,'train_mem.csv' ) ,inference_memory_csv_file=os.path.join(A_ ,'inf_mem.csv' ) ,train_time_csv_file=os.path.join(A_ ,'train_time.csv' ) ,env_info_csv_file=os.path.join(A_ ,'env.csv' ) ,multi_process=A_ ,) A = PyTorchBenchmark(A_ ) benchmark.run() self.assertTrue(Path(os.path.join(A_ ,'inf_time.csv' ) ).exists() ) self.assertTrue(Path(os.path.join(A_ ,'train_time.csv' ) ).exists() ) self.assertTrue(Path(os.path.join(A_ ,'inf_mem.csv' ) ).exists() ) self.assertTrue(Path(os.path.join(A_ ,'train_mem.csv' ) ).exists() ) self.assertTrue(Path(os.path.join(A_ ,'env.csv' ) ).exists() ) def _SCREAMING_SNAKE_CASE ( self : Dict ) -> List[str]: A = 'sshleifer/tiny-gpt2' def _check_summary_is_not_empty(A_ : Optional[int] ): self.assertTrue(hasattr(A_ ,'sequential' ) ) self.assertTrue(hasattr(A_ ,'cumulative' ) ) self.assertTrue(hasattr(A_ ,'current' ) ) self.assertTrue(hasattr(A_ ,'total' ) ) with tempfile.TemporaryDirectory() as tmp_dir: A = PyTorchBenchmarkArguments( models=[MODEL_ID] ,training=A_ ,inference=A_ ,sequence_lengths=[8] ,batch_sizes=[1] ,log_filename=os.path.join(A_ ,'log.txt' ) ,log_print=A_ ,trace_memory_line_by_line=A_ ,multi_process=A_ ,) A = PyTorchBenchmark(A_ ) A = benchmark.run() _check_summary_is_not_empty(result.inference_summary ) _check_summary_is_not_empty(result.train_summary ) self.assertTrue(Path(os.path.join(A_ ,'log.txt' ) ).exists() )
74
1
"""simple docstring""" def _snake_case ( snake_case__ : str ): A = 0 for ch in input_str: A = ord(snake_case__ ) A = pow(2 , snake_case__ ) # If we already turned on bit for current character's unicode if bitmap >> ch_unicode & 1 == 1: return False bitmap |= ch_bit_index_on return True if __name__ == "__main__": import doctest doctest.testmod()
74
"""simple docstring""" # Lint as: python3 import dataclasses import re from dataclasses import dataclass from functools import total_ordering from typing import Optional, Union _lowercase = re.compile(r'''^(?P<major>\d+)''' r'''\.(?P<minor>\d+)''' r'''\.(?P<patch>\d+)$''') @total_ordering @dataclass class lowerCAmelCase_ : '''simple docstring''' _lowerCamelCase: str _lowerCamelCase: Optional[str] = None _lowerCamelCase: Optional[Union[str, int]] = None _lowerCamelCase: Optional[Union[str, int]] = None _lowerCamelCase: Optional[Union[str, int]] = None def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> List[str]: A , A , A = _str_to_version_tuple(self.version_str ) def __repr__( self : Optional[int] ) -> Dict: return F'{self.tuple[0]}.{self.tuple[1]}.{self.tuple[2]}' @property def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> int: return self.major, self.minor, self.patch def _SCREAMING_SNAKE_CASE ( self : Optional[int] ,A_ : Tuple ) -> Union[str, Any]: if isinstance(A_ ,A_ ): return Version(A_ ) elif isinstance(A_ ,A_ ): return other raise TypeError(F'{other} (type {type(A_ )}) cannot be compared to version.' ) def __eq__( self : List[Any] ,A_ : Dict ) -> Any: try: A = self._validate_operand(A_ ) except (TypeError, ValueError): return False else: return self.tuple == other.tuple def __lt__( self : List[Any] ,A_ : Optional[int] ) -> Tuple: A = self._validate_operand(A_ ) return self.tuple < other.tuple def __hash__( self : Union[str, Any] ) -> Union[str, Any]: return hash(_version_tuple_to_str(self.tuple ) ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : Any ,A_ : List[str] ) -> List[str]: A = {f.name for f in dataclasses.fields(cls )} return cls(**{k: v for k, v in dic.items() if k in field_names} ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> str: return self.version_str def _snake_case ( snake_case__ : List[str] ): A = _VERSION_REG.match(snake_case__ ) if not res: raise ValueError(F'Invalid version \'{version_str}\'. Format should be x.y.z with {{x,y,z}} being digits.' ) return tuple(int(snake_case__ ) for v in [res.group('major' ), res.group('minor' ), res.group('patch' )] ) def _snake_case ( snake_case__ : str ): return ".".join(str(snake_case__ ) for v in version_tuple )
74
1
"""simple docstring""" from datetime import datetime import requests from bsa import BeautifulSoup if __name__ == "__main__": _lowercase = input('''Enter image url: ''').strip() print(F"""Downloading image from {url} ...""") _lowercase = BeautifulSoup(requests.get(url).content, '''html.parser''') # The image URL is in the content field of the first meta tag with property og:image _lowercase = soup.find('''meta''', {'''property''': '''og:image'''})['''content'''] _lowercase = requests.get(image_url).content _lowercase = F"""{datetime.now():%Y-%m-%d_%H:%M:%S}.jpg""" with open(file_name, '''wb''') as fp: fp.write(image_data) print(F"""Done. Image saved to disk as {file_name}.""")
74
"""simple docstring""" import dataclasses import json import sys import types from argparse import ArgumentDefaultsHelpFormatter, ArgumentParser, ArgumentTypeError from copy import copy from enum import Enum from inspect import isclass from pathlib import Path from typing import Any, Callable, Dict, Iterable, List, Literal, NewType, Optional, Tuple, Union, get_type_hints import yaml _lowercase = NewType('''DataClass''', Any) _lowercase = NewType('''DataClassType''', Any) def _snake_case ( snake_case__ : Tuple ): if isinstance(snake_case__ , snake_case__ ): return v if v.lower() in ("yes", "true", "t", "y", "1"): return True elif v.lower() in ("no", "false", "f", "n", "0"): return False else: raise ArgumentTypeError( F'Truthy value expected: got {v} but expected one of yes/no, true/false, t/f, y/n, 1/0 (case insensitive).' ) def _snake_case ( snake_case__ : list ): A = {str(snake_case__ ): choice for choice in choices} return lambda snake_case__ : str_to_choice.get(snake_case__ , snake_case__ ) def _snake_case ( *, snake_case__ : Union[str, List[str]] = None , snake_case__ : str = None , snake_case__ : Any = dataclasses.MISSING , snake_case__ : Callable[[], Any] = dataclasses.MISSING , snake_case__ : dict = None , **snake_case__ : Any , ): if metadata is None: # Important, don't use as default param in function signature because dict is mutable and shared across function calls A = {} if aliases is not None: A = aliases if help is not None: A = help return dataclasses.field(metadata=snake_case__ , default=snake_case__ , default_factory=snake_case__ , **snake_case__ ) class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: Iterable[DataClassType] def __init__( self : List[str] ,A_ : Union[DataClassType, Iterable[DataClassType]] ,**A_ : Any ) -> Optional[int]: # To make the default appear when using --help if "formatter_class" not in kwargs: A = ArgumentDefaultsHelpFormatter super().__init__(**A_ ) if dataclasses.is_dataclass(A_ ): A = [dataclass_types] A = list(A_ ) for dtype in self.dataclass_types: self._add_dataclass_arguments(A_ ) @staticmethod def _SCREAMING_SNAKE_CASE ( A_ : ArgumentParser ,A_ : dataclasses.Field ) -> Optional[Any]: A = F'--{field.name}' A = field.metadata.copy() # field.metadata is not used at all by Data Classes, # it is provided as a third-party extension mechanism. if isinstance(field.type ,A_ ): raise RuntimeError( 'Unresolved type detected, which should have been done with the help of ' '`typing.get_type_hints` method by default' ) A = kwargs.pop('aliases' ,[] ) if isinstance(A_ ,A_ ): A = [aliases] A = getattr(field.type ,'__origin__' ,field.type ) if origin_type is Union or (hasattr(A_ ,'UnionType' ) and isinstance(A_ ,types.UnionType )): if str not in field.type.__args__ and ( len(field.type.__args__ ) != 2 or type(A_ ) not in field.type.__args__ ): raise ValueError( 'Only `Union[X, NoneType]` (i.e., `Optional[X]`) is allowed for `Union` because' ' the argument parser only supports one type per argument.' F' Problem encountered in field \'{field.name}\'.' ) if type(A_ ) not in field.type.__args__: # filter `str` in Union A = field.type.__args__[0] if field.type.__args__[1] == str else field.type.__args__[1] A = getattr(field.type ,'__origin__' ,field.type ) elif bool not in field.type.__args__: # filter `NoneType` in Union (except for `Union[bool, NoneType]`) A = ( field.type.__args__[0] if isinstance(A_ ,field.type.__args__[1] ) else field.type.__args__[1] ) A = getattr(field.type ,'__origin__' ,field.type ) # A variable to store kwargs for a boolean field, if needed # so that we can init a `no_*` complement argument (see below) A = {} if origin_type is Literal or (isinstance(field.type ,A_ ) and issubclass(field.type ,A_ )): if origin_type is Literal: A = field.type.__args__ else: A = [x.value for x in field.type] A = make_choice_type_function(kwargs['choices'] ) if field.default is not dataclasses.MISSING: A = field.default else: A = True elif field.type is bool or field.type == Optional[bool]: # Copy the currect kwargs to use to instantiate a `no_*` complement argument below. # We do not initialize it here because the `no_*` alternative must be instantiated after the real argument A = copy(A_ ) # Hack because type=bool in argparse does not behave as we want. A = string_to_bool if field.type is bool or (field.default is not None and field.default is not dataclasses.MISSING): # Default value is False if we have no default when of type bool. A = False if field.default is dataclasses.MISSING else field.default # This is the value that will get picked if we don't include --field_name in any way A = default # This tells argparse we accept 0 or 1 value after --field_name A = '?' # This is the value that will get picked if we do --field_name (without value) A = True elif isclass(A_ ) and issubclass(A_ ,A_ ): A = field.type.__args__[0] A = '+' if field.default_factory is not dataclasses.MISSING: A = field.default_factory() elif field.default is dataclasses.MISSING: A = True else: A = field.type if field.default is not dataclasses.MISSING: A = field.default elif field.default_factory is not dataclasses.MISSING: A = field.default_factory() else: A = True parser.add_argument(A_ ,*A_ ,**A_ ) # Add a complement `no_*` argument for a boolean field AFTER the initial field has already been added. # Order is important for arguments with the same destination! # We use a copy of earlier kwargs because the original kwargs have changed a lot before reaching down # here and we do not need those changes/additional keys. if field.default is True and (field.type is bool or field.type == Optional[bool]): A = False parser.add_argument(F'--no_{field.name}' ,action='store_false' ,dest=field.name ,**A_ ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ,A_ : DataClassType ) -> List[Any]: if hasattr(A_ ,'_argument_group_name' ): A = self.add_argument_group(dtype._argument_group_name ) else: A = self try: A = get_type_hints(A_ ) except NameError: raise RuntimeError( F'Type resolution failed for {dtype}. Try declaring the class in global scope or ' 'removing line of `from __future__ import annotations` which opts in Postponed ' 'Evaluation of Annotations (PEP 563)' ) except TypeError as ex: # Remove this block when we drop Python 3.9 support if sys.version_info[:2] < (3, 10) and "unsupported operand type(s) for |" in str(A_ ): A = '.'.join(map(A_ ,sys.version_info[:3] ) ) raise RuntimeError( F'Type resolution failed for {dtype} on Python {python_version}. Try removing ' 'line of `from __future__ import annotations` which opts in union types as ' '`X | Y` (PEP 604) via Postponed Evaluation of Annotations (PEP 563). To ' 'support Python versions that lower than 3.10, you need to use ' '`typing.Union[X, Y]` instead of `X | Y` and `typing.Optional[X]` instead of ' '`X | None`.' ) from ex raise for field in dataclasses.fields(A_ ): if not field.init: continue A = type_hints[field.name] self._parse_dataclass_field(A_ ,A_ ) def _SCREAMING_SNAKE_CASE ( self : Tuple ,A_ : Any=None ,A_ : int=False ,A_ : Any=True ,A_ : List[str]=None ,A_ : Union[str, Any]=None ,) -> Tuple[DataClass, ...]: if args_file_flag or args_filename or (look_for_args_file and len(sys.argv )): A = [] if args_filename: args_files.append(Path(A_ ) ) elif look_for_args_file and len(sys.argv ): args_files.append(Path(sys.argv[0] ).with_suffix('.args' ) ) # args files specified via command line flag should overwrite default args files so we add them last if args_file_flag: # Create special parser just to extract the args_file_flag values A = ArgumentParser() args_file_parser.add_argument(A_ ,type=A_ ,action='append' ) # Use only remaining args for further parsing (remove the args_file_flag) A , A = args_file_parser.parse_known_args(args=A_ ) A = vars(A_ ).get(args_file_flag.lstrip('-' ) ,A_ ) if cmd_args_file_paths: args_files.extend([Path(A_ ) for p in cmd_args_file_paths] ) A = [] for args_file in args_files: if args_file.exists(): file_args += args_file.read_text().split() # in case of duplicate arguments the last one has precedence # args specified via the command line should overwrite args from files, so we add them last A = file_args + args if args is not None else file_args + sys.argv[1:] A , A = self.parse_known_args(args=A_ ) A = [] for dtype in self.dataclass_types: A = {f.name for f in dataclasses.fields(A_ ) if f.init} A = {k: v for k, v in vars(A_ ).items() if k in keys} for k in keys: delattr(A_ ,A_ ) A = dtype(**A_ ) outputs.append(A_ ) if len(namespace.__dict__ ) > 0: # additional namespace. outputs.append(A_ ) if return_remaining_strings: return (*outputs, remaining_args) else: if remaining_args: raise ValueError(F'Some specified arguments are not used by the HfArgumentParser: {remaining_args}' ) return (*outputs,) def _SCREAMING_SNAKE_CASE ( self : List[Any] ,A_ : Dict[str, Any] ,A_ : bool = False ) -> Tuple[DataClass, ...]: A = set(args.keys() ) A = [] for dtype in self.dataclass_types: A = {f.name for f in dataclasses.fields(A_ ) if f.init} A = {k: v for k, v in args.items() if k in keys} unused_keys.difference_update(inputs.keys() ) A = dtype(**A_ ) outputs.append(A_ ) if not allow_extra_keys and unused_keys: raise ValueError(F'Some keys are not used by the HfArgumentParser: {sorted(A_ )}' ) return tuple(A_ ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : str ,A_ : bool = False ) -> Tuple[DataClass, ...]: with open(Path(A_ ) ,encoding='utf-8' ) as open_json_file: A = json.loads(open_json_file.read() ) A = self.parse_dict(A_ ,allow_extra_keys=A_ ) return tuple(A_ ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : str ,A_ : bool = False ) -> Tuple[DataClass, ...]: A = self.parse_dict(yaml.safe_load(Path(A_ ).read_text() ) ,allow_extra_keys=A_ ) return tuple(A_ )
74
1
"""simple docstring""" from typing import List import numpy as np def _snake_case ( snake_case__ : dict ): A = {key: len(snake_case__ ) for key, value in gen_kwargs.items() if isinstance(snake_case__ , snake_case__ )} if len(set(lists_lengths.values() ) ) > 1: raise RuntimeError( ( 'Sharding is ambiguous for this dataset: ' + 'we found several data sources lists of different lengths, and we don\'t know over which list we should parallelize:\n' + '\n'.join(F'\t- key {key} has length {length}' for key, length in lists_lengths.items() ) + '\nTo fix this, check the \'gen_kwargs\' and make sure to use lists only for data sources, ' + 'and use tuples otherwise. In the end there should only be one single list, or several lists with the same length.' ) ) A = max(lists_lengths.values() , default=0 ) return max(1 , snake_case__ ) def _snake_case ( snake_case__ : int , snake_case__ : int ): A = [] for group_idx in range(snake_case__ ): A = num_shards // max_num_jobs + (group_idx < (num_shards % max_num_jobs)) if num_shards_to_add == 0: break A = shards_indices_per_group[-1].stop if shards_indices_per_group else 0 A = range(snake_case__ , start + num_shards_to_add ) shards_indices_per_group.append(snake_case__ ) return shards_indices_per_group def _snake_case ( snake_case__ : dict , snake_case__ : int ): A = _number_of_shards_in_gen_kwargs(snake_case__ ) if num_shards == 1: return [dict(snake_case__ )] else: A = _distribute_shards(num_shards=snake_case__ , max_num_jobs=snake_case__ ) return [ { key: [value[shard_idx] for shard_idx in shard_indices_per_group[group_idx]] if isinstance(snake_case__ , snake_case__ ) else value for key, value in gen_kwargs.items() } for group_idx in range(len(snake_case__ ) ) ] def _snake_case ( snake_case__ : List[dict] ): return { key: [value for gen_kwargs in gen_kwargs_list for value in gen_kwargs[key]] if isinstance(gen_kwargs_list[0][key] , snake_case__ ) else gen_kwargs_list[0][key] for key in gen_kwargs_list[0] } def _snake_case ( snake_case__ : np.random.Generator , snake_case__ : dict ): A = {len(snake_case__ ) for value in gen_kwargs.values() if isinstance(snake_case__ , snake_case__ )} A = {} for size in list_sizes: A = list(range(snake_case__ ) ) rng.shuffle(indices_per_size[size] ) # Now let's copy the gen_kwargs and shuffle the lists based on their sizes A = dict(snake_case__ ) for key, value in shuffled_kwargs.items(): if isinstance(snake_case__ , snake_case__ ): A = [value[i] for i in indices_per_size[len(snake_case__ )]] return shuffled_kwargs
74
"""simple docstring""" import argparse import json import os 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 from accelerate.utils.deepspeed import DummyOptim, DummyScheduler _lowercase = 16 _lowercase = 32 def _snake_case ( snake_case__ : Accelerator , snake_case__ : int = 16 , snake_case__ : str = "bert-base-cased" ): A = AutoTokenizer.from_pretrained(snake_case__ ) A = load_dataset('glue' , 'mrpc' ) def tokenize_function(snake_case__ : Dict ): # max_length=None => use the model max length (it's actually the default) A = tokenizer(examples['sentence1'] , examples['sentence2'] , truncation=snake_case__ , max_length=snake_case__ ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset A = datasets.map( snake_case__ , batched=snake_case__ , remove_columns=['idx', 'sentence1', 'sentence2'] , load_from_cache_file=snake_case__ ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library A = tokenized_datasets.rename_column('label' , 'labels' ) def collate_fn(snake_case__ : int ): # On TPU it's best to pad everything to the same length or training will be very slow. if accelerator.distributed_type == DistributedType.TPU: return tokenizer.pad(snake_case__ , padding='max_length' , max_length=128 , return_tensors='pt' ) return tokenizer.pad(snake_case__ , padding='longest' , return_tensors='pt' ) # Instantiate dataloaders. A = DataLoader( tokenized_datasets['train'] , shuffle=snake_case__ , collate_fn=snake_case__ , batch_size=snake_case__ ) A = DataLoader( tokenized_datasets['validation'] , shuffle=snake_case__ , collate_fn=snake_case__ , batch_size=snake_case__ ) return train_dataloader, eval_dataloader def _snake_case ( snake_case__ : Optional[int] , snake_case__ : Optional[int] ): # Initialize accelerator A = Accelerator() # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs A = config['lr'] A = int(config['num_epochs'] ) A = int(config['seed'] ) A = int(config['batch_size'] ) A = args.model_name_or_path set_seed(snake_case__ ) A , A = get_dataloaders(snake_case__ , snake_case__ , snake_case__ ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) A = AutoModelForSequenceClassification.from_pretrained(snake_case__ , return_dict=snake_case__ ) # Instantiate optimizer A = ( AdamW if accelerator.state.deepspeed_plugin is None or 'optimizer' not in accelerator.state.deepspeed_plugin.deepspeed_config else DummyOptim ) A = optimizer_cls(params=model.parameters() , lr=snake_case__ ) if accelerator.state.deepspeed_plugin is not None: A = accelerator.state.deepspeed_plugin.deepspeed_config[ 'gradient_accumulation_steps' ] else: A = 1 A = (len(snake_case__ ) * num_epochs) // gradient_accumulation_steps # Instantiate scheduler if ( accelerator.state.deepspeed_plugin is None or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config ): A = get_linear_schedule_with_warmup( optimizer=snake_case__ , num_warmup_steps=0 , num_training_steps=snake_case__ , ) else: A = DummyScheduler(snake_case__ , total_num_steps=snake_case__ , warmup_num_steps=0 ) # 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. A , A , A , A , A = accelerator.prepare( snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ ) # We need to keep track of how many total steps we have iterated over A = 0 # We also need to keep track of the stating epoch so files are named properly A = 0 # Now we train the model A = evaluate.load('glue' , 'mrpc' ) A = 0 A = {} for epoch in range(snake_case__ , snake_case__ ): model.train() for step, batch in enumerate(snake_case__ ): A = model(**snake_case__ ) A = outputs.loss A = loss / gradient_accumulation_steps accelerator.backward(snake_case__ ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() overall_step += 1 model.eval() A = 0 for step, batch in enumerate(snake_case__ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): A = model(**snake_case__ ) A = outputs.logits.argmax(dim=-1 ) # It is slightly faster to call this once, than multiple times A , A = accelerator.gather( (predictions, batch['labels']) ) # If we are in a multiprocess environment, the last batch has duplicates if accelerator.use_distributed: if step == len(snake_case__ ) - 1: A = predictions[: len(eval_dataloader.dataset ) - samples_seen] A = references[: len(eval_dataloader.dataset ) - samples_seen] else: samples_seen += references.shape[0] metric.add_batch( predictions=snake_case__ , references=snake_case__ , ) A = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F'epoch {epoch}:' , snake_case__ ) A = eval_metric['accuracy'] if best_performance < eval_metric["accuracy"]: A = eval_metric['accuracy'] if args.performance_lower_bound is not None: assert ( args.performance_lower_bound <= best_performance ), F'Best performance metric {best_performance} is lower than the lower bound {args.performance_lower_bound}' accelerator.wait_for_everyone() if accelerator.is_main_process: with open(os.path.join(args.output_dir , 'all_results.json' ) , 'w' ) as f: json.dump(snake_case__ , snake_case__ ) def _snake_case ( ): A = argparse.ArgumentParser(description='Simple example of training script tracking peak GPU memory usage.' ) parser.add_argument( '--model_name_or_path' , type=snake_case__ , default='bert-base-cased' , help='Path to pretrained model or model identifier from huggingface.co/models.' , required=snake_case__ , ) parser.add_argument( '--output_dir' , type=snake_case__ , default='.' , help='Optional save directory where all checkpoint folders will be stored. Default is the current working directory.' , ) parser.add_argument( '--performance_lower_bound' , type=snake_case__ , default=snake_case__ , help='Optional lower bound for the performance metric. If set, the training will throw error when the performance metric drops below this value.' , ) parser.add_argument( '--num_epochs' , type=snake_case__ , default=3 , help='Number of train epochs.' , ) A = parser.parse_args() A = {'lr': 2e-5, 'num_epochs': args.num_epochs, 'seed': 42, 'batch_size': 16} training_function(snake_case__ , snake_case__ ) if __name__ == "__main__": main()
74
1
"""simple docstring""" from .glue import GlueDataset, GlueDataTrainingArguments from .language_modeling import ( LineByLineTextDataset, LineByLineWithRefDataset, LineByLineWithSOPTextDataset, TextDataset, TextDatasetForNextSentencePrediction, ) from .squad import SquadDataset, SquadDataTrainingArguments
74
"""simple docstring""" 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 lowerCAmelCase_ : '''simple docstring''' def __init__( self : Optional[Any] ,A_ : str ,A_ : Dict=13 ,A_ : str=7 ,A_ : str=True ,A_ : Any=True ,A_ : Optional[Any]=True ,A_ : Any=True ,A_ : Optional[Any]=True ,A_ : Any=False ,A_ : str=False ,A_ : Tuple=False ,A_ : str=2 ,A_ : Optional[int]=99 ,A_ : Union[str, Any]=0 ,A_ : Optional[Any]=32 ,A_ : Optional[int]=5 ,A_ : Optional[int]=4 ,A_ : Union[str, Any]=0.1 ,A_ : List[str]=0.1 ,A_ : Union[str, Any]=512 ,A_ : Union[str, Any]=2 ,A_ : Any=0.02 ,A_ : List[str]=2 ,A_ : int=4 ,A_ : int="last" ,A_ : Dict=True ,A_ : Union[str, Any]=None ,A_ : Any=0 ,) -> List[Any]: A = parent A = batch_size A = seq_length A = is_training A = use_input_lengths A = use_token_type_ids A = use_labels A = gelu_activation A = sinusoidal_embeddings A = causal A = asm A = n_langs A = vocab_size A = n_special A = hidden_size A = num_hidden_layers A = num_attention_heads A = hidden_dropout_prob A = attention_probs_dropout_prob A = max_position_embeddings A = type_sequence_label_size A = initializer_range A = num_labels A = num_choices A = summary_type A = use_proj A = scope A = bos_token_id def _SCREAMING_SNAKE_CASE ( self : Dict ) -> Union[str, Any]: A = ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size ) A = random_attention_mask([self.batch_size, self.seq_length] ) A = None if self.use_input_lengths: A = ( ids_tensor([self.batch_size] ,vocab_size=2 ) + self.seq_length - 2 ) # small variation of seq_length A = None if self.use_token_type_ids: A = ids_tensor([self.batch_size, self.seq_length] ,self.n_langs ) A = None A = None A = None if self.use_labels: A = ids_tensor([self.batch_size] ,self.type_sequence_label_size ) A = ids_tensor([self.batch_size, self.seq_length] ,self.num_labels ) A = ids_tensor([self.batch_size] ,2 ).float() A = ids_tensor([self.batch_size] ,self.num_choices ) A = 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 : Optional[int] ) -> Dict: 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 : List[Any] ,A_ : Any ,A_ : int ,A_ : Dict ,A_ : str ,A_ : Optional[Any] ,A_ : List[str] ,A_ : Union[str, Any] ,A_ : int ,A_ : str ,) -> Any: A = XLMModel(config=A_ ) model.to(A_ ) model.eval() A = model(A_ ,lengths=A_ ,langs=A_ ) A = model(A_ ,langs=A_ ) A = model(A_ ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) def _SCREAMING_SNAKE_CASE ( self : List[str] ,A_ : Any ,A_ : str ,A_ : Optional[int] ,A_ : Union[str, Any] ,A_ : Optional[int] ,A_ : str ,A_ : Any ,A_ : str ,A_ : Dict ,) -> Dict: A = XLMWithLMHeadModel(A_ ) model.to(A_ ) model.eval() A = 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 : Union[str, Any] ,A_ : List[str] ,A_ : Union[str, Any] ,A_ : Union[str, Any] ,A_ : List[str] ,A_ : Any ,A_ : Optional[int] ,A_ : Optional[int] ,A_ : Optional[int] ,A_ : Optional[Any] ,) -> int: A = XLMForQuestionAnsweringSimple(A_ ) model.to(A_ ) model.eval() A = model(A_ ) A = model(A_ ,start_positions=A_ ,end_positions=A_ ) A = 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 : Any ,A_ : Tuple ,A_ : Optional[int] ,A_ : Any ,A_ : List[Any] ,A_ : int ,A_ : Tuple ,A_ : Tuple ,A_ : List[str] ,A_ : Optional[int] ,) -> List[Any]: A = XLMForQuestionAnswering(A_ ) model.to(A_ ) model.eval() A = model(A_ ) A = model( A_ ,start_positions=A_ ,end_positions=A_ ,cls_index=A_ ,is_impossible=A_ ,p_mask=A_ ,) A = model( A_ ,start_positions=A_ ,end_positions=A_ ,cls_index=A_ ,is_impossible=A_ ,) ((A) , ) = result_with_labels.to_tuple() A = model(A_ ,start_positions=A_ ,end_positions=A_ ) ((A) , ) = 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 : List[Any] ,A_ : Tuple ,A_ : int ,A_ : Optional[int] ,A_ : List[str] ,A_ : str ,A_ : Optional[Any] ,A_ : Optional[int] ,A_ : Optional[Any] ,A_ : List[Any] ,) -> Optional[int]: A = XLMForSequenceClassification(A_ ) model.to(A_ ) model.eval() A = model(A_ ) A = 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 : int ,A_ : List[Any] ,A_ : str ,A_ : Optional[Any] ,A_ : List[Any] ,A_ : Optional[int] ,A_ : Tuple ,A_ : Union[str, Any] ,A_ : Optional[int] ,A_ : Optional[int] ,) -> List[str]: A = self.num_labels A = XLMForTokenClassification(A_ ) model.to(A_ ) model.eval() A = 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 : Dict ,A_ : Optional[int] ,A_ : Union[str, Any] ,A_ : List[str] ,A_ : Optional[int] ,A_ : List[str] ,A_ : Optional[Any] ,A_ : Union[str, Any] ,A_ : Dict ,A_ : List[Any] ,) -> List[str]: A = self.num_choices A = XLMForMultipleChoice(config=A_ ) model.to(A_ ) model.eval() A = input_ids.unsqueeze(1 ).expand(-1 ,self.num_choices ,-1 ).contiguous() A = token_type_ids.unsqueeze(1 ).expand(-1 ,self.num_choices ,-1 ).contiguous() A = input_mask.unsqueeze(1 ).expand(-1 ,self.num_choices ,-1 ).contiguous() A = 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 : Dict ) -> int: A = self.prepare_config_and_inputs() ( ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ) = config_and_inputs A = {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'lengths': input_lengths} return config, inputs_dict @require_torch class lowerCAmelCase_ ( _lowercase , _lowercase , _lowercase , unittest.TestCase ): '''simple docstring''' _lowerCamelCase: Union[str, Any] = ( ( XLMModel, XLMWithLMHeadModel, XLMForQuestionAnswering, XLMForSequenceClassification, XLMForQuestionAnsweringSimple, XLMForTokenClassification, XLMForMultipleChoice, ) if is_torch_available() else () ) _lowerCamelCase: str = ( (XLMWithLMHeadModel,) if is_torch_available() else () ) # TODO (PVP): Check other models whether language generation is also applicable _lowerCamelCase: Optional[int] = ( { '''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 : Any ,A_ : Optional[int] ,A_ : Union[str, Any] ,A_ : Union[str, Any] ,A_ : Any ,A_ : Any ) -> Any: 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 : int ,A_ : str ,A_ : Optional[int] ,A_ : List[Any]=False ) -> int: A = super()._prepare_for_class(A_ ,A_ ,return_labels=A_ ) if return_labels: if model_class.__name__ == "XLMForQuestionAnswering": A = torch.zeros( self.model_tester.batch_size ,dtype=torch.long ,device=A_ ) A = torch.zeros( self.model_tester.batch_size ,dtype=torch.long ,device=A_ ) return inputs_dict def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Optional[Any]: A = XLMModelTester(self ) A = ConfigTester(self ,config_class=A_ ,emb_dim=37 ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> str: self.config_tester.run_common_tests() def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Any: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_model(*A_ ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> List[Any]: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_lm_head(*A_ ) def _SCREAMING_SNAKE_CASE ( self : Any ) -> Tuple: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_simple_qa(*A_ ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> List[Any]: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_qa(*A_ ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Any: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_sequence_classif(*A_ ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Optional[Any]: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_token_classif(*A_ ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Any: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_for_multiple_choice(*A_ ) def _SCREAMING_SNAKE_CASE ( self : Tuple ,A_ : Union[str, Any] ,A_ : Any ,A_ : str ,A_ : Tuple ,A_ : Any ,A_ : Any=False ,A_ : Any=1 ) -> List[Any]: 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 A = min_length + idx + 1 A = min_length + idx + 1 A = ( 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 : Dict ,A_ : Optional[int] ,A_ : str ,A_ : Optional[int] ,A_ : int ,A_ : Any ,A_ : str=False ,A_ : Any=1 ) -> Tuple: 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 A = min_length + idx + 1 A = (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 : List[Any] ) -> Optional[Any]: for model_name in XLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: A = XLMModel.from_pretrained(A_ ) self.assertIsNotNone(A_ ) @require_torch class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' @slow def _SCREAMING_SNAKE_CASE ( self : Dict ) -> str: A = XLMWithLMHeadModel.from_pretrained('xlm-mlm-en-2048' ) model.to(A_ ) A = torch.tensor([[14, 447]] ,dtype=torch.long ,device=A_ ) # the president A = [ 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 A = model.generate(A_ ,do_sample=A_ ) self.assertListEqual(output_ids[0].cpu().numpy().tolist() ,A_ )
74
1
"""simple docstring""" import math def _snake_case ( snake_case__ : list , snake_case__ : int = 0 , snake_case__ : int = 0 ): A = end or len(snake_case__ ) for i in range(snake_case__ , snake_case__ ): A = i A = array[i] while temp_index != start and temp_index_value < array[temp_index - 1]: A = array[temp_index - 1] temp_index -= 1 A = temp_index_value return array def _snake_case ( snake_case__ : list , snake_case__ : int , snake_case__ : int ): # Max Heap A = index A = 2 * index + 1 # Left Node A = 2 * index + 2 # Right Node if left_index < heap_size and array[largest] < array[left_index]: A = left_index if right_index < heap_size and array[largest] < array[right_index]: A = right_index if largest != index: A , A = array[largest], array[index] heapify(snake_case__ , snake_case__ , snake_case__ ) def _snake_case ( snake_case__ : list ): A = len(snake_case__ ) for i in range(n // 2 , -1 , -1 ): heapify(snake_case__ , snake_case__ , snake_case__ ) for i in range(n - 1 , 0 , -1 ): A , A = array[0], array[i] heapify(snake_case__ , 0 , snake_case__ ) return array def _snake_case ( snake_case__ : list , snake_case__ : int , snake_case__ : int , snake_case__ : int ): if (array[first_index] > array[middle_index]) != ( array[first_index] > array[last_index] ): return array[first_index] elif (array[middle_index] > array[first_index]) != ( array[middle_index] > array[last_index] ): return array[middle_index] else: return array[last_index] def _snake_case ( snake_case__ : list , snake_case__ : int , snake_case__ : int , snake_case__ : int ): A = low A = high while True: while array[i] < pivot: i += 1 j -= 1 while pivot < array[j]: j -= 1 if i >= j: return i A , A = array[j], array[i] i += 1 def _snake_case ( snake_case__ : list ): if len(snake_case__ ) == 0: return array A = 2 * math.ceil(math.loga(len(snake_case__ ) ) ) A = 16 return intro_sort(snake_case__ , 0 , len(snake_case__ ) , snake_case__ , snake_case__ ) def _snake_case ( snake_case__ : list , snake_case__ : int , snake_case__ : int , snake_case__ : int , snake_case__ : int ): while end - start > size_threshold: if max_depth == 0: return heap_sort(snake_case__ ) max_depth -= 1 A = median_of_a(snake_case__ , snake_case__ , start + ((end - start) // 2) + 1 , end - 1 ) A = partition(snake_case__ , snake_case__ , snake_case__ , snake_case__ ) intro_sort(snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ ) A = p return insertion_sort(snake_case__ , snake_case__ , snake_case__ ) if __name__ == "__main__": import doctest doctest.testmod() _lowercase = input('''Enter numbers separated by a comma : ''').strip() _lowercase = [float(item) for item in user_input.split(''',''')] print(sort(unsorted))
74
"""simple docstring""" from dataclasses import dataclass, field from typing import Tuple from ..utils import cached_property, is_tf_available, logging, requires_backends from .benchmark_args_utils import BenchmarkArguments if is_tf_available(): import tensorflow as tf _lowercase = logging.get_logger(__name__) @dataclass class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: Optional[int] = [ '''no_inference''', '''no_cuda''', '''no_tpu''', '''no_speed''', '''no_memory''', '''no_env_print''', '''no_multi_process''', ] def __init__( self : int ,**A_ : Any ) -> Any: for deprecated_arg in self.deprecated_args: if deprecated_arg in kwargs: A = deprecated_arg[3:] A = not kwargs.pop(A_ ) logger.warning( F'{deprecated_arg} is depreciated. Please use --no-{positive_arg} or' F' {positive_arg}={kwargs[positive_arg]}' ) A = kwargs.pop('tpu_name' ,self.tpu_name ) A = kwargs.pop('device_idx' ,self.device_idx ) A = kwargs.pop('eager_mode' ,self.eager_mode ) A = kwargs.pop('use_xla' ,self.use_xla ) super().__init__(**A_ ) _lowerCamelCase: str = field( default=_lowercase , metadata={'''help''': '''Name of TPU'''} , ) _lowerCamelCase: int = field( default=0 , metadata={'''help''': '''CPU / GPU device index. Defaults to 0.'''} , ) _lowerCamelCase: bool = field(default=_lowercase , metadata={'''help''': '''Benchmark models in eager model.'''} ) _lowerCamelCase: bool = field( default=_lowercase , metadata={ '''help''': '''Benchmark models using XLA JIT compilation. Note that `eager_model` has to be set to `False`.''' } , ) @cached_property def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Tuple["tf.distribute.cluster_resolver.TPUClusterResolver"]: requires_backends(self ,['tf'] ) A = None if self.tpu: try: if self.tpu_name: A = tf.distribute.cluster_resolver.TPUClusterResolver(self.tpu_name ) else: A = tf.distribute.cluster_resolver.TPUClusterResolver() except ValueError: A = None return tpu @cached_property def _SCREAMING_SNAKE_CASE ( self : Tuple ) -> Tuple["tf.distribute.Strategy", "tf.distribute.cluster_resolver.TPUClusterResolver"]: requires_backends(self ,['tf'] ) if self.is_tpu: tf.config.experimental_connect_to_cluster(self._setup_tpu ) tf.tpu.experimental.initialize_tpu_system(self._setup_tpu ) A = tf.distribute.TPUStrategy(self._setup_tpu ) else: # currently no multi gpu is allowed if self.is_gpu: # TODO: Currently only single GPU is supported tf.config.set_visible_devices(self.gpu_list[self.device_idx] ,'GPU' ) A = tf.distribute.OneDeviceStrategy(device=F'/gpu:{self.device_idx}' ) else: tf.config.set_visible_devices([] ,'GPU' ) # disable GPU A = tf.distribute.OneDeviceStrategy(device=F'/cpu:{self.device_idx}' ) return strategy @property def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> bool: requires_backends(self ,['tf'] ) return self._setup_tpu is not None @property def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> "tf.distribute.Strategy": requires_backends(self ,['tf'] ) return self._setup_strategy @property def _SCREAMING_SNAKE_CASE ( self : int ) -> str: requires_backends(self ,['tf'] ) return tf.config.list_physical_devices('GPU' ) @property def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> int: requires_backends(self ,['tf'] ) if self.cuda: return len(self.gpu_list ) return 0 @property def _SCREAMING_SNAKE_CASE ( self : str ) -> bool: return self.n_gpu > 0
74
1
"""simple docstring""" import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_video_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import VivitImageProcessor class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' def __init__( self : str ,A_ : Optional[int] ,A_ : Optional[int]=7 ,A_ : List[Any]=3 ,A_ : Optional[int]=10 ,A_ : Optional[Any]=18 ,A_ : Any=30 ,A_ : Union[str, Any]=400 ,A_ : Dict=True ,A_ : Union[str, Any]=None ,A_ : Any=True ,A_ : Optional[int]=[0.5, 0.5, 0.5] ,A_ : Union[str, Any]=[0.5, 0.5, 0.5] ,A_ : Union[str, Any]=None ,) -> Any: A = size if size is not None else {'shortest_edge': 18} A = crop_size if crop_size is not None else {'height': 18, 'width': 18} A = parent A = batch_size A = num_channels A = num_frames A = image_size A = min_resolution A = max_resolution A = do_resize A = size A = do_normalize A = image_mean A = image_std A = crop_size def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> Union[str, Any]: return { "image_mean": self.image_mean, "image_std": self.image_std, "do_normalize": self.do_normalize, "do_resize": self.do_resize, "size": self.size, "crop_size": self.crop_size, } @require_torch @require_vision class lowerCAmelCase_ ( _lowercase , unittest.TestCase ): '''simple docstring''' _lowerCamelCase: str = VivitImageProcessor if is_vision_available() else None def _SCREAMING_SNAKE_CASE ( self : int ) -> str: A = VivitImageProcessingTester(self ) @property def _SCREAMING_SNAKE_CASE ( self : Tuple ) -> Optional[Any]: return self.image_processor_tester.prepare_image_processor_dict() def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> int: A = 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_center_crop' ) ) self.assertTrue(hasattr(A_ ,'size' ) ) def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> List[Any]: A = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size ,{'shortest_edge': 18} ) self.assertEqual(image_processor.crop_size ,{'height': 18, 'width': 18} ) A = self.image_processing_class.from_dict(self.image_processor_dict ,size=42 ,crop_size=84 ) self.assertEqual(image_processor.size ,{'shortest_edge': 42} ) self.assertEqual(image_processor.crop_size ,{'height': 84, 'width': 84} ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Tuple: # Initialize image_processing A = self.image_processing_class(**self.image_processor_dict ) # create random PIL videos A = prepare_video_inputs(self.image_processor_tester ,equal_resolution=A_ ) for video in video_inputs: self.assertIsInstance(A_ ,A_ ) self.assertIsInstance(video[0] ,Image.Image ) # Test not batched input A = image_processing(video_inputs[0] ,return_tensors='pt' ).pixel_values self.assertEqual( encoded_videos.shape ,( 1, self.image_processor_tester.num_frames, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) ,) # Test batched A = image_processing(A_ ,return_tensors='pt' ).pixel_values self.assertEqual( encoded_videos.shape ,( self.image_processor_tester.batch_size, self.image_processor_tester.num_frames, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) ,) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Optional[int]: # Initialize image_processing A = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors A = prepare_video_inputs(self.image_processor_tester ,equal_resolution=A_ ,numpify=A_ ) for video in video_inputs: self.assertIsInstance(A_ ,A_ ) self.assertIsInstance(video[0] ,np.ndarray ) # Test not batched input A = image_processing(video_inputs[0] ,return_tensors='pt' ).pixel_values self.assertEqual( encoded_videos.shape ,( 1, self.image_processor_tester.num_frames, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) ,) # Test batched A = image_processing(A_ ,return_tensors='pt' ).pixel_values self.assertEqual( encoded_videos.shape ,( self.image_processor_tester.batch_size, self.image_processor_tester.num_frames, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) ,) def _SCREAMING_SNAKE_CASE ( self : int ) -> Optional[int]: # Initialize image_processing A = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors A = prepare_video_inputs(self.image_processor_tester ,equal_resolution=A_ ,torchify=A_ ) for video in video_inputs: self.assertIsInstance(A_ ,A_ ) self.assertIsInstance(video[0] ,torch.Tensor ) # Test not batched input A = image_processing(video_inputs[0] ,return_tensors='pt' ).pixel_values self.assertEqual( encoded_videos.shape ,( 1, self.image_processor_tester.num_frames, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) ,) # Test batched A = image_processing(A_ ,return_tensors='pt' ).pixel_values self.assertEqual( encoded_videos.shape ,( self.image_processor_tester.batch_size, self.image_processor_tester.num_frames, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) ,)
74
"""simple docstring""" import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..bit import BitConfig _lowercase = logging.get_logger(__name__) _lowercase = { '''Intel/dpt-large''': '''https://huggingface.co/Intel/dpt-large/resolve/main/config.json''', # See all DPT models at https://huggingface.co/models?filter=dpt } class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: Tuple = '''dpt''' def __init__( self : str ,A_ : Tuple=768 ,A_ : int=12 ,A_ : Optional[int]=12 ,A_ : Optional[int]=3072 ,A_ : List[str]="gelu" ,A_ : str=0.0 ,A_ : int=0.0 ,A_ : str=0.02 ,A_ : str=1e-12 ,A_ : str=384 ,A_ : Dict=16 ,A_ : Union[str, Any]=3 ,A_ : Dict=False ,A_ : Any=True ,A_ : Optional[int]=[2, 5, 8, 11] ,A_ : Optional[Any]="project" ,A_ : Tuple=[4, 2, 1, 0.5] ,A_ : int=[96, 192, 384, 768] ,A_ : int=256 ,A_ : str=-1 ,A_ : Optional[int]=False ,A_ : Optional[int]=True ,A_ : Union[str, Any]=0.4 ,A_ : Union[str, Any]=255 ,A_ : Union[str, Any]=0.1 ,A_ : List[str]=[1, 1024, 24, 24] ,A_ : List[str]=[0, 1] ,A_ : List[Any]=None ,**A_ : Tuple ,) -> Union[str, Any]: super().__init__(**A_ ) A = hidden_size A = is_hybrid if self.is_hybrid: if backbone_config is None: logger.info('Initializing the config with a `BiT` backbone.' ) A = { 'global_padding': 'same', 'layer_type': 'bottleneck', 'depths': [3, 4, 9], 'out_features': ['stage1', 'stage2', 'stage3'], 'embedding_dynamic_padding': True, } A = BitConfig(**A_ ) elif isinstance(A_ ,A_ ): logger.info('Initializing the config with a `BiT` backbone.' ) A = BitConfig(**A_ ) elif isinstance(A_ ,A_ ): A = backbone_config else: raise ValueError( F'backbone_config must be a dictionary or a `PretrainedConfig`, got {backbone_config.__class__}.' ) A = backbone_featmap_shape A = neck_ignore_stages if readout_type != "project": raise ValueError('Readout type must be \'project\' when using `DPT-hybrid` mode.' ) else: A = None A = None A = [] A = num_hidden_layers A = num_attention_heads A = intermediate_size A = hidden_act A = hidden_dropout_prob A = attention_probs_dropout_prob A = initializer_range A = layer_norm_eps A = image_size A = patch_size A = num_channels A = qkv_bias A = backbone_out_indices if readout_type not in ["ignore", "add", "project"]: raise ValueError('Readout_type must be one of [\'ignore\', \'add\', \'project\']' ) A = readout_type A = reassemble_factors A = neck_hidden_sizes A = fusion_hidden_size A = head_in_index A = use_batch_norm_in_fusion_residual # auxiliary head attributes (semantic segmentation) A = use_auxiliary_head A = auxiliary_loss_weight A = semantic_loss_ignore_index A = semantic_classifier_dropout def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> str: A = copy.deepcopy(self.__dict__ ) if output["backbone_config"] is not None: A = self.backbone_config.to_dict() A = self.__class__.model_type return output
74
1
"""simple docstring""" from __future__ import annotations _lowercase = 1.6021e-19 # units = C def _snake_case ( snake_case__ : float , snake_case__ : float , snake_case__ : float , ): if (conductivity, electron_conc, mobility).count(0 ) != 1: raise ValueError('You cannot supply more or less than 2 values' ) elif conductivity < 0: raise ValueError('Conductivity cannot be negative' ) elif electron_conc < 0: raise ValueError('Electron concentration cannot be negative' ) elif mobility < 0: raise ValueError('mobility cannot be negative' ) elif conductivity == 0: return ( "conductivity", mobility * electron_conc * ELECTRON_CHARGE, ) elif electron_conc == 0: return ( "electron_conc", conductivity / (mobility * ELECTRON_CHARGE), ) else: return ( "mobility", conductivity / (electron_conc * ELECTRON_CHARGE), ) if __name__ == "__main__": import doctest doctest.testmod()
74
"""simple docstring""" from __future__ import annotations import math _lowercase = '''2020.9.26''' _lowercase = '''xcodz-dot, cclaus, dhruvmanila''' def _snake_case ( snake_case__ : float , snake_case__ : float , snake_case__ : float , snake_case__ : float , snake_case__ : float ): if not all(isinstance(snake_case__ , (float, int) ) for val in locals().values() ): A = F'Input values must either be float or int: {list(locals().values() )}' raise TypeError(snake_case__ ) A = ((x * distance) / (z + distance)) * scale A = ((y * distance) / (z + distance)) * scale return projected_x, projected_y def _snake_case ( snake_case__ : float , snake_case__ : float , snake_case__ : float , snake_case__ : str , snake_case__ : float ): if not isinstance(snake_case__ , snake_case__ ): raise TypeError('Axis must be a str' ) A = locals() del input_variables["axis"] if not all(isinstance(snake_case__ , (float, int) ) for val in input_variables.values() ): A = ( 'Input values except axis must either be float or int: ' F'{list(input_variables.values() )}' ) raise TypeError(snake_case__ ) A = (angle % 360) / 450 * 180 / math.pi if axis == "z": A = x * math.cos(snake_case__ ) - y * math.sin(snake_case__ ) A = y * math.cos(snake_case__ ) + x * math.sin(snake_case__ ) A = z elif axis == "x": A = y * math.cos(snake_case__ ) - z * math.sin(snake_case__ ) A = z * math.cos(snake_case__ ) + y * math.sin(snake_case__ ) A = x elif axis == "y": A = x * math.cos(snake_case__ ) - z * math.sin(snake_case__ ) A = z * math.cos(snake_case__ ) + x * math.sin(snake_case__ ) A = y else: raise ValueError('not a valid axis, choose one of \'x\', \'y\', \'z\'' ) return new_x, new_y, new_z if __name__ == "__main__": import doctest doctest.testmod() print(F"""{convert_to_ad(1.0, 2.0, 3.0, 10.0, 10.0) = }""") print(F"""{rotate(1.0, 2.0, 3.0, 'y', 90.0) = }""")
74
1
"""simple docstring""" import math import random from typing import Any from .hill_climbing import SearchProblem def _snake_case ( snake_case__ : Dict , snake_case__ : bool = True , snake_case__ : float = math.inf , snake_case__ : float = -math.inf , snake_case__ : float = math.inf , snake_case__ : float = -math.inf , snake_case__ : bool = False , snake_case__ : float = 100 , snake_case__ : float = 0.01 , snake_case__ : float = 1 , ): A = False A = search_prob A = start_temperate A = [] A = 0 A = None while not search_end: A = current_state.score() if best_state is None or current_score > best_state.score(): A = current_state scores.append(snake_case__ ) iterations += 1 A = None A = current_state.get_neighbors() while ( next_state is None and neighbors ): # till we do not find a neighbor that we can move to A = random.randint(0 , len(snake_case__ ) - 1 ) # picking a random neighbor A = neighbors.pop(snake_case__ ) A = picked_neighbor.score() - current_score if ( picked_neighbor.x > max_x or picked_neighbor.x < min_x or picked_neighbor.y > max_y or picked_neighbor.y < min_y ): continue # neighbor outside our bounds if not find_max: A = change * -1 # in case we are finding minimum if change > 0: # improves the solution A = picked_neighbor else: A = (math.e) ** ( change / current_temp ) # probability generation function if random.random() < probability: # random number within probability A = picked_neighbor A = current_temp - (current_temp * rate_of_decrease) if current_temp < threshold_temp or next_state is None: # temperature below threshold, or could not find a suitable neighbor A = True else: A = next_state if visualization: from matplotlib import pyplot as plt plt.plot(range(snake_case__ ) , snake_case__ ) plt.xlabel('Iterations' ) plt.ylabel('Function values' ) plt.show() return best_state if __name__ == "__main__": def _snake_case ( snake_case__ : Dict , snake_case__ : List[Any] ): return (x**2) + (y**2) # starting the problem with initial coordinates (12, 47) _lowercase = SearchProblem(x=12, y=47, step_size=1, function_to_optimize=test_fa) _lowercase = simulated_annealing( prob, find_max=False, max_x=1_00, min_x=5, max_y=50, min_y=-5, visualization=True ) print( '''The minimum score for f(x, y) = x^2 + y^2 with the domain 100 > x > 5 ''' F"""and 50 > y > - 5 found via hill climbing: {local_min.score()}""" ) # starting the problem with initial coordinates (12, 47) _lowercase = SearchProblem(x=12, y=47, step_size=1, function_to_optimize=test_fa) _lowercase = simulated_annealing( prob, find_max=True, max_x=1_00, min_x=5, max_y=50, min_y=-5, visualization=True ) print( '''The maximum score for f(x, y) = x^2 + y^2 with the domain 100 > x > 5 ''' F"""and 50 > y > - 5 found via hill climbing: {local_min.score()}""" ) def _snake_case ( snake_case__ : Any , snake_case__ : Dict ): return (3 * x**2) - (6 * y) _lowercase = SearchProblem(x=3, y=4, step_size=1, function_to_optimize=test_fa) _lowercase = simulated_annealing(prob, find_max=False, visualization=True) print( '''The minimum score for f(x, y) = 3*x^2 - 6*y found via hill climbing: ''' F"""{local_min.score()}""" ) _lowercase = SearchProblem(x=3, y=4, step_size=1, function_to_optimize=test_fa) _lowercase = simulated_annealing(prob, find_max=True, visualization=True) print( '''The maximum score for f(x, y) = 3*x^2 - 6*y found via hill climbing: ''' F"""{local_min.score()}""" )
74
"""simple docstring""" class lowerCAmelCase_ : '''simple docstring''' def __init__( self : int ,A_ : int ) -> Union[str, Any]: A = n A = [None] * self.n A = 0 # index of the first element A = 0 A = 0 def __len__( self : int ) -> int: return self.size def _SCREAMING_SNAKE_CASE ( self : Any ) -> bool: return self.size == 0 def _SCREAMING_SNAKE_CASE ( self : Dict ) -> Tuple: return False if self.is_empty() else self.array[self.front] def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : List[Any] ) -> int: if self.size >= self.n: raise Exception('QUEUE IS FULL' ) A = data A = (self.rear + 1) % self.n self.size += 1 return self def _SCREAMING_SNAKE_CASE ( self : int ) -> List[Any]: if self.size == 0: raise Exception('UNDERFLOW' ) A = self.array[self.front] A = None A = (self.front + 1) % self.n self.size -= 1 return temp
74
1
"""simple docstring""" from collections.abc import Sequence from queue import Queue class lowerCAmelCase_ : '''simple docstring''' def __init__( self : List[str] ,A_ : Any ,A_ : List[Any] ,A_ : str ,A_ : Optional[Any]=None ,A_ : List[Any]=None ) -> Optional[int]: A = start A = end A = val A = (start + end) // 2 A = left A = right def __repr__( self : List[str] ) -> Optional[Any]: return F'SegmentTreeNode(start={self.start}, end={self.end}, val={self.val})' class lowerCAmelCase_ : '''simple docstring''' def __init__( self : str ,A_ : Sequence ,A_ : Optional[Any] ) -> Dict: A = collection A = function if self.collection: A = self._build_tree(0 ,len(A_ ) - 1 ) def _SCREAMING_SNAKE_CASE ( self : Tuple ,A_ : Optional[int] ,A_ : Dict ) -> Dict: self._update_tree(self.root ,A_ ,A_ ) def _SCREAMING_SNAKE_CASE ( self : Dict ,A_ : int ,A_ : int ) -> Union[str, Any]: return self._query_range(self.root ,A_ ,A_ ) def _SCREAMING_SNAKE_CASE ( self : Any ,A_ : str ,A_ : Optional[int] ) -> Tuple: if start == end: return SegmentTreeNode(A_ ,A_ ,self.collection[start] ) A = (start + end) // 2 A = self._build_tree(A_ ,A_ ) A = self._build_tree(mid + 1 ,A_ ) return SegmentTreeNode(A_ ,A_ ,self.fn(left.val ,right.val ) ,A_ ,A_ ) def _SCREAMING_SNAKE_CASE ( self : List[str] ,A_ : List[Any] ,A_ : Union[str, Any] ,A_ : Any ) -> List[Any]: if node.start == i and node.end == i: A = val return if i <= node.mid: self._update_tree(node.left ,A_ ,A_ ) else: self._update_tree(node.right ,A_ ,A_ ) A = self.fn(node.left.val ,node.right.val ) def _SCREAMING_SNAKE_CASE ( self : Tuple ,A_ : Dict ,A_ : List[str] ,A_ : Tuple ) -> str: if node.start == i and node.end == j: return node.val if i <= node.mid: if j <= node.mid: # range in left child tree return self._query_range(node.left ,A_ ,A_ ) else: # range in left child tree and right child tree return self.fn( self._query_range(node.left ,A_ ,node.mid ) ,self._query_range(node.right ,node.mid + 1 ,A_ ) ,) else: # range in right child tree return self._query_range(node.right ,A_ ,A_ ) def _SCREAMING_SNAKE_CASE ( self : Any ) -> List[str]: if self.root is not None: A = Queue() queue.put(self.root ) while not queue.empty(): A = queue.get() yield node if node.left is not None: queue.put(node.left ) if node.right is not None: queue.put(node.right ) if __name__ == "__main__": import operator for fn in [operator.add, max, min]: print('''*''' * 50) _lowercase = SegmentTree([2, 1, 5, 3, 4], fn) for node in arr.traverse(): print(node) print() arr.update(1, 5) for node in arr.traverse(): print(node) print() print(arr.query_range(3, 4)) # 7 print(arr.query_range(2, 2)) # 5 print(arr.query_range(1, 3)) # 13 print()
74
"""simple docstring""" import warnings from ...utils import logging from .image_processing_yolos import YolosImageProcessor _lowercase = logging.get_logger(__name__) class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' def __init__( self : Union[str, Any] ,*A_ : List[str] ,**A_ : int ) -> None: warnings.warn( 'The class YolosFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please' ' use YolosImageProcessor instead.' ,A_ ,) super().__init__(*A_ ,**A_ )
74
1
"""simple docstring""" import contextlib import copy import random from typing import Any, Dict, Iterable, Optional, Union import numpy as np import torch from .utils import deprecate, is_transformers_available if is_transformers_available(): import transformers def _snake_case ( snake_case__ : int ): random.seed(snake_case__ ) np.random.seed(snake_case__ ) torch.manual_seed(snake_case__ ) torch.cuda.manual_seed_all(snake_case__ ) # ^^ safe to call this function even if cuda is not available class lowerCAmelCase_ : '''simple docstring''' def __init__( self : Optional[int] ,A_ : Iterable[torch.nn.Parameter] ,A_ : float = 0.99_99 ,A_ : float = 0.0 ,A_ : int = 0 ,A_ : bool = False ,A_ : Union[float, int] = 1.0 ,A_ : Union[float, int] = 2 / 3 ,A_ : Optional[Any] = None ,A_ : Dict[str, Any] = None ,**A_ : int ,) -> Optional[Any]: if isinstance(A_ ,torch.nn.Module ): A = ( 'Passing a `torch.nn.Module` to `ExponentialMovingAverage` is deprecated. ' 'Please pass the parameters of the module instead.' ) deprecate( 'passing a `torch.nn.Module` to `ExponentialMovingAverage`' ,'1.0.0' ,A_ ,standard_warn=A_ ,) A = parameters.parameters() # set use_ema_warmup to True if a torch.nn.Module is passed for backwards compatibility A = True if kwargs.get('max_value' ,A_ ) is not None: A = 'The `max_value` argument is deprecated. Please use `decay` instead.' deprecate('max_value' ,'1.0.0' ,A_ ,standard_warn=A_ ) A = kwargs['max_value'] if kwargs.get('min_value' ,A_ ) is not None: A = 'The `min_value` argument is deprecated. Please use `min_decay` instead.' deprecate('min_value' ,'1.0.0' ,A_ ,standard_warn=A_ ) A = kwargs['min_value'] A = list(A_ ) A = [p.clone().detach() for p in parameters] if kwargs.get('device' ,A_ ) is not None: A = 'The `device` argument is deprecated. Please use `to` instead.' deprecate('device' ,'1.0.0' ,A_ ,standard_warn=A_ ) self.to(device=kwargs['device'] ) A = None A = decay A = min_decay A = update_after_step A = use_ema_warmup A = inv_gamma A = power A = 0 A = None # set in `step()` A = model_cls A = model_config @classmethod def _SCREAMING_SNAKE_CASE ( cls : int ,A_ : int ,A_ : Optional[Any] ) -> "EMAModel": A , A = model_cls.load_config(A_ ,return_unused_kwargs=A_ ) A = model_cls.from_pretrained(A_ ) A = cls(model.parameters() ,model_cls=A_ ,model_config=model.config ) ema_model.load_state_dict(A_ ) return ema_model def _SCREAMING_SNAKE_CASE ( self : Any ,A_ : Optional[Any] ) -> List[str]: if self.model_cls is None: raise ValueError('`save_pretrained` can only be used if `model_cls` was defined at __init__.' ) if self.model_config is None: raise ValueError('`save_pretrained` can only be used if `model_config` was defined at __init__.' ) A = self.model_cls.from_config(self.model_config ) A = self.state_dict() state_dict.pop('shadow_params' ,A_ ) model.register_to_config(**A_ ) self.copy_to(model.parameters() ) model.save_pretrained(A_ ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : int ) -> float: A = max(0 ,optimization_step - self.update_after_step - 1 ) if step <= 0: return 0.0 if self.use_ema_warmup: A = 1 - (1 + step / self.inv_gamma) ** -self.power else: A = (1 + step) / (10 + step) A = min(A_ ,self.decay ) # make sure decay is not smaller than min_decay A = max(A_ ,self.min_decay ) return cur_decay_value @torch.no_grad() def _SCREAMING_SNAKE_CASE ( self : List[Any] ,A_ : Iterable[torch.nn.Parameter] ) -> Any: if isinstance(A_ ,torch.nn.Module ): A = ( 'Passing a `torch.nn.Module` to `ExponentialMovingAverage.step` is deprecated. ' 'Please pass the parameters of the module instead.' ) deprecate( 'passing a `torch.nn.Module` to `ExponentialMovingAverage.step`' ,'1.0.0' ,A_ ,standard_warn=A_ ,) A = parameters.parameters() A = list(A_ ) self.optimization_step += 1 # Compute the decay factor for the exponential moving average. A = self.get_decay(self.optimization_step ) A = decay A = 1 - decay A = contextlib.nullcontext if is_transformers_available() and transformers.deepspeed.is_deepspeed_zeroa_enabled(): import deepspeed for s_param, param in zip(self.shadow_params ,A_ ): if is_transformers_available() and transformers.deepspeed.is_deepspeed_zeroa_enabled(): A = deepspeed.zero.GatheredParameters(A_ ,modifier_rank=A_ ) with context_manager(): if param.requires_grad: s_param.sub_(one_minus_decay * (s_param - param) ) else: s_param.copy_(A_ ) def _SCREAMING_SNAKE_CASE ( self : Dict ,A_ : Iterable[torch.nn.Parameter] ) -> None: A = list(A_ ) for s_param, param in zip(self.shadow_params ,A_ ): param.data.copy_(s_param.to(param.device ).data ) def _SCREAMING_SNAKE_CASE ( self : str ,A_ : int=None ,A_ : Tuple=None ) -> None: A = [ p.to(device=A_ ,dtype=A_ ) if p.is_floating_point() else p.to(device=A_ ) for p in self.shadow_params ] def _SCREAMING_SNAKE_CASE ( self : str ) -> dict: return { "decay": self.decay, "min_decay": self.min_decay, "optimization_step": self.optimization_step, "update_after_step": self.update_after_step, "use_ema_warmup": self.use_ema_warmup, "inv_gamma": self.inv_gamma, "power": self.power, "shadow_params": self.shadow_params, } def _SCREAMING_SNAKE_CASE ( self : str ,A_ : Iterable[torch.nn.Parameter] ) -> None: A = [param.detach().cpu().clone() for param in parameters] def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : Iterable[torch.nn.Parameter] ) -> None: if self.temp_stored_params is None: raise RuntimeError('This ExponentialMovingAverage has no `store()`ed weights ' 'to `restore()`' ) for c_param, param in zip(self.temp_stored_params ,A_ ): param.data.copy_(c_param.data ) # Better memory-wise. A = None def _SCREAMING_SNAKE_CASE ( self : Dict ,A_ : dict ) -> None: A = copy.deepcopy(A_ ) A = state_dict.get('decay' ,self.decay ) if self.decay < 0.0 or self.decay > 1.0: raise ValueError('Decay must be between 0 and 1' ) A = state_dict.get('min_decay' ,self.min_decay ) if not isinstance(self.min_decay ,A_ ): raise ValueError('Invalid min_decay' ) A = state_dict.get('optimization_step' ,self.optimization_step ) if not isinstance(self.optimization_step ,A_ ): raise ValueError('Invalid optimization_step' ) A = state_dict.get('update_after_step' ,self.update_after_step ) if not isinstance(self.update_after_step ,A_ ): raise ValueError('Invalid update_after_step' ) A = state_dict.get('use_ema_warmup' ,self.use_ema_warmup ) if not isinstance(self.use_ema_warmup ,A_ ): raise ValueError('Invalid use_ema_warmup' ) A = state_dict.get('inv_gamma' ,self.inv_gamma ) if not isinstance(self.inv_gamma ,(float, int) ): raise ValueError('Invalid inv_gamma' ) A = state_dict.get('power' ,self.power ) if not isinstance(self.power ,(float, int) ): raise ValueError('Invalid power' ) A = state_dict.get('shadow_params' ,A_ ) if shadow_params is not None: A = shadow_params if not isinstance(self.shadow_params ,A_ ): raise ValueError('shadow_params must be a list' ) if not all(isinstance(A_ ,torch.Tensor ) for p in self.shadow_params ): raise ValueError('shadow_params must all be Tensors' )
74
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging _lowercase = logging.get_logger(__name__) _lowercase = { '''bigcode/gpt_bigcode-santacoder''': '''https://huggingface.co/bigcode/gpt_bigcode-santacoder/resolve/main/config.json''', } class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: List[str] = '''gpt_bigcode''' _lowerCamelCase: List[Any] = ['''past_key_values'''] _lowerCamelCase: int = { '''hidden_size''': '''n_embd''', '''max_position_embeddings''': '''n_positions''', '''num_attention_heads''': '''n_head''', '''num_hidden_layers''': '''n_layer''', } def __init__( self : Optional[int] ,A_ : Dict=5_0257 ,A_ : Union[str, Any]=1024 ,A_ : str=768 ,A_ : Any=12 ,A_ : Any=12 ,A_ : Optional[int]=None ,A_ : Any="gelu_pytorch_tanh" ,A_ : List[str]=0.1 ,A_ : Optional[int]=0.1 ,A_ : List[str]=0.1 ,A_ : Tuple=1e-5 ,A_ : Optional[int]=0.02 ,A_ : List[str]=True ,A_ : Optional[Any]=True ,A_ : List[Any]=5_0256 ,A_ : Union[str, Any]=5_0256 ,A_ : int=True ,A_ : Optional[Any]=True ,A_ : Dict=True ,**A_ : Union[str, Any] ,) -> Union[str, Any]: A = vocab_size A = n_positions A = n_embd A = n_layer A = n_head A = n_inner A = activation_function A = resid_pdrop A = embd_pdrop A = attn_pdrop A = layer_norm_epsilon A = initializer_range A = scale_attn_weights A = use_cache A = attention_softmax_in_fpaa A = scale_attention_softmax_in_fpaa A = multi_query A = bos_token_id A = eos_token_id super().__init__(bos_token_id=A_ ,eos_token_id=A_ ,**A_ )
74
1
"""simple docstring""" import faiss # 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 requests # noqa: F401 # Here to have a nice missing dependency error message early on import sklearn # noqa: F401 # Here to have a nice missing dependency error message early on import tqdm # noqa: F401 # Here to have a nice missing dependency error message early on from mauve import compute_mauve # From: mauve-text import datasets _lowercase = '''\ @inproceedings{pillutla-etal:mauve:neurips2021, title={MAUVE: Measuring the Gap Between Neural Text and Human Text using Divergence Frontiers}, author={Pillutla, Krishna and Swayamdipta, Swabha and Zellers, Rowan and Thickstun, John and Welleck, Sean and Choi, Yejin and Harchaoui, Zaid}, booktitle = {NeurIPS}, year = {2021} } ''' _lowercase = '''\ MAUVE is a library built on PyTorch and HuggingFace Transformers to measure the gap between neural text and human text with the eponymous MAUVE measure. MAUVE summarizes both Type I and Type II errors measured softly using Kullback–Leibler (KL) divergences. For details, see the MAUVE paper: https://arxiv.org/abs/2102.01454 (Neurips, 2021). This metrics is a wrapper around the official implementation of MAUVE: https://github.com/krishnap25/mauve ''' _lowercase = ''' Calculates MAUVE scores between two lists of generated text and reference text. Args: predictions: list of generated text to score. Each predictions 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. Optional Args: num_buckets: the size of the histogram to quantize P and Q. Options: \'auto\' (default) or an integer pca_max_data: the number data points to use for PCA dimensionality reduction prior to clustering. If -1, use all the data. Default -1 kmeans_explained_var: amount of variance of the data to keep in dimensionality reduction by PCA. Default 0.9 kmeans_num_redo: number of times to redo k-means clustering (the best objective is kept). Default 5 kmeans_max_iter: maximum number of k-means iterations. Default 500 featurize_model_name: name of the model from which features are obtained. Default \'gpt2-large\' Use one of [\'gpt2\', \'gpt2-medium\', \'gpt2-large\', \'gpt2-xl\']. device_id: Device for featurization. Supply a GPU id (e.g. 0 or 3) to use GPU. If no GPU with this id is found, use CPU max_text_length: maximum number of tokens to consider. Default 1024 divergence_curve_discretization_size: Number of points to consider on the divergence curve. Default 25 mauve_scaling_factor: "c" from the paper. Default 5. verbose: If True (default), print running time updates seed: random seed to initialize k-means cluster assignments. Returns: mauve: MAUVE score, a number between 0 and 1. Larger values indicate that P and Q are closer, frontier_integral: Frontier Integral, a number between 0 and 1. Smaller values indicate that P and Q are closer, divergence_curve: a numpy.ndarray of shape (m, 2); plot it with matplotlib to view the divergence curve, p_hist: a discrete distribution, which is a quantized version of the text distribution p_text, q_hist: same as above, but with q_text. Examples: >>> # faiss segfaults in doctest for some reason, so the .compute call is not tested with doctest >>> import datasets >>> mauve = datasets.load_metric(\'mauve\') >>> predictions = ["hello there", "general kenobi"] >>> references = ["hello there", "general kenobi"] >>> out = mauve.compute(predictions=predictions, references=references) # doctest: +SKIP >>> print(out.mauve) # doctest: +SKIP 1.0 ''' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class lowerCAmelCase_ ( datasets.Metric ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Any: return datasets.MetricInfo( description=_DESCRIPTION ,citation=_CITATION ,homepage='https://github.com/krishnap25/mauve' ,inputs_description=_KWARGS_DESCRIPTION ,features=datasets.Features( { 'predictions': datasets.Value('string' ,id='sequence' ), 'references': datasets.Value('string' ,id='sequence' ), } ) ,codebase_urls=['https://github.com/krishnap25/mauve'] ,reference_urls=[ 'https://arxiv.org/abs/2102.01454', 'https://github.com/krishnap25/mauve', ] ,) def _SCREAMING_SNAKE_CASE ( self : int ,A_ : Optional[Any] ,A_ : Union[str, Any] ,A_ : Dict=None ,A_ : Union[str, Any]=None ,A_ : List[Any]=None ,A_ : List[Any]=None ,A_ : Optional[Any]="auto" ,A_ : Optional[int]=-1 ,A_ : Dict=0.9 ,A_ : Tuple=5 ,A_ : int=500 ,A_ : List[Any]="gpt2-large" ,A_ : Dict=-1 ,A_ : int=1024 ,A_ : Optional[Any]=25 ,A_ : str=5 ,A_ : Dict=True ,A_ : Optional[int]=25 ,) -> str: A = compute_mauve( p_text=A_ ,q_text=A_ ,p_features=A_ ,q_features=A_ ,p_tokens=A_ ,q_tokens=A_ ,num_buckets=A_ ,pca_max_data=A_ ,kmeans_explained_var=A_ ,kmeans_num_redo=A_ ,kmeans_max_iter=A_ ,featurize_model_name=A_ ,device_id=A_ ,max_text_length=A_ ,divergence_curve_discretization_size=A_ ,mauve_scaling_factor=A_ ,verbose=A_ ,seed=A_ ,) return out
74
"""simple docstring""" import math import os import re import sys import unittest from pathlib import Path from typing import Tuple from unittest.mock import patch from parameterized import parameterized from transformers.testing_utils import ( CaptureStderr, ExtendSysPath, TestCasePlus, execute_subprocess_async, get_gpu_count, get_torch_dist_unique_port, require_apex, require_bitsandbytes, require_fairscale, require_torch, require_torch_gpu, require_torch_multi_gpu, require_torch_non_multi_gpu, slow, ) from transformers.trainer_callback import TrainerState from transformers.trainer_utils import set_seed _lowercase = os.path.abspath(os.path.dirname(__file__)) with ExtendSysPath(F"""{bindir}/../../examples/pytorch/translation"""): from run_translation import main # noqa set_seed(42) _lowercase = '''sshleifer/student_marian_en_ro_6_1''' _lowercase = '''sshleifer/tiny-mbart''' @require_torch class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : Any ,A_ : Union[str, Any]=False ,A_ : Optional[int]=None ,A_ : List[str]=True ,A_ : Tuple=True ,A_ : Union[str, Any]=True ,A_ : List[str]=True ,) -> Tuple: A = self.run_trainer( eval_steps=1 ,max_len=12 ,model_name=A_ ,num_train_epochs=1 ,distributed=A_ ,extra_args_str=A_ ,predict_with_generate=A_ ,do_train=A_ ,do_eval=A_ ,do_predict=A_ ,) A = TrainerState.load_from_json(os.path.join(A_ ,'trainer_state.json' ) ).log_history if not do_eval: return A = [log for log in logs if 'eval_loss' in log.keys()] A = eval_metrics[0] if predict_with_generate: assert "eval_bleu" in first_step_stats A = eval_metrics[-1] assert isinstance(last_step_stats['eval_bleu'] ,A_ ) assert not math.isnan(float(last_step_stats['eval_loss'] ) ), "eval_loss must not be `nan`" @require_torch_non_multi_gpu def _SCREAMING_SNAKE_CASE ( self : str ) -> Dict: self.run_seqaseq_quick() @require_torch_multi_gpu def _SCREAMING_SNAKE_CASE ( self : int ) -> int: self.run_seqaseq_quick(distributed=A_ ) @require_torch_multi_gpu def _SCREAMING_SNAKE_CASE ( self : str ) -> List[Any]: self.run_seqaseq_quick(distributed=A_ ) @unittest.skip('Requires an update of the env running those tests' ) @require_torch_multi_gpu @require_fairscale def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Dict: self.run_seqaseq_quick(distributed=A_ ,extra_args_str='--sharded_ddp simple' ) @unittest.skip('Requires an update of the env running those tests' ) @require_torch_multi_gpu @require_fairscale def _SCREAMING_SNAKE_CASE ( self : Any ) -> int: self.run_seqaseq_quick(distributed=A_ ,extra_args_str='--sharded_ddp simple --fp16' ) @unittest.skip('Requires an update of the env running those tests' ) @require_torch_multi_gpu @require_fairscale def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> List[Any]: self.run_seqaseq_quick(distributed=A_ ,extra_args_str='--sharded_ddp zero_dp_2' ,predict_with_generate=A_ ) @unittest.skip('Requires an update of the env running those tests' ) @require_torch_multi_gpu @require_fairscale def _SCREAMING_SNAKE_CASE ( self : Dict ) -> Dict: self.run_seqaseq_quick( distributed=A_ ,extra_args_str='--sharded_ddp zero_dp_2 --fp16' ,predict_with_generate=A_ ) @require_apex @require_torch_gpu def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> Optional[Any]: # XXX: apex breaks the trainer if it's run twice e.g. run_seq2seq.main() from the same # program and it breaks other tests that run from the same pytest worker, therefore until this is # sorted out it must be run only in an external program, that is distributed=True in this # test and only under one or more gpus - if we want cpu will need to make a special test # # specifically to the problem traced it to self.optimizer.step() - if it's run 2nd time via # 2nd main() call it botches the future eval. # self.run_seqaseq_quick(distributed=A_ ,extra_args_str='--fp16 --fp16_backend=apex' ) # test 2nd time - was getting eval_loss': nan' # to reproduce the problem set distributed=False self.run_seqaseq_quick(distributed=A_ ,extra_args_str='--fp16 --fp16_backend=apex' ) @parameterized.expand(['base', 'low', 'high', 'mixed'] ) @require_torch_multi_gpu def _SCREAMING_SNAKE_CASE ( self : str ,A_ : Dict ) -> List[str]: # as each sub-test is slow-ish split into multiple sub-tests to avoid CI timeout A = { # test with the default log_level - should be info and thus log info once 'base': {'extra_args_str': '', 'n_matches': 1}, # test with low log_level and log_level_replica - should be noisy on all processes # now the info string should appear twice on 2 processes 'low': {'extra_args_str': '--log_level debug --log_level_replica debug', 'n_matches': 2}, # test with high log_level and low log_level_replica # now the info string should appear once only on the replica 'high': {'extra_args_str': '--log_level error --log_level_replica debug', 'n_matches': 1}, # test with high log_level and log_level_replica - should be quiet on all processes 'mixed': {'extra_args_str': '--log_level error --log_level_replica error', 'n_matches': 0}, } A = experiments[experiment_id] A = {'distributed': True, 'predict_with_generate': False, 'do_eval': False, 'do_predict': False} A = 'Running training' with CaptureStderr() as cl: self.run_seqaseq_quick(**A_ ,extra_args_str=data['extra_args_str'] ) A = len(re.findall(A_ ,cl.err ) ) self.assertEqual(A_ ,data['n_matches'] ) @slow def _SCREAMING_SNAKE_CASE ( self : Tuple ) -> str: A = self.run_trainer( eval_steps=2 ,max_len=128 ,model_name=A_ ,learning_rate=3e-4 ,num_train_epochs=10 ,distributed=A_ ,) # Check metrics A = TrainerState.load_from_json(os.path.join(A_ ,'trainer_state.json' ) ).log_history A = [log for log in logs if 'eval_loss' in log.keys()] A = eval_metrics[0] A = eval_metrics[-1] assert first_step_stats["eval_loss"] > last_step_stats["eval_loss"], "model learned nothing" assert isinstance(last_step_stats['eval_bleu'] ,A_ ) # test if do_predict saves generations and metrics A = os.listdir(A_ ) A = {os.path.basename(A_ ) for p in contents} assert "generated_predictions.txt" in contents assert "predict_results.json" in contents @slow @require_bitsandbytes def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Optional[int]: from transformers.training_args import OptimizerNames def train_and_return_metrics(A_ : str ) -> Tuple[int, float]: A = '--skip_memory_metrics 0' A = self.run_trainer( max_len=128 ,model_name=A_ ,learning_rate=3e-4 ,num_train_epochs=1 ,optim=A_ ,distributed=A_ ,extra_args_str=A_ ,do_eval=A_ ,do_predict=A_ ,n_gpus_to_use=1 ,) # Check metrics A = TrainerState.load_from_json(Path(A_ ,'trainer_state.json' ) ).log_history A = int(logs[0]['train_mem_gpu_peaked_delta'] / 2**20 ) A = int(logs[0]['train_mem_gpu_alloc_delta'] / 2**20 ) A = logs[0]['train_loss'] return gpu_peak_mem_mb, gpu_alloc_mem_mb, loss A , A , A = train_and_return_metrics(OptimizerNames.ADAMW_TORCH.value ) A , A , A = train_and_return_metrics(OptimizerNames.ADAMW_BNB.value ) A = gpu_alloc_mem_orig - gpu_alloc_mem_bnb A = gpu_peak_mem_orig + gpu_alloc_mem_orig A = gpu_peak_mem_bnb + gpu_alloc_mem_bnb A = gpu_total_mem_orig - gpu_total_mem_bnb # sshleifer/student_marian_en_ro_6_1 has 54M parameter, 29M of which is `nn.Embedding` which # doesn't get quantized and remains in fp32. Therefore we only have 25M parameters quantized # in 2 bytes and the diff in optim memory usage is derived as so: # # - normal 25*8=~200MB (8 bytes per param) # - bnb 25*2= ~50MB (2 bytes per param) # # Thus we should expect ~150MB total memory saved. # # Peak memory should be the same - the total should be different by about that same margin # # After leaving a small margin to accommodate for differences between gpus let's check # that we have at least 120MB in savings A = 120 # uncomment the following if this test starts failing - requires py38 for a new print feature # gpu_peak_mem_diff = gpu_peak_mem_orig - gpu_peak_mem_bnb # print(f"{gpu_alloc_mem_orig=}MB {gpu_peak_mem_orig=}MB {gpu_alloc_mem_orig+gpu_peak_mem_orig=}MB") # print(f" {gpu_alloc_mem_bnb=}MB {gpu_peak_mem_bnb=}MB {gpu_alloc_mem_bnb+gpu_peak_mem_bnb=}MB") # print(f"{gpu_alloc_mem_diff=}MB") # print(f"{gpu_peak_mem_diff=}MB") # print(f"{gpu_total_mem_orig=}MB, {gpu_total_mem_bnb=}MB") # print(f"{gpu_total_mem_diff=}MB, {gpu_total_mem_diff=}MB") self.assertGreater( A_ ,A_ ,'should use ~150MB less alloc gpu memory with BNB, compared to without it for this model but got' F' a difference of {gpu_alloc_mem_diff}MB, with gpu_alloc_mem_orig={gpu_alloc_mem_orig}MB and' F' gpu_alloc_mem_bnb={gpu_alloc_mem_bnb}MB' ,) self.assertGreater( A_ ,A_ ,'should use ~150MB less total gpu memory with BNB, compared to without it for this model but got' F' a difference of {gpu_total_mem_diff}MB, with gpu_total_mem_orig={gpu_total_mem_orig}MB and' F' gpu_total_mem_bnb={gpu_total_mem_bnb}MB' ,) self.assertEqual( A_ ,A_ ,F'loss should be the same, but got loss_orig={loss_orig}, loss_bnb={loss_bnb}' ) def _SCREAMING_SNAKE_CASE ( self : List[str] ,A_ : int ,A_ : str ,A_ : int ,A_ : float = 3e-3 ,A_ : str = "adafactor" ,A_ : bool = False ,A_ : str = None ,A_ : int = 0 ,A_ : bool = True ,A_ : bool = True ,A_ : bool = True ,A_ : bool = True ,A_ : int = None ,) -> Dict: A = self.test_file_dir / '../fixtures/tests_samples/wmt_en_ro' A = self.get_auto_remove_tmp_dir() A = F'\n --model_name_or_path {model_name}\n --train_file {data_dir}/train.json\n --validation_file {data_dir}/val.json\n --test_file {data_dir}/test.json\n --output_dir {output_dir}\n --overwrite_output_dir\n --max_train_samples 8\n --max_source_length {max_len}\n --max_target_length {max_len}\n --do_train\n --num_train_epochs {str(A_ )}\n --per_device_train_batch_size 4\n --learning_rate {learning_rate}\n --warmup_steps 8\n --logging_steps 0\n --logging_strategy no\n --save_steps {str(A_ )}\n --group_by_length\n --label_smoothing_factor 0.1\n --target_lang ro_RO\n --source_lang en_XX\n '.split() A = F'\n --do_eval\n --per_device_eval_batch_size 4\n --max_eval_samples 8\n --val_max_target_length {max_len}\n --evaluation_strategy steps\n --eval_steps {str(A_ )}\n '.split() A = '\n --do_predict\n '.split() A = [] if do_train: args += args_train if do_eval: args += args_eval if do_predict: args += args_predict if predict_with_generate: args += "--predict_with_generate".split() if do_train: if optim == "adafactor": args += "--adafactor".split() else: args += F'--optim {optim}'.split() if extra_args_str is not None: args += extra_args_str.split() if distributed: if n_gpus_to_use is None: A = get_gpu_count() A = get_torch_dist_unique_port() A = F'\n -m torch.distributed.run\n --nproc_per_node={n_gpus_to_use}\n --master_port={master_port}\n {self.examples_dir_str}/pytorch/translation/run_translation.py\n '.split() A = [sys.executable] + distributed_args + args # keep for quick debug # print(" ".join([f"\nPYTHONPATH={self.src_dir_str}"] +cmd)); die execute_subprocess_async(A_ ,env=self.get_env() ) else: A = ['run_translation.py'] + args with patch.object(A_ ,'argv' ,A_ ): main() return output_dir
74
1
"""simple docstring""" from collections import deque from math import floor from random import random from time import time class lowerCAmelCase_ : '''simple docstring''' def __init__( self : List[Any] ) -> str: A = {} def _SCREAMING_SNAKE_CASE ( self : List[Any] ,A_ : Tuple ,A_ : List[Any] ,A_ : int=1 ) -> Optional[Any]: if self.graph.get(A_ ): if self.graph[u].count([w, v] ) == 0: self.graph[u].append([w, v] ) else: A = [[w, v]] if not self.graph.get(A_ ): A = [] def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Union[str, Any]: return list(self.graph ) def _SCREAMING_SNAKE_CASE ( self : Dict ,A_ : Optional[Any] ,A_ : Dict ) -> Any: if self.graph.get(A_ ): for _ in self.graph[u]: if _[1] == v: self.graph[u].remove(A_ ) def _SCREAMING_SNAKE_CASE ( self : str ,A_ : int=-2 ,A_ : Dict=-1 ) -> Any: if s == d: return [] A = [] A = [] if s == -2: A = list(self.graph )[0] stack.append(A_ ) visited.append(A_ ) A = s while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: A = s for node in self.graph[s]: if visited.count(node[1] ) < 1: if node[1] == d: visited.append(A_ ) return visited else: stack.append(node[1] ) visited.append(node[1] ) A = node[1] break # check if all the children are visited if s == ss: stack.pop() if len(A_ ) != 0: A = stack[len(A_ ) - 1] else: A = ss # check if se have reached the starting point if len(A_ ) == 0: return visited def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : List[str]=-1 ) -> Optional[int]: if c == -1: A = floor(random() * 1_0000 ) + 10 for i in range(A_ ): # every vertex has max 100 edges for _ in range(floor(random() * 102 ) + 1 ): A = floor(random() * c ) + 1 if n != i: self.add_pair(A_ ,A_ ,1 ) def _SCREAMING_SNAKE_CASE ( self : Any ,A_ : List[str]=-2 ) -> Tuple: A = deque() A = [] if s == -2: A = list(self.graph )[0] d.append(A_ ) visited.append(A_ ) while d: A = d.popleft() if len(self.graph[s] ) != 0: for node in self.graph[s]: if visited.count(node[1] ) < 1: d.append(node[1] ) visited.append(node[1] ) return visited def _SCREAMING_SNAKE_CASE ( self : Optional[int] ,A_ : Optional[int] ) -> Dict: A = 0 for x in self.graph: for y in self.graph[x]: if y[1] == u: count += 1 return count def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ,A_ : List[str] ) -> List[str]: return len(self.graph[u] ) def _SCREAMING_SNAKE_CASE ( self : Tuple ,A_ : List[str]=-2 ) -> Optional[Any]: A = [] A = [] if s == -2: A = list(self.graph )[0] stack.append(A_ ) visited.append(A_ ) A = s A = [] while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: A = s for node in self.graph[s]: if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) A = node[1] break # check if all the children are visited if s == ss: sorted_nodes.append(stack.pop() ) if len(A_ ) != 0: A = stack[len(A_ ) - 1] else: A = ss # check if se have reached the starting point if len(A_ ) == 0: return sorted_nodes def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> Tuple: A = [] A = [] A = list(self.graph )[0] stack.append(A_ ) visited.append(A_ ) A = -2 A = [] A = s A = False A = set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: A = s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): A = len(A_ ) - 1 while len_stack >= 0: if stack[len_stack] == node[1]: anticipating_nodes.add(node[1] ) break else: anticipating_nodes.add(stack[len_stack] ) len_stack -= 1 if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) A = node[1] break # check if all the children are visited if s == ss: stack.pop() A = True if len(A_ ) != 0: A = stack[len(A_ ) - 1] else: A = False indirect_parents.append(A_ ) A = s A = ss # check if se have reached the starting point if len(A_ ) == 0: return list(A_ ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Union[str, Any]: A = [] A = [] A = list(self.graph )[0] stack.append(A_ ) visited.append(A_ ) A = -2 A = [] A = s A = False A = set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: A = s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): A = len(A_ ) - 1 while len_stack_minus_one >= 0: if stack[len_stack_minus_one] == node[1]: anticipating_nodes.add(node[1] ) break else: return True if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) A = node[1] break # check if all the children are visited if s == ss: stack.pop() A = True if len(A_ ) != 0: A = stack[len(A_ ) - 1] else: A = False indirect_parents.append(A_ ) A = s A = ss # check if se have reached the starting point if len(A_ ) == 0: return False def _SCREAMING_SNAKE_CASE ( self : Any ,A_ : Optional[Any]=-2 ,A_ : Union[str, Any]=-1 ) -> str: A = time() self.dfs(A_ ,A_ ) A = time() return end - begin def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ,A_ : str=-2 ) -> List[str]: A = time() self.bfs(A_ ) A = time() return end - begin class lowerCAmelCase_ : '''simple docstring''' def __init__( self : int ) -> Dict: A = {} def _SCREAMING_SNAKE_CASE ( self : Optional[int] ,A_ : Optional[int] ,A_ : Optional[Any] ,A_ : int=1 ) -> str: # check if the u exists if self.graph.get(A_ ): # if there already is a edge if self.graph[u].count([w, v] ) == 0: self.graph[u].append([w, v] ) else: # if u does not exist A = [[w, v]] # add the other way if self.graph.get(A_ ): # if there already is a edge if self.graph[v].count([w, u] ) == 0: self.graph[v].append([w, u] ) else: # if u does not exist A = [[w, u]] def _SCREAMING_SNAKE_CASE ( self : Any ,A_ : Dict ,A_ : int ) -> int: if self.graph.get(A_ ): for _ in self.graph[u]: if _[1] == v: self.graph[u].remove(A_ ) # the other way round if self.graph.get(A_ ): for _ in self.graph[v]: if _[1] == u: self.graph[v].remove(A_ ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ,A_ : Any=-2 ,A_ : Optional[Any]=-1 ) -> Tuple: if s == d: return [] A = [] A = [] if s == -2: A = list(self.graph )[0] stack.append(A_ ) visited.append(A_ ) A = s while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: A = s for node in self.graph[s]: if visited.count(node[1] ) < 1: if node[1] == d: visited.append(A_ ) return visited else: stack.append(node[1] ) visited.append(node[1] ) A = node[1] break # check if all the children are visited if s == ss: stack.pop() if len(A_ ) != 0: A = stack[len(A_ ) - 1] else: A = ss # check if se have reached the starting point if len(A_ ) == 0: return visited def _SCREAMING_SNAKE_CASE ( self : Optional[int] ,A_ : Dict=-1 ) -> Tuple: if c == -1: A = floor(random() * 1_0000 ) + 10 for i in range(A_ ): # every vertex has max 100 edges for _ in range(floor(random() * 102 ) + 1 ): A = floor(random() * c ) + 1 if n != i: self.add_pair(A_ ,A_ ,1 ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : Union[str, Any]=-2 ) -> Union[str, Any]: A = deque() A = [] if s == -2: A = list(self.graph )[0] d.append(A_ ) visited.append(A_ ) while d: A = d.popleft() if len(self.graph[s] ) != 0: for node in self.graph[s]: if visited.count(node[1] ) < 1: d.append(node[1] ) visited.append(node[1] ) return visited def _SCREAMING_SNAKE_CASE ( self : Tuple ,A_ : Tuple ) -> Any: return len(self.graph[u] ) def _SCREAMING_SNAKE_CASE ( self : Tuple ) -> List[str]: A = [] A = [] A = list(self.graph )[0] stack.append(A_ ) visited.append(A_ ) A = -2 A = [] A = s A = False A = set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: A = s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): A = len(A_ ) - 1 while len_stack >= 0: if stack[len_stack] == node[1]: anticipating_nodes.add(node[1] ) break else: anticipating_nodes.add(stack[len_stack] ) len_stack -= 1 if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) A = node[1] break # check if all the children are visited if s == ss: stack.pop() A = True if len(A_ ) != 0: A = stack[len(A_ ) - 1] else: A = False indirect_parents.append(A_ ) A = s A = ss # check if se have reached the starting point if len(A_ ) == 0: return list(A_ ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Optional[int]: A = [] A = [] A = list(self.graph )[0] stack.append(A_ ) visited.append(A_ ) A = -2 A = [] A = s A = False A = set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: A = s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): A = len(A_ ) - 1 while len_stack_minus_one >= 0: if stack[len_stack_minus_one] == node[1]: anticipating_nodes.add(node[1] ) break else: return True if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) A = node[1] break # check if all the children are visited if s == ss: stack.pop() A = True if len(A_ ) != 0: A = stack[len(A_ ) - 1] else: A = False indirect_parents.append(A_ ) A = s A = ss # check if se have reached the starting point if len(A_ ) == 0: return False def _SCREAMING_SNAKE_CASE ( self : Any ) -> List[str]: return list(self.graph ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : Tuple=-2 ,A_ : Any=-1 ) -> List[Any]: A = time() self.dfs(A_ ,A_ ) A = time() return end - begin def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : Union[str, Any]=-2 ) -> str: A = time() self.bfs(A_ ) A = time() return end - begin
74
"""simple docstring""" from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging _lowercase = logging.get_logger(__name__) _lowercase = { '''facebook/deit-base-distilled-patch16-224''': ( '''https://huggingface.co/facebook/deit-base-patch16-224/resolve/main/config.json''' ), # See all DeiT models at https://huggingface.co/models?filter=deit } class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: Optional[Any] = '''deit''' def __init__( self : int ,A_ : Optional[Any]=768 ,A_ : Union[str, Any]=12 ,A_ : Dict=12 ,A_ : int=3072 ,A_ : Optional[Any]="gelu" ,A_ : Dict=0.0 ,A_ : Any=0.0 ,A_ : str=0.02 ,A_ : Tuple=1e-12 ,A_ : Union[str, Any]=224 ,A_ : Optional[Any]=16 ,A_ : List[Any]=3 ,A_ : Optional[Any]=True ,A_ : Optional[int]=16 ,**A_ : Union[str, Any] ,) -> Dict: super().__init__(**A_ ) A = hidden_size A = num_hidden_layers A = num_attention_heads A = intermediate_size A = hidden_act A = hidden_dropout_prob A = attention_probs_dropout_prob A = initializer_range A = layer_norm_eps A = image_size A = patch_size A = num_channels A = qkv_bias A = encoder_stride class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: int = version.parse('''1.11''' ) @property def _SCREAMING_SNAKE_CASE ( self : Tuple ) -> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ] ) @property def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> float: return 1e-4
74
1
"""simple docstring""" import math from collections import defaultdict from typing import List, Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from .scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin, SchedulerOutput def _snake_case ( snake_case__ : List[Any] , snake_case__ : Optional[int]=0.999 , snake_case__ : Union[str, Any]="cosine" , ): if alpha_transform_type == "cosine": def alpha_bar_fn(snake_case__ : Union[str, Any] ): return math.cos((t + 0.008) / 1.008 * math.pi / 2 ) ** 2 elif alpha_transform_type == "exp": def alpha_bar_fn(snake_case__ : Dict ): return math.exp(t * -12.0 ) else: raise ValueError(F'Unsupported alpha_tranform_type: {alpha_transform_type}' ) A = [] for i in range(snake_case__ ): A = i / num_diffusion_timesteps A = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar_fn(snake_case__ ) / alpha_bar_fn(snake_case__ ) , snake_case__ ) ) return torch.tensor(snake_case__ , dtype=torch.floataa ) class lowerCAmelCase_ ( _lowercase , _lowercase ): '''simple docstring''' _lowerCamelCase: Optional[int] = [e.name for e in KarrasDiffusionSchedulers] _lowerCamelCase: Optional[Any] = 2 @register_to_config def __init__( self : str ,A_ : int = 1000 ,A_ : float = 0.0_00_85 ,A_ : float = 0.0_12 ,A_ : str = "linear" ,A_ : Optional[Union[np.ndarray, List[float]]] = None ,A_ : str = "epsilon" ,A_ : Optional[bool] = False ,A_ : Optional[bool] = False ,A_ : float = 1.0 ,A_ : str = "linspace" ,A_ : int = 0 ,) -> List[str]: if trained_betas is not None: A = torch.tensor(A_ ,dtype=torch.floataa ) elif beta_schedule == "linear": A = torch.linspace(A_ ,A_ ,A_ ,dtype=torch.floataa ) elif beta_schedule == "scaled_linear": # this schedule is very specific to the latent diffusion model. A = ( torch.linspace(beta_start**0.5 ,beta_end**0.5 ,A_ ,dtype=torch.floataa ) ** 2 ) elif beta_schedule == "squaredcos_cap_v2": # Glide cosine schedule A = betas_for_alpha_bar(A_ ,alpha_transform_type='cosine' ) elif beta_schedule == "exp": A = betas_for_alpha_bar(A_ ,alpha_transform_type='exp' ) else: raise NotImplementedError(F'{beta_schedule} does is not implemented for {self.__class__}' ) A = 1.0 - self.betas A = torch.cumprod(self.alphas ,dim=0 ) # set all values self.set_timesteps(A_ ,A_ ,A_ ) A = use_karras_sigmas def _SCREAMING_SNAKE_CASE ( self : int ,A_ : Tuple ,A_ : Tuple=None ) -> Tuple: if schedule_timesteps is None: A = self.timesteps A = (schedule_timesteps == timestep).nonzero() # The sigma index that is taken for the **very** first `step` # is always the second index (or the last index if there is only 1) # This way we can ensure we don't accidentally skip a sigma in # case we start in the middle of the denoising schedule (e.g. for image-to-image) if len(self._index_counter ) == 0: A = 1 if len(A_ ) > 1 else 0 else: A = timestep.cpu().item() if torch.is_tensor(A_ ) else timestep A = self._index_counter[timestep_int] return indices[pos].item() @property def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> List[Any]: # standard deviation of the initial noise distribution if self.config.timestep_spacing in ["linspace", "trailing"]: return self.sigmas.max() return (self.sigmas.max() ** 2 + 1) ** 0.5 def _SCREAMING_SNAKE_CASE ( self : List[Any] ,A_ : torch.FloatTensor ,A_ : Union[float, torch.FloatTensor] ,) -> torch.FloatTensor: A = self.index_for_timestep(A_ ) A = self.sigmas[step_index] A = sample / ((sigma**2 + 1) ** 0.5) return sample def _SCREAMING_SNAKE_CASE ( self : str ,A_ : int ,A_ : Union[str, torch.device] = None ,A_ : Optional[int] = None ,) -> Optional[Any]: A = num_inference_steps A = num_train_timesteps or self.config.num_train_timesteps # "linspace", "leading", "trailing" corresponds to annotation of Table 2. of https://arxiv.org/abs/2305.08891 if self.config.timestep_spacing == "linspace": A = np.linspace(0 ,num_train_timesteps - 1 ,A_ ,dtype=A_ )[::-1].copy() elif self.config.timestep_spacing == "leading": A = num_train_timesteps // self.num_inference_steps # creates integer timesteps by multiplying by ratio # casting to int to avoid issues when num_inference_step is power of 3 A = (np.arange(0 ,A_ ) * step_ratio).round()[::-1].copy().astype(A_ ) timesteps += self.config.steps_offset elif self.config.timestep_spacing == "trailing": A = num_train_timesteps / self.num_inference_steps # creates integer timesteps by multiplying by ratio # casting to int to avoid issues when num_inference_step is power of 3 A = (np.arange(A_ ,0 ,-step_ratio )).round().copy().astype(A_ ) timesteps -= 1 else: raise ValueError( F'{self.config.timestep_spacing} is not supported. Please make sure to choose one of \'linspace\', \'leading\' or \'trailing\'.' ) A = np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5 ) A = np.log(A_ ) A = np.interp(A_ ,np.arange(0 ,len(A_ ) ) ,A_ ) if self.config.use_karras_sigmas: A = self._convert_to_karras(in_sigmas=A_ ,num_inference_steps=self.num_inference_steps ) A = np.array([self._sigma_to_t(A_ ,A_ ) for sigma in sigmas] ) A = np.concatenate([sigmas, [0.0]] ).astype(np.floataa ) A = torch.from_numpy(A_ ).to(device=A_ ) A = torch.cat([sigmas[:1], sigmas[1:-1].repeat_interleave(2 ), sigmas[-1:]] ) A = torch.from_numpy(A_ ) A = torch.cat([timesteps[:1], timesteps[1:].repeat_interleave(2 )] ) if str(A_ ).startswith('mps' ): # mps does not support float64 A = timesteps.to(A_ ,dtype=torch.floataa ) else: A = timesteps.to(device=A_ ) # empty dt and derivative A = None A = None # for exp beta schedules, such as the one for `pipeline_shap_e.py` # we need an index counter A = defaultdict(A_ ) def _SCREAMING_SNAKE_CASE ( self : Any ,A_ : Optional[Any] ,A_ : List[str] ) -> Dict: # get log sigma A = np.log(A_ ) # get distribution A = log_sigma - log_sigmas[:, np.newaxis] # get sigmas range A = np.cumsum((dists >= 0) ,axis=0 ).argmax(axis=0 ).clip(max=log_sigmas.shape[0] - 2 ) A = low_idx + 1 A = log_sigmas[low_idx] A = log_sigmas[high_idx] # interpolate sigmas A = (low - log_sigma) / (low - high) A = np.clip(A_ ,0 ,1 ) # transform interpolation to time range A = (1 - w) * low_idx + w * high_idx A = t.reshape(sigma.shape ) return t def _SCREAMING_SNAKE_CASE ( self : List[str] ,A_ : torch.FloatTensor ,A_ : int ) -> torch.FloatTensor: A = in_sigmas[-1].item() A = in_sigmas[0].item() A = 7.0 # 7.0 is the value used in the paper A = np.linspace(0 ,1 ,A_ ) A = sigma_min ** (1 / rho) A = sigma_max ** (1 / rho) A = (max_inv_rho + ramp * (min_inv_rho - max_inv_rho)) ** rho return sigmas @property def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Dict: return self.dt is None def _SCREAMING_SNAKE_CASE ( self : Tuple ,A_ : Union[torch.FloatTensor, np.ndarray] ,A_ : Union[float, torch.FloatTensor] ,A_ : Union[torch.FloatTensor, np.ndarray] ,A_ : bool = True ,) -> Union[SchedulerOutput, Tuple]: A = self.index_for_timestep(A_ ) # advance index counter by 1 A = timestep.cpu().item() if torch.is_tensor(A_ ) else timestep self._index_counter[timestep_int] += 1 if self.state_in_first_order: A = self.sigmas[step_index] A = self.sigmas[step_index + 1] else: # 2nd order / Heun's method A = self.sigmas[step_index - 1] A = self.sigmas[step_index] # currently only gamma=0 is supported. This usually works best anyways. # We can support gamma in the future but then need to scale the timestep before # passing it to the model which requires a change in API A = 0 A = sigma * (gamma + 1) # Note: sigma_hat == sigma for now # 1. compute predicted original sample (x_0) from sigma-scaled predicted noise if self.config.prediction_type == "epsilon": A = sigma_hat if self.state_in_first_order else sigma_next A = sample - sigma_input * model_output elif self.config.prediction_type == "v_prediction": A = sigma_hat if self.state_in_first_order else sigma_next A = model_output * (-sigma_input / (sigma_input**2 + 1) ** 0.5) + ( sample / (sigma_input**2 + 1) ) elif self.config.prediction_type == "sample": A = model_output else: raise ValueError( F'prediction_type given as {self.config.prediction_type} must be one of `epsilon`, or `v_prediction`' ) if self.config.clip_sample: A = pred_original_sample.clamp( -self.config.clip_sample_range ,self.config.clip_sample_range ) if self.state_in_first_order: # 2. Convert to an ODE derivative for 1st order A = (sample - pred_original_sample) / sigma_hat # 3. delta timestep A = sigma_next - sigma_hat # store for 2nd order step A = derivative A = dt A = sample else: # 2. 2nd order / Heun's method A = (sample - pred_original_sample) / sigma_next A = (self.prev_derivative + derivative) / 2 # 3. take prev timestep & sample A = self.dt A = self.sample # free dt and derivative # Note, this puts the scheduler in "first order mode" A = None A = None A = None A = sample + derivative * dt if not return_dict: return (prev_sample,) return SchedulerOutput(prev_sample=A_ ) def _SCREAMING_SNAKE_CASE ( self : int ,A_ : torch.FloatTensor ,A_ : torch.FloatTensor ,A_ : torch.FloatTensor ,) -> torch.FloatTensor: # Make sure sigmas and timesteps have the same device and dtype as original_samples A = self.sigmas.to(device=original_samples.device ,dtype=original_samples.dtype ) if original_samples.device.type == "mps" and torch.is_floating_point(A_ ): # mps does not support float64 A = self.timesteps.to(original_samples.device ,dtype=torch.floataa ) A = timesteps.to(original_samples.device ,dtype=torch.floataa ) else: A = self.timesteps.to(original_samples.device ) A = timesteps.to(original_samples.device ) A = [self.index_for_timestep(A_ ,A_ ) for t in timesteps] A = sigmas[step_indices].flatten() while len(sigma.shape ) < len(original_samples.shape ): A = sigma.unsqueeze(-1 ) A = original_samples + noise * sigma return noisy_samples def __len__( self : Dict ) -> int: return self.config.num_train_timesteps
74
"""simple docstring""" import math from collections import defaultdict from typing import List, Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from .scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin, SchedulerOutput def _snake_case ( snake_case__ : List[Any] , snake_case__ : Optional[int]=0.999 , snake_case__ : Union[str, Any]="cosine" , ): if alpha_transform_type == "cosine": def alpha_bar_fn(snake_case__ : Union[str, Any] ): return math.cos((t + 0.008) / 1.008 * math.pi / 2 ) ** 2 elif alpha_transform_type == "exp": def alpha_bar_fn(snake_case__ : Dict ): return math.exp(t * -12.0 ) else: raise ValueError(F'Unsupported alpha_tranform_type: {alpha_transform_type}' ) A = [] for i in range(snake_case__ ): A = i / num_diffusion_timesteps A = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar_fn(snake_case__ ) / alpha_bar_fn(snake_case__ ) , snake_case__ ) ) return torch.tensor(snake_case__ , dtype=torch.floataa ) class lowerCAmelCase_ ( _lowercase , _lowercase ): '''simple docstring''' _lowerCamelCase: Optional[int] = [e.name for e in KarrasDiffusionSchedulers] _lowerCamelCase: Optional[Any] = 2 @register_to_config def __init__( self : str ,A_ : int = 1000 ,A_ : float = 0.0_00_85 ,A_ : float = 0.0_12 ,A_ : str = "linear" ,A_ : Optional[Union[np.ndarray, List[float]]] = None ,A_ : str = "epsilon" ,A_ : Optional[bool] = False ,A_ : Optional[bool] = False ,A_ : float = 1.0 ,A_ : str = "linspace" ,A_ : int = 0 ,) -> List[str]: if trained_betas is not None: A = torch.tensor(A_ ,dtype=torch.floataa ) elif beta_schedule == "linear": A = torch.linspace(A_ ,A_ ,A_ ,dtype=torch.floataa ) elif beta_schedule == "scaled_linear": # this schedule is very specific to the latent diffusion model. A = ( torch.linspace(beta_start**0.5 ,beta_end**0.5 ,A_ ,dtype=torch.floataa ) ** 2 ) elif beta_schedule == "squaredcos_cap_v2": # Glide cosine schedule A = betas_for_alpha_bar(A_ ,alpha_transform_type='cosine' ) elif beta_schedule == "exp": A = betas_for_alpha_bar(A_ ,alpha_transform_type='exp' ) else: raise NotImplementedError(F'{beta_schedule} does is not implemented for {self.__class__}' ) A = 1.0 - self.betas A = torch.cumprod(self.alphas ,dim=0 ) # set all values self.set_timesteps(A_ ,A_ ,A_ ) A = use_karras_sigmas def _SCREAMING_SNAKE_CASE ( self : int ,A_ : Tuple ,A_ : Tuple=None ) -> Tuple: if schedule_timesteps is None: A = self.timesteps A = (schedule_timesteps == timestep).nonzero() # The sigma index that is taken for the **very** first `step` # is always the second index (or the last index if there is only 1) # This way we can ensure we don't accidentally skip a sigma in # case we start in the middle of the denoising schedule (e.g. for image-to-image) if len(self._index_counter ) == 0: A = 1 if len(A_ ) > 1 else 0 else: A = timestep.cpu().item() if torch.is_tensor(A_ ) else timestep A = self._index_counter[timestep_int] return indices[pos].item() @property def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> List[Any]: # standard deviation of the initial noise distribution if self.config.timestep_spacing in ["linspace", "trailing"]: return self.sigmas.max() return (self.sigmas.max() ** 2 + 1) ** 0.5 def _SCREAMING_SNAKE_CASE ( self : List[Any] ,A_ : torch.FloatTensor ,A_ : Union[float, torch.FloatTensor] ,) -> torch.FloatTensor: A = self.index_for_timestep(A_ ) A = self.sigmas[step_index] A = sample / ((sigma**2 + 1) ** 0.5) return sample def _SCREAMING_SNAKE_CASE ( self : str ,A_ : int ,A_ : Union[str, torch.device] = None ,A_ : Optional[int] = None ,) -> Optional[Any]: A = num_inference_steps A = num_train_timesteps or self.config.num_train_timesteps # "linspace", "leading", "trailing" corresponds to annotation of Table 2. of https://arxiv.org/abs/2305.08891 if self.config.timestep_spacing == "linspace": A = np.linspace(0 ,num_train_timesteps - 1 ,A_ ,dtype=A_ )[::-1].copy() elif self.config.timestep_spacing == "leading": A = num_train_timesteps // self.num_inference_steps # creates integer timesteps by multiplying by ratio # casting to int to avoid issues when num_inference_step is power of 3 A = (np.arange(0 ,A_ ) * step_ratio).round()[::-1].copy().astype(A_ ) timesteps += self.config.steps_offset elif self.config.timestep_spacing == "trailing": A = num_train_timesteps / self.num_inference_steps # creates integer timesteps by multiplying by ratio # casting to int to avoid issues when num_inference_step is power of 3 A = (np.arange(A_ ,0 ,-step_ratio )).round().copy().astype(A_ ) timesteps -= 1 else: raise ValueError( F'{self.config.timestep_spacing} is not supported. Please make sure to choose one of \'linspace\', \'leading\' or \'trailing\'.' ) A = np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5 ) A = np.log(A_ ) A = np.interp(A_ ,np.arange(0 ,len(A_ ) ) ,A_ ) if self.config.use_karras_sigmas: A = self._convert_to_karras(in_sigmas=A_ ,num_inference_steps=self.num_inference_steps ) A = np.array([self._sigma_to_t(A_ ,A_ ) for sigma in sigmas] ) A = np.concatenate([sigmas, [0.0]] ).astype(np.floataa ) A = torch.from_numpy(A_ ).to(device=A_ ) A = torch.cat([sigmas[:1], sigmas[1:-1].repeat_interleave(2 ), sigmas[-1:]] ) A = torch.from_numpy(A_ ) A = torch.cat([timesteps[:1], timesteps[1:].repeat_interleave(2 )] ) if str(A_ ).startswith('mps' ): # mps does not support float64 A = timesteps.to(A_ ,dtype=torch.floataa ) else: A = timesteps.to(device=A_ ) # empty dt and derivative A = None A = None # for exp beta schedules, such as the one for `pipeline_shap_e.py` # we need an index counter A = defaultdict(A_ ) def _SCREAMING_SNAKE_CASE ( self : Any ,A_ : Optional[Any] ,A_ : List[str] ) -> Dict: # get log sigma A = np.log(A_ ) # get distribution A = log_sigma - log_sigmas[:, np.newaxis] # get sigmas range A = np.cumsum((dists >= 0) ,axis=0 ).argmax(axis=0 ).clip(max=log_sigmas.shape[0] - 2 ) A = low_idx + 1 A = log_sigmas[low_idx] A = log_sigmas[high_idx] # interpolate sigmas A = (low - log_sigma) / (low - high) A = np.clip(A_ ,0 ,1 ) # transform interpolation to time range A = (1 - w) * low_idx + w * high_idx A = t.reshape(sigma.shape ) return t def _SCREAMING_SNAKE_CASE ( self : List[str] ,A_ : torch.FloatTensor ,A_ : int ) -> torch.FloatTensor: A = in_sigmas[-1].item() A = in_sigmas[0].item() A = 7.0 # 7.0 is the value used in the paper A = np.linspace(0 ,1 ,A_ ) A = sigma_min ** (1 / rho) A = sigma_max ** (1 / rho) A = (max_inv_rho + ramp * (min_inv_rho - max_inv_rho)) ** rho return sigmas @property def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Dict: return self.dt is None def _SCREAMING_SNAKE_CASE ( self : Tuple ,A_ : Union[torch.FloatTensor, np.ndarray] ,A_ : Union[float, torch.FloatTensor] ,A_ : Union[torch.FloatTensor, np.ndarray] ,A_ : bool = True ,) -> Union[SchedulerOutput, Tuple]: A = self.index_for_timestep(A_ ) # advance index counter by 1 A = timestep.cpu().item() if torch.is_tensor(A_ ) else timestep self._index_counter[timestep_int] += 1 if self.state_in_first_order: A = self.sigmas[step_index] A = self.sigmas[step_index + 1] else: # 2nd order / Heun's method A = self.sigmas[step_index - 1] A = self.sigmas[step_index] # currently only gamma=0 is supported. This usually works best anyways. # We can support gamma in the future but then need to scale the timestep before # passing it to the model which requires a change in API A = 0 A = sigma * (gamma + 1) # Note: sigma_hat == sigma for now # 1. compute predicted original sample (x_0) from sigma-scaled predicted noise if self.config.prediction_type == "epsilon": A = sigma_hat if self.state_in_first_order else sigma_next A = sample - sigma_input * model_output elif self.config.prediction_type == "v_prediction": A = sigma_hat if self.state_in_first_order else sigma_next A = model_output * (-sigma_input / (sigma_input**2 + 1) ** 0.5) + ( sample / (sigma_input**2 + 1) ) elif self.config.prediction_type == "sample": A = model_output else: raise ValueError( F'prediction_type given as {self.config.prediction_type} must be one of `epsilon`, or `v_prediction`' ) if self.config.clip_sample: A = pred_original_sample.clamp( -self.config.clip_sample_range ,self.config.clip_sample_range ) if self.state_in_first_order: # 2. Convert to an ODE derivative for 1st order A = (sample - pred_original_sample) / sigma_hat # 3. delta timestep A = sigma_next - sigma_hat # store for 2nd order step A = derivative A = dt A = sample else: # 2. 2nd order / Heun's method A = (sample - pred_original_sample) / sigma_next A = (self.prev_derivative + derivative) / 2 # 3. take prev timestep & sample A = self.dt A = self.sample # free dt and derivative # Note, this puts the scheduler in "first order mode" A = None A = None A = None A = sample + derivative * dt if not return_dict: return (prev_sample,) return SchedulerOutput(prev_sample=A_ ) def _SCREAMING_SNAKE_CASE ( self : int ,A_ : torch.FloatTensor ,A_ : torch.FloatTensor ,A_ : torch.FloatTensor ,) -> torch.FloatTensor: # Make sure sigmas and timesteps have the same device and dtype as original_samples A = self.sigmas.to(device=original_samples.device ,dtype=original_samples.dtype ) if original_samples.device.type == "mps" and torch.is_floating_point(A_ ): # mps does not support float64 A = self.timesteps.to(original_samples.device ,dtype=torch.floataa ) A = timesteps.to(original_samples.device ,dtype=torch.floataa ) else: A = self.timesteps.to(original_samples.device ) A = timesteps.to(original_samples.device ) A = [self.index_for_timestep(A_ ,A_ ) for t in timesteps] A = sigmas[step_indices].flatten() while len(sigma.shape ) < len(original_samples.shape ): A = sigma.unsqueeze(-1 ) A = original_samples + noise * sigma return noisy_samples def __len__( self : Dict ) -> int: return self.config.num_train_timesteps
74
1
"""simple docstring""" # 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_torch_available, is_vision_available _lowercase = { '''configuration_efficientnet''': [ '''EFFICIENTNET_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''EfficientNetConfig''', '''EfficientNetOnnxConfig''', ] } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase = ['''EfficientNetImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase = [ '''EFFICIENTNET_PRETRAINED_MODEL_ARCHIVE_LIST''', '''EfficientNetForImageClassification''', '''EfficientNetModel''', '''EfficientNetPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_efficientnet import ( EFFICIENTNET_PRETRAINED_CONFIG_ARCHIVE_MAP, EfficientNetConfig, EfficientNetOnnxConfig, ) try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_efficientnet import EfficientNetImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_efficientnet import ( EFFICIENTNET_PRETRAINED_MODEL_ARCHIVE_LIST, EfficientNetForImageClassification, EfficientNetModel, EfficientNetPreTrainedModel, ) else: import sys _lowercase = _LazyModule(__name__, globals()['''__file__'''], _import_structure)
74
"""simple docstring""" class lowerCAmelCase_ : '''simple docstring''' def __init__( self : Dict ,A_ : list[int] ) -> None: A = len(A_ ) A = [0] * len_array if len_array > 0: A = array[0] for i in range(1 ,A_ ): A = self.prefix_sum[i - 1] + array[i] def _SCREAMING_SNAKE_CASE ( self : str ,A_ : int ,A_ : int ) -> int: if start == 0: return self.prefix_sum[end] return self.prefix_sum[end] - self.prefix_sum[start - 1] def _SCREAMING_SNAKE_CASE ( self : str ,A_ : int ) -> bool: A = {0} for sum_item in self.prefix_sum: if sum_item - target_sum in sums: return True sums.add(A_ ) return False if __name__ == "__main__": import doctest doctest.testmod()
74
1
"""simple docstring""" import math from collections.abc import Iterator from itertools import takewhile def _snake_case ( snake_case__ : int ): 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(math.sqrt(snake_case__ ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def _snake_case ( ): A = 2 while True: if is_prime(snake_case__ ): yield num num += 1 def _snake_case ( snake_case__ : int = 200_0000 ): return sum(takewhile(lambda snake_case__ : x < n , prime_generator() ) ) if __name__ == "__main__": print(F"""{solution() = }""")
74
"""simple docstring""" import argparse import torch from huggingface_hub import hf_hub_download from transformers import AutoTokenizer, RobertaPreLayerNormConfig, RobertaPreLayerNormForMaskedLM from transformers.utils import logging logging.set_verbosity_info() _lowercase = logging.get_logger(__name__) def _snake_case ( snake_case__ : str , snake_case__ : str ): A = RobertaPreLayerNormConfig.from_pretrained( snake_case__ , architectures=['RobertaPreLayerNormForMaskedLM'] ) # convert state_dict A = torch.load(hf_hub_download(repo_id=snake_case__ , filename='pytorch_model.bin' ) ) A = {} for tensor_key, tensor_value in original_state_dict.items(): # The transformer implementation gives the model a unique name, rather than overwiriting 'roberta' if tensor_key.startswith('roberta.' ): A = 'roberta_prelayernorm.' + tensor_key[len('roberta.' ) :] # The original implementation contains weights which are not used, remove them from the state_dict if tensor_key.endswith('.self.LayerNorm.weight' ) or tensor_key.endswith('.self.LayerNorm.bias' ): continue A = tensor_value A = RobertaPreLayerNormForMaskedLM.from_pretrained( pretrained_model_name_or_path=snake_case__ , config=snake_case__ , state_dict=snake_case__ ) model.save_pretrained(snake_case__ ) # convert tokenizer A = AutoTokenizer.from_pretrained(snake_case__ ) tokenizer.save_pretrained(snake_case__ ) if __name__ == "__main__": _lowercase = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--checkpoint-repo''', default=None, type=str, required=True, help='''Path the official PyTorch dump, e.g. \'andreasmadsen/efficient_mlm_m0.40\'.''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) _lowercase = parser.parse_args() convert_roberta_prelayernorm_checkpoint_to_pytorch(args.checkpoint_repo, args.pytorch_dump_folder_path)
74
1
"""simple docstring""" from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) 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 ( VersatileDiffusionDualGuidedPipeline, VersatileDiffusionImageVariationPipeline, VersatileDiffusionPipeline, VersatileDiffusionTextToImagePipeline, ) else: from .modeling_text_unet import UNetFlatConditionModel from .pipeline_versatile_diffusion import VersatileDiffusionPipeline from .pipeline_versatile_diffusion_dual_guided import VersatileDiffusionDualGuidedPipeline from .pipeline_versatile_diffusion_image_variation import VersatileDiffusionImageVariationPipeline from .pipeline_versatile_diffusion_text_to_image import VersatileDiffusionTextToImagePipeline
74
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging _lowercase = logging.get_logger(__name__) _lowercase = { '''junnyu/roformer_chinese_small''': '''https://huggingface.co/junnyu/roformer_chinese_small/resolve/main/config.json''', '''junnyu/roformer_chinese_base''': '''https://huggingface.co/junnyu/roformer_chinese_base/resolve/main/config.json''', '''junnyu/roformer_chinese_char_small''': ( '''https://huggingface.co/junnyu/roformer_chinese_char_small/resolve/main/config.json''' ), '''junnyu/roformer_chinese_char_base''': ( '''https://huggingface.co/junnyu/roformer_chinese_char_base/resolve/main/config.json''' ), '''junnyu/roformer_small_discriminator''': ( '''https://huggingface.co/junnyu/roformer_small_discriminator/resolve/main/config.json''' ), '''junnyu/roformer_small_generator''': ( '''https://huggingface.co/junnyu/roformer_small_generator/resolve/main/config.json''' ), # See all RoFormer models at https://huggingface.co/models?filter=roformer } class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: Optional[Any] = '''roformer''' def __init__( self : Tuple ,A_ : Optional[int]=5_0000 ,A_ : Tuple=None ,A_ : Optional[Any]=768 ,A_ : Dict=12 ,A_ : Optional[int]=12 ,A_ : Union[str, Any]=3072 ,A_ : Dict="gelu" ,A_ : Dict=0.1 ,A_ : List[Any]=0.1 ,A_ : List[Any]=1536 ,A_ : List[str]=2 ,A_ : Any=0.02 ,A_ : str=1e-12 ,A_ : Optional[int]=0 ,A_ : List[str]=False ,A_ : Tuple=True ,**A_ : List[str] ,) -> Dict: super().__init__(pad_token_id=A_ ,**A_ ) A = vocab_size A = hidden_size if embedding_size is None else embedding_size A = hidden_size A = num_hidden_layers A = num_attention_heads A = hidden_act A = intermediate_size A = hidden_dropout_prob A = attention_probs_dropout_prob A = max_position_embeddings A = type_vocab_size A = initializer_range A = layer_norm_eps A = rotary_value A = use_cache class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' @property def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": A = {0: 'batch', 1: 'choice', 2: 'sequence'} else: A = {0: 'batch', 1: 'sequence'} A = {0: 'batch', 1: 'sequence'} return OrderedDict( [ ('input_ids', dynamic_axis), ('attention_mask', dynamic_axis), ('token_type_ids', dynamic_axis), ] )
74
1
"""simple docstring""" # Usage: # ./gen-card-facebook-wmt19.py import os from pathlib import Path def _snake_case ( snake_case__ : Optional[Any] , snake_case__ : Any , snake_case__ : Dict ): A = { 'en': 'Machine learning is great, isn\'t it?', 'ru': 'Машинное обучение - это здорово, не так ли?', 'de': 'Maschinelles Lernen ist großartig, oder?', } # BLUE scores as follows: # "pair": [fairseq, transformers] A = { 'ru-en': ['[41.3](http://matrix.statmt.org/matrix/output/1907?run_id=6937)', '39.20'], 'en-ru': ['[36.4](http://matrix.statmt.org/matrix/output/1914?run_id=6724)', '33.47'], 'en-de': ['[43.1](http://matrix.statmt.org/matrix/output/1909?run_id=6862)', '42.83'], 'de-en': ['[42.3](http://matrix.statmt.org/matrix/output/1902?run_id=6750)', '41.35'], } A = F'{src_lang}-{tgt_lang}' A = F'\n---\nlanguage: \n- {src_lang}\n- {tgt_lang}\nthumbnail:\ntags:\n- translation\n- wmt19\n- facebook\nlicense: apache-2.0\ndatasets:\n- wmt19\nmetrics:\n- bleu\n---\n\n# FSMT\n\n## Model description\n\nThis is a ported version of [fairseq wmt19 transformer](https://github.com/pytorch/fairseq/blob/master/examples/wmt19/README.md) for {src_lang}-{tgt_lang}.\n\nFor more details, please see, [Facebook FAIR\'s WMT19 News Translation Task Submission](https://arxiv.org/abs/1907.06616).\n\nThe abbreviation FSMT stands for FairSeqMachineTranslation\n\nAll four models are available:\n\n* [wmt19-en-ru](https://huggingface.co/facebook/wmt19-en-ru)\n* [wmt19-ru-en](https://huggingface.co/facebook/wmt19-ru-en)\n* [wmt19-en-de](https://huggingface.co/facebook/wmt19-en-de)\n* [wmt19-de-en](https://huggingface.co/facebook/wmt19-de-en)\n\n## Intended uses & limitations\n\n#### How to use\n\n```python\nfrom transformers import FSMTForConditionalGeneration, FSMTTokenizer\nmname = "facebook/wmt19-{src_lang}-{tgt_lang}"\ntokenizer = FSMTTokenizer.from_pretrained(mname)\nmodel = FSMTForConditionalGeneration.from_pretrained(mname)\n\ninput = "{texts[src_lang]}"\ninput_ids = tokenizer.encode(input, return_tensors="pt")\noutputs = model.generate(input_ids)\ndecoded = tokenizer.decode(outputs[0], skip_special_tokens=True)\nprint(decoded) # {texts[tgt_lang]}\n\n```\n\n#### Limitations and bias\n\n- The original (and this ported model) doesn\'t seem to handle well inputs with repeated sub-phrases, [content gets truncated](https://discuss.huggingface.co/t/issues-with-translating-inputs-containing-repeated-phrases/981)\n\n## Training data\n\nPretrained weights were left identical to the original model released by fairseq. For more details, please, see the [paper](https://arxiv.org/abs/1907.06616).\n\n## Eval results\n\npair | fairseq | transformers\n-------|---------|----------\n{pair} | {scores[pair][0]} | {scores[pair][1]}\n\nThe score is slightly below the score reported by `fairseq`, since `transformers`` currently doesn\'t support:\n- model ensemble, therefore the best performing checkpoint was ported (``model4.pt``).\n- re-ranking\n\nThe score was calculated using this code:\n\n```bash\ngit clone https://github.com/huggingface/transformers\ncd transformers\nexport PAIR={pair}\nexport DATA_DIR=data/$PAIR\nexport SAVE_DIR=data/$PAIR\nexport BS=8\nexport NUM_BEAMS=15\nmkdir -p $DATA_DIR\nsacrebleu -t wmt19 -l $PAIR --echo src > $DATA_DIR/val.source\nsacrebleu -t wmt19 -l $PAIR --echo ref > $DATA_DIR/val.target\necho $PAIR\nPYTHONPATH="src:examples/seq2seq" python examples/seq2seq/run_eval.py facebook/wmt19-$PAIR $DATA_DIR/val.source $SAVE_DIR/test_translations.txt --reference_path $DATA_DIR/val.target --score_path $SAVE_DIR/test_bleu.json --bs $BS --task translation --num_beams $NUM_BEAMS\n```\nnote: fairseq reports using a beam of 50, so you should get a slightly higher score if re-run with `--num_beams 50`.\n\n## Data Sources\n\n- [training, etc.](http://www.statmt.org/wmt19/)\n- [test set](http://matrix.statmt.org/test_sets/newstest2019.tgz?1556572561)\n\n\n### BibTeX entry and citation info\n\n```bibtex\n@inproceedings{{...,\n year={{2020}},\n title={{Facebook FAIR\'s WMT19 News Translation Task Submission}},\n author={{Ng, Nathan and Yee, Kyra and Baevski, Alexei and Ott, Myle and Auli, Michael and Edunov, Sergey}},\n booktitle={{Proc. of WMT}},\n}}\n```\n\n\n## TODO\n\n- port model ensemble (fairseq uses 4 model checkpoints)\n\n' os.makedirs(snake_case__ , exist_ok=snake_case__ ) A = os.path.join(snake_case__ , 'README.md' ) print(F'Generating {path}' ) with open(snake_case__ , 'w' , encoding='utf-8' ) as f: f.write(snake_case__ ) # make sure we are under the root of the project _lowercase = Path(__file__).resolve().parent.parent.parent _lowercase = repo_dir / '''model_cards''' for model_name in ["wmt19-ru-en", "wmt19-en-ru", "wmt19-en-de", "wmt19-de-en"]: _lowercase , _lowercase , _lowercase = model_name.split('''-''') _lowercase = model_cards_dir / '''facebook''' / model_name write_model_card(model_card_dir, src_lang=src_lang, tgt_lang=tgt_lang)
74
"""simple docstring""" import argparse import torch from torch import nn from transformers import MBartConfig, MBartForConditionalGeneration def _snake_case ( snake_case__ : Dict ): A = [ 'encoder.version', 'decoder.version', 'model.encoder.version', 'model.decoder.version', '_float_tensor', 'decoder.output_projection.weight', ] for k in ignore_keys: state_dict.pop(snake_case__ , snake_case__ ) def _snake_case ( snake_case__ : int ): A , A = emb.weight.shape A = nn.Linear(snake_case__ , snake_case__ , bias=snake_case__ ) A = emb.weight.data return lin_layer def _snake_case ( snake_case__ : List[str] , snake_case__ : Any="facebook/mbart-large-en-ro" , snake_case__ : Optional[int]=False , snake_case__ : List[str]=False ): A = torch.load(snake_case__ , map_location='cpu' )['model'] remove_ignore_keys_(snake_case__ ) A = state_dict['encoder.embed_tokens.weight'].shape[0] A = MBartConfig.from_pretrained(snake_case__ , vocab_size=snake_case__ ) if mbart_aa and finetuned: A = 'relu' A = state_dict['decoder.embed_tokens.weight'] A = MBartForConditionalGeneration(snake_case__ ) model.model.load_state_dict(snake_case__ ) if finetuned: A = make_linear_from_emb(model.model.shared ) return model if __name__ == "__main__": _lowercase = argparse.ArgumentParser() # Required parameters parser.add_argument( '''fairseq_path''', type=str, help='''bart.large, bart.large.cnn or a path to a model.pt on local filesystem.''' ) parser.add_argument('''pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') parser.add_argument( '''--hf_config''', default='''facebook/mbart-large-cc25''', type=str, help='''Which huggingface architecture to use: mbart-large''', ) parser.add_argument('''--mbart_50''', action='''store_true''', help='''whether the model is mMART-50 checkpoint''') parser.add_argument('''--finetuned''', action='''store_true''', help='''whether the model is a fine-tuned checkpoint''') _lowercase = parser.parse_args() _lowercase = convert_fairseq_mbart_checkpoint_from_disk( args.fairseq_path, hf_config_path=args.hf_config, finetuned=args.finetuned, mbart_aa=args.mbart_aa ) model.save_pretrained(args.pytorch_dump_folder_path)
74
1
"""simple docstring""" _lowercase = '''Tobias Carryer''' from time import time class lowerCAmelCase_ : '''simple docstring''' def __init__( self : Optional[Any] ,A_ : Optional[int] ,A_ : Any ,A_ : Union[str, Any] ,A_ : Dict=int(time() ) ) -> str: # noqa: B008 A = multiplier A = increment A = modulo A = seed def _SCREAMING_SNAKE_CASE ( self : str ) -> Optional[Any]: A = (self.multiplier * self.seed + self.increment) % self.modulo return self.seed if __name__ == "__main__": # Show the LCG in action. _lowercase = LinearCongruentialGenerator(1_66_45_25, 10_13_90_42_23, 2 << 31) while True: print(lcg.next_number())
74
"""simple docstring""" import argparse import struct import unittest class lowerCAmelCase_ : '''simple docstring''' def __init__( self : Tuple ,A_ : bytes ) -> None: A = data # Initialize hash values A = [ 0X6_A_0_9_E_6_6_7, 0XB_B_6_7_A_E_8_5, 0X3_C_6_E_F_3_7_2, 0XA_5_4_F_F_5_3_A, 0X5_1_0_E_5_2_7_F, 0X9_B_0_5_6_8_8_C, 0X1_F_8_3_D_9_A_B, 0X5_B_E_0_C_D_1_9, ] # Initialize round constants A = [ 0X4_2_8_A_2_F_9_8, 0X7_1_3_7_4_4_9_1, 0XB_5_C_0_F_B_C_F, 0XE_9_B_5_D_B_A_5, 0X3_9_5_6_C_2_5_B, 0X5_9_F_1_1_1_F_1, 0X9_2_3_F_8_2_A_4, 0XA_B_1_C_5_E_D_5, 0XD_8_0_7_A_A_9_8, 0X1_2_8_3_5_B_0_1, 0X2_4_3_1_8_5_B_E, 0X5_5_0_C_7_D_C_3, 0X7_2_B_E_5_D_7_4, 0X8_0_D_E_B_1_F_E, 0X9_B_D_C_0_6_A_7, 0XC_1_9_B_F_1_7_4, 0XE_4_9_B_6_9_C_1, 0XE_F_B_E_4_7_8_6, 0X0_F_C_1_9_D_C_6, 0X2_4_0_C_A_1_C_C, 0X2_D_E_9_2_C_6_F, 0X4_A_7_4_8_4_A_A, 0X5_C_B_0_A_9_D_C, 0X7_6_F_9_8_8_D_A, 0X9_8_3_E_5_1_5_2, 0XA_8_3_1_C_6_6_D, 0XB_0_0_3_2_7_C_8, 0XB_F_5_9_7_F_C_7, 0XC_6_E_0_0_B_F_3, 0XD_5_A_7_9_1_4_7, 0X0_6_C_A_6_3_5_1, 0X1_4_2_9_2_9_6_7, 0X2_7_B_7_0_A_8_5, 0X2_E_1_B_2_1_3_8, 0X4_D_2_C_6_D_F_C, 0X5_3_3_8_0_D_1_3, 0X6_5_0_A_7_3_5_4, 0X7_6_6_A_0_A_B_B, 0X8_1_C_2_C_9_2_E, 0X9_2_7_2_2_C_8_5, 0XA_2_B_F_E_8_A_1, 0XA_8_1_A_6_6_4_B, 0XC_2_4_B_8_B_7_0, 0XC_7_6_C_5_1_A_3, 0XD_1_9_2_E_8_1_9, 0XD_6_9_9_0_6_2_4, 0XF_4_0_E_3_5_8_5, 0X1_0_6_A_A_0_7_0, 0X1_9_A_4_C_1_1_6, 0X1_E_3_7_6_C_0_8, 0X2_7_4_8_7_7_4_C, 0X3_4_B_0_B_C_B_5, 0X3_9_1_C_0_C_B_3, 0X4_E_D_8_A_A_4_A, 0X5_B_9_C_C_A_4_F, 0X6_8_2_E_6_F_F_3, 0X7_4_8_F_8_2_E_E, 0X7_8_A_5_6_3_6_F, 0X8_4_C_8_7_8_1_4, 0X8_C_C_7_0_2_0_8, 0X9_0_B_E_F_F_F_A, 0XA_4_5_0_6_C_E_B, 0XB_E_F_9_A_3_F_7, 0XC_6_7_1_7_8_F_2, ] A = self.preprocessing(self.data ) self.final_hash() @staticmethod def _SCREAMING_SNAKE_CASE ( A_ : bytes ) -> bytes: A = B'\x80' + (B'\x00' * (63 - (len(A_ ) + 8) % 64)) A = struct.pack('>Q' ,(len(A_ ) * 8) ) return data + padding + big_endian_integer def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> None: # Convert into blocks of 64 bytes A = [ self.preprocessed_data[x : x + 64] for x in range(0 ,len(self.preprocessed_data ) ,64 ) ] for block in self.blocks: # Convert the given block into a list of 4 byte integers A = list(struct.unpack('>16L' ,A_ ) ) # add 48 0-ed integers words += [0] * 48 A , A , A , A , A , A , A , A = self.hashes for index in range(0 ,64 ): if index > 15: # modify the zero-ed indexes at the end of the array A = ( self.ror(words[index - 15] ,7 ) ^ self.ror(words[index - 15] ,18 ) ^ (words[index - 15] >> 3) ) A = ( self.ror(words[index - 2] ,17 ) ^ self.ror(words[index - 2] ,19 ) ^ (words[index - 2] >> 10) ) A = ( words[index - 16] + sa + words[index - 7] + sa ) % 0X1_0_0_0_0_0_0_0_0 # Compression A = self.ror(A_ ,6 ) ^ self.ror(A_ ,11 ) ^ self.ror(A_ ,25 ) A = (e & f) ^ ((~e & 0XF_F_F_F_F_F_F_F) & g) A = ( h + sa + ch + self.round_constants[index] + words[index] ) % 0X1_0_0_0_0_0_0_0_0 A = self.ror(A_ ,2 ) ^ self.ror(A_ ,13 ) ^ self.ror(A_ ,22 ) A = (a & b) ^ (a & c) ^ (b & c) A = (sa + maj) % 0X1_0_0_0_0_0_0_0_0 A , A , A , A , A , A , A , A = ( g, f, e, ((d + tempa) % 0X1_0_0_0_0_0_0_0_0), c, b, a, ((tempa + tempa) % 0X1_0_0_0_0_0_0_0_0), ) A = [a, b, c, d, e, f, g, h] # Modify final values A = [ ((element + mutated_hash_values[index]) % 0X1_0_0_0_0_0_0_0_0) for index, element in enumerate(self.hashes ) ] A = ''.join([hex(A_ )[2:].zfill(8 ) for value in self.hashes] ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ,A_ : int ,A_ : int ) -> int: return 0XF_F_F_F_F_F_F_F & (value << (32 - rotations)) | (value >> rotations) class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> None: import hashlib A = bytes('Test String' ,'utf-8' ) self.assertEqual(SHAaaa(A_ ).hash ,hashlib.shaaaa(A_ ).hexdigest() ) def _snake_case ( ): import doctest doctest.testmod() A = argparse.ArgumentParser() parser.add_argument( '-s' , '--string' , dest='input_string' , default='Hello World!! Welcome to Cryptography' , help='Hash the string' , ) parser.add_argument( '-f' , '--file' , dest='input_file' , help='Hash contents of a file' ) A = parser.parse_args() A = args.input_string # hash input should be a bytestring if args.input_file: with open(args.input_file , 'rb' ) as f: A = f.read() else: A = bytes(snake_case__ , 'utf-8' ) print(SHAaaa(snake_case__ ).hash ) if __name__ == "__main__": main()
74
1
"""simple docstring""" import warnings from ...utils import is_sklearn_available, requires_backends if is_sklearn_available(): from scipy.stats import pearsonr, spearmanr from sklearn.metrics import fa_score, matthews_corrcoef _lowercase = ( '''This metric will be removed from the library soon, metrics should be handled with the 🤗 Evaluate ''' '''library. You can have a look at this example script for pointers: ''' '''https://github.com/huggingface/transformers/blob/main/examples/pytorch/text-classification/run_glue.py''' ) def _snake_case ( snake_case__ : Dict , snake_case__ : List[str] ): warnings.warn(snake_case__ , snake_case__ ) requires_backends(snake_case__ , 'sklearn' ) return (preds == labels).mean() def _snake_case ( snake_case__ : Any , snake_case__ : Union[str, Any] ): warnings.warn(snake_case__ , snake_case__ ) requires_backends(snake_case__ , 'sklearn' ) A = simple_accuracy(snake_case__ , snake_case__ ) A = fa_score(y_true=snake_case__ , y_pred=snake_case__ ) return { "acc": acc, "f1": fa, "acc_and_f1": (acc + fa) / 2, } def _snake_case ( snake_case__ : str , snake_case__ : Union[str, Any] ): warnings.warn(snake_case__ , snake_case__ ) requires_backends(snake_case__ , 'sklearn' ) A = pearsonr(snake_case__ , snake_case__ )[0] A = spearmanr(snake_case__ , snake_case__ )[0] return { "pearson": pearson_corr, "spearmanr": spearman_corr, "corr": (pearson_corr + spearman_corr) / 2, } def _snake_case ( snake_case__ : Any , snake_case__ : Optional[int] , snake_case__ : str ): warnings.warn(snake_case__ , snake_case__ ) requires_backends(snake_case__ , 'sklearn' ) assert len(snake_case__ ) == len(snake_case__ ), F'Predictions and labels have mismatched lengths {len(snake_case__ )} and {len(snake_case__ )}' if task_name == "cola": return {"mcc": matthews_corrcoef(snake_case__ , snake_case__ )} elif task_name == "sst-2": return {"acc": simple_accuracy(snake_case__ , snake_case__ )} elif task_name == "mrpc": return acc_and_fa(snake_case__ , snake_case__ ) elif task_name == "sts-b": return pearson_and_spearman(snake_case__ , snake_case__ ) elif task_name == "qqp": return acc_and_fa(snake_case__ , snake_case__ ) elif task_name == "mnli": return {"mnli/acc": simple_accuracy(snake_case__ , snake_case__ )} elif task_name == "mnli-mm": return {"mnli-mm/acc": simple_accuracy(snake_case__ , snake_case__ )} elif task_name == "qnli": return {"acc": simple_accuracy(snake_case__ , snake_case__ )} elif task_name == "rte": return {"acc": simple_accuracy(snake_case__ , snake_case__ )} elif task_name == "wnli": return {"acc": simple_accuracy(snake_case__ , snake_case__ )} elif task_name == "hans": return {"acc": simple_accuracy(snake_case__ , snake_case__ )} else: raise KeyError(snake_case__ ) def _snake_case ( snake_case__ : Optional[int] , snake_case__ : Union[str, Any] , snake_case__ : Optional[Any] ): warnings.warn(snake_case__ , snake_case__ ) requires_backends(snake_case__ , 'sklearn' ) if len(snake_case__ ) != len(snake_case__ ): raise ValueError(F'Predictions and labels have mismatched lengths {len(snake_case__ )} and {len(snake_case__ )}' ) if task_name == "xnli": return {"acc": simple_accuracy(snake_case__ , snake_case__ )} else: raise KeyError(snake_case__ )
74
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) _lowercase = {'''configuration_deit''': ['''DEIT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''DeiTConfig''', '''DeiTOnnxConfig''']} try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase = ['''DeiTFeatureExtractor'''] _lowercase = ['''DeiTImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase = [ '''DEIT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''DeiTForImageClassification''', '''DeiTForImageClassificationWithTeacher''', '''DeiTForMaskedImageModeling''', '''DeiTModel''', '''DeiTPreTrainedModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase = [ '''TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFDeiTForImageClassification''', '''TFDeiTForImageClassificationWithTeacher''', '''TFDeiTForMaskedImageModeling''', '''TFDeiTModel''', '''TFDeiTPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_deit import DEIT_PRETRAINED_CONFIG_ARCHIVE_MAP, DeiTConfig, DeiTOnnxConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_deit import DeiTFeatureExtractor from .image_processing_deit import DeiTImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_deit import ( DEIT_PRETRAINED_MODEL_ARCHIVE_LIST, DeiTForImageClassification, DeiTForImageClassificationWithTeacher, DeiTForMaskedImageModeling, DeiTModel, DeiTPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_deit import ( TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST, TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher, TFDeiTForMaskedImageModeling, TFDeiTModel, TFDeiTPreTrainedModel, ) else: import sys _lowercase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
74
1
"""simple docstring""" from typing import Callable, Optional, Union from ...configuration_utils import PretrainedConfig from ...utils import logging _lowercase = logging.get_logger(__name__) _lowercase = { '''microsoft/xprophetnet-large-wiki100-cased''': ( '''https://huggingface.co/microsoft/xprophetnet-large-wiki100-cased/resolve/main/config.json''' ), } class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: int = '''xlm-prophetnet''' _lowerCamelCase: List[str] = ['''past_key_values'''] _lowerCamelCase: int = { '''num_attention_heads''': '''num_encoder_attention_heads''', } def __init__( self : Tuple ,A_ : Optional[float] = 0.1 ,A_ : Optional[Union[str, Callable]] = "gelu" ,A_ : Optional[int] = 3_0522 ,A_ : Optional[int] = 1024 ,A_ : Optional[int] = 4096 ,A_ : Optional[int] = 12 ,A_ : Optional[int] = 16 ,A_ : Optional[int] = 4096 ,A_ : Optional[int] = 12 ,A_ : Optional[int] = 16 ,A_ : Optional[float] = 0.1 ,A_ : Optional[float] = 0.1 ,A_ : Optional[int] = 512 ,A_ : Optional[float] = 0.02 ,A_ : Optional[bool] = True ,A_ : Optional[bool] = True ,A_ : Optional[int] = 0 ,A_ : Optional[int] = 2 ,A_ : Optional[int] = 32 ,A_ : Optional[int] = 128 ,A_ : Optional[bool] = False ,A_ : Optional[float] = 0.0 ,A_ : Optional[bool] = True ,A_ : Optional[int] = 0 ,A_ : Optional[int] = 1 ,A_ : Optional[int] = 2 ,**A_ : List[str] ,) -> int: A = vocab_size A = hidden_size A = encoder_ffn_dim A = num_encoder_layers A = num_encoder_attention_heads A = decoder_ffn_dim A = num_decoder_layers A = num_decoder_attention_heads A = max_position_embeddings A = init_std # Normal(0, this parameter) A = activation_function # parameters for xlmprophetnet A = ngram A = num_buckets A = relative_max_distance A = disable_ngram_loss A = eps # 3 Types of Dropout A = attention_dropout A = activation_dropout A = dropout A = use_cache super().__init__( pad_token_id=A_ ,bos_token_id=A_ ,eos_token_id=A_ ,is_encoder_decoder=A_ ,add_cross_attention=A_ ,decoder_start_token_id=A_ ,**A_ ,) @property def _SCREAMING_SNAKE_CASE ( self : int ) -> int: return self.num_encoder_layers + self.num_decoder_layers @num_hidden_layers.setter def _SCREAMING_SNAKE_CASE ( self : str ,A_ : Any ) -> Union[str, Any]: raise NotImplementedError( 'This model does not support the setting of `num_hidden_layers`. Please set `num_encoder_layers` and' ' `num_decoder_layers`.' )
74
"""simple docstring""" from __future__ import annotations import requests def _snake_case ( snake_case__ : str ): A = F'https://hacker-news.firebaseio.com/v0/item/{story_id}.json?print=pretty' return requests.get(snake_case__ ).json() def _snake_case ( snake_case__ : int = 10 ): A = 'https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty' A = requests.get(snake_case__ ).json()[:max_stories] return [get_hackernews_story(snake_case__ ) for story_id in story_ids] def _snake_case ( snake_case__ : int = 10 ): A = hackernews_top_stories(snake_case__ ) return "\n".join('* [{title}]({url})'.format(**snake_case__ ) for story in stories ) if __name__ == "__main__": print(hackernews_top_stories_as_markdown())
74
1