code
stringlengths
86
54.5k
code_codestyle
int64
0
371
style_context
stringlengths
87
49.2k
style_context_codestyle
int64
0
349
label
int64
0
1
"""simple docstring""" from typing import List, Optional import numpy as np from ...processing_utils import ProcessorMixin from ...utils import to_numpy class SCREAMING_SNAKE_CASE__ ( UpperCAmelCase__ ): __lowerCAmelCase : Union[str, Any] = 'EncodecFeatureExtractor' __lowerCAmelCase : List[Any] = ('T5Tokenizer', 'T5TokenizerFast') def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Any: '''simple docstring''' super().__init__(__lowerCAmelCase , __lowerCAmelCase ) UpperCAmelCase : Optional[Any] = self.feature_extractor UpperCAmelCase : Union[str, Any] = False def SCREAMING_SNAKE_CASE ( self , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=True ) -> int: '''simple docstring''' return self.tokenizer.get_decoder_prompt_ids(task=__lowerCAmelCase , language=__lowerCAmelCase , no_timestamps=__lowerCAmelCase ) def __call__( self , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) -> List[str]: '''simple docstring''' if self._in_target_context_manager: return self.current_processor(*__lowerCAmelCase , **__lowerCAmelCase ) UpperCAmelCase : Optional[int] = kwargs.pop("""audio""" , __lowerCAmelCase ) UpperCAmelCase : List[Any] = kwargs.pop("""sampling_rate""" , __lowerCAmelCase ) UpperCAmelCase : Dict = kwargs.pop("""text""" , __lowerCAmelCase ) if len(__lowerCAmelCase ) > 0: UpperCAmelCase : Optional[int] = args[0] UpperCAmelCase : List[str] = args[1:] if audio is None and text is None: raise ValueError("""You need to specify either an `audio` or `text` input to process.""" ) if text is not None: UpperCAmelCase : Any = self.tokenizer(__lowerCAmelCase , **__lowerCAmelCase ) if audio is not None: UpperCAmelCase : List[Any] = self.feature_extractor(__lowerCAmelCase , *__lowerCAmelCase , sampling_rate=__lowerCAmelCase , **__lowerCAmelCase ) if audio is None: return inputs elif text is None: return audio_inputs else: UpperCAmelCase : Union[str, Any] = audio_inputs["""input_values"""] if "padding_mask" in audio_inputs: UpperCAmelCase : List[Any] = audio_inputs["""padding_mask"""] return inputs def SCREAMING_SNAKE_CASE ( self , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) -> Any: '''simple docstring''' UpperCAmelCase : Any = kwargs.pop("""audio""" , __lowerCAmelCase ) UpperCAmelCase : Optional[int] = kwargs.pop("""padding_mask""" , __lowerCAmelCase ) if len(__lowerCAmelCase ) > 0: UpperCAmelCase : Any = args[0] UpperCAmelCase : List[Any] = args[1:] if audio_values is not None: return self._decode_audio(__lowerCAmelCase , padding_mask=__lowerCAmelCase ) else: return self.tokenizer.batch_decode(*__lowerCAmelCase , **__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) -> List[str]: '''simple docstring''' return self.tokenizer.decode(*__lowerCAmelCase , **__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None ) -> Dict: '''simple docstring''' UpperCAmelCase : Optional[int] = to_numpy(__lowerCAmelCase ) UpperCAmelCase , UpperCAmelCase , UpperCAmelCase : Optional[int] = audio_values.shape if padding_mask is None: return list(__lowerCAmelCase ) UpperCAmelCase : Any = to_numpy(__lowerCAmelCase ) # match the sequence length of the padding mask to the generated audio arrays by padding with the **non-padding** # token (so that the generated audio values are **not** treated as padded tokens) UpperCAmelCase : Any = seq_len - padding_mask.shape[-1] UpperCAmelCase : Union[str, Any] = 1 - self.feature_extractor.padding_value UpperCAmelCase : Dict = np.pad(__lowerCAmelCase , ((0, 0), (0, difference)) , """constant""" , constant_values=__lowerCAmelCase ) UpperCAmelCase : Any = audio_values.tolist() for i in range(__lowerCAmelCase ): UpperCAmelCase : str = np.asarray(audio_values[i] )[ padding_mask[i][None, :] != self.feature_extractor.padding_value ] UpperCAmelCase : Optional[Any] = sliced_audio.reshape(__lowerCAmelCase , -1 ) return audio_values
109
import logging import os import sys import warnings from dataclasses import dataclass, field from random import randint from typing import Optional import datasets import evaluate import numpy as np from datasets import DatasetDict, load_dataset import transformers from transformers import ( AutoConfig, AutoFeatureExtractor, AutoModelForAudioClassification, HfArgumentParser, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import get_last_checkpoint from transformers.utils import check_min_version, send_example_telemetry from transformers.utils.versions import require_version _a = logging.getLogger(__name__) # Will error if the minimal version of Transformers is not installed. Remove at your own risks. check_min_version("4.31.0") require_version("datasets>=1.14.0", "To fix: pip install -r examples/pytorch/audio-classification/requirements.txt") def lowerCAmelCase__(__snake_case ,__snake_case ,__snake_case = 16000 ) -> Any: '''simple docstring''' lowerCamelCase__ = int(round(sample_rate * max_length ) ) if len(__snake_case ) <= sample_length: return wav lowerCamelCase__ = randint(0 ,len(__snake_case ) - sample_length - 1 ) return wav[random_offset : random_offset + sample_length] @dataclass class __A : '''simple docstring''' lowerCAmelCase_ = field(default=lowerCAmelCase , metadata={"""help""": """Name of a dataset from the datasets package"""} ) lowerCAmelCase_ = field( default=lowerCAmelCase , metadata={"""help""": """The configuration name of the dataset to use (via the datasets library)."""} ) lowerCAmelCase_ = field( default=lowerCAmelCase , metadata={"""help""": """A file containing the training audio paths and labels."""} ) lowerCAmelCase_ = field( default=lowerCAmelCase , metadata={"""help""": """A file containing the validation audio paths and labels."""} ) lowerCAmelCase_ = field( default="""train""" , metadata={ """help""": """The name of the training data set split to use (via the datasets library). Defaults to 'train'""" } , ) lowerCAmelCase_ = field( default="""validation""" , metadata={ """help""": ( """The name of the training data set split to use (via the datasets library). Defaults to 'validation'""" ) } , ) lowerCAmelCase_ = field( default="""audio""" , metadata={"""help""": """The name of the dataset column containing the audio data. Defaults to 'audio'"""} , ) lowerCAmelCase_ = field( default="""label""" , metadata={"""help""": """The name of the dataset column containing the labels. Defaults to 'label'"""} ) lowerCAmelCase_ = field( default=lowerCAmelCase , metadata={ """help""": ( """For debugging purposes or quicker training, truncate the number of training examples to this """ """value if set.""" ) } , ) lowerCAmelCase_ = field( default=lowerCAmelCase , metadata={ """help""": ( """For debugging purposes or quicker training, truncate the number of evaluation examples to this """ """value if set.""" ) } , ) lowerCAmelCase_ = field( default=20 , metadata={"""help""": """Audio clips will be randomly cut to this length during training if the value is set."""} , ) @dataclass class __A : '''simple docstring''' lowerCAmelCase_ = field( default="""facebook/wav2vec2-base""" , metadata={"""help""": """Path to pretrained model or model identifier from huggingface.co/models"""} , ) lowerCAmelCase_ = field( default=lowerCAmelCase , metadata={"""help""": """Pretrained config name or path if not the same as model_name"""} ) lowerCAmelCase_ = field( default=lowerCAmelCase , metadata={"""help""": """Where do you want to store the pretrained models downloaded from the Hub"""} ) lowerCAmelCase_ = field( default="""main""" , metadata={"""help""": """The specific model version to use (can be a branch name, tag name or commit id)."""} , ) lowerCAmelCase_ = field( default=lowerCAmelCase , metadata={"""help""": """Name or path of preprocessor config."""} ) lowerCAmelCase_ = field( default=lowerCAmelCase , metadata={"""help""": """Whether to freeze the feature encoder layers of the model."""} ) lowerCAmelCase_ = field( default=lowerCAmelCase , metadata={"""help""": """Whether to generate an attention mask in the feature extractor."""} ) lowerCAmelCase_ = field( default=lowerCAmelCase , metadata={ """help""": ( """Will use the token generated when running `huggingface-cli login` (necessary to use this script """ """with private models).""" ) } , ) lowerCAmelCase_ = field( default=lowerCAmelCase , metadata={"""help""": """Whether to freeze the feature extractor layers of the model."""} ) lowerCAmelCase_ = field( default=lowerCAmelCase , metadata={"""help""": """Will enable to load a pretrained model whose head dimensions are different."""} , ) def __lowerCamelCase ( self ): '''simple docstring''' if not self.freeze_feature_extractor and self.freeze_feature_encoder: warnings.warn( '''The argument `--freeze_feature_extractor` is deprecated and ''' '''will be removed in a future version. Use `--freeze_feature_encoder`''' '''instead. Setting `freeze_feature_encoder==True`.''' , __lowerCAmelCase , ) if self.freeze_feature_extractor and not self.freeze_feature_encoder: raise ValueError( '''The argument `--freeze_feature_extractor` is deprecated and ''' '''should not be used in combination with `--freeze_feature_encoder`.''' '''Only make use of `--freeze_feature_encoder`.''' ) def lowerCAmelCase__() -> Optional[int]: '''simple docstring''' lowerCamelCase__ = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith('''.json''' ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ = parser.parse_args_into_dataclasses() # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The # information sent is the one passed as arguments along with your Python/PyTorch versions. send_example_telemetry('''run_audio_classification''' ,__snake_case ,__snake_case ) # Setup logging logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''' ,datefmt='''%m/%d/%Y %H:%M:%S''' ,handlers=[logging.StreamHandler(sys.stdout )] ,) if training_args.should_log: # The default of training_args.log_level is passive, so we set log level at info here to have that default. transformers.utils.logging.set_verbosity_info() lowerCamelCase__ = training_args.get_process_log_level() logger.setLevel(__snake_case ) transformers.utils.logging.set_verbosity(__snake_case ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Log on each process the small summary: logger.warning( F'Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu} ' + F'distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}' ) logger.info(F'Training/evaluation parameters {training_args}' ) # Set seed before initializing model. set_seed(training_args.seed ) # Detecting last checkpoint. lowerCamelCase__ = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: lowerCamelCase__ = get_last_checkpoint(training_args.output_dir ) if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0: raise ValueError( F'Output directory ({training_args.output_dir}) already exists and is not empty. ' '''Use --overwrite_output_dir to train from scratch.''' ) elif last_checkpoint is not None and training_args.resume_from_checkpoint is None: logger.info( F'Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change ' '''the `--output_dir` or add `--overwrite_output_dir` to train from scratch.''' ) # Initialize our dataset and prepare it for the audio classification task. lowerCamelCase__ = DatasetDict() lowerCamelCase__ = load_dataset( data_args.dataset_name ,data_args.dataset_config_name ,split=data_args.train_split_name ,use_auth_token=True if model_args.use_auth_token else None ,) lowerCamelCase__ = load_dataset( data_args.dataset_name ,data_args.dataset_config_name ,split=data_args.eval_split_name ,use_auth_token=True if model_args.use_auth_token else None ,) if data_args.audio_column_name not in raw_datasets["train"].column_names: raise ValueError( F'--audio_column_name {data_args.audio_column_name} not found in dataset \'{data_args.dataset_name}\'. ' '''Make sure to set `--audio_column_name` to the correct audio column - one of ''' F'{", ".join(raw_datasets["train"].column_names )}.' ) if data_args.label_column_name not in raw_datasets["train"].column_names: raise ValueError( F'--label_column_name {data_args.label_column_name} not found in dataset \'{data_args.dataset_name}\'. ' '''Make sure to set `--label_column_name` to the correct text column - one of ''' F'{", ".join(raw_datasets["train"].column_names )}.' ) # Setting `return_attention_mask=True` is the way to get a correctly masked mean-pooling over # transformer outputs in the classifier, but it doesn't always lead to better accuracy lowerCamelCase__ = AutoFeatureExtractor.from_pretrained( model_args.feature_extractor_name or model_args.model_name_or_path ,return_attention_mask=model_args.attention_mask ,cache_dir=model_args.cache_dir ,revision=model_args.model_revision ,use_auth_token=True if model_args.use_auth_token else None ,) # `datasets` takes care of automatically loading and resampling the audio, # so we just need to set the correct target sampling rate. lowerCamelCase__ = raw_datasets.cast_column( data_args.audio_column_name ,datasets.features.Audio(sampling_rate=feature_extractor.sampling_rate ) ) lowerCamelCase__ = feature_extractor.model_input_names[0] def train_transforms(__snake_case ): lowerCamelCase__ = [] for audio in batch[data_args.audio_column_name]: lowerCamelCase__ = random_subsample( audio['''array'''] ,max_length=data_args.max_length_seconds ,sample_rate=feature_extractor.sampling_rate ) subsampled_wavs.append(__snake_case ) lowerCamelCase__ = feature_extractor(__snake_case ,sampling_rate=feature_extractor.sampling_rate ) lowerCamelCase__ = {model_input_name: inputs.get(__snake_case )} lowerCamelCase__ = list(batch[data_args.label_column_name] ) return output_batch def val_transforms(__snake_case ): lowerCamelCase__ = [audio['''array'''] for audio in batch[data_args.audio_column_name]] lowerCamelCase__ = feature_extractor(__snake_case ,sampling_rate=feature_extractor.sampling_rate ) lowerCamelCase__ = {model_input_name: inputs.get(__snake_case )} lowerCamelCase__ = list(batch[data_args.label_column_name] ) return output_batch # Prepare label mappings. # We'll include these in the model's config to get human readable labels in the Inference API. lowerCamelCase__ = raw_datasets['''train'''].features[data_args.label_column_name].names lowerCamelCase__ , lowerCamelCase__ = {}, {} for i, label in enumerate(__snake_case ): lowerCamelCase__ = str(__snake_case ) lowerCamelCase__ = label # Load the accuracy metric from the datasets package lowerCamelCase__ = evaluate.load('''accuracy''' ) # Define our compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with # `predictions` and `label_ids` fields) and has to return a dictionary string to float. def compute_metrics(__snake_case ): lowerCamelCase__ = np.argmax(eval_pred.predictions ,axis=1 ) return metric.compute(predictions=__snake_case ,references=eval_pred.label_ids ) lowerCamelCase__ = AutoConfig.from_pretrained( model_args.config_name or model_args.model_name_or_path ,num_labels=len(__snake_case ) ,labelaid=__snake_case ,idalabel=__snake_case ,finetuning_task='''audio-classification''' ,cache_dir=model_args.cache_dir ,revision=model_args.model_revision ,use_auth_token=True if model_args.use_auth_token else None ,) lowerCamelCase__ = AutoModelForAudioClassification.from_pretrained( model_args.model_name_or_path ,from_tf=bool('''.ckpt''' in model_args.model_name_or_path ) ,config=__snake_case ,cache_dir=model_args.cache_dir ,revision=model_args.model_revision ,use_auth_token=True if model_args.use_auth_token else None ,ignore_mismatched_sizes=model_args.ignore_mismatched_sizes ,) # freeze the convolutional waveform encoder if model_args.freeze_feature_encoder: model.freeze_feature_encoder() if training_args.do_train: if data_args.max_train_samples is not None: lowerCamelCase__ = ( raw_datasets['''train'''].shuffle(seed=training_args.seed ).select(range(data_args.max_train_samples ) ) ) # Set the training transforms raw_datasets["train"].set_transform(__snake_case ,output_all_columns=__snake_case ) if training_args.do_eval: if data_args.max_eval_samples is not None: lowerCamelCase__ = ( raw_datasets['''eval'''].shuffle(seed=training_args.seed ).select(range(data_args.max_eval_samples ) ) ) # Set the validation transforms raw_datasets["eval"].set_transform(__snake_case ,output_all_columns=__snake_case ) # Initialize our trainer lowerCamelCase__ = Trainer( model=__snake_case ,args=__snake_case ,train_dataset=raw_datasets['''train'''] if training_args.do_train else None ,eval_dataset=raw_datasets['''eval'''] if training_args.do_eval else None ,compute_metrics=__snake_case ,tokenizer=__snake_case ,) # Training if training_args.do_train: lowerCamelCase__ = None if training_args.resume_from_checkpoint is not None: lowerCamelCase__ = training_args.resume_from_checkpoint elif last_checkpoint is not None: lowerCamelCase__ = last_checkpoint lowerCamelCase__ = trainer.train(resume_from_checkpoint=__snake_case ) trainer.save_model() trainer.log_metrics('''train''' ,train_result.metrics ) trainer.save_metrics('''train''' ,train_result.metrics ) trainer.save_state() # Evaluation if training_args.do_eval: lowerCamelCase__ = trainer.evaluate() trainer.log_metrics('''eval''' ,__snake_case ) trainer.save_metrics('''eval''' ,__snake_case ) # Write model card and (optionally) push to hub lowerCamelCase__ = { '''finetuned_from''': model_args.model_name_or_path, '''tasks''': '''audio-classification''', '''dataset''': data_args.dataset_name, '''tags''': ['''audio-classification'''], } if training_args.push_to_hub: trainer.push_to_hub(**__snake_case ) else: trainer.create_model_card(**__snake_case ) if __name__ == "__main__": main()
209
0
'''simple docstring''' def __SCREAMING_SNAKE_CASE ( _SCREAMING_SNAKE_CASE ): _snake_case = 1 _snake_case = 2 while i * i <= n: _snake_case = 0 while n % i == 0: n //= i multiplicity += 1 n_divisors *= multiplicity + 1 i += 1 if n > 1: n_divisors *= 2 return n_divisors def __SCREAMING_SNAKE_CASE ( ): _snake_case = 1 _snake_case = 1 while True: i += 1 t_num += i if count_divisors(_SCREAMING_SNAKE_CASE ) > 500: break return t_num if __name__ == "__main__": print(solution())
270
'''simple docstring''' import unittest from transformers import DebertaConfig, is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( DebertaForMaskedLM, DebertaForQuestionAnswering, DebertaForSequenceClassification, DebertaForTokenClassification, DebertaModel, ) from transformers.models.deberta.modeling_deberta import DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST class _lowerCAmelCase ( __snake_case ): '''simple docstring''' def __init__(self , UpperCAmelCase , UpperCAmelCase=13 , UpperCAmelCase=7 , UpperCAmelCase=True , UpperCAmelCase=True , UpperCAmelCase=True , UpperCAmelCase=True , UpperCAmelCase=99 , UpperCAmelCase=32 , UpperCAmelCase=5 , UpperCAmelCase=4 , UpperCAmelCase=37 , UpperCAmelCase="gelu" , UpperCAmelCase=0.1 , UpperCAmelCase=0.1 , UpperCAmelCase=512 , UpperCAmelCase=16 , UpperCAmelCase=2 , UpperCAmelCase=0.02 , UpperCAmelCase=False , UpperCAmelCase=True , UpperCAmelCase="None" , UpperCAmelCase=3 , UpperCAmelCase=4 , UpperCAmelCase=None , ) -> Optional[Any]: _snake_case = parent _snake_case = batch_size _snake_case = seq_length _snake_case = is_training _snake_case = use_input_mask _snake_case = use_token_type_ids _snake_case = use_labels _snake_case = vocab_size _snake_case = hidden_size _snake_case = num_hidden_layers _snake_case = num_attention_heads _snake_case = intermediate_size _snake_case = hidden_act _snake_case = hidden_dropout_prob _snake_case = attention_probs_dropout_prob _snake_case = max_position_embeddings _snake_case = type_vocab_size _snake_case = type_sequence_label_size _snake_case = initializer_range _snake_case = num_labels _snake_case = num_choices _snake_case = relative_attention _snake_case = position_biased_input _snake_case = pos_att_type _snake_case = scope def lowercase (self ) -> List[Any]: _snake_case = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _snake_case = None if self.use_input_mask: _snake_case = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) _snake_case = None if self.use_token_type_ids: _snake_case = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) _snake_case = None _snake_case = None _snake_case = None if self.use_labels: _snake_case = ids_tensor([self.batch_size] , self.type_sequence_label_size ) _snake_case = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) _snake_case = ids_tensor([self.batch_size] , self.num_choices ) _snake_case = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def lowercase (self ) -> int: return DebertaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , relative_attention=self.relative_attention , position_biased_input=self.position_biased_input , pos_att_type=self.pos_att_type , ) def lowercase (self ) -> int: _snake_case = self.get_config() _snake_case = 300 return config def lowercase (self , UpperCAmelCase ) -> Dict: self.parent.assertListEqual(list(result.loss.size() ) , [] ) def lowercase (self , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) -> Optional[Any]: _snake_case = DebertaModel(config=UpperCAmelCase ) model.to(UpperCAmelCase ) model.eval() _snake_case = model(UpperCAmelCase , attention_mask=UpperCAmelCase , token_type_ids=UpperCAmelCase )[0] _snake_case = model(UpperCAmelCase , token_type_ids=UpperCAmelCase )[0] _snake_case = model(UpperCAmelCase )[0] self.parent.assertListEqual(list(sequence_output.size() ) , [self.batch_size, self.seq_length, self.hidden_size] ) def lowercase (self , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) -> str: _snake_case = DebertaForMaskedLM(config=UpperCAmelCase ) model.to(UpperCAmelCase ) model.eval() _snake_case = model(UpperCAmelCase , attention_mask=UpperCAmelCase , token_type_ids=UpperCAmelCase , labels=UpperCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def lowercase (self , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) -> List[str]: _snake_case = self.num_labels _snake_case = DebertaForSequenceClassification(UpperCAmelCase ) model.to(UpperCAmelCase ) model.eval() _snake_case = model(UpperCAmelCase , attention_mask=UpperCAmelCase , token_type_ids=UpperCAmelCase , labels=UpperCAmelCase ) self.parent.assertListEqual(list(result.logits.size() ) , [self.batch_size, self.num_labels] ) self.check_loss_output(UpperCAmelCase ) def lowercase (self , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) -> Any: _snake_case = self.num_labels _snake_case = DebertaForTokenClassification(config=UpperCAmelCase ) model.to(UpperCAmelCase ) model.eval() _snake_case = model(UpperCAmelCase , attention_mask=UpperCAmelCase , token_type_ids=UpperCAmelCase , labels=UpperCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def lowercase (self , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) -> Any: _snake_case = DebertaForQuestionAnswering(config=UpperCAmelCase ) model.to(UpperCAmelCase ) model.eval() _snake_case = model( UpperCAmelCase , attention_mask=UpperCAmelCase , token_type_ids=UpperCAmelCase , start_positions=UpperCAmelCase , end_positions=UpperCAmelCase , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def lowercase (self ) -> Tuple: _snake_case = self.prepare_config_and_inputs() ( ( _snake_case ), ( _snake_case ), ( _snake_case ), ( _snake_case ), ( _snake_case ), ( _snake_case ), ( _snake_case ), ) = config_and_inputs _snake_case = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class _lowerCAmelCase ( __snake_case , __snake_case , unittest.TestCase ): '''simple docstring''' lowerCAmelCase_ = ( ( DebertaModel, DebertaForMaskedLM, DebertaForSequenceClassification, DebertaForTokenClassification, DebertaForQuestionAnswering, ) if is_torch_available() else () ) lowerCAmelCase_ = ( { "feature-extraction": DebertaModel, "fill-mask": DebertaForMaskedLM, "question-answering": DebertaForQuestionAnswering, "text-classification": DebertaForSequenceClassification, "token-classification": DebertaForTokenClassification, "zero-shot": DebertaForSequenceClassification, } if is_torch_available() else {} ) lowerCAmelCase_ = True lowerCAmelCase_ = False lowerCAmelCase_ = False lowerCAmelCase_ = False lowerCAmelCase_ = False def lowercase (self ) -> Any: _snake_case = DebertaModelTester(self ) _snake_case = ConfigTester(self , config_class=UpperCAmelCase , hidden_size=37 ) def lowercase (self ) -> List[str]: self.config_tester.run_common_tests() def lowercase (self ) -> Tuple: _snake_case = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_model(*UpperCAmelCase ) def lowercase (self ) -> str: _snake_case = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_sequence_classification(*UpperCAmelCase ) def lowercase (self ) -> int: _snake_case = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_masked_lm(*UpperCAmelCase ) def lowercase (self ) -> Any: _snake_case = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_question_answering(*UpperCAmelCase ) def lowercase (self ) -> str: _snake_case = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_token_classification(*UpperCAmelCase ) @slow def lowercase (self ) -> Tuple: for model_name in DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _snake_case = DebertaModel.from_pretrained(UpperCAmelCase ) self.assertIsNotNone(UpperCAmelCase ) @require_torch @require_sentencepiece @require_tokenizers class _lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' @unittest.skip(reason="""Model not available yet""" ) def lowercase (self ) -> Any: pass @slow def lowercase (self ) -> Dict: _snake_case = DebertaModel.from_pretrained("""microsoft/deberta-base""" ) _snake_case = torch.tensor([[0, 31414, 232, 328, 740, 1140, 12695, 69, 46078, 1588, 2]] ) _snake_case = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) with torch.no_grad(): _snake_case = model(UpperCAmelCase , attention_mask=UpperCAmelCase )[0] # compare the actual values for a slice. _snake_case = torch.tensor( [[[-0.5986, -0.8055, -0.8462], [1.4484, -0.9348, -0.8059], [0.3123, 0.0032, -1.4131]]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , UpperCAmelCase , atol=1e-4 ) , f"""{output[:, 1:4, 1:4]}""" )
270
1
def lowerCAmelCase ( _lowerCAmelCase : str ): """simple docstring""" return [ txt[:a] + txt[a].upper() + txt[a + 1 :] for a in range(len(_lowerCAmelCase ) ) if txt[a].isalpha() ] if __name__ == "__main__": __import__("doctest").testmod()
169
from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCAmelCase : List[Any] = logging.get_logger(__name__) _lowerCAmelCase : List[str] = { "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 _UpperCamelCase ( lowerCAmelCase ): UpperCAmelCase_ = """realm""" def __init__( self :str , lowerCamelCase :List[Any]=3_0522 , lowerCamelCase :Optional[int]=768 , lowerCamelCase :Any=128 , lowerCamelCase :Tuple=12 , lowerCamelCase :str=12 , lowerCamelCase :List[str]=8 , lowerCamelCase :List[str]=3072 , lowerCamelCase :List[str]="gelu_new" , lowerCamelCase :int=0.1 , lowerCamelCase :Optional[Any]=0.1 , lowerCamelCase :int=512 , lowerCamelCase :Union[str, Any]=2 , lowerCamelCase :str=0.02 , lowerCamelCase :Tuple=1e-12 , lowerCamelCase :Dict=256 , lowerCamelCase :int=10 , lowerCamelCase :List[str]=1e-3 , lowerCamelCase :str=5 , lowerCamelCase :Optional[int]=320 , lowerCamelCase :Union[str, Any]=1335_3718 , lowerCamelCase :str=5000 , lowerCamelCase :str=1 , lowerCamelCase :List[Any]=0 , lowerCamelCase :Tuple=2 , **lowerCamelCase :Optional[int] , ) -> Optional[Any]: super().__init__(pad_token_id=lowerCamelCase , bos_token_id=lowerCamelCase , eos_token_id=lowerCamelCase , **lowerCamelCase ) # Common config UpperCAmelCase__ = vocab_size UpperCAmelCase__ = max_position_embeddings UpperCAmelCase__ = hidden_size UpperCAmelCase__ = retriever_proj_size UpperCAmelCase__ = num_hidden_layers UpperCAmelCase__ = num_attention_heads UpperCAmelCase__ = num_candidates UpperCAmelCase__ = intermediate_size UpperCAmelCase__ = hidden_act UpperCAmelCase__ = hidden_dropout_prob UpperCAmelCase__ = attention_probs_dropout_prob UpperCAmelCase__ = initializer_range UpperCAmelCase__ = type_vocab_size UpperCAmelCase__ = layer_norm_eps # Reader config UpperCAmelCase__ = span_hidden_size UpperCAmelCase__ = max_span_width UpperCAmelCase__ = reader_layer_norm_eps UpperCAmelCase__ = reader_beam_size UpperCAmelCase__ = reader_seq_len # Retrieval config UpperCAmelCase__ = num_block_records UpperCAmelCase__ = searcher_beam_size
169
1
"""simple docstring""" from ..utils import DummyObject, requires_backends class lowerCamelCase__ ( metaclass=A ): """simple docstring""" __a = ["""keras_nlp"""] def __init__( self : str , *UpperCamelCase : List[Any] , **UpperCamelCase : Dict ): '''simple docstring''' requires_backends(self , ["""keras_nlp"""] )
320
"""simple docstring""" from __future__ import annotations def lowerCamelCase ( _UpperCamelCase : list[float] , _UpperCamelCase : list[float] ) -> float: '''simple docstring''' __UpperCAmelCase : Tuple = sorted(numsa + numsa ) __UpperCAmelCase ,__UpperCAmelCase : Dict = divmod(len(_UpperCamelCase ) , 2 ) if mod == 1: return all_numbers[div] else: return (all_numbers[div] + all_numbers[div - 1]) / 2 if __name__ == "__main__": import doctest doctest.testmod() UpperCAmelCase : List[Any] = [float(x) for x in input('Enter the elements of first array: ').split()] UpperCAmelCase : Optional[int] = [float(x) for x in input('Enter the elements of second array: ').split()] print(F"The median of two arrays is: {median_of_two_arrays(array_a, array_a)}")
320
1
"""simple docstring""" from typing import TYPE_CHECKING from ....utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __UpperCamelCase = { '''configuration_mctct''': ['''MCTCT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''MCTCTConfig'''], '''feature_extraction_mctct''': ['''MCTCTFeatureExtractor'''], '''processing_mctct''': ['''MCTCTProcessor'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase = [ '''MCTCT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''MCTCTForCTC''', '''MCTCTModel''', '''MCTCTPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_mctct import MCTCT_PRETRAINED_CONFIG_ARCHIVE_MAP, MCTCTConfig from .feature_extraction_mctct import MCTCTFeatureExtractor from .processing_mctct import MCTCTProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mctct import MCTCT_PRETRAINED_MODEL_ARCHIVE_LIST, MCTCTForCTC, MCTCTModel, MCTCTPreTrainedModel else: import sys __UpperCamelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
69
"""simple docstring""" from __future__ import annotations import unittest from transformers import is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import numpy as np import tensorflow as tf from transformers import ( TF_FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST, FlaubertConfig, TFFlaubertForMultipleChoice, TFFlaubertForQuestionAnsweringSimple, TFFlaubertForSequenceClassification, TFFlaubertForTokenClassification, TFFlaubertModel, TFFlaubertWithLMHeadModel, ) class __lowerCAmelCase : def __init__( self , __UpperCAmelCase , ): '''simple docstring''' __UpperCamelCase = parent __UpperCamelCase = 13 __UpperCamelCase = 7 __UpperCamelCase = True __UpperCamelCase = True __UpperCamelCase = True __UpperCamelCase = True __UpperCamelCase = True __UpperCamelCase = False __UpperCamelCase = False __UpperCamelCase = False __UpperCamelCase = 2 __UpperCamelCase = 99 __UpperCamelCase = 0 __UpperCamelCase = 32 __UpperCamelCase = 2 __UpperCamelCase = 4 __UpperCamelCase = 0.1 __UpperCamelCase = 0.1 __UpperCamelCase = 512 __UpperCamelCase = 16 __UpperCamelCase = 2 __UpperCamelCase = 0.0_2 __UpperCamelCase = 3 __UpperCamelCase = 4 __UpperCamelCase = 'last' __UpperCamelCase = True __UpperCamelCase = None __UpperCamelCase = 0 def UpperCAmelCase ( self ): '''simple docstring''' __UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __UpperCamelCase = random_attention_mask([self.batch_size, self.seq_length] , dtype=tf.floataa ) __UpperCamelCase = None if self.use_input_lengths: __UpperCamelCase = ( ids_tensor([self.batch_size] , vocab_size=2 ) + self.seq_length - 2 ) # small variation of seq_length __UpperCamelCase = None if self.use_token_type_ids: __UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.n_langs ) __UpperCamelCase = None __UpperCamelCase = None __UpperCamelCase = None if self.use_labels: __UpperCamelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __UpperCamelCase = ids_tensor([self.batch_size] , 2 , dtype=tf.floataa ) __UpperCamelCase = ids_tensor([self.batch_size] , self.num_choices ) __UpperCamelCase = FlaubertConfig( 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 , bos_token_id=self.bos_token_id , ) return ( config, input_ids, token_type_ids, input_lengths, sequence_labels, token_labels, is_impossible_labels, choice_labels, input_mask, ) def UpperCAmelCase ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , ): '''simple docstring''' __UpperCamelCase = TFFlaubertModel(config=__UpperCAmelCase ) __UpperCamelCase = {'input_ids': input_ids, 'lengths': input_lengths, 'langs': token_type_ids} __UpperCamelCase = model(__UpperCAmelCase ) __UpperCamelCase = [input_ids, input_mask] __UpperCamelCase = model(__UpperCAmelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCAmelCase ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , ): '''simple docstring''' __UpperCamelCase = TFFlaubertWithLMHeadModel(__UpperCAmelCase ) __UpperCamelCase = {'input_ids': input_ids, 'lengths': input_lengths, 'langs': token_type_ids} __UpperCamelCase = model(__UpperCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCAmelCase ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , ): '''simple docstring''' __UpperCamelCase = TFFlaubertForQuestionAnsweringSimple(__UpperCAmelCase ) __UpperCamelCase = {'input_ids': input_ids, 'lengths': input_lengths} __UpperCamelCase = model(__UpperCAmelCase ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def UpperCAmelCase ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , ): '''simple docstring''' __UpperCamelCase = TFFlaubertForSequenceClassification(__UpperCAmelCase ) __UpperCamelCase = {'input_ids': input_ids, 'lengths': input_lengths} __UpperCamelCase = model(__UpperCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def UpperCAmelCase ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , ): '''simple docstring''' __UpperCamelCase = self.num_labels __UpperCamelCase = TFFlaubertForTokenClassification(config=__UpperCAmelCase ) __UpperCamelCase = {'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids} __UpperCamelCase = model(__UpperCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def UpperCAmelCase ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , ): '''simple docstring''' __UpperCamelCase = self.num_choices __UpperCamelCase = TFFlaubertForMultipleChoice(config=__UpperCAmelCase ) __UpperCamelCase = tf.tile(tf.expand_dims(__UpperCAmelCase , 1 ) , (1, self.num_choices, 1) ) __UpperCamelCase = tf.tile(tf.expand_dims(__UpperCAmelCase , 1 ) , (1, self.num_choices, 1) ) __UpperCamelCase = tf.tile(tf.expand_dims(__UpperCAmelCase , 1 ) , (1, self.num_choices, 1) ) __UpperCamelCase = { 'input_ids': multiple_choice_inputs_ids, 'attention_mask': multiple_choice_input_mask, 'token_type_ids': multiple_choice_token_type_ids, } __UpperCamelCase = model(__UpperCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def UpperCAmelCase ( self ): '''simple docstring''' __UpperCamelCase = self.prepare_config_and_inputs() ( ( __UpperCamelCase ) , ( __UpperCamelCase ) , ( __UpperCamelCase ) , ( __UpperCamelCase ) , ( __UpperCamelCase ) , ( __UpperCamelCase ) , ( __UpperCamelCase ) , ( __UpperCamelCase ) , ( __UpperCamelCase ) , ) = config_and_inputs __UpperCamelCase = { 'input_ids': input_ids, 'token_type_ids': token_type_ids, 'langs': token_type_ids, 'lengths': input_lengths, } return config, inputs_dict @require_tf class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): lowercase = ( ( TFFlaubertModel, TFFlaubertWithLMHeadModel, TFFlaubertForSequenceClassification, TFFlaubertForQuestionAnsweringSimple, TFFlaubertForTokenClassification, TFFlaubertForMultipleChoice, ) if is_tf_available() else () ) lowercase = ( (TFFlaubertWithLMHeadModel,) if is_tf_available() else () ) # TODO (PVP): Check other models whether language generation is also applicable lowercase = ( { "feature-extraction": TFFlaubertModel, "fill-mask": TFFlaubertWithLMHeadModel, "question-answering": TFFlaubertForQuestionAnsweringSimple, "text-classification": TFFlaubertForSequenceClassification, "token-classification": TFFlaubertForTokenClassification, "zero-shot": TFFlaubertForSequenceClassification, } if is_tf_available() else {} ) lowercase = False lowercase = False def UpperCAmelCase ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' 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 UpperCAmelCase ( self ): '''simple docstring''' __UpperCamelCase = TFFlaubertModelTester(self ) __UpperCamelCase = ConfigTester(self , config_class=__UpperCAmelCase , emb_dim=37 ) def UpperCAmelCase ( self ): '''simple docstring''' self.config_tester.run_common_tests() def UpperCAmelCase ( self ): '''simple docstring''' __UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_model(*__UpperCAmelCase ) def UpperCAmelCase ( self ): '''simple docstring''' __UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_lm_head(*__UpperCAmelCase ) def UpperCAmelCase ( self ): '''simple docstring''' __UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_qa(*__UpperCAmelCase ) def UpperCAmelCase ( self ): '''simple docstring''' __UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_sequence_classif(*__UpperCAmelCase ) def UpperCAmelCase ( self ): '''simple docstring''' __UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_for_token_classification(*__UpperCAmelCase ) def UpperCAmelCase ( self ): '''simple docstring''' __UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_for_multiple_choice(*__UpperCAmelCase ) @slow def UpperCAmelCase ( self ): '''simple docstring''' for model_name in TF_FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __UpperCamelCase = TFFlaubertModel.from_pretrained(__UpperCAmelCase ) self.assertIsNotNone(__UpperCAmelCase ) @require_tf @require_sentencepiece @require_tokenizers class __lowerCAmelCase ( unittest.TestCase ): @slow def UpperCAmelCase ( self ): '''simple docstring''' __UpperCamelCase = TFFlaubertModel.from_pretrained('jplu/tf-flaubert-small-cased' ) __UpperCamelCase = tf.convert_to_tensor( [[0, 158, 735, 2592, 1424, 6727, 82, 1]] , dtype=tf.intaa , ) # "J'aime flaubert !" __UpperCamelCase = model(__UpperCAmelCase )[0] __UpperCamelCase = tf.TensorShape((1, 8, 512) ) self.assertEqual(output.shape , __UpperCAmelCase ) # compare the actual values for a slice. __UpperCamelCase = tf.convert_to_tensor( [ [ [-1.8_7_6_8_7_7_3, -1.5_6_6_5_5_5, 0.2_7_0_7_2_4_1_8], [-1.6_9_2_0_0_3_8, -0.5_8_7_3_5_0_5, 1.9_3_2_9_5_9_9], [-2.9_5_6_3_9_8_5, -1.6_9_9_3_8_3_5, 1.7_9_7_2_0_5_2], ] ] , dtype=tf.floataa , ) self.assertTrue(np.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1E-4 ) )
316
0
"""simple docstring""" def _snake_case ( lowercase__ : list[int] , lowercase__ : int ) -> bool: '''simple docstring''' lowerCAmelCase_ :List[str] = len(__a ) lowerCAmelCase_ :Optional[int] = [[False] * (required_sum + 1) for _ in range(arr_len + 1 )] # for each arr value, a sum of zero(0) can be formed by not taking any element # hence True/1 for i in range(arr_len + 1 ): lowerCAmelCase_ :Optional[Any] = True # sum is not zero and set is empty then false for i in range(1 , required_sum + 1 ): lowerCAmelCase_ :Dict = False for i in range(1 , arr_len + 1 ): for j in range(1 , required_sum + 1 ): if arr[i - 1] > j: lowerCAmelCase_ :Union[str, Any] = subset[i - 1][j] if arr[i - 1] <= j: lowerCAmelCase_ :Tuple = subset[i - 1][j] or subset[i - 1][j - arr[i - 1]] return subset[arr_len][required_sum] if __name__ == "__main__": import doctest doctest.testmod()
364
"""simple docstring""" def _snake_case ( lowercase__ : int = 5_0 ) -> int: '''simple docstring''' lowerCAmelCase_ :int = [1] * (length + 1) for row_length in range(3 , length + 1 ): for block_length in range(3 , row_length + 1 ): for block_start in range(row_length - block_length ): ways_number[row_length] += ways_number[ row_length - block_start - block_length - 1 ] ways_number[row_length] += 1 return ways_number[length] if __name__ == "__main__": print(F"""{solution() = }""")
1
0
'''simple docstring''' import unittest from pathlib import Path from tempfile import TemporaryDirectory from transformers import AutoConfig, TFGPTaLMHeadModel, is_keras_nlp_available, is_tf_available from transformers.models.gpta.tokenization_gpta import GPTaTokenizer from transformers.testing_utils import require_keras_nlp, require_tf, slow if is_tf_available(): import tensorflow as tf if is_keras_nlp_available(): from transformers.models.gpta import TFGPTaTokenizer A_ = ["gpt2"] A_ = "gpt2" if is_tf_available(): class _snake_case ( tf.Module ): def __init__( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : List[str] ): super().__init__() SCREAMING_SNAKE_CASE:Optional[Any] = tokenizer SCREAMING_SNAKE_CASE:List[str] = AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE:List[str] = TFGPTaLMHeadModel.from_config(SCREAMING_SNAKE_CASE__ ) @tf.function(input_signature=(tf.TensorSpec((None,) ,tf.string ,name="text" ),) ) def __UpperCamelCase ( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : List[str] ): SCREAMING_SNAKE_CASE:List[str] = self.tokenizer(SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE:str = tokenized["input_ids"].to_tensor() SCREAMING_SNAKE_CASE:Dict = tf.cast(input_ids_dense > 0 ,tf.intaa ) # input_mask = tf.reshape(input_mask, [-1, MAX_SEQ_LEN]) SCREAMING_SNAKE_CASE:str = self.model(input_ids=SCREAMING_SNAKE_CASE__ ,attention_mask=SCREAMING_SNAKE_CASE__ )["logits"] return outputs @require_tf @require_keras_nlp class _snake_case ( unittest.TestCase ): def __UpperCamelCase ( self : Any ): super().setUp() SCREAMING_SNAKE_CASE:Dict = [GPTaTokenizer.from_pretrained(SCREAMING_SNAKE_CASE__ ) for checkpoint in (TOKENIZER_CHECKPOINTS)] SCREAMING_SNAKE_CASE:Tuple = [TFGPTaTokenizer.from_pretrained(SCREAMING_SNAKE_CASE__ ) for checkpoint in TOKENIZER_CHECKPOINTS] assert len(self.tokenizers ) == len(self.tf_tokenizers ) SCREAMING_SNAKE_CASE:Dict = [ "This is a straightforward English test sentence.", "This one has some weird characters\rto\nsee\r\nif those\u00E9break things.", "Now we're going to add some Chinese: 一 二 三 一二三", "And some much more rare Chinese: 齉 堃 齉堃", "Je vais aussi écrire en français pour tester les accents", "Classical Irish also has some unusual characters, so in they go: Gaelaċ, ꝼ", ] SCREAMING_SNAKE_CASE:Any = list(zip(self.test_sentences ,self.test_sentences[::-1] ) ) def __UpperCamelCase ( self : Tuple ): for tokenizer, tf_tokenizer in zip(self.tokenizers ,self.tf_tokenizers ): for test_inputs in self.test_sentences: SCREAMING_SNAKE_CASE:List[Any] = tokenizer([test_inputs] ,return_tensors="tf" ) SCREAMING_SNAKE_CASE:Dict = tf_tokenizer([test_inputs] ) for key in python_outputs.keys(): # convert them to numpy to avoid messing with ragged tensors SCREAMING_SNAKE_CASE:List[str] = python_outputs[key].numpy() SCREAMING_SNAKE_CASE:Optional[Any] = tf_outputs[key].numpy() self.assertTrue(tf.reduce_all(python_outputs_values.shape == tf_outputs_values.shape ) ) self.assertTrue(tf.reduce_all(tf.cast(SCREAMING_SNAKE_CASE__ ,tf.intaa ) == tf_outputs_values ) ) @slow def __UpperCamelCase ( self : Optional[Any] ): for tf_tokenizer in self.tf_tokenizers: SCREAMING_SNAKE_CASE:int = tf.function(SCREAMING_SNAKE_CASE__ ) for test_inputs in self.test_sentences: SCREAMING_SNAKE_CASE:Dict = tf.constant(SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE:Union[str, Any] = compiled_tokenizer(SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE:Optional[int] = tf_tokenizer(SCREAMING_SNAKE_CASE__ ) for key in eager_outputs.keys(): self.assertTrue(tf.reduce_all(eager_outputs[key] == compiled_outputs[key] ) ) @slow def __UpperCamelCase ( self : int ): for tf_tokenizer in self.tf_tokenizers: SCREAMING_SNAKE_CASE:Any = ModelToSave(tokenizer=SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE:Dict = tf.convert_to_tensor([self.test_sentences[0]] ) SCREAMING_SNAKE_CASE:Tuple = model.serving(SCREAMING_SNAKE_CASE__ ) # Build model with some sample inputs with TemporaryDirectory() as tempdir: SCREAMING_SNAKE_CASE:Dict = Path(SCREAMING_SNAKE_CASE__ ) / "saved.model" tf.saved_model.save(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,signatures={"serving_default": model.serving} ) SCREAMING_SNAKE_CASE:Optional[Any] = tf.saved_model.load(SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE:Dict = loaded_model.signatures["serving_default"](SCREAMING_SNAKE_CASE__ )["output_0"] # We may see small differences because the loaded model is compiled, so we need an epsilon for the test self.assertTrue(tf.reduce_all(out == loaded_output ) ) @slow def __UpperCamelCase ( self : str ): for tf_tokenizer in self.tf_tokenizers: SCREAMING_SNAKE_CASE:Tuple = tf.convert_to_tensor([self.test_sentences[0]] ) SCREAMING_SNAKE_CASE:Any = tf_tokenizer(SCREAMING_SNAKE_CASE__ ) # Build model with some sample inputs SCREAMING_SNAKE_CASE:List[str] = tf_tokenizer.get_config() SCREAMING_SNAKE_CASE:Optional[int] = TFGPTaTokenizer.from_config(SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE:List[Any] = model_from_config(SCREAMING_SNAKE_CASE__ ) for key in from_config_output.keys(): self.assertTrue(tf.reduce_all(from_config_output[key] == out[key] ) ) @slow def __UpperCamelCase ( self : str ): for tf_tokenizer in self.tf_tokenizers: # for the test to run SCREAMING_SNAKE_CASE:Dict = 123_123 for max_length in [3, 5, 1_024]: SCREAMING_SNAKE_CASE:int = tf.convert_to_tensor([self.test_sentences[0]] ) SCREAMING_SNAKE_CASE:List[str] = tf_tokenizer(SCREAMING_SNAKE_CASE__ ,max_length=SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE:Union[str, Any] = out["input_ids"].numpy().shape[1] assert out_length == max_length
139
'''simple docstring''' from __future__ import annotations A_ = list[list[int]] # assigning initial values to the grid A_ = [ [3, 0, 6, 5, 0, 8, 4, 0, 0], [5, 2, 0, 0, 0, 0, 0, 0, 0], [0, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], [9, 0, 0, 8, 6, 3, 0, 0, 5], [0, 5, 0, 0, 9, 0, 6, 0, 0], [1, 3, 0, 0, 0, 0, 2, 5, 0], [0, 0, 0, 0, 0, 0, 0, 7, 4], [0, 0, 5, 2, 0, 6, 3, 0, 0], ] # a grid with no solution A_ = [ [5, 0, 6, 5, 0, 8, 4, 0, 3], [5, 2, 0, 0, 0, 0, 0, 0, 2], [1, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], [9, 0, 0, 8, 6, 3, 0, 0, 5], [0, 5, 0, 0, 9, 0, 6, 0, 0], [1, 3, 0, 0, 0, 0, 2, 5, 0], [0, 0, 0, 0, 0, 0, 0, 7, 4], [0, 0, 5, 2, 0, 6, 3, 0, 0], ] def A_ ( snake_case , snake_case , snake_case , snake_case ): for i in range(9 ): if grid[row][i] == n or grid[i][column] == n: return False for i in range(3 ): for j in range(3 ): if grid[(row - row % 3) + i][(column - column % 3) + j] == n: return False return True def A_ ( snake_case ): for i in range(9 ): for j in range(9 ): if grid[i][j] == 0: return i, j return None def A_ ( snake_case ): if location := find_empty_location(snake_case ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE:Optional[int] = location else: # If the location is ``None``, then the grid is solved. return grid for digit in range(1 , 10 ): if is_safe(snake_case , snake_case , snake_case , snake_case ): SCREAMING_SNAKE_CASE:List[str] = digit if sudoku(snake_case ) is not None: return grid SCREAMING_SNAKE_CASE:List[Any] = 0 return None def A_ ( snake_case ): for row in grid: for cell in row: print(snake_case , end=" " ) print() if __name__ == "__main__": # make a copy of grid so that you can compare with the unmodified grid for example_grid in (initial_grid, no_solution): print("\nExample grid:\n" + "=" * 20) print_solution(example_grid) print("\nExample grid solution:") A_ = sudoku(example_grid) if solution is not None: print_solution(solution) else: print("Cannot find a solution.")
139
1
'''simple docstring''' def a__ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = len(a__ ) while cur > 1: # Find the maximum number in arr __SCREAMING_SNAKE_CASE = arr.index(max(arr[0:cur] ) ) # Reverse from 0 to mi __SCREAMING_SNAKE_CASE = arr[mi::-1] + arr[mi + 1 : len(a__ )] # Reverse whole list __SCREAMING_SNAKE_CASE = arr[cur - 1 :: -1] + arr[cur : len(a__ )] cur -= 1 return arr if __name__ == "__main__": UpperCAmelCase : Tuple = input('Enter numbers separated by a comma:\n').strip() UpperCAmelCase : str = [int(item) for item in user_input.split(',')] print(pancake_sort(unsorted))
331
'''simple docstring''' import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, XLMRobertaTokenizer from diffusers import AltDiffusionPipeline, AutoencoderKL, DDIMScheduler, PNDMScheduler, UNetaDConditionModel from diffusers.pipelines.alt_diffusion.modeling_roberta_series import ( RobertaSeriesConfig, RobertaSeriesModelWithTransformation, ) from diffusers.utils import slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class lowerCAmelCase__ ( a , a , a , unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = AltDiffusionPipeline lowerCAmelCase__ = TEXT_TO_IMAGE_PARAMS lowerCAmelCase__ = TEXT_TO_IMAGE_BATCH_PARAMS lowerCAmelCase__ = TEXT_TO_IMAGE_IMAGE_PARAMS lowerCAmelCase__ = TEXT_TO_IMAGE_IMAGE_PARAMS def UpperCAmelCase__ ( self : List[str] ) -> Optional[int]: """simple docstring""" torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , cross_attention_dim=32 , ) __SCREAMING_SNAKE_CASE = DDIMScheduler( beta_start=0.00085 , beta_end=0.012 , beta_schedule="""scaled_linear""" , clip_sample=__SCREAMING_SNAKE_CASE , set_alpha_to_one=__SCREAMING_SNAKE_CASE , ) torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , ) # TODO: address the non-deterministic text encoder (fails for save-load tests) # torch.manual_seed(0) # text_encoder_config = RobertaSeriesConfig( # hidden_size=32, # project_dim=32, # intermediate_size=37, # layer_norm_eps=1e-05, # num_attention_heads=4, # num_hidden_layers=5, # vocab_size=5002, # ) # text_encoder = RobertaSeriesModelWithTransformation(text_encoder_config) torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , projection_dim=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=5_002 , ) __SCREAMING_SNAKE_CASE = CLIPTextModel(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = XLMRobertaTokenizer.from_pretrained("""hf-internal-testing/tiny-xlm-roberta""" ) __SCREAMING_SNAKE_CASE = 77 __SCREAMING_SNAKE_CASE = { """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """safety_checker""": None, """feature_extractor""": None, } return components def UpperCAmelCase__ ( self : Tuple , __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : Dict=0 ) -> List[str]: """simple docstring""" if str(__SCREAMING_SNAKE_CASE ).startswith("""mps""" ): __SCREAMING_SNAKE_CASE = torch.manual_seed(__SCREAMING_SNAKE_CASE ) else: __SCREAMING_SNAKE_CASE = torch.Generator(device=__SCREAMING_SNAKE_CASE ).manual_seed(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = { """prompt""": """A painting of a squirrel eating a burger""", """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 6.0, """output_type""": """numpy""", } return inputs def UpperCAmelCase__ ( self : Any ) -> Tuple: """simple docstring""" super().test_attention_slicing_forward_pass(expected_max_diff=3E-3 ) def UpperCAmelCase__ ( self : Tuple ) -> str: """simple docstring""" super().test_inference_batch_single_identical(expected_max_diff=3E-3 ) def UpperCAmelCase__ ( self : Optional[int] ) -> Tuple: """simple docstring""" __SCREAMING_SNAKE_CASE = """cpu""" # ensure determinism for the device-dependent torch.Generator __SCREAMING_SNAKE_CASE = self.get_dummy_components() torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = RobertaSeriesConfig( hidden_size=32 , project_dim=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , vocab_size=5_002 , ) # TODO: remove after fixing the non-deterministic text encoder __SCREAMING_SNAKE_CASE = RobertaSeriesModelWithTransformation(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = text_encoder __SCREAMING_SNAKE_CASE = AltDiffusionPipeline(**__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = alt_pipe.to(__SCREAMING_SNAKE_CASE ) alt_pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.get_dummy_inputs(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = """A photo of an astronaut""" __SCREAMING_SNAKE_CASE = alt_pipe(**__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = output.images __SCREAMING_SNAKE_CASE = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) __SCREAMING_SNAKE_CASE = np.array( [0.5748162, 0.60447145, 0.48821217, 0.50100636, 0.5431185, 0.45763683, 0.49657696, 0.48132733, 0.47573093] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def UpperCAmelCase__ ( self : int ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = """cpu""" # ensure determinism for the device-dependent torch.Generator __SCREAMING_SNAKE_CASE = self.get_dummy_components() __SCREAMING_SNAKE_CASE = PNDMScheduler(skip_prk_steps=__SCREAMING_SNAKE_CASE ) torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = RobertaSeriesConfig( hidden_size=32 , project_dim=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , vocab_size=5_002 , ) # TODO: remove after fixing the non-deterministic text encoder __SCREAMING_SNAKE_CASE = RobertaSeriesModelWithTransformation(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = text_encoder __SCREAMING_SNAKE_CASE = AltDiffusionPipeline(**__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = alt_pipe.to(__SCREAMING_SNAKE_CASE ) alt_pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.get_dummy_inputs(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = alt_pipe(**__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = output.images __SCREAMING_SNAKE_CASE = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) __SCREAMING_SNAKE_CASE = np.array( [0.51605093, 0.5707241, 0.47365507, 0.50578886, 0.5633877, 0.4642503, 0.5182081, 0.48763484, 0.49084237] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 @slow @require_torch_gpu class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def UpperCAmelCase__ ( self : Any ) -> Optional[Any]: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCAmelCase__ ( self : Union[str, Any] ) -> Tuple: """simple docstring""" __SCREAMING_SNAKE_CASE = AltDiffusionPipeline.from_pretrained("""BAAI/AltDiffusion""" , safety_checker=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = alt_pipe.to(__SCREAMING_SNAKE_CASE ) alt_pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = """A painting of a squirrel eating a burger""" __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = alt_pipe([prompt] , generator=__SCREAMING_SNAKE_CASE , guidance_scale=6.0 , num_inference_steps=20 , output_type="""np""" ) __SCREAMING_SNAKE_CASE = output.images __SCREAMING_SNAKE_CASE = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) __SCREAMING_SNAKE_CASE = np.array([0.1010, 0.0800, 0.0794, 0.0885, 0.0843, 0.0762, 0.0769, 0.0729, 0.0586] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def UpperCAmelCase__ ( self : List[Any] ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = DDIMScheduler.from_pretrained("""BAAI/AltDiffusion""" , subfolder="""scheduler""" ) __SCREAMING_SNAKE_CASE = AltDiffusionPipeline.from_pretrained("""BAAI/AltDiffusion""" , scheduler=__SCREAMING_SNAKE_CASE , safety_checker=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = alt_pipe.to(__SCREAMING_SNAKE_CASE ) alt_pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = """A painting of a squirrel eating a burger""" __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = alt_pipe([prompt] , generator=__SCREAMING_SNAKE_CASE , num_inference_steps=2 , output_type="""numpy""" ) __SCREAMING_SNAKE_CASE = output.images __SCREAMING_SNAKE_CASE = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) __SCREAMING_SNAKE_CASE = np.array([0.4019, 0.4052, 0.3810, 0.4119, 0.3916, 0.3982, 0.4651, 0.4195, 0.5323] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
331
1
"""simple docstring""" def SCREAMING_SNAKE_CASE__ ( __UpperCAmelCase , __UpperCAmelCase ) -> int: lowercase__: Union[str, Any] = [1] for i in range(2 , __UpperCAmelCase ): factorials.append(factorials[-1] * i ) assert 0 <= k < factorials[-1] * n, "k out of bounds" lowercase__: List[str] = [] lowercase__: Tuple = list(range(__UpperCAmelCase ) ) # Find permutation while factorials: lowercase__: str = factorials.pop() lowercase__, lowercase__: Union[str, Any] = divmod(__UpperCAmelCase , __UpperCAmelCase ) permutation.append(elements[number] ) elements.remove(elements[number] ) permutation.append(elements[0] ) return permutation if __name__ == "__main__": import doctest doctest.testmod()
177
"""simple docstring""" from jiwer import compute_measures import datasets __A = "\\n@inproceedings{inproceedings,\n author = {Morris, Andrew and Maier, Viktoria and Green, Phil},\n year = {2004},\n month = {01},\n pages = {},\n title = {From WER and RIL to MER and WIL: improved evaluation measures for connected speech recognition.}\n}\n" __A = "\\nWord error rate (WER) is a common metric of the performance of an automatic speech recognition system.\n\nThe general difficulty of measuring performance lies in the fact that the recognized word sequence can have a different length from the reference word sequence (supposedly the correct one). The WER is derived from the Levenshtein distance, working at the word level instead of the phoneme level. The WER is a valuable tool for comparing different systems as well as for evaluating improvements within one system. This kind of measurement, however, provides no details on the nature of translation errors and further work is therefore required to identify the main source(s) of error and to focus any research effort.\n\nThis problem is solved by first aligning the recognized word sequence with the reference (spoken) word sequence using dynamic string alignment. Examination of this issue is seen through a theory called the power law that states the correlation between perplexity and word error rate.\n\nWord error rate can then be computed as:\n\nWER = (S + D + I) / N = (S + D + I) / (S + D + C)\n\nwhere\n\nS is the number of substitutions,\nD is the number of deletions,\nI is the number of insertions,\nC is the number of correct words,\nN is the number of words in the reference (N=S+D+C).\n\nThis value indicates the average number of errors per reference word. The lower the value, the better the\nperformance of the ASR system with a WER of 0 being a perfect score.\n" __A = "\nCompute WER score of transcribed segments against references.\n\nArgs:\n references: List of references for each speech input.\n predictions: List of transcriptions to score.\n concatenate_texts (bool, default=False): Whether to concatenate all input texts or compute WER iteratively.\n\nReturns:\n (float): the word error rate\n\nExamples:\n\n >>> predictions = [\"this is the prediction\", \"there is an other sample\"]\n >>> references = [\"this is the reference\", \"there is another one\"]\n >>> wer = datasets.load_metric(\"wer\")\n >>> wer_score = wer.compute(predictions=predictions, references=references)\n >>> print(wer_score)\n 0.5\n" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION ,_KWARGS_DESCRIPTION ) class UpperCAmelCase (datasets.Metric ): """simple docstring""" def _snake_case ( self ): return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Value('''string''' , id='''sequence''' ), '''references''': datasets.Value('''string''' , id='''sequence''' ), } ) , codebase_urls=['''https://github.com/jitsi/jiwer/'''] , reference_urls=[ '''https://en.wikipedia.org/wiki/Word_error_rate''', ] , ) def _snake_case ( self , _UpperCAmelCase=None , _UpperCAmelCase=None , _UpperCAmelCase=False ): if concatenate_texts: return compute_measures(_UpperCAmelCase , _UpperCAmelCase )["wer"] else: lowercase__: Dict = 0 lowercase__: Union[str, Any] = 0 for prediction, reference in zip(_UpperCAmelCase , _UpperCAmelCase ): lowercase__: Tuple = compute_measures(_UpperCAmelCase , _UpperCAmelCase ) incorrect += measures["substitutions"] + measures["deletions"] + measures["insertions"] total += measures["substitutions"] + measures["deletions"] + measures["hits"] return incorrect / total
177
1
'''simple docstring''' import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import AddedToken from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_rembert import RemBertTokenizer else: _SCREAMING_SNAKE_CASE = None _SCREAMING_SNAKE_CASE = logging.get_logger(__name__) _SCREAMING_SNAKE_CASE = {'''vocab_file''': '''sentencepiece.model''', '''tokenizer_file''': '''tokenizer.json'''} _SCREAMING_SNAKE_CASE = { '''vocab_file''': { '''google/rembert''': '''https://huggingface.co/google/rembert/resolve/main/sentencepiece.model''', }, '''tokenizer_file''': { '''google/rembert''': '''https://huggingface.co/google/rembert/resolve/main/tokenizer.json''', }, } _SCREAMING_SNAKE_CASE = { '''google/rembert''': 2_5_6, } _SCREAMING_SNAKE_CASE = '''▁''' class __lowercase ( lowerCAmelCase__ ): '''simple docstring''' a : Optional[Any] = VOCAB_FILES_NAMES a : Optional[int] = PRETRAINED_VOCAB_FILES_MAP a : Optional[int] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES a : Union[str, Any] = RemBertTokenizer def __init__(self ,_lowerCamelCase=None ,_lowerCamelCase=None ,_lowerCamelCase=True ,_lowerCamelCase=True ,_lowerCamelCase=False ,_lowerCamelCase="[CLS]" ,_lowerCamelCase="[SEP]" ,_lowerCamelCase="<unk>" ,_lowerCamelCase="[SEP]" ,_lowerCamelCase="<pad>" ,_lowerCamelCase="[CLS]" ,_lowerCamelCase="[MASK]" ,**_lowerCamelCase ,) -> Any: '''simple docstring''' __lowercase = AddedToken(_lowerCamelCase ,lstrip=_lowerCamelCase ,rstrip=_lowerCamelCase ) if isinstance(_lowerCamelCase ,_lowerCamelCase ) else mask_token super().__init__( _lowerCamelCase ,tokenizer_file=_lowerCamelCase ,do_lower_case=_lowerCamelCase ,remove_space=_lowerCamelCase ,keep_accents=_lowerCamelCase ,bos_token=_lowerCamelCase ,eos_token=_lowerCamelCase ,unk_token=_lowerCamelCase ,sep_token=_lowerCamelCase ,pad_token=_lowerCamelCase ,cls_token=_lowerCamelCase ,mask_token=_lowerCamelCase ,**_lowerCamelCase ,) __lowercase = do_lower_case __lowercase = remove_space __lowercase = keep_accents __lowercase = vocab_file __lowercase = False if not self.vocab_file else True def _UpperCAmelCase (self ,_lowerCamelCase ,_lowerCamelCase = None ) -> List[int]: '''simple docstring''' __lowercase = [self.sep_token_id] __lowercase = [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 _UpperCAmelCase (self ,_lowerCamelCase ,_lowerCamelCase = None ,_lowerCamelCase = False ) -> List[int]: '''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(_lowerCamelCase )) + [1] + ([0] * len(_lowerCamelCase )) + [1] return [1] + ([0] * len(_lowerCamelCase )) + [1] def _UpperCAmelCase (self ,_lowerCamelCase ,_lowerCamelCase = None ) -> List[int]: '''simple docstring''' __lowercase = [self.sep_token_id] __lowercase = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def _UpperCAmelCase (self ,_lowerCamelCase ,_lowerCamelCase = None ) -> Tuple[str]: '''simple docstring''' if not os.path.isdir(_lowerCamelCase ): logger.error('''Vocabulary path ({}) should be a directory'''.format(_lowerCamelCase ) ) return __lowercase = os.path.join( _lowerCamelCase ,(filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_lowerCamelCase ): copyfile(self.vocab_file ,_lowerCamelCase ) return (out_vocab_file,)
217
'''simple docstring''' import argparse import os from pathlib import Path import fairseq import torch from packaging import version from torch import nn from transformers import ( BartConfig, BartForConditionalGeneration, BartForSequenceClassification, BartModel, BartTokenizer, ) from transformers.utils import logging _SCREAMING_SNAKE_CASE = ['''bart.large''', '''bart.large.mnli''', '''bart.large.cnn''', '''bart_xsum/model.pt'''] _SCREAMING_SNAKE_CASE = {'''bart.large''': BartModel, '''bart.large.mnli''': BartForSequenceClassification} if version.parse(fairseq.__version__) < version.parse('''0.9.0'''): raise Exception('''requires fairseq >= 0.9.0''') logging.set_verbosity_info() _SCREAMING_SNAKE_CASE = logging.get_logger(__name__) _SCREAMING_SNAKE_CASE = ''' Hello world! cécé herlolip''' _SCREAMING_SNAKE_CASE = [ ('''model.classification_heads.mnli.dense.weight''', '''classification_head.dense.weight'''), ('''model.classification_heads.mnli.dense.bias''', '''classification_head.dense.bias'''), ('''model.classification_heads.mnli.out_proj.weight''', '''classification_head.out_proj.weight'''), ('''model.classification_heads.mnli.out_proj.bias''', '''classification_head.out_proj.bias'''), ] def _lowerCAmelCase ( lowerCamelCase_ : int ): __lowercase = [ '''encoder.version''', '''decoder.version''', '''model.encoder.version''', '''model.decoder.version''', '''_float_tensor''', ] for k in ignore_keys: state_dict.pop(lowerCamelCase_ , lowerCamelCase_ ) def _lowerCAmelCase ( lowerCamelCase_ : Tuple , lowerCamelCase_ : str , lowerCamelCase_ : Union[str, Any] ): __lowercase = dct.pop(lowerCamelCase_ ) __lowercase = val def _lowerCAmelCase ( lowerCamelCase_ : Any ): __lowercase = torch.load(lowerCamelCase_ , map_location='''cpu''' ) __lowercase = torch.hub.load('''pytorch/fairseq''' , '''bart.large.cnn''' ).eval() hub_interface.model.load_state_dict(sd['''model'''] ) return hub_interface def _lowerCAmelCase ( lowerCamelCase_ : List[str] ): __lowercase , __lowercase = emb.weight.shape __lowercase = nn.Linear(lowerCamelCase_ , lowerCamelCase_ , bias=lowerCamelCase_ ) __lowercase = emb.weight.data return lin_layer @torch.no_grad() def _lowerCAmelCase ( lowerCamelCase_ : Union[str, Any] , lowerCamelCase_ : Optional[Any] , lowerCamelCase_ : List[Any]=None ): if not os.path.exists(lowerCamelCase_ ): __lowercase = torch.hub.load('''pytorch/fairseq''' , lowerCamelCase_ ).eval() else: __lowercase = load_xsum_checkpoint(lowerCamelCase_ ) bart.model.upgrade_state_dict(bart.model.state_dict() ) if hf_checkpoint_name is None: __lowercase = checkpoint_path.replace('''.''' , '''-''' ) __lowercase = BartConfig.from_pretrained(lowerCamelCase_ ) __lowercase = bart.encode(lowerCamelCase_ ).unsqueeze(0 ) __lowercase = BartTokenizer.from_pretrained(lowerCamelCase_ ).encode(lowerCamelCase_ , return_tensors='''pt''' ).unsqueeze(0 ) if not torch.eq(lowerCamelCase_ , lowerCamelCase_ ).all(): raise ValueError( f"converted tokenizer and pretrained tokenizer returned different output: {tokens} != {tokensa}" ) if checkpoint_path == "bart.large.mnli": __lowercase = bart.state_dict() remove_ignore_keys_(lowerCamelCase_ ) __lowercase = state_dict['''model.decoder.embed_tokens.weight'''] for src, dest in mnli_rename_keys: rename_key(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) __lowercase = BartForSequenceClassification(lowerCamelCase_ ).eval() model.load_state_dict(lowerCamelCase_ ) __lowercase = bart.predict('''mnli''' , lowerCamelCase_ , return_logits=lowerCamelCase_ ) __lowercase = model(lowerCamelCase_ )[0] # logits else: # no classification heads to worry about __lowercase = bart.model.state_dict() remove_ignore_keys_(lowerCamelCase_ ) __lowercase = state_dict['''decoder.embed_tokens.weight'''] __lowercase = bart.extract_features(lowerCamelCase_ ) if hf_checkpoint_name == "facebook/bart-large": __lowercase = BartModel(lowerCamelCase_ ).eval() model.load_state_dict(lowerCamelCase_ ) __lowercase = model(lowerCamelCase_ ).model[0] else: __lowercase = BartForConditionalGeneration(lowerCamelCase_ ).eval() # an existing summarization ckpt model.model.load_state_dict(lowerCamelCase_ ) if hasattr(lowerCamelCase_ , '''lm_head''' ): __lowercase = make_linear_from_emb(model.model.shared ) __lowercase = model.model(lowerCamelCase_ )[0] # Check results if fairseq_output.shape != new_model_outputs.shape: raise ValueError( f"`fairseq_output` shape and `new_model_output` shape are different: {fairseq_output.shape=}, {new_model_outputs.shape}" ) if (fairseq_output != new_model_outputs).any().item(): raise ValueError('''Some values in `fairseq_output` are different from `new_model_outputs`''' ) Path(lowerCamelCase_ ).mkdir(exist_ok=lowerCamelCase_ ) model.save_pretrained(lowerCamelCase_ ) if __name__ == "__main__": _SCREAMING_SNAKE_CASE = 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=None, type=str, help='''Which huggingface architecture to use: bart-large-xsum''' ) _SCREAMING_SNAKE_CASE = parser.parse_args() convert_bart_checkpoint(args.fairseq_path, args.pytorch_dump_folder_path, hf_checkpoint_name=args.hf_config)
217
1
from collections import OrderedDict from typing import TYPE_CHECKING, Any, Mapping, Optional, Union from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig, OnnxSeqaSeqConfigWithPast from ...utils import logging if TYPE_CHECKING: from ...feature_extraction_utils import FeatureExtractionMixin from ...tokenization_utils_base import PreTrainedTokenizerBase from ...utils import TensorType lowercase : List[str] = logging.get_logger(__name__) lowercase : Any = { """openai/whisper-base""": """https://huggingface.co/openai/whisper-base/resolve/main/config.json""", } # fmt: off lowercase : List[str] = [ 1, 2, 7, 8, 9, 1_0, 1_4, 2_5, 2_6, 2_7, 2_8, 2_9, 3_1, 5_8, 5_9, 6_0, 6_1, 6_2, 6_3, 9_0, 9_1, 9_2, 9_3, 3_5_7, 3_6_6, 4_3_8, 5_3_2, 6_8_5, 7_0_5, 7_9_6, 9_3_0, 1_0_5_8, 1_2_2_0, 1_2_6_7, 1_2_7_9, 1_3_0_3, 1_3_4_3, 1_3_7_7, 1_3_9_1, 1_6_3_5, 1_7_8_2, 1_8_7_5, 2_1_6_2, 2_3_6_1, 2_4_8_8, 3_4_6_7, 4_0_0_8, 4_2_1_1, 4_6_0_0, 4_8_0_8, 5_2_9_9, 5_8_5_5, 6_3_2_9, 7_2_0_3, 9_6_0_9, 9_9_5_9, 1_0_5_6_3, 1_0_7_8_6, 1_1_4_2_0, 1_1_7_0_9, 1_1_9_0_7, 1_3_1_6_3, 1_3_6_9_7, 1_3_7_0_0, 1_4_8_0_8, 1_5_3_0_6, 1_6_4_1_0, 1_6_7_9_1, 1_7_9_9_2, 1_9_2_0_3, 1_9_5_1_0, 2_0_7_2_4, 2_2_3_0_5, 2_2_9_3_5, 2_7_0_0_7, 3_0_1_0_9, 3_0_4_2_0, 3_3_4_0_9, 3_4_9_4_9, 4_0_2_8_3, 4_0_4_9_3, 4_0_5_4_9, 4_7_2_8_2, 4_9_1_4_6, 5_0_2_5_7, 5_0_3_5_9, 5_0_3_6_0, 5_0_3_6_1 ] lowercase : List[Any] = [ 1, 2, 7, 8, 9, 1_0, 1_4, 2_5, 2_6, 2_7, 2_8, 2_9, 3_1, 5_8, 5_9, 6_0, 6_1, 6_2, 6_3, 9_0, 9_1, 9_2, 9_3, 3_5_9, 5_0_3, 5_2_2, 5_4_2, 8_7_3, 8_9_3, 9_0_2, 9_1_8, 9_2_2, 9_3_1, 1_3_5_0, 1_8_5_3, 1_9_8_2, 2_4_6_0, 2_6_2_7, 3_2_4_6, 3_2_5_3, 3_2_6_8, 3_5_3_6, 3_8_4_6, 3_9_6_1, 4_1_8_3, 4_6_6_7, 6_5_8_5, 6_6_4_7, 7_2_7_3, 9_0_6_1, 9_3_8_3, 1_0_4_2_8, 1_0_9_2_9, 1_1_9_3_8, 1_2_0_3_3, 1_2_3_3_1, 1_2_5_6_2, 1_3_7_9_3, 1_4_1_5_7, 1_4_6_3_5, 1_5_2_6_5, 1_5_6_1_8, 1_6_5_5_3, 1_6_6_0_4, 1_8_3_6_2, 1_8_9_5_6, 2_0_0_7_5, 2_1_6_7_5, 2_2_5_2_0, 2_6_1_3_0, 2_6_1_6_1, 2_6_4_3_5, 2_8_2_7_9, 2_9_4_6_4, 3_1_6_5_0, 3_2_3_0_2, 3_2_4_7_0, 3_6_8_6_5, 4_2_8_6_3, 4_7_4_2_5, 4_9_8_7_0, 5_0_2_5_4, 5_0_2_5_8, 5_0_3_6_0, 5_0_3_6_1, 5_0_3_6_2 ] class A__ ( __UpperCAmelCase ): """simple docstring""" __A : int = '''whisper''' __A : List[Any] = ['''past_key_values'''] __A : Optional[int] = {'''num_attention_heads''': '''encoder_attention_heads''', '''hidden_size''': '''d_model'''} def __init__( self , lowercase=5_1865 , lowercase=80 , lowercase=6 , lowercase=4 , lowercase=6 , lowercase=4 , lowercase=1536 , lowercase=1536 , lowercase=0.0 , lowercase=0.0 , lowercase=5_0257 , lowercase=True , lowercase=True , lowercase="gelu" , lowercase=256 , lowercase=0.0 , lowercase=0.0 , lowercase=0.0 , lowercase=0.02 , lowercase=False , lowercase=1500 , lowercase=448 , lowercase=5_0256 , lowercase=5_0256 , lowercase=5_0256 , lowercase=None , lowercase=[220, 5_0256] , lowercase=False , lowercase=256 , lowercase=False , lowercase=0.05 , lowercase=10 , lowercase=2 , lowercase=0.0 , lowercase=10 , lowercase=0 , lowercase=7 , **lowercase , ) -> str: '''simple docstring''' a__ : int = vocab_size a__ : int = num_mel_bins a__ : Optional[int] = d_model a__ : List[str] = encoder_layers a__ : Dict = encoder_attention_heads a__ : List[str] = decoder_layers a__ : Tuple = decoder_attention_heads a__ : List[str] = decoder_ffn_dim a__ : Optional[Any] = encoder_ffn_dim a__ : Tuple = dropout a__ : Optional[int] = attention_dropout a__ : Any = activation_dropout a__ : Any = activation_function a__ : List[Any] = init_std a__ : Optional[int] = encoder_layerdrop a__ : Union[str, Any] = decoder_layerdrop a__ : Tuple = use_cache a__ : List[str] = encoder_layers a__ : Dict = scale_embedding # scale factor will be sqrt(d_model) if True a__ : Dict = max_source_positions a__ : Dict = max_target_positions # Audio Classification-specific parameters. Feel free to ignore for other classes. a__ : Optional[int] = classifier_proj_size a__ : List[Any] = use_weighted_layer_sum # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 a__ : List[Any] = apply_spec_augment a__ : int = mask_time_prob a__ : int = mask_time_length a__ : List[Any] = mask_time_min_masks a__ : str = mask_feature_prob a__ : Optional[int] = mask_feature_length a__ : Union[str, Any] = mask_feature_min_masks a__ : Tuple = median_filter_width super().__init__( pad_token_id=lowercase , bos_token_id=lowercase , eos_token_id=lowercase , is_encoder_decoder=lowercase , decoder_start_token_id=lowercase , suppress_tokens=lowercase , begin_suppress_tokens=lowercase , **lowercase , ) class A__ ( __UpperCAmelCase ): """simple docstring""" @property def __lowercase ( self) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' a__ : List[str] = OrderedDict( [ ('input_features', {0: 'batch', 1: 'feature_size', 2: 'encoder_sequence'}), ]) if self.use_past: a__ : Optional[Any] = {0: 'batch'} else: a__ : Optional[Any] = {0: 'batch', 1: 'decoder_sequence'} if self.use_past: self.fill_with_past_key_values_(lowercase , direction='inputs') return common_inputs def __lowercase ( self , lowercase , lowercase = -1 , lowercase = -1 , lowercase = False , lowercase = None , lowercase = 2_2050 , lowercase = 5.0 , lowercase = 220 , ) -> Mapping[str, Any]: '''simple docstring''' a__ : Union[str, Any] = OrderedDict() a__ : int = OnnxConfig.generate_dummy_inputs( self , preprocessor=preprocessor.feature_extractor , batch_size=lowercase , framework=lowercase , sampling_rate=lowercase , time_duration=lowercase , frequency=lowercase , ) a__ : List[Any] = encoder_inputs['input_features'].shape[2] a__ : Optional[int] = encoder_sequence_length // 2 if self.use_past else seq_length a__ : Any = super().generate_dummy_inputs( preprocessor.tokenizer , lowercase , lowercase , lowercase , lowercase) a__ : List[str] = encoder_inputs.pop('input_features') a__ : Optional[int] = decoder_inputs.pop('decoder_input_ids') if "past_key_values" in decoder_inputs: a__ : List[str] = decoder_inputs.pop('past_key_values') return dummy_inputs @property def __lowercase ( self) -> float: '''simple docstring''' return 1e-3
99
import inspect import unittest from transformers import ViTHybridConfig from transformers.testing_utils import require_accelerate, require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ViTHybridForImageClassification, ViTHybridImageProcessor, ViTHybridModel from transformers.models.vit_hybrid.modeling_vit_hybrid import VIT_HYBRID_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image class A__ : """simple docstring""" def __init__( self , lowercase , lowercase=13 , lowercase=64 , lowercase=2 , lowercase=3 , lowercase=True , lowercase=True , lowercase=32 , lowercase=5 , lowercase=4 , lowercase=37 , lowercase="gelu" , lowercase=0.1 , lowercase=0.1 , lowercase=10 , lowercase=0.02 , lowercase=[1, 16, 4, 4] , lowercase=None , ) -> List[Any]: '''simple docstring''' a__ : Optional[int] = parent a__ : Optional[int] = batch_size a__ : Any = image_size a__ : Optional[Any] = patch_size a__ : Optional[Any] = num_channels a__ : int = is_training a__ : List[str] = use_labels a__ : List[str] = hidden_size a__ : Tuple = num_hidden_layers a__ : Optional[Any] = num_attention_heads a__ : Union[str, Any] = intermediate_size a__ : Optional[int] = hidden_act a__ : Optional[Any] = hidden_dropout_prob a__ : Any = attention_probs_dropout_prob a__ : Any = type_sequence_label_size a__ : Tuple = initializer_range a__ : Tuple = scope a__ : int = backbone_featmap_shape # in ViT hybrid, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) # the number of patches is based on the feature map of the backbone, which by default uses an output stride # of 32, which means that the feature map has a spatial resolution of 1/32 of the input image size a__ : Any = (self.image_size // 32) ** 2 a__ : List[Any] = num_patches + 1 def __lowercase ( self) -> Any: '''simple docstring''' a__ : List[str] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) a__ : int = None if self.use_labels: a__ : int = ids_tensor([self.batch_size] , self.type_sequence_label_size) a__ : List[str] = self.get_config() return config, pixel_values, labels def __lowercase ( self) -> Dict: '''simple docstring''' a__ : List[str] = { 'global_padding': 'same', 'layer_type': 'bottleneck', 'depths': [3, 4, 9], 'out_features': ['stage1', 'stage2', 'stage3'], 'embedding_dynamic_padding': True, 'hidden_sizes': [4, 8, 16, 32], 'num_groups': 2, } return ViTHybridConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=lowercase , initializer_range=self.initializer_range , backbone_featmap_shape=self.backbone_featmap_shape , backbone_config=lowercase , ) def __lowercase ( self , lowercase , lowercase , lowercase) -> List[str]: '''simple docstring''' a__ : List[str] = ViTHybridModel(config=lowercase) model.to(lowercase) model.eval() a__ : Union[str, Any] = model(lowercase) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size)) def __lowercase ( self , lowercase , lowercase , lowercase) -> Union[str, Any]: '''simple docstring''' a__ : Dict = self.type_sequence_label_size a__ : Union[str, Any] = ViTHybridForImageClassification(lowercase) model.to(lowercase) model.eval() a__ : Tuple = model(lowercase , labels=lowercase) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size)) def __lowercase ( self) -> Any: '''simple docstring''' a__ : List[str] = self.prepare_config_and_inputs() a__ , a__ , a__ : Union[str, Any] = config_and_inputs a__ : str = {'pixel_values': pixel_values} return config, inputs_dict @require_torch class A__ ( __UpperCAmelCase , __UpperCAmelCase , unittest.TestCase ): """simple docstring""" __A : Optional[Any] = (ViTHybridModel, ViTHybridForImageClassification) if is_torch_available() else () __A : List[str] = ( {'''feature-extraction''': ViTHybridModel, '''image-classification''': ViTHybridForImageClassification} if is_torch_available() else {} ) __A : Any = False __A : Optional[int] = False __A : Optional[Any] = False def __lowercase ( self) -> Optional[Any]: '''simple docstring''' a__ : Any = ViTHybridModelTester(self) a__ : Any = ConfigTester(self , config_class=lowercase , has_text_modality=lowercase , hidden_size=37) def __lowercase ( self) -> List[Any]: '''simple docstring''' self.config_tester.run_common_tests() @unittest.skip(reason='ViT does not use inputs_embeds') def __lowercase ( self) -> Dict: '''simple docstring''' pass def __lowercase ( self) -> Optional[Any]: '''simple docstring''' a__ , a__ : List[str] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: a__ : str = model_class(lowercase) self.assertIsInstance(model.get_input_embeddings() , (nn.Module)) a__ : str = model.get_output_embeddings() self.assertTrue(x is None or isinstance(lowercase , nn.Linear)) def __lowercase ( self) -> int: '''simple docstring''' a__ , a__ : str = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: a__ : Union[str, Any] = model_class(lowercase) a__ : Union[str, Any] = inspect.signature(model.forward) # signature.parameters is an OrderedDict => so arg_names order is deterministic a__ : Optional[Any] = [*signature.parameters.keys()] a__ : Dict = ['pixel_values'] self.assertListEqual(arg_names[:1] , lowercase) def __lowercase ( self) -> Any: '''simple docstring''' a__ : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowercase) def __lowercase ( self) -> Optional[Any]: '''simple docstring''' a__ : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*lowercase) def __lowercase ( self) -> Dict: '''simple docstring''' a__ , a__ : Tuple = self.model_tester.prepare_config_and_inputs_for_common() a__ : Tuple = _config_zero_init(lowercase) for model_class in self.all_model_classes: a__ : List[Any] = model_class(config=lowercase) # Skip the check for the backbone for name, module in model.named_modules(): if module.__class__.__name__ == "ViTHybridPatchEmbeddings": a__ : Dict = [F'{name}.{key}' for key in module.state_dict().keys()] break for name, param in model.named_parameters(): if param.requires_grad: if name in backbone_params: continue self.assertIn( ((param.data.mean() * 1e9).round() / 1e9).item() , [0.0, 1.0] , msg=F'Parameter {name} of model {model_class} seems not properly initialized' , ) @slow def __lowercase ( self) -> Any: '''simple docstring''' for model_name in VIT_HYBRID_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: a__ : Optional[Any] = ViTHybridModel.from_pretrained(lowercase) self.assertIsNotNone(lowercase) def A_ ( ) -> int: a__ : Dict = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_torch @require_vision class A__ ( unittest.TestCase ): """simple docstring""" @cached_property def __lowercase ( self) -> Optional[Any]: '''simple docstring''' return ( ViTHybridImageProcessor.from_pretrained(VIT_HYBRID_PRETRAINED_MODEL_ARCHIVE_LIST[0]) if is_vision_available() else None ) @slow def __lowercase ( self) -> Any: '''simple docstring''' a__ : List[str] = ViTHybridForImageClassification.from_pretrained(VIT_HYBRID_PRETRAINED_MODEL_ARCHIVE_LIST[0]).to( lowercase) a__ : List[str] = self.default_image_processor a__ : List[Any] = prepare_img() a__ : Any = image_processor(images=lowercase , return_tensors='pt').to(lowercase) # forward pass with torch.no_grad(): a__ : Optional[Any] = model(**lowercase) # verify the logits a__ : Optional[Any] = torch.Size((1, 1000)) self.assertEqual(outputs.logits.shape , lowercase) a__ : Any = torch.tensor([-1.90_90, -0.49_93, -0.23_89]).to(lowercase) self.assertTrue(torch.allclose(outputs.logits[0, :3] , lowercase , atol=1e-4)) @slow @require_accelerate def __lowercase ( self) -> Optional[int]: '''simple docstring''' a__ : List[str] = ViTHybridImageProcessor.from_pretrained('google/vit-hybrid-base-bit-384') a__ : Union[str, Any] = ViTHybridForImageClassification.from_pretrained('google/vit-hybrid-base-bit-384' , device_map='auto') a__ : Any = prepare_img() a__ : str = image_processor(images=lowercase , return_tensors='pt') a__ : List[Any] = model(**lowercase) a__ : int = outputs.logits # model predicts one of the 1000 ImageNet classes a__ : List[str] = logits.argmax(-1).item() self.assertTrue(model.config.idalabel[predicted_class_idx] , 'tabby, tabby cat')
99
1
import unittest import numpy as np from transformers import AlbertConfig, 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.albert.modeling_flax_albert import ( FlaxAlbertForMaskedLM, FlaxAlbertForMultipleChoice, FlaxAlbertForPreTraining, FlaxAlbertForQuestionAnswering, FlaxAlbertForSequenceClassification, FlaxAlbertForTokenClassification, FlaxAlbertModel, ) class _snake_case ( unittest.TestCase ): def __init__( self , _a , _a=13 , _a=7 , _a=True , _a=True , _a=True , _a=True , _a=99 , _a=32 , _a=5 , _a=4 , _a=37 , _a="gelu" , _a=0.1 , _a=0.1 , _a=512 , _a=16 , _a=2 , _a=0.02 , _a=4 , ): __magic_name__ : str = parent __magic_name__ : Union[str, Any] = batch_size __magic_name__ : List[str] = seq_length __magic_name__ : Optional[int] = is_training __magic_name__ : str = use_attention_mask __magic_name__ : List[str] = use_token_type_ids __magic_name__ : str = use_labels __magic_name__ : Tuple = vocab_size __magic_name__ : Dict = hidden_size __magic_name__ : int = num_hidden_layers __magic_name__ : Tuple = num_attention_heads __magic_name__ : str = intermediate_size __magic_name__ : List[str] = hidden_act __magic_name__ : Union[str, Any] = hidden_dropout_prob __magic_name__ : Tuple = attention_probs_dropout_prob __magic_name__ : Any = max_position_embeddings __magic_name__ : Tuple = type_vocab_size __magic_name__ : Any = type_sequence_label_size __magic_name__ : str = initializer_range __magic_name__ : Dict = num_choices def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : int = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __magic_name__ : Optional[Any] = None if self.use_attention_mask: __magic_name__ : Optional[Any] = random_attention_mask([self.batch_size, self.seq_length] ) __magic_name__ : Union[str, Any] = None if self.use_token_type_ids: __magic_name__ : str = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __magic_name__ : Dict = AlbertConfig( 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=__lowerCAmelCase , initializer_range=self.initializer_range , ) return config, input_ids, token_type_ids, attention_mask def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : str = self.prepare_config_and_inputs() __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ : Any = config_and_inputs __magic_name__ : Union[str, Any] = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": attention_mask} return config, inputs_dict @require_flax class _snake_case ( lowerCAmelCase_ , unittest.TestCase ): UpperCamelCase__ = ( ( FlaxAlbertModel, FlaxAlbertForPreTraining, FlaxAlbertForMaskedLM, FlaxAlbertForMultipleChoice, FlaxAlbertForQuestionAnswering, FlaxAlbertForSequenceClassification, FlaxAlbertForTokenClassification, FlaxAlbertForQuestionAnswering, ) if is_flax_available() else () ) def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : List[Any] = FlaxAlbertModelTester(self ) @slow def SCREAMING_SNAKE_CASE ( self ): for model_class_name in self.all_model_classes: __magic_name__ : Any = model_class_name.from_pretrained("albert-base-v2" ) __magic_name__ : Any = model(np.ones((1, 1) ) ) self.assertIsNotNone(__lowerCAmelCase ) @require_flax class _snake_case ( unittest.TestCase ): @slow def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : List[str] = FlaxAlbertModel.from_pretrained("albert-base-v2" ) __magic_name__ : Optional[Any] = np.array([[0, 345, 232, 328, 740, 140, 1_695, 69, 6_078, 1_588, 2]] ) __magic_name__ : List[Any] = np.array([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) __magic_name__ : Tuple = model(__lowerCAmelCase , attention_mask=__lowerCAmelCase )[0] __magic_name__ : str = (1, 11, 768) self.assertEqual(output.shape , __lowerCAmelCase ) __magic_name__ : Optional[int] = np.array( [[[-0.65_13, 1.50_35, -0.27_66], [-0.65_15, 1.50_46, -0.27_80], [-0.65_12, 1.50_49, -0.27_84]]] ) self.assertTrue(jnp.allclose(output[:, 1:4, 1:4] , __lowerCAmelCase , atol=1e-4 ) )
358
from __future__ import annotations snake_case : Optional[int] = { "A": ["B", "C", "E"], "B": ["A", "D", "E"], "C": ["A", "F", "G"], "D": ["B"], "E": ["A", "B", "D"], "F": ["C"], "G": ["C"], } class _snake_case : def __init__( self , _a , _a ): __magic_name__ : Any = graph # mapping node to its parent in resulting breadth first tree __magic_name__ : dict[str, str | None] = {} __magic_name__ : List[str] = source_vertex def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : List[str] = {self.source_vertex} __magic_name__ : Optional[int] = None __magic_name__ : int = [self.source_vertex] # first in first out queue while queue: __magic_name__ : Optional[Any] = queue.pop(0 ) for adjacent_vertex in self.graph[vertex]: if adjacent_vertex not in visited: visited.add(_a ) __magic_name__ : Dict = vertex queue.append(_a ) def SCREAMING_SNAKE_CASE ( self , _a ): if target_vertex == self.source_vertex: return self.source_vertex __magic_name__ : str = self.parent.get(_a ) if target_vertex_parent is None: __magic_name__ : Union[str, Any] = ( f'''No path from vertex: {self.source_vertex} to vertex: {target_vertex}''' ) raise ValueError(_a ) return self.shortest_path(_a ) + f'''->{target_vertex}''' if __name__ == "__main__": snake_case : int = Graph(graph, "G") g.breath_first_search() print(g.shortest_path("D")) print(g.shortest_path("G")) print(g.shortest_path("Foo"))
41
0
def lowerCAmelCase_ ( _snake_case : int ) -> int: '''simple docstring''' if not isinstance(_snake_case , _snake_case ): raise TypeError("Input value must be an 'int' type" ) __magic_name__ : List[Any] = 0 while number: position += 1 number >>= 1 return position if __name__ == "__main__": import doctest doctest.testmod()
281
import math def lowerCAmelCase_ ( _snake_case : float , _snake_case : float ) -> float: '''simple docstring''' return math.pow(_snake_case , 2 ) - a def lowerCAmelCase_ ( _snake_case : float ) -> float: '''simple docstring''' return 2 * x def lowerCAmelCase_ ( _snake_case : float ) -> float: '''simple docstring''' __magic_name__ : Optional[int] = 2.0 while start <= a: __magic_name__ : str = math.pow(_snake_case , 2 ) return start def lowerCAmelCase_ ( _snake_case : float , _snake_case : int = 9999 , _snake_case : float = 0.00_000_000_000_001 ) -> float: '''simple docstring''' if a < 0: raise ValueError("math domain error" ) __magic_name__ : Optional[int] = get_initial_point(_snake_case ) for _ in range(_snake_case ): __magic_name__ : int = value __magic_name__ : str = value - fx(_snake_case , _snake_case ) / fx_derivative(_snake_case ) if abs(prev_value - value ) < tolerance: return value return value if __name__ == "__main__": from doctest import testmod testmod()
281
1
def _lowerCamelCase( lowercase__ , lowercase__ ) -> int: '''simple docstring''' if len(lowercase__ ) != len(lowercase__ ): raise ValueError('String lengths must match!' ) __lowercase= 0 for chara, chara in zip(lowercase__ , lowercase__ ): if chara != chara: count += 1 return count if __name__ == "__main__": import doctest doctest.testmod()
366
lowerCAmelCase = [ 9_9_9, 8_0_0, 7_9_9, 6_0_0, 5_9_9, 5_0_0, 4_0_0, 3_9_9, 3_7_7, 3_5_5, 3_3_3, 3_1_1, 2_8_8, 2_6_6, 2_4_4, 2_2_2, 2_0_0, 1_9_9, 1_7_7, 1_5_5, 1_3_3, 1_1_1, 8_8, 6_6, 4_4, 2_2, 0, ] lowerCAmelCase = [ 9_9_9, 9_7_6, 9_5_2, 9_2_8, 9_0_5, 8_8_2, 8_5_8, 8_5_7, 8_1_0, 7_6_2, 7_1_5, 7_1_4, 5_7_2, 4_2_9, 4_2_8, 2_8_6, 2_8_5, 2_3_8, 1_9_0, 1_4_3, 1_4_2, 1_1_8, 9_5, 7_1, 4_7, 2_4, 0, ] lowerCAmelCase = [ 9_9_9, 9_8_8, 9_7_7, 9_6_6, 9_5_5, 9_4_4, 9_3_3, 9_2_2, 9_1_1, 9_0_0, 8_9_9, 8_7_9, 8_5_9, 8_4_0, 8_2_0, 8_0_0, 7_9_9, 7_6_6, 7_3_3, 7_0_0, 6_9_9, 6_5_0, 6_0_0, 5_9_9, 5_0_0, 4_9_9, 4_0_0, 3_9_9, 3_5_0, 3_0_0, 2_9_9, 2_6_6, 2_3_3, 2_0_0, 1_9_9, 1_7_9, 1_5_9, 1_4_0, 1_2_0, 1_0_0, 9_9, 8_8, 7_7, 6_6, 5_5, 4_4, 3_3, 2_2, 1_1, 0, ] lowerCAmelCase = [ 9_9_9, 9_9_5, 9_9_2, 9_8_9, 9_8_5, 9_8_1, 9_7_8, 9_7_5, 9_7_1, 9_6_7, 9_6_4, 9_6_1, 9_5_7, 9_5_6, 9_5_1, 9_4_7, 9_4_2, 9_3_7, 9_3_3, 9_2_8, 9_2_3, 9_1_9, 9_1_4, 9_1_3, 9_0_8, 9_0_3, 8_9_7, 8_9_2, 8_8_7, 8_8_1, 8_7_6, 8_7_1, 8_7_0, 8_6_4, 8_5_8, 8_5_2, 8_4_6, 8_4_0, 8_3_4, 8_2_8, 8_2_7, 8_2_0, 8_1_3, 8_0_6, 7_9_9, 7_9_2, 7_8_5, 7_8_4, 7_7_7, 7_7_0, 7_6_3, 7_5_6, 7_4_9, 7_4_2, 7_4_1, 7_3_3, 7_2_4, 7_1_6, 7_0_7, 6_9_9, 6_9_8, 6_8_8, 6_7_7, 6_6_6, 6_5_6, 6_5_5, 6_4_5, 6_3_4, 6_2_3, 6_1_3, 6_1_2, 5_9_8, 5_8_4, 5_7_0, 5_6_9, 5_5_5, 5_4_1, 5_2_7, 5_2_6, 5_0_5, 4_8_4, 4_8_3, 4_6_2, 4_4_0, 4_3_9, 3_9_6, 3_9_5, 3_5_2, 3_5_1, 3_0_8, 3_0_7, 2_6_4, 2_6_3, 2_2_0, 2_1_9, 1_7_6, 1_3_2, 8_8, 4_4, 0, ] lowerCAmelCase = [ 9_9_9, 9_9_7, 9_9_5, 9_9_2, 9_9_0, 9_8_8, 9_8_6, 9_8_4, 9_8_1, 9_7_9, 9_7_7, 9_7_5, 9_7_2, 9_7_0, 9_6_8, 9_6_6, 9_6_4, 9_6_1, 9_5_9, 9_5_7, 9_5_6, 9_5_4, 9_5_1, 9_4_9, 9_4_6, 9_4_4, 9_4_1, 9_3_9, 9_3_6, 9_3_4, 9_3_1, 9_2_9, 9_2_6, 9_2_4, 9_2_1, 9_1_9, 9_1_6, 9_1_4, 9_1_3, 9_1_0, 9_0_7, 9_0_5, 9_0_2, 8_9_9, 8_9_6, 8_9_3, 8_9_1, 8_8_8, 8_8_5, 8_8_2, 8_7_9, 8_7_7, 8_7_4, 8_7_1, 8_7_0, 8_6_7, 8_6_4, 8_6_1, 8_5_8, 8_5_5, 8_5_2, 8_4_9, 8_4_6, 8_4_3, 8_4_0, 8_3_7, 8_3_4, 8_3_1, 8_2_8, 8_2_7, 8_2_4, 8_2_1, 8_1_7, 8_1_4, 8_1_1, 8_0_8, 8_0_4, 8_0_1, 7_9_8, 7_9_5, 7_9_1, 7_8_8, 7_8_5, 7_8_4, 7_8_0, 7_7_7, 7_7_4, 7_7_0, 7_6_6, 7_6_3, 7_6_0, 7_5_6, 7_5_2, 7_4_9, 7_4_6, 7_4_2, 7_4_1, 7_3_7, 7_3_3, 7_3_0, 7_2_6, 7_2_2, 7_1_8, 7_1_4, 7_1_0, 7_0_7, 7_0_3, 6_9_9, 6_9_8, 6_9_4, 6_9_0, 6_8_5, 6_8_1, 6_7_7, 6_7_3, 6_6_9, 6_6_4, 6_6_0, 6_5_6, 6_5_5, 6_5_0, 6_4_6, 6_4_1, 6_3_6, 6_3_2, 6_2_7, 6_2_2, 6_1_8, 6_1_3, 6_1_2, 6_0_7, 6_0_2, 5_9_6, 5_9_1, 5_8_6, 5_8_0, 5_7_5, 5_7_0, 5_6_9, 5_6_3, 5_5_7, 5_5_1, 5_4_5, 5_3_9, 5_3_3, 5_2_7, 5_2_6, 5_1_9, 5_1_2, 5_0_5, 4_9_8, 4_9_1, 4_8_4, 4_8_3, 4_7_4, 4_6_6, 4_5_7, 4_4_9, 4_4_0, 4_3_9, 4_2_8, 4_1_8, 4_0_7, 3_9_6, 3_9_5, 3_8_1, 3_6_6, 3_5_2, 3_5_1, 3_3_0, 3_0_8, 3_0_7, 2_8_6, 2_6_4, 2_6_3, 2_4_2, 2_2_0, 2_1_9, 1_7_6, 1_7_5, 1_3_2, 1_3_1, 8_8, 4_4, 0, ] lowerCAmelCase = [ 9_9_9, 9_9_1, 9_8_2, 9_7_4, 9_6_6, 9_5_8, 9_5_0, 9_4_1, 9_3_3, 9_2_5, 9_1_6, 9_0_8, 9_0_0, 8_9_9, 8_7_4, 8_5_0, 8_2_5, 8_0_0, 7_9_9, 7_0_0, 6_0_0, 5_0_0, 4_0_0, 3_0_0, 2_0_0, 1_0_0, 0, ] lowerCAmelCase = [ 9_9_9, 9_9_2, 9_8_5, 9_7_8, 9_7_1, 9_6_4, 9_5_7, 9_4_9, 9_4_2, 9_3_5, 9_2_8, 9_2_1, 9_1_4, 9_0_7, 9_0_0, 8_9_9, 8_7_9, 8_5_9, 8_4_0, 8_2_0, 8_0_0, 7_9_9, 7_6_6, 7_3_3, 7_0_0, 6_9_9, 6_5_0, 6_0_0, 5_9_9, 5_0_0, 4_9_9, 4_0_0, 3_9_9, 3_0_0, 2_9_9, 2_0_0, 1_9_9, 1_0_0, 9_9, 0, ] lowerCAmelCase = [ 9_9_9, 9_9_6, 9_9_2, 9_8_9, 9_8_5, 9_8_2, 9_7_9, 9_7_5, 9_7_2, 9_6_8, 9_6_5, 9_6_1, 9_5_8, 9_5_5, 9_5_1, 9_4_8, 9_4_4, 9_4_1, 9_3_8, 9_3_4, 9_3_1, 9_2_7, 9_2_4, 9_2_0, 9_1_7, 9_1_4, 9_1_0, 9_0_7, 9_0_3, 9_0_0, 8_9_9, 8_9_1, 8_8_4, 8_7_6, 8_6_9, 8_6_1, 8_5_3, 8_4_6, 8_3_8, 8_3_0, 8_2_3, 8_1_5, 8_0_8, 8_0_0, 7_9_9, 7_8_8, 7_7_7, 7_6_6, 7_5_5, 7_4_4, 7_3_3, 7_2_2, 7_1_1, 7_0_0, 6_9_9, 6_8_8, 6_7_7, 6_6_6, 6_5_5, 6_4_4, 6_3_3, 6_2_2, 6_1_1, 6_0_0, 5_9_9, 5_8_5, 5_7_1, 5_5_7, 5_4_2, 5_2_8, 5_1_4, 5_0_0, 4_9_9, 4_8_5, 4_7_1, 4_5_7, 4_4_2, 4_2_8, 4_1_4, 4_0_0, 3_9_9, 3_7_9, 3_5_9, 3_4_0, 3_2_0, 3_0_0, 2_9_9, 2_7_9, 2_5_9, 2_4_0, 2_2_0, 2_0_0, 1_9_9, 1_6_6, 1_3_3, 1_0_0, 9_9, 6_6, 3_3, 0, ]
304
0
"""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 ) _UpperCamelCase : Any = logging.getLogger(__name__) def a_ ( ): '''simple docstring''' lowercase__ : Union[str, Any] = argparse.ArgumentParser( description='Preprocess the data to avoid re-doing it several times by (tokenization + token_to_ids).' ) parser.add_argument('--file_path' , type=_lowerCAmelCase , default='data/dump.txt' , help='The path to the data.' ) parser.add_argument('--tokenizer_type' , type=_lowerCAmelCase , default='bert' , choices=['bert', 'roberta', 'gpt2'] ) parser.add_argument('--tokenizer_name' , type=_lowerCAmelCase , default='bert-base-uncased' , help='The tokenizer to use.' ) parser.add_argument('--dump_file' , type=_lowerCAmelCase , default='data/dump' , help='The dump file prefix.' ) lowercase__ : Any = parser.parse_args() logger.info(f"""Loading Tokenizer ({args.tokenizer_name})""" ) if args.tokenizer_type == "bert": lowercase__ : Tuple = BertTokenizer.from_pretrained(args.tokenizer_name ) lowercase__ : Optional[int] = tokenizer.special_tokens_map['cls_token'] # `[CLS]` lowercase__ : List[str] = tokenizer.special_tokens_map['sep_token'] # `[SEP]` elif args.tokenizer_type == "roberta": lowercase__ : Optional[int] = RobertaTokenizer.from_pretrained(args.tokenizer_name ) lowercase__ : Dict = tokenizer.special_tokens_map['cls_token'] # `<s>` lowercase__ : Any = tokenizer.special_tokens_map['sep_token'] # `</s>` elif args.tokenizer_type == "gpt2": lowercase__ : List[str] = GPTaTokenizer.from_pretrained(args.tokenizer_name ) lowercase__ : Any = tokenizer.special_tokens_map['bos_token'] # `<|endoftext|>` lowercase__ : Tuple = 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: lowercase__ : int = fp.readlines() logger.info('Start encoding' ) logger.info(f"""{len(_lowerCAmelCase )} examples to process.""" ) lowercase__ : Optional[Any] = [] lowercase__ : Optional[int] = 0 lowercase__ : List[Any] = 1_0000 lowercase__ : int = time.time() for text in data: lowercase__ : Any = f"""{bos} {text.strip()} {sep}""" lowercase__ : Optional[int] = tokenizer.encode(_lowerCAmelCase , add_special_tokens=_lowerCAmelCase ) rslt.append(_lowerCAmelCase ) iter += 1 if iter % interval == 0: lowercase__ : List[str] = time.time() logger.info(f"""{iter} examples processed. - {(end-start):.2f}s/{interval}expl""" ) lowercase__ : List[Any] = time.time() logger.info('Finished binarization' ) logger.info(f"""{len(_lowerCAmelCase )} examples processed.""" ) lowercase__ : Tuple = f"""{args.dump_file}.{args.tokenizer_name}.pickle""" lowercase__ : Any = tokenizer.vocab_size if vocab_size < (1 << 16): lowercase__ : Tuple = [np.uintaa(_lowerCAmelCase ) for d in rslt] else: lowercase__ : Dict = [np.intaa(_lowerCAmelCase ) for d in rslt] random.shuffle(rslt_ ) logger.info(f"""Dump to {dp_file}""" ) with open(_lowerCAmelCase , 'wb' ) as handle: pickle.dump(rslt_ , _lowerCAmelCase , protocol=pickle.HIGHEST_PROTOCOL ) if __name__ == "__main__": main()
77
"""simple docstring""" from . import __version__ # Backward compatibility imports, to make sure all those objects can be found in file_utils from .utils import ( CLOUDFRONT_DISTRIB_PREFIX, CONFIG_NAME, DISABLE_TELEMETRY, DUMMY_INPUTS, DUMMY_MASK, ENV_VARS_TRUE_AND_AUTO_VALUES, ENV_VARS_TRUE_VALUES, FEATURE_EXTRACTOR_NAME, FLAX_WEIGHTS_NAME, HF_MODULES_CACHE, HUGGINGFACE_CO_PREFIX, HUGGINGFACE_CO_RESOLVE_ENDPOINT, MODEL_CARD_NAME, MULTIPLE_CHOICE_DUMMY_INPUTS, PYTORCH_PRETRAINED_BERT_CACHE, PYTORCH_TRANSFORMERS_CACHE, S3_BUCKET_PREFIX, SENTENCEPIECE_UNDERLINE, SPIECE_UNDERLINE, TF2_WEIGHTS_NAME, TF_WEIGHTS_NAME, TORCH_FX_REQUIRED_VERSION, TRANSFORMERS_CACHE, TRANSFORMERS_DYNAMIC_MODULE_NAME, USE_JAX, USE_TF, USE_TORCH, WEIGHTS_INDEX_NAME, WEIGHTS_NAME, ContextManagers, DummyObject, EntryNotFoundError, ExplicitEnum, ModelOutput, PaddingStrategy, PushToHubMixin, RepositoryNotFoundError, RevisionNotFoundError, TensorType, _LazyModule, add_code_sample_docstrings, add_end_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, cached_property, copy_func, default_cache_path, define_sagemaker_information, get_cached_models, get_file_from_repo, get_full_repo_name, get_torch_version, has_file, http_user_agent, is_apex_available, is_bsa_available, is_coloredlogs_available, is_datasets_available, is_detectrona_available, is_faiss_available, is_flax_available, is_ftfy_available, is_in_notebook, is_ipex_available, is_librosa_available, is_offline_mode, is_onnx_available, is_pandas_available, is_phonemizer_available, is_protobuf_available, is_psutil_available, is_pyanvml_available, is_pyctcdecode_available, is_pytesseract_available, is_pytorch_quantization_available, is_rjieba_available, is_sagemaker_dp_enabled, is_sagemaker_mp_enabled, is_scipy_available, is_sentencepiece_available, is_seqio_available, is_sklearn_available, is_soundfile_availble, is_spacy_available, is_speech_available, is_tensor, is_tensorflow_probability_available, is_tfaonnx_available, is_tf_available, is_timm_available, is_tokenizers_available, is_torch_available, is_torch_bfaa_available, is_torch_cuda_available, is_torch_fx_available, is_torch_fx_proxy, is_torch_mps_available, is_torch_tfaa_available, is_torch_tpu_available, is_torchaudio_available, is_training_run_on_sagemaker, is_vision_available, replace_return_docstrings, requires_backends, to_numpy, to_py_obj, torch_only_method, )
77
1
"""simple docstring""" from __future__ import annotations import sys from collections import deque from typing import Generic, TypeVar A_ = TypeVar('''T''') class lowercase( Generic[T] ): '''simple docstring''' lowercase__ = 42 # Cache store of keys lowercase__ = 42 # References of the keys in cache lowercase__ = 10 # Maximum capacity of cache def __init__( self: Any, a_: int ): '''simple docstring''' _snake_case : str = deque() _snake_case : str = set() if not n: _snake_case : Union[str, Any] = sys.maxsize elif n < 0: raise ValueError("""n should be an integer greater than 0.""" ) else: _snake_case : str = n def UpperCamelCase_ ( self: List[Any], a_: T ): '''simple docstring''' if x not in self.key_reference: if len(self.dq_store ) == LRUCache._MAX_CAPACITY: _snake_case : int = self.dq_store.pop() self.key_reference.remove(_lowerCAmelCase ) else: self.dq_store.remove(_lowerCAmelCase ) self.dq_store.appendleft(_lowerCAmelCase ) self.key_reference.add(_lowerCAmelCase ) def UpperCamelCase_ ( self: Optional[Any] ): '''simple docstring''' for k in self.dq_store: print(_lowerCAmelCase ) def __repr__( self: str ): '''simple docstring''' return f"LRUCache({self._MAX_CAPACITY}) => {list(self.dq_store )}" if __name__ == "__main__": import doctest doctest.testmod() A_ = LRUCache(4) lru_cache.refer('''A''') lru_cache.refer(2) lru_cache.refer(3) lru_cache.refer('''A''') lru_cache.refer(4) lru_cache.refer(5) lru_cache.display() print(lru_cache) assert str(lru_cache) == "LRUCache(4) => [5, 4, 'A', 3]"
354
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available A_ = { '''configuration_maskformer''': ['''MASKFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''MaskFormerConfig'''], '''configuration_maskformer_swin''': ['''MaskFormerSwinConfig'''], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ = ['''MaskFormerFeatureExtractor'''] A_ = ['''MaskFormerImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ = [ '''MASKFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''', '''MaskFormerForInstanceSegmentation''', '''MaskFormerModel''', '''MaskFormerPreTrainedModel''', ] A_ = [ '''MaskFormerSwinBackbone''', '''MaskFormerSwinModel''', '''MaskFormerSwinPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_maskformer import MASKFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, MaskFormerConfig from .configuration_maskformer_swin import MaskFormerSwinConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_maskformer import MaskFormerFeatureExtractor from .image_processing_maskformer import MaskFormerImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_maskformer import ( MASKFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, MaskFormerForInstanceSegmentation, MaskFormerModel, MaskFormerPreTrainedModel, ) from .modeling_maskformer_swin import ( MaskFormerSwinBackbone, MaskFormerSwinModel, MaskFormerSwinPreTrainedModel, ) else: import sys A_ = _LazyModule(__name__, globals()['''__file__'''], _import_structure)
132
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available SCREAMING_SNAKE_CASE__ : Union[str, Any] = { "configuration_time_series_transformer": [ "TIME_SERIES_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "TimeSeriesTransformerConfig", ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : Optional[int] = [ "TIME_SERIES_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "TimeSeriesTransformerForPrediction", "TimeSeriesTransformerModel", "TimeSeriesTransformerPreTrainedModel", ] if TYPE_CHECKING: from .configuration_time_series_transformer import ( TIME_SERIES_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, TimeSeriesTransformerConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_time_series_transformer import ( TIME_SERIES_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TimeSeriesTransformerForPrediction, TimeSeriesTransformerModel, TimeSeriesTransformerPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE__ : Union[str, Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
270
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 lowerCAmelCase__ ( unittest.TestCase ): def __A ( self : Optional[int] ) -> List[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 __A ( self : List[str] , SCREAMING_SNAKE_CASE__ : List[Any] ) -> Optional[Any]: # configuration for running training on smdistributed Model Parallel __lowerCamelCase = { '''enabled''': True, '''processes_per_host''': 8, } __lowerCamelCase = { '''enabled''': True, '''parameters''': { '''microbatches''': 4, '''placement_strategy''': '''spread''', '''pipeline''': '''interleaved''', '''optimize''': '''speed''', '''partitions''': 4, '''ddp''': True, }, } __lowerCamelCase = {'''smdistributed''': {'''modelparallel''': smp_options}, '''mpi''': mpi_options} __lowerCamelCase = '''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_00, } , metric_definitions=self.env.metric_definitions , distribution=SCREAMING_SNAKE_CASE__ , py_version='''py36''' , ) def __A ( self : List[Any] , SCREAMING_SNAKE_CASE__ : List[Any] ) -> List[str]: TrainingJobAnalytics(SCREAMING_SNAKE_CASE__ ).export_csv(f'''{self.env.test_path}/{job_name}_metrics.csv''' ) @parameterized.expand([(1,)] ) def __A ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Optional[int]: # create estimator __lowerCamelCase = self.create_estimator(SCREAMING_SNAKE_CASE__ ) # run training estimator.fit() # result dataframe __lowerCamelCase = TrainingJobAnalytics(estimator.latest_training_job.name ).dataframe() # extract kpis __lowerCamelCase = list(result_metrics_df[result_metrics_df.metric_name == '''eval_accuracy''']['''value'''] ) __lowerCamelCase = list(result_metrics_df[result_metrics_df.metric_name == '''eval_loss''']['''value'''] ) # get train time from SageMaker job, this includes starting, preprocessing, stopping __lowerCamelCase = ( Session().describe_training_job(estimator.latest_training_job.name ).get('''TrainingTimeInSeconds''' , 99_99_99 ) ) # 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__ )
270
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available _a = { 'configuration_transfo_xl': ['TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP', 'TransfoXLConfig'], 'tokenization_transfo_xl': ['TransfoXLCorpus', 'TransfoXLTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _a = [ 'TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST', 'AdaptiveEmbedding', 'TransfoXLForSequenceClassification', 'TransfoXLLMHeadModel', 'TransfoXLModel', 'TransfoXLPreTrainedModel', 'load_tf_weights_in_transfo_xl', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _a = [ 'TF_TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFAdaptiveEmbedding', 'TFTransfoXLForSequenceClassification', 'TFTransfoXLLMHeadModel', 'TFTransfoXLMainLayer', 'TFTransfoXLModel', 'TFTransfoXLPreTrainedModel', ] if TYPE_CHECKING: from .configuration_transfo_xl import TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP, TransfoXLConfig from .tokenization_transfo_xl import TransfoXLCorpus, TransfoXLTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_transfo_xl import ( TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST, AdaptiveEmbedding, TransfoXLForSequenceClassification, TransfoXLLMHeadModel, TransfoXLModel, TransfoXLPreTrainedModel, load_tf_weights_in_transfo_xl, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_transfo_xl import ( TF_TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST, TFAdaptiveEmbedding, TFTransfoXLForSequenceClassification, TFTransfoXLLMHeadModel, TFTransfoXLMainLayer, TFTransfoXLModel, TFTransfoXLPreTrainedModel, ) else: import sys _a = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
371
"""simple docstring""" import re from filelock import FileLock try: import nltk _a = True except (ImportError, ModuleNotFoundError): _a = False if NLTK_AVAILABLE: with FileLock('.lock') as lock: nltk.download('punkt', quiet=True) def _A ( UpperCamelCase_ : str) -> str: '''simple docstring''' re.sub("<n>", "", UpperCamelCase_) # remove pegasus newline char assert NLTK_AVAILABLE, "nltk must be installed to separate newlines between sentences. (pip install nltk)" return "\n".join(nltk.sent_tokenize(UpperCamelCase_))
144
0
"""simple docstring""" from ..utils import DummyObject, requires_backends class __lowerCamelCase ( metaclass=a__ ): '''simple docstring''' A_ : str = ['keras_nlp'] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> Tuple: requires_backends(self , ['''keras_nlp'''] )
320
"""simple docstring""" import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import AddedToken from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_rembert import RemBertTokenizer else: __snake_case = None __snake_case = logging.get_logger(__name__) __snake_case = {'''vocab_file''': '''sentencepiece.model''', '''tokenizer_file''': '''tokenizer.json'''} __snake_case = { '''vocab_file''': { '''google/rembert''': '''https://huggingface.co/google/rembert/resolve/main/sentencepiece.model''', }, '''tokenizer_file''': { '''google/rembert''': '''https://huggingface.co/google/rembert/resolve/main/tokenizer.json''', }, } __snake_case = { '''google/rembert''': 256, } __snake_case = '''▁''' class __lowerCamelCase ( a__ ): '''simple docstring''' A_ : Optional[Any] = VOCAB_FILES_NAMES A_ : List[str] = PRETRAINED_VOCAB_FILES_MAP A_ : str = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES A_ : List[Any] = RemBertTokenizer def __init__( self , __UpperCAmelCase=None , __UpperCAmelCase=None , __UpperCAmelCase=True , __UpperCAmelCase=True , __UpperCAmelCase=False , __UpperCAmelCase="[CLS]" , __UpperCAmelCase="[SEP]" , __UpperCAmelCase="<unk>" , __UpperCAmelCase="[SEP]" , __UpperCAmelCase="<pad>" , __UpperCAmelCase="[CLS]" , __UpperCAmelCase="[MASK]" , **__UpperCAmelCase , ) -> List[Any]: # Mask token behave like a normal word, i.e. include the space before it _a = AddedToken(__UpperCAmelCase , lstrip=__UpperCAmelCase , rstrip=__UpperCAmelCase ) if isinstance(__UpperCAmelCase , __UpperCAmelCase ) else mask_token super().__init__( __UpperCAmelCase , tokenizer_file=__UpperCAmelCase , do_lower_case=__UpperCAmelCase , remove_space=__UpperCAmelCase , keep_accents=__UpperCAmelCase , bos_token=__UpperCAmelCase , eos_token=__UpperCAmelCase , unk_token=__UpperCAmelCase , sep_token=__UpperCAmelCase , pad_token=__UpperCAmelCase , cls_token=__UpperCAmelCase , mask_token=__UpperCAmelCase , **__UpperCAmelCase , ) _a = do_lower_case _a = remove_space _a = keep_accents _a = vocab_file _a = False if not self.vocab_file else True def _UpperCAmelCase ( self , __UpperCAmelCase , __UpperCAmelCase = None ) -> List[int]: _a = [self.sep_token_id] _a = [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 _UpperCAmelCase ( self , __UpperCAmelCase , __UpperCAmelCase = None , __UpperCAmelCase = False ) -> List[int]: 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(__UpperCAmelCase )) + [1] + ([0] * len(__UpperCAmelCase )) + [1] return [1] + ([0] * len(__UpperCAmelCase )) + [1] def _UpperCAmelCase ( self , __UpperCAmelCase , __UpperCAmelCase = None ) -> List[int]: _a = [self.sep_token_id] _a = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def _UpperCAmelCase ( self , __UpperCAmelCase , __UpperCAmelCase = None ) -> Tuple[str]: if not os.path.isdir(__UpperCAmelCase ): logger.error('''Vocabulary path ({}) should be a directory'''.format(__UpperCAmelCase ) ) return _a = os.path.join( __UpperCAmelCase , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__UpperCAmelCase ): copyfile(self.vocab_file , __UpperCAmelCase ) return (out_vocab_file,)
320
1
import os from shutil import copyfile from typing import List, Optional, Tuple from tokenizers import processors from ...tokenization_utils import AddedToken, BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_nllb import NllbTokenizer else: __a = None __a = logging.get_logger(__name__) __a = {'''vocab_file''': '''sentencepiece.bpe.model''', '''tokenizer_file''': '''tokenizer.json'''} __a = { '''vocab_file''': { '''facebook/nllb-200-distilled-600M''': ( '''https://huggingface.co/facebook/nllb-200-distilled-600M/resolve/main/sentencepiece.bpe.model''' ), }, '''tokenizer_file''': { '''facebook/nllb-200-distilled-600M''': ( '''https://huggingface.co/facebook/nllb-200-distilled-600M/resolve/main/tokenizer.json''' ), }, } __a = { '''facebook/nllb-large-en-ro''': 10_24, '''facebook/nllb-200-distilled-600M''': 10_24, } # fmt: off __a = ['''ace_Arab''', '''ace_Latn''', '''acm_Arab''', '''acq_Arab''', '''aeb_Arab''', '''afr_Latn''', '''ajp_Arab''', '''aka_Latn''', '''amh_Ethi''', '''apc_Arab''', '''arb_Arab''', '''ars_Arab''', '''ary_Arab''', '''arz_Arab''', '''asm_Beng''', '''ast_Latn''', '''awa_Deva''', '''ayr_Latn''', '''azb_Arab''', '''azj_Latn''', '''bak_Cyrl''', '''bam_Latn''', '''ban_Latn''', '''bel_Cyrl''', '''bem_Latn''', '''ben_Beng''', '''bho_Deva''', '''bjn_Arab''', '''bjn_Latn''', '''bod_Tibt''', '''bos_Latn''', '''bug_Latn''', '''bul_Cyrl''', '''cat_Latn''', '''ceb_Latn''', '''ces_Latn''', '''cjk_Latn''', '''ckb_Arab''', '''crh_Latn''', '''cym_Latn''', '''dan_Latn''', '''deu_Latn''', '''dik_Latn''', '''dyu_Latn''', '''dzo_Tibt''', '''ell_Grek''', '''eng_Latn''', '''epo_Latn''', '''est_Latn''', '''eus_Latn''', '''ewe_Latn''', '''fao_Latn''', '''pes_Arab''', '''fij_Latn''', '''fin_Latn''', '''fon_Latn''', '''fra_Latn''', '''fur_Latn''', '''fuv_Latn''', '''gla_Latn''', '''gle_Latn''', '''glg_Latn''', '''grn_Latn''', '''guj_Gujr''', '''hat_Latn''', '''hau_Latn''', '''heb_Hebr''', '''hin_Deva''', '''hne_Deva''', '''hrv_Latn''', '''hun_Latn''', '''hye_Armn''', '''ibo_Latn''', '''ilo_Latn''', '''ind_Latn''', '''isl_Latn''', '''ita_Latn''', '''jav_Latn''', '''jpn_Jpan''', '''kab_Latn''', '''kac_Latn''', '''kam_Latn''', '''kan_Knda''', '''kas_Arab''', '''kas_Deva''', '''kat_Geor''', '''knc_Arab''', '''knc_Latn''', '''kaz_Cyrl''', '''kbp_Latn''', '''kea_Latn''', '''khm_Khmr''', '''kik_Latn''', '''kin_Latn''', '''kir_Cyrl''', '''kmb_Latn''', '''kon_Latn''', '''kor_Hang''', '''kmr_Latn''', '''lao_Laoo''', '''lvs_Latn''', '''lij_Latn''', '''lim_Latn''', '''lin_Latn''', '''lit_Latn''', '''lmo_Latn''', '''ltg_Latn''', '''ltz_Latn''', '''lua_Latn''', '''lug_Latn''', '''luo_Latn''', '''lus_Latn''', '''mag_Deva''', '''mai_Deva''', '''mal_Mlym''', '''mar_Deva''', '''min_Latn''', '''mkd_Cyrl''', '''plt_Latn''', '''mlt_Latn''', '''mni_Beng''', '''khk_Cyrl''', '''mos_Latn''', '''mri_Latn''', '''zsm_Latn''', '''mya_Mymr''', '''nld_Latn''', '''nno_Latn''', '''nob_Latn''', '''npi_Deva''', '''nso_Latn''', '''nus_Latn''', '''nya_Latn''', '''oci_Latn''', '''gaz_Latn''', '''ory_Orya''', '''pag_Latn''', '''pan_Guru''', '''pap_Latn''', '''pol_Latn''', '''por_Latn''', '''prs_Arab''', '''pbt_Arab''', '''quy_Latn''', '''ron_Latn''', '''run_Latn''', '''rus_Cyrl''', '''sag_Latn''', '''san_Deva''', '''sat_Beng''', '''scn_Latn''', '''shn_Mymr''', '''sin_Sinh''', '''slk_Latn''', '''slv_Latn''', '''smo_Latn''', '''sna_Latn''', '''snd_Arab''', '''som_Latn''', '''sot_Latn''', '''spa_Latn''', '''als_Latn''', '''srd_Latn''', '''srp_Cyrl''', '''ssw_Latn''', '''sun_Latn''', '''swe_Latn''', '''swh_Latn''', '''szl_Latn''', '''tam_Taml''', '''tat_Cyrl''', '''tel_Telu''', '''tgk_Cyrl''', '''tgl_Latn''', '''tha_Thai''', '''tir_Ethi''', '''taq_Latn''', '''taq_Tfng''', '''tpi_Latn''', '''tsn_Latn''', '''tso_Latn''', '''tuk_Latn''', '''tum_Latn''', '''tur_Latn''', '''twi_Latn''', '''tzm_Tfng''', '''uig_Arab''', '''ukr_Cyrl''', '''umb_Latn''', '''urd_Arab''', '''uzn_Latn''', '''vec_Latn''', '''vie_Latn''', '''war_Latn''', '''wol_Latn''', '''xho_Latn''', '''ydd_Hebr''', '''yor_Latn''', '''yue_Hant''', '''zho_Hans''', '''zho_Hant''', '''zul_Latn'''] class __SCREAMING_SNAKE_CASE ( a__ ): A : Optional[Any] = VOCAB_FILES_NAMES A : Union[str, Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES A : Optional[int] = PRETRAINED_VOCAB_FILES_MAP A : str = ['input_ids', 'attention_mask'] A : List[Any] = NllbTokenizer A : Dict = [] A : str = [] def __init__( self , SCREAMING_SNAKE_CASE__=None , SCREAMING_SNAKE_CASE__=None , SCREAMING_SNAKE_CASE__="<s>" , SCREAMING_SNAKE_CASE__="</s>" , SCREAMING_SNAKE_CASE__="</s>" , SCREAMING_SNAKE_CASE__="<s>" , SCREAMING_SNAKE_CASE__="<unk>" , SCREAMING_SNAKE_CASE__="<pad>" , SCREAMING_SNAKE_CASE__="<mask>" , SCREAMING_SNAKE_CASE__=None , SCREAMING_SNAKE_CASE__=None , SCREAMING_SNAKE_CASE__=None , SCREAMING_SNAKE_CASE__=False , **SCREAMING_SNAKE_CASE__ , ): lowercase : Dict = AddedToken(_lowerCamelCase , lstrip=_lowerCamelCase , rstrip=_lowerCamelCase ) if isinstance(_lowerCamelCase , _lowerCamelCase ) else mask_token lowercase : Union[str, Any] = legacy_behaviour super().__init__( vocab_file=_lowerCamelCase , tokenizer_file=_lowerCamelCase , bos_token=_lowerCamelCase , eos_token=_lowerCamelCase , sep_token=_lowerCamelCase , cls_token=_lowerCamelCase , unk_token=_lowerCamelCase , pad_token=_lowerCamelCase , mask_token=_lowerCamelCase , src_lang=_lowerCamelCase , tgt_lang=_lowerCamelCase , additional_special_tokens=_lowerCamelCase , legacy_behaviour=_lowerCamelCase , **_lowerCamelCase , ) lowercase : str = vocab_file lowercase : int = False if not self.vocab_file else True lowercase : Any = FAIRSEQ_LANGUAGE_CODES.copy() if additional_special_tokens is not None: # Only add those special tokens if they are not already there. _additional_special_tokens.extend( [t for t in additional_special_tokens if t not in _additional_special_tokens] ) self.add_special_tokens({'''additional_special_tokens''': _additional_special_tokens} ) lowercase : str = { lang_code: self.convert_tokens_to_ids(_lowerCamelCase ) for lang_code in FAIRSEQ_LANGUAGE_CODES } lowercase : Any = src_lang if src_lang is not None else '''eng_Latn''' lowercase : Tuple = self.convert_tokens_to_ids(self._src_lang ) lowercase : Union[str, Any] = tgt_lang self.set_src_lang_special_tokens(self._src_lang ) @property def __lowerCamelCase ( self ): return self._src_lang @src_lang.setter def __lowerCamelCase ( self , SCREAMING_SNAKE_CASE__ ): lowercase : Dict = new_src_lang self.set_src_lang_special_tokens(self._src_lang ) def __lowerCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = None ): if token_ids_a is None: return self.prefix_tokens + token_ids_a + self.suffix_tokens # We don't expect to process pairs, but leave the pair logic for API consistency return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens def __lowerCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = None ): lowercase : Dict = [self.sep_token_id] lowercase : List[str] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def __lowerCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ): if src_lang is None or tgt_lang is None: raise ValueError('''Translation requires a `src_lang` and a `tgt_lang` for this model''' ) lowercase : List[Any] = src_lang lowercase : List[Any] = self(_lowerCamelCase , add_special_tokens=_lowerCamelCase , return_tensors=_lowerCamelCase , **_lowerCamelCase ) lowercase : str = self.convert_tokens_to_ids(_lowerCamelCase ) lowercase : Tuple = tgt_lang_id return inputs def __lowerCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = "eng_Latn" , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = "fra_Latn" , **SCREAMING_SNAKE_CASE__ , ): lowercase : Dict = src_lang lowercase : Any = tgt_lang return super().prepare_seqaseq_batch(_lowerCamelCase , _lowerCamelCase , **_lowerCamelCase ) def __lowerCamelCase ( self ): return self.set_src_lang_special_tokens(self.src_lang ) def __lowerCamelCase ( self ): return self.set_tgt_lang_special_tokens(self.tgt_lang ) def __lowerCamelCase ( self , SCREAMING_SNAKE_CASE__ ): lowercase : Optional[int] = self.convert_tokens_to_ids(_lowerCamelCase ) if self.legacy_behaviour: lowercase : Tuple = [] lowercase : int = [self.eos_token_id, self.cur_lang_code] else: lowercase : Any = [self.cur_lang_code] lowercase : str = [self.eos_token_id] lowercase : Dict = self.convert_ids_to_tokens(self.prefix_tokens ) lowercase : str = self.convert_ids_to_tokens(self.suffix_tokens ) lowercase : Tuple = processors.TemplateProcessing( single=prefix_tokens_str + ['''$A'''] + suffix_tokens_str , pair=prefix_tokens_str + ['''$A''', '''$B'''] + suffix_tokens_str , special_tokens=list(zip(prefix_tokens_str + suffix_tokens_str , self.prefix_tokens + self.suffix_tokens ) ) , ) def __lowerCamelCase ( self , SCREAMING_SNAKE_CASE__ ): lowercase : str = self.convert_tokens_to_ids(_lowerCamelCase ) if self.legacy_behaviour: lowercase : Tuple = [] lowercase : Optional[Any] = [self.eos_token_id, self.cur_lang_code] else: lowercase : Dict = [self.cur_lang_code] lowercase : Tuple = [self.eos_token_id] lowercase : List[Any] = self.convert_ids_to_tokens(self.prefix_tokens ) lowercase : int = self.convert_ids_to_tokens(self.suffix_tokens ) lowercase : Union[str, Any] = processors.TemplateProcessing( single=prefix_tokens_str + ['''$A'''] + suffix_tokens_str , pair=prefix_tokens_str + ['''$A''', '''$B'''] + suffix_tokens_str , special_tokens=list(zip(prefix_tokens_str + suffix_tokens_str , self.prefix_tokens + self.suffix_tokens ) ) , ) def __lowerCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = None ): if not self.can_save_slow_tokenizer: raise ValueError( '''Your fast tokenizer does not have the necessary information to save the vocabulary for a slow ''' '''tokenizer.''' ) if not os.path.isdir(_lowerCamelCase ): logger.error(f"""Vocabulary path ({save_directory}) should be a directory.""" ) return lowercase : Any = os.path.join( _lowerCamelCase , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_lowerCamelCase ): copyfile(self.vocab_file , _lowerCamelCase ) return (out_vocab_file,)
354
from ...configuration_utils import PretrainedConfig from ...utils import logging __a = logging.get_logger(__name__) __a = { '''MIT/ast-finetuned-audioset-10-10-0.4593''': ( '''https://huggingface.co/MIT/ast-finetuned-audioset-10-10-0.4593/resolve/main/config.json''' ), } class __SCREAMING_SNAKE_CASE ( A__ ): A : Union[str, Any] = 'audio-spectrogram-transformer' def __init__( self , SCREAMING_SNAKE_CASE__=768 , SCREAMING_SNAKE_CASE__=12 , SCREAMING_SNAKE_CASE__=12 , SCREAMING_SNAKE_CASE__=3072 , SCREAMING_SNAKE_CASE__="gelu" , SCREAMING_SNAKE_CASE__=0.0 , SCREAMING_SNAKE_CASE__=0.0 , SCREAMING_SNAKE_CASE__=0.02 , SCREAMING_SNAKE_CASE__=1E-12 , SCREAMING_SNAKE_CASE__=16 , SCREAMING_SNAKE_CASE__=True , SCREAMING_SNAKE_CASE__=10 , SCREAMING_SNAKE_CASE__=10 , SCREAMING_SNAKE_CASE__=1024 , SCREAMING_SNAKE_CASE__=128 , **SCREAMING_SNAKE_CASE__ , ): super().__init__(**SCREAMING_SNAKE_CASE__ ) lowercase : Any = hidden_size lowercase : Optional[Any] = num_hidden_layers lowercase : Any = num_attention_heads lowercase : Optional[int] = intermediate_size lowercase : List[str] = hidden_act lowercase : Tuple = hidden_dropout_prob lowercase : Optional[Any] = attention_probs_dropout_prob lowercase : Optional[Any] = initializer_range lowercase : str = layer_norm_eps lowercase : Any = patch_size lowercase : Tuple = qkv_bias lowercase : str = frequency_stride lowercase : Union[str, Any] = time_stride lowercase : Dict = max_length lowercase : List[str] = num_mel_bins
173
0
import os import unittest from huggingface_hub.utils import are_progress_bars_disabled import transformers.models.bart.tokenization_bart from transformers import logging from transformers.testing_utils import CaptureLogger, mockenv, mockenv_context from transformers.utils.logging import disable_progress_bar, enable_progress_bar class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' def UpperCamelCase_ ( self : int ): __A = logging.get_logger() # the current default level is logging.WARNING __A = logging.get_verbosity() logging.set_verbosity_error() self.assertEqual(logger.getEffectiveLevel() ,logging.get_verbosity() ) logging.set_verbosity_warning() self.assertEqual(logger.getEffectiveLevel() ,logging.get_verbosity() ) logging.set_verbosity_info() self.assertEqual(logger.getEffectiveLevel() ,logging.get_verbosity() ) logging.set_verbosity_debug() self.assertEqual(logger.getEffectiveLevel() ,logging.get_verbosity() ) # restore to the original level logging.set_verbosity(A ) def UpperCamelCase_ ( self : Dict ): __A = logging.get_verbosity() __A = logging.get_logger("transformers.models.bart.tokenization_bart" ) __A = "Testing 1, 2, 3" # should be able to log warnings (if default settings weren't overridden by `pytest --log-level-all`) if level_origin <= logging.WARNING: with CaptureLogger(A ) as cl: logger.warning(A ) self.assertEqual(cl.out ,msg + "\n" ) # this is setting the level for all of `transformers.*` loggers logging.set_verbosity_error() # should not be able to log warnings with CaptureLogger(A ) as cl: logger.warning(A ) self.assertEqual(cl.out ,"" ) # should be able to log warnings again logging.set_verbosity_warning() with CaptureLogger(A ) as cl: logger.warning(A ) self.assertEqual(cl.out ,msg + "\n" ) # restore to the original level logging.set_verbosity(A ) @mockenv(TRANSFORMERS_VERBOSITY="error" ) def UpperCamelCase_ ( self : Optional[Any] ): # reset for the env var to take effect, next time some logger call is made transformers.utils.logging._reset_library_root_logger() # this action activates the env var __A = logging.get_logger("transformers.models.bart.tokenization_bart" ) __A = os.getenv("TRANSFORMERS_VERBOSITY" ,A ) __A = logging.log_levels[env_level_str] __A = logging.get_verbosity() self.assertEqual( A ,A ,f'''TRANSFORMERS_VERBOSITY={env_level_str}/{env_level}, but internal verbosity is {current_level}''' ,) # restore to the original level __A = "" transformers.utils.logging._reset_library_root_logger() @mockenv(TRANSFORMERS_VERBOSITY="super-error" ) def UpperCamelCase_ ( self : Tuple ): # reset for the env var to take effect, next time some logger call is made transformers.utils.logging._reset_library_root_logger() __A = logging.logging.getLogger() with CaptureLogger(A ) as cl: # this action activates the env var logging.get_logger("transformers.models.bart.tokenization_bart" ) self.assertIn("Unknown option TRANSFORMERS_VERBOSITY=super-error" ,cl.out ) # no need to restore as nothing was changed def UpperCamelCase_ ( self : int ): # testing `logger.warning_advice()` transformers.utils.logging._reset_library_root_logger() __A = logging.get_logger("transformers.models.bart.tokenization_bart" ) __A = "Testing 1, 2, 3" with mockenv_context(TRANSFORMERS_NO_ADVISORY_WARNINGS="1" ): # nothing should be logged as env var disables this method with CaptureLogger(A ) as cl: logger.warning_advice(A ) self.assertEqual(cl.out ,"" ) with mockenv_context(TRANSFORMERS_NO_ADVISORY_WARNINGS="" ): # should log normally as TRANSFORMERS_NO_ADVISORY_WARNINGS is unset with CaptureLogger(A ) as cl: logger.warning_advice(A ) self.assertEqual(cl.out ,msg + "\n" ) def UpperCAmelCase ( ) -> List[str]: """simple docstring""" disable_progress_bar() assert are_progress_bars_disabled() enable_progress_bar() assert not are_progress_bars_disabled()
15
'''simple docstring''' from __future__ import annotations import queue class __A : def __init__(self : Optional[Any] , __a : str ): UpperCAmelCase_ = data UpperCAmelCase_ = None UpperCAmelCase_ = None def lowerCAmelCase_ ( ) -> TreeNode: '''simple docstring''' print("\n********Press N to stop entering at any point of time********\n" ) UpperCAmelCase_ = input("Enter the value of the root node: " ).strip().lower() UpperCAmelCase_ = queue.Queue() UpperCAmelCase_ = TreeNode(int(snake_case_ ) ) q.put(snake_case_ ) while not q.empty(): UpperCAmelCase_ = q.get() UpperCAmelCase_ = f"""Enter the left node of {node_found.data}: """ UpperCAmelCase_ = input(snake_case_ ).strip().lower() or "n" if check == "n": return tree_node UpperCAmelCase_ = TreeNode(int(snake_case_ ) ) UpperCAmelCase_ = left_node q.put(snake_case_ ) UpperCAmelCase_ = f"""Enter the right node of {node_found.data}: """ UpperCAmelCase_ = input(snake_case_ ).strip().lower() or "n" if check == "n": return tree_node UpperCAmelCase_ = TreeNode(int(snake_case_ ) ) UpperCAmelCase_ = right_node q.put(snake_case_ ) raise def lowerCAmelCase_ ( snake_case_ : TreeNode ) -> None: '''simple docstring''' if not isinstance(snake_case_ , snake_case_ ) or not node: return print(node.data , end="," ) pre_order(node.left ) pre_order(node.right ) def lowerCAmelCase_ ( snake_case_ : TreeNode ) -> None: '''simple docstring''' if not isinstance(snake_case_ , snake_case_ ) or not node: return in_order(node.left ) print(node.data , end="," ) in_order(node.right ) def lowerCAmelCase_ ( snake_case_ : TreeNode ) -> None: '''simple docstring''' if not isinstance(snake_case_ , snake_case_ ) or not node: return post_order(node.left ) post_order(node.right ) print(node.data , end="," ) def lowerCAmelCase_ ( snake_case_ : TreeNode ) -> None: '''simple docstring''' if not isinstance(snake_case_ , snake_case_ ) or not node: return UpperCAmelCase_ = queue.Queue() q.put(snake_case_ ) while not q.empty(): UpperCAmelCase_ = q.get() print(node_dequeued.data , end="," ) if node_dequeued.left: q.put(node_dequeued.left ) if node_dequeued.right: q.put(node_dequeued.right ) def lowerCAmelCase_ ( snake_case_ : TreeNode ) -> None: '''simple docstring''' if not isinstance(snake_case_ , snake_case_ ) or not node: return UpperCAmelCase_ = queue.Queue() q.put(snake_case_ ) while not q.empty(): UpperCAmelCase_ = [] while not q.empty(): UpperCAmelCase_ = q.get() print(node_dequeued.data , end="," ) if node_dequeued.left: list_.append(node_dequeued.left ) if node_dequeued.right: list_.append(node_dequeued.right ) print() for node in list_: q.put(snake_case_ ) def lowerCAmelCase_ ( snake_case_ : TreeNode ) -> None: '''simple docstring''' if not isinstance(snake_case_ , snake_case_ ) or not node: return UpperCAmelCase_ = [] UpperCAmelCase_ = node while n or stack: while n: # start from root node, find its left child print(n.data , end="," ) stack.append(snake_case_ ) UpperCAmelCase_ = n.left # end of while means current node doesn't have left child UpperCAmelCase_ = stack.pop() # start to traverse its right child UpperCAmelCase_ = n.right def lowerCAmelCase_ ( snake_case_ : TreeNode ) -> None: '''simple docstring''' if not isinstance(snake_case_ , snake_case_ ) or not node: return UpperCAmelCase_ = [] UpperCAmelCase_ = node while n or stack: while n: stack.append(snake_case_ ) UpperCAmelCase_ = n.left UpperCAmelCase_ = stack.pop() print(n.data , end="," ) UpperCAmelCase_ = n.right def lowerCAmelCase_ ( snake_case_ : TreeNode ) -> None: '''simple docstring''' if not isinstance(snake_case_ , snake_case_ ) or not node: return UpperCAmelCase_ , UpperCAmelCase_ = [], [] UpperCAmelCase_ = node stacka.append(snake_case_ ) while stacka: # to find the reversed order of post order, store it in stack2 UpperCAmelCase_ = stacka.pop() if n.left: stacka.append(n.left ) if n.right: stacka.append(n.right ) stacka.append(snake_case_ ) while stacka: # pop up from stack2 will be the post order print(stacka.pop().data , end="," ) def lowerCAmelCase_ ( snake_case_ : str = "" , snake_case_ : Any=50 , snake_case_ : Union[str, Any]="*" ) -> str: '''simple docstring''' if not s: return "\n" + width * char UpperCAmelCase_ , UpperCAmelCase_ = divmod(width - len(snake_case_ ) - 2 , 2 ) return f"""{left * char} {s} {(left + extra) * char}""" if __name__ == "__main__": import doctest doctest.testmod() print(prompt('Binary Tree Traversals')) SCREAMING_SNAKE_CASE_: TreeNode =build_tree() print(prompt('Pre Order Traversal')) pre_order(node) print(prompt() + '\n') print(prompt('In Order Traversal')) in_order(node) print(prompt() + '\n') print(prompt('Post Order Traversal')) post_order(node) print(prompt() + '\n') print(prompt('Level Order Traversal')) level_order(node) print(prompt() + '\n') print(prompt('Actual Level Order Traversal')) level_order_actual(node) print('*' * 50 + '\n') print(prompt('Pre Order Traversal - Iteration Version')) pre_order_iter(node) print(prompt() + '\n') print(prompt('In Order Traversal - Iteration Version')) in_order_iter(node) print(prompt() + '\n') print(prompt('Post Order Traversal - Iteration Version')) post_order_iter(node) print(prompt())
1
0
"""simple docstring""" import unittest import torch from torch import nn from accelerate.test_utils import require_cuda from accelerate.utils.memory import find_executable_batch_size, release_memory def lowerCamelCase_ (): raise RuntimeError('''CUDA out of memory.''' ) class _UpperCAmelCase ( nn.Module ): '''simple docstring''' def __init__( self ) -> List[str]: super().__init__() _UpperCAmelCase : Any = nn.Linear(3 , 4 ) _UpperCAmelCase : int = nn.BatchNormad(4 ) _UpperCAmelCase : int = nn.Linear(4 , 5 ) def __lowerCAmelCase ( self , A ) -> List[str]: return self.lineara(self.batchnorm(self.lineara(A ) ) ) class _UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' def __lowerCAmelCase ( self ) -> List[str]: _UpperCAmelCase : str = [] @find_executable_batch_size(starting_batch_size=1_2_8 ) def mock_training_loop_function(A ): nonlocal batch_sizes batch_sizes.append(A ) if batch_size != 8: raise_fake_out_of_memory() mock_training_loop_function() self.assertListEqual(A , [1_2_8, 6_4, 3_2, 1_6, 8] ) def __lowerCAmelCase ( self ) -> Optional[Any]: _UpperCAmelCase : int = [] @find_executable_batch_size(starting_batch_size=1_2_8 ) def mock_training_loop_function(A , A ): nonlocal batch_sizes batch_sizes.append(A ) if batch_size != 8: raise_fake_out_of_memory() return batch_size, arga _UpperCAmelCase : Union[str, Any] = mock_training_loop_function('''hello''' ) self.assertListEqual(A , [1_2_8, 6_4, 3_2, 1_6, 8] ) self.assertListEqual([bs, arga] , [8, '''hello'''] ) def __lowerCAmelCase ( self ) -> str: @find_executable_batch_size(starting_batch_size=0 ) def mock_training_loop_function(A ): pass with self.assertRaises(A ) as cm: mock_training_loop_function() self.assertIn('''No executable batch size found, reached zero.''' , cm.exception.args[0] ) def __lowerCAmelCase ( self ) -> Optional[int]: @find_executable_batch_size(starting_batch_size=1_6 ) def mock_training_loop_function(A ): if batch_size > 0: raise_fake_out_of_memory() pass with self.assertRaises(A ) as cm: mock_training_loop_function() self.assertIn('''No executable batch size found, reached zero.''' , cm.exception.args[0] ) def __lowerCAmelCase ( self ) -> Dict: @find_executable_batch_size(starting_batch_size=1_2_8 ) def mock_training_loop_function(A , A , A ): if batch_size != 8: raise raise_fake_out_of_memory() with self.assertRaises(A ) as cm: mock_training_loop_function(1_2_8 , '''hello''' , '''world''' ) self.assertIn('''Batch size was passed into `f`''' , cm.exception.args[0] ) self.assertIn('''`f(arg1=\'hello\', arg2=\'world\')''' , cm.exception.args[0] ) def __lowerCAmelCase ( self ) -> str: @find_executable_batch_size(starting_batch_size=1_6 ) def mock_training_loop_function(A ): raise ValueError('''Oops, we had an error!''' ) with self.assertRaises(A ) as cm: mock_training_loop_function() self.assertIn('''Oops, we had an error!''' , cm.exception.args[0] ) @require_cuda def __lowerCAmelCase ( self ) -> int: _UpperCAmelCase : List[str] = torch.cuda.memory_allocated() _UpperCAmelCase : List[str] = ModelForTest() model.cuda() self.assertGreater(torch.cuda.memory_allocated() , A ) _UpperCAmelCase : Union[str, Any] = release_memory(A ) self.assertEqual(torch.cuda.memory_allocated() , A )
353
"""simple docstring""" _lowerCAmelCase :List[str] = 0 # The first color of the flag. _lowerCAmelCase :Optional[Any] = 1 # The second color of the flag. _lowerCAmelCase :List[Any] = 2 # The third color of the flag. _lowerCAmelCase :Any = (red, white, blue) def lowerCamelCase_ (UpperCamelCase__ : list ): if not sequence: return [] if len(UpperCamelCase__ ) == 1: return list(UpperCamelCase__ ) _UpperCAmelCase : List[Any] = 0 _UpperCAmelCase : str = len(UpperCamelCase__ ) - 1 _UpperCAmelCase : Optional[int] = 0 while mid <= high: if sequence[mid] == colors[0]: _UpperCAmelCase , _UpperCAmelCase : Dict = sequence[mid], sequence[low] low += 1 mid += 1 elif sequence[mid] == colors[1]: mid += 1 elif sequence[mid] == colors[2]: _UpperCAmelCase , _UpperCAmelCase : List[Any] = sequence[high], sequence[mid] high -= 1 else: _UpperCAmelCase : Tuple = F'The elements inside the sequence must contains only {colors} values' raise ValueError(UpperCamelCase__ ) return sequence if __name__ == "__main__": import doctest doctest.testmod() _lowerCAmelCase :Tuple = input('Enter numbers separated by commas:\n').strip() _lowerCAmelCase :Dict = [int(item.strip()) for item in user_input.split(',')] print(f"{dutch_national_flag_sort(unsorted)}")
68
0
from math import asin, atan, cos, radians, sin, sqrt, tan _snake_case = 637_8137.0 _snake_case = 635_6752.31_4245 _snake_case = 6_37_81_37 def lowercase_( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): '''simple docstring''' lowerCamelCase : int = (AXIS_A - AXIS_B) / AXIS_A lowerCamelCase : int = atan((1 - flattening) * tan(radians(SCREAMING_SNAKE_CASE_ ) ) ) lowerCamelCase : Dict = atan((1 - flattening) * tan(radians(SCREAMING_SNAKE_CASE_ ) ) ) lowerCamelCase : Tuple = radians(SCREAMING_SNAKE_CASE_ ) lowerCamelCase : int = radians(SCREAMING_SNAKE_CASE_ ) # Equation lowerCamelCase : List[str] = sin((phi_a - phi_a) / 2 ) lowerCamelCase : List[str] = sin((lambda_a - lambda_a) / 2 ) # Square both values sin_sq_phi *= sin_sq_phi sin_sq_lambda *= sin_sq_lambda lowerCamelCase : Tuple = sqrt(sin_sq_phi + (cos(SCREAMING_SNAKE_CASE_ ) * cos(SCREAMING_SNAKE_CASE_ ) * sin_sq_lambda) ) return 2 * RADIUS * asin(SCREAMING_SNAKE_CASE_ ) if __name__ == "__main__": import doctest doctest.testmod()
283
def lowercase_( SCREAMING_SNAKE_CASE_ = 4000000 ): '''simple docstring''' lowerCamelCase : Any = [0, 1] lowerCamelCase : Union[str, Any] = 0 while fib[i] <= n: fib.append(fib[i] + fib[i + 1] ) if fib[i + 2] > n: break i += 1 lowerCamelCase : Union[str, Any] = 0 for j in range(len(SCREAMING_SNAKE_CASE_ ) - 1 ): if fib[j] % 2 == 0: total += fib[j] return total if __name__ == "__main__": print(f'''{solution() = }''')
283
1
import numpy as np def lowerCAmelCase_ (lowerCAmelCase__: Optional[int] , lowerCAmelCase__: Any , lowerCAmelCase__: Dict , lowerCAmelCase__: Tuple , lowerCAmelCase__: Optional[Any] ): """simple docstring""" UpperCAmelCase_: int = int(np.ceil((x_end - xa) / h ) ) UpperCAmelCase_: int = np.zeros((n + 1,) ) UpperCAmelCase_: Tuple = ya UpperCAmelCase_: int = xa for k in range(lowerCAmelCase__ ): UpperCAmelCase_: Tuple = f(lowerCAmelCase__ , y[k] ) UpperCAmelCase_: Union[str, Any] = f(x + 0.5 * h , y[k] + 0.5 * h * ka ) UpperCAmelCase_: List[Any] = f(x + 0.5 * h , y[k] + 0.5 * h * ka ) UpperCAmelCase_: Dict = f(x + h , y[k] + h * ka ) UpperCAmelCase_: Tuple = y[k] + (1 / 6) * h * (ka + 2 * ka + 2 * ka + ka) x += h return y if __name__ == "__main__": import doctest doctest.testmod()
365
import unittest from transformers import ( MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, Pipeline, ZeroShotClassificationPipeline, pipeline, ) from transformers.testing_utils import is_pipeline_test, nested_simplify, require_tf, require_torch, slow from .test_pipelines_common import ANY # These 2 model types require different inputs than those of the usual text models. a : Tuple = {'LayoutLMv2Config', 'LayoutLMv3Config'} @is_pipeline_test class _a ( unittest.TestCase ): A = MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING A = TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if model_mapping is not None: A = {config: model for config, model in model_mapping.items() if config.__name__ not in _TO_SKIP} if tf_model_mapping is not None: A = { config: model for config, model in tf_model_mapping.items() if config.__name__ not in _TO_SKIP } def __snake_case (self, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ ) -> Dict: UpperCAmelCase_: Dict = ZeroShotClassificationPipeline( model=SCREAMING_SNAKE_CASE_, tokenizer=SCREAMING_SNAKE_CASE_, candidate_labels=["""polics""", """health"""] ) return classifier, ["Who are you voting for in 2020?", "My stomach hurts."] def __snake_case (self, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ ) -> Dict: UpperCAmelCase_: Dict = classifier("""Who are you voting for in 2020?""", candidate_labels="""politics""" ) self.assertEqual(SCREAMING_SNAKE_CASE_, {"""sequence""": ANY(SCREAMING_SNAKE_CASE_ ), """labels""": [ANY(SCREAMING_SNAKE_CASE_ )], """scores""": [ANY(SCREAMING_SNAKE_CASE_ )]} ) # No kwarg UpperCAmelCase_: Optional[int] = classifier("""Who are you voting for in 2020?""", ["""politics"""] ) self.assertEqual(SCREAMING_SNAKE_CASE_, {"""sequence""": ANY(SCREAMING_SNAKE_CASE_ ), """labels""": [ANY(SCREAMING_SNAKE_CASE_ )], """scores""": [ANY(SCREAMING_SNAKE_CASE_ )]} ) UpperCAmelCase_: Optional[int] = classifier("""Who are you voting for in 2020?""", candidate_labels=["""politics"""] ) self.assertEqual(SCREAMING_SNAKE_CASE_, {"""sequence""": ANY(SCREAMING_SNAKE_CASE_ ), """labels""": [ANY(SCREAMING_SNAKE_CASE_ )], """scores""": [ANY(SCREAMING_SNAKE_CASE_ )]} ) UpperCAmelCase_: List[Any] = classifier("""Who are you voting for in 2020?""", candidate_labels="""politics, public health""" ) self.assertEqual( SCREAMING_SNAKE_CASE_, {"""sequence""": ANY(SCREAMING_SNAKE_CASE_ ), """labels""": [ANY(SCREAMING_SNAKE_CASE_ ), ANY(SCREAMING_SNAKE_CASE_ )], """scores""": [ANY(SCREAMING_SNAKE_CASE_ ), ANY(SCREAMING_SNAKE_CASE_ )]} ) self.assertAlmostEqual(sum(nested_simplify(outputs["""scores"""] ) ), 1.0 ) UpperCAmelCase_: Tuple = classifier("""Who are you voting for in 2020?""", candidate_labels=["""politics""", """public health"""] ) self.assertEqual( SCREAMING_SNAKE_CASE_, {"""sequence""": ANY(SCREAMING_SNAKE_CASE_ ), """labels""": [ANY(SCREAMING_SNAKE_CASE_ ), ANY(SCREAMING_SNAKE_CASE_ )], """scores""": [ANY(SCREAMING_SNAKE_CASE_ ), ANY(SCREAMING_SNAKE_CASE_ )]} ) self.assertAlmostEqual(sum(nested_simplify(outputs["""scores"""] ) ), 1.0 ) UpperCAmelCase_: str = classifier( """Who are you voting for in 2020?""", candidate_labels="""politics""", hypothesis_template="""This text is about {}""" ) self.assertEqual(SCREAMING_SNAKE_CASE_, {"""sequence""": ANY(SCREAMING_SNAKE_CASE_ ), """labels""": [ANY(SCREAMING_SNAKE_CASE_ )], """scores""": [ANY(SCREAMING_SNAKE_CASE_ )]} ) # https://github.com/huggingface/transformers/issues/13846 UpperCAmelCase_: Union[str, Any] = classifier(["""I am happy"""], ["""positive""", """negative"""] ) self.assertEqual( SCREAMING_SNAKE_CASE_, [ {"""sequence""": ANY(SCREAMING_SNAKE_CASE_ ), """labels""": [ANY(SCREAMING_SNAKE_CASE_ ), ANY(SCREAMING_SNAKE_CASE_ )], """scores""": [ANY(SCREAMING_SNAKE_CASE_ ), ANY(SCREAMING_SNAKE_CASE_ )]} for i in range(1 ) ], ) UpperCAmelCase_: Dict = classifier(["""I am happy""", """I am sad"""], ["""positive""", """negative"""] ) self.assertEqual( SCREAMING_SNAKE_CASE_, [ {"""sequence""": ANY(SCREAMING_SNAKE_CASE_ ), """labels""": [ANY(SCREAMING_SNAKE_CASE_ ), ANY(SCREAMING_SNAKE_CASE_ )], """scores""": [ANY(SCREAMING_SNAKE_CASE_ ), ANY(SCREAMING_SNAKE_CASE_ )]} for i in range(2 ) ], ) with self.assertRaises(SCREAMING_SNAKE_CASE_ ): classifier("""""", candidate_labels="""politics""" ) with self.assertRaises(SCREAMING_SNAKE_CASE_ ): classifier(SCREAMING_SNAKE_CASE_, candidate_labels="""politics""" ) with self.assertRaises(SCREAMING_SNAKE_CASE_ ): classifier("""Who are you voting for in 2020?""", candidate_labels="""""" ) with self.assertRaises(SCREAMING_SNAKE_CASE_ ): classifier("""Who are you voting for in 2020?""", candidate_labels=SCREAMING_SNAKE_CASE_ ) with self.assertRaises(SCREAMING_SNAKE_CASE_ ): classifier( """Who are you voting for in 2020?""", candidate_labels="""politics""", hypothesis_template="""Not formatting template""", ) with self.assertRaises(SCREAMING_SNAKE_CASE_ ): classifier( """Who are you voting for in 2020?""", candidate_labels="""politics""", hypothesis_template=SCREAMING_SNAKE_CASE_, ) self.run_entailment_id(SCREAMING_SNAKE_CASE_ ) def __snake_case (self, SCREAMING_SNAKE_CASE_ ) -> Union[str, Any]: UpperCAmelCase_: int = zero_shot_classifier.model.config UpperCAmelCase_: Optional[int] = config.labelaid UpperCAmelCase_: str = zero_shot_classifier.entailment_id UpperCAmelCase_: Union[str, Any] = {"""LABEL_0""": 0, """LABEL_1""": 1, """LABEL_2""": 2} self.assertEqual(zero_shot_classifier.entailment_id, -1 ) UpperCAmelCase_: int = {"""entailment""": 0, """neutral""": 1, """contradiction""": 2} self.assertEqual(zero_shot_classifier.entailment_id, 0 ) UpperCAmelCase_: Dict = {"""ENTAIL""": 0, """NON-ENTAIL""": 1} self.assertEqual(zero_shot_classifier.entailment_id, 0 ) UpperCAmelCase_: Tuple = {"""ENTAIL""": 2, """NEUTRAL""": 1, """CONTR""": 0} self.assertEqual(zero_shot_classifier.entailment_id, 2 ) UpperCAmelCase_: Any = original_labelaid self.assertEqual(SCREAMING_SNAKE_CASE_, zero_shot_classifier.entailment_id ) @require_torch def __snake_case (self ) -> str: UpperCAmelCase_: Any = pipeline( """zero-shot-classification""", model="""sshleifer/tiny-distilbert-base-cased-distilled-squad""", framework="""pt""", ) # There was a regression in 4.10 for this # Adding a test so we don't make the mistake again. # https://github.com/huggingface/transformers/issues/13381#issuecomment-912343499 zero_shot_classifier( """Who are you voting for in 2020?""" * 100, candidate_labels=["""politics""", """public health""", """science"""] ) @require_torch def __snake_case (self ) -> Union[str, Any]: UpperCAmelCase_: str = pipeline( """zero-shot-classification""", model="""sshleifer/tiny-distilbert-base-cased-distilled-squad""", framework="""pt""", ) UpperCAmelCase_: Tuple = zero_shot_classifier( """Who are you voting for in 2020?""", candidate_labels=["""politics""", """public health""", """science"""] ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE_ ), { """sequence""": """Who are you voting for in 2020?""", """labels""": ["""science""", """public health""", """politics"""], """scores""": [0.3_3_3, 0.3_3_3, 0.3_3_3], }, ) @require_tf def __snake_case (self ) -> int: UpperCAmelCase_: List[Any] = pipeline( """zero-shot-classification""", model="""sshleifer/tiny-distilbert-base-cased-distilled-squad""", framework="""tf""", ) UpperCAmelCase_: Optional[Any] = zero_shot_classifier( """Who are you voting for in 2020?""", candidate_labels=["""politics""", """public health""", """science"""] ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE_ ), { """sequence""": """Who are you voting for in 2020?""", """labels""": ["""science""", """public health""", """politics"""], """scores""": [0.3_3_3, 0.3_3_3, 0.3_3_3], }, ) @slow @require_torch def __snake_case (self ) -> Optional[int]: UpperCAmelCase_: List[Any] = pipeline("""zero-shot-classification""", model="""roberta-large-mnli""", framework="""pt""" ) UpperCAmelCase_: Optional[int] = zero_shot_classifier( """Who are you voting for in 2020?""", candidate_labels=["""politics""", """public health""", """science"""] ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE_ ), { """sequence""": """Who are you voting for in 2020?""", """labels""": ["""politics""", """public health""", """science"""], """scores""": [0.9_7_6, 0.0_1_5, 0.0_0_9], }, ) UpperCAmelCase_: Optional[Any] = zero_shot_classifier( """The dominant sequence transduction models are based on complex recurrent or convolutional neural networks""" """ in an encoder-decoder configuration. The best performing models also connect the encoder and decoder""" """ through an attention mechanism. We propose a new simple network architecture, the Transformer, based""" """ solely on attention mechanisms, dispensing with recurrence and convolutions entirely. Experiments on two""" """ machine translation tasks show these models to be superior in quality while being more parallelizable""" """ and requiring significantly less time to train. Our model achieves 28.4 BLEU on the WMT 2014""" """ English-to-German translation task, improving over the existing best results, including ensembles by""" """ over 2 BLEU. On the WMT 2014 English-to-French translation task, our model establishes a new""" """ single-model state-of-the-art BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small""" """ fraction of the training costs of the best models from the literature. We show that the Transformer""" """ generalizes well to other tasks by applying it successfully to English constituency parsing both with""" """ large and limited training data.""", candidate_labels=["""machine learning""", """statistics""", """translation""", """vision"""], multi_label=SCREAMING_SNAKE_CASE_, ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE_ ), { """sequence""": ( """The dominant sequence transduction models are based on complex recurrent or convolutional neural""" """ networks in an encoder-decoder configuration. The best performing models also connect the""" """ encoder and decoder through an attention mechanism. We propose a new simple network""" """ architecture, the Transformer, based solely on attention mechanisms, dispensing with recurrence""" """ and convolutions entirely. Experiments on two machine translation tasks show these models to be""" """ superior in quality while being more parallelizable and requiring significantly less time to""" """ train. Our model achieves 28.4 BLEU on the WMT 2014 English-to-German translation task,""" """ improving over the existing best results, including ensembles by over 2 BLEU. On the WMT 2014""" """ English-to-French translation task, our model establishes a new single-model state-of-the-art""" """ BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small fraction of the training""" """ costs of the best models from the literature. We show that the Transformer generalizes well to""" """ other tasks by applying it successfully to English constituency parsing both with large and""" """ limited training data.""" ), """labels""": ["""translation""", """machine learning""", """vision""", """statistics"""], """scores""": [0.8_1_7, 0.7_1_3, 0.0_1_8, 0.0_1_8], }, ) @slow @require_tf def __snake_case (self ) -> Optional[int]: UpperCAmelCase_: List[str] = pipeline("""zero-shot-classification""", model="""roberta-large-mnli""", framework="""tf""" ) UpperCAmelCase_: Optional[Any] = zero_shot_classifier( """Who are you voting for in 2020?""", candidate_labels=["""politics""", """public health""", """science"""] ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE_ ), { """sequence""": """Who are you voting for in 2020?""", """labels""": ["""politics""", """public health""", """science"""], """scores""": [0.9_7_6, 0.0_1_5, 0.0_0_9], }, ) UpperCAmelCase_: Any = zero_shot_classifier( """The dominant sequence transduction models are based on complex recurrent or convolutional neural networks""" """ in an encoder-decoder configuration. The best performing models also connect the encoder and decoder""" """ through an attention mechanism. We propose a new simple network architecture, the Transformer, based""" """ solely on attention mechanisms, dispensing with recurrence and convolutions entirely. Experiments on two""" """ machine translation tasks show these models to be superior in quality while being more parallelizable""" """ and requiring significantly less time to train. Our model achieves 28.4 BLEU on the WMT 2014""" """ English-to-German translation task, improving over the existing best results, including ensembles by""" """ over 2 BLEU. On the WMT 2014 English-to-French translation task, our model establishes a new""" """ single-model state-of-the-art BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small""" """ fraction of the training costs of the best models from the literature. We show that the Transformer""" """ generalizes well to other tasks by applying it successfully to English constituency parsing both with""" """ large and limited training data.""", candidate_labels=["""machine learning""", """statistics""", """translation""", """vision"""], multi_label=SCREAMING_SNAKE_CASE_, ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE_ ), { """sequence""": ( """The dominant sequence transduction models are based on complex recurrent or convolutional neural""" """ networks in an encoder-decoder configuration. The best performing models also connect the""" """ encoder and decoder through an attention mechanism. We propose a new simple network""" """ architecture, the Transformer, based solely on attention mechanisms, dispensing with recurrence""" """ and convolutions entirely. Experiments on two machine translation tasks show these models to be""" """ superior in quality while being more parallelizable and requiring significantly less time to""" """ train. Our model achieves 28.4 BLEU on the WMT 2014 English-to-German translation task,""" """ improving over the existing best results, including ensembles by over 2 BLEU. On the WMT 2014""" """ English-to-French translation task, our model establishes a new single-model state-of-the-art""" """ BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small fraction of the training""" """ costs of the best models from the literature. We show that the Transformer generalizes well to""" """ other tasks by applying it successfully to English constituency parsing both with large and""" """ limited training data.""" ), """labels""": ["""translation""", """machine learning""", """vision""", """statistics"""], """scores""": [0.8_1_7, 0.7_1_3, 0.0_1_8, 0.0_1_8], }, )
82
0
"""simple docstring""" import os from huggingface_hub.constants import HUGGINGFACE_HUB_CACHE, hf_cache_home __A = HUGGINGFACE_HUB_CACHE __A = "config.json" __A = "diffusion_pytorch_model.bin" __A = "diffusion_flax_model.msgpack" __A = "model.onnx" __A = "diffusion_pytorch_model.safetensors" __A = "weights.pb" __A = "https://huggingface.co" __A = default_cache_path __A = "diffusers_modules" __A = os.getenv("HF_MODULES_CACHE", os.path.join(hf_cache_home, "modules")) __A = ["fp16", "non-ema"] __A = ".self_attn"
217
"""simple docstring""" def a__ ( __SCREAMING_SNAKE_CASE ) -> int: __lowerCAmelCase: Optional[Any] = 1 for i in range(1 , num + 1 ): fact *= i return fact def a__ ( __SCREAMING_SNAKE_CASE ) -> int: __lowerCAmelCase: List[str] = 0 while number > 0: __lowerCAmelCase: Any = number % 1_0 sum_of_digits += last_digit __lowerCAmelCase: List[Any] = number // 1_0 # Removing the last_digit from the given number return sum_of_digits def a__ ( __SCREAMING_SNAKE_CASE = 1_0_0 ) -> int: __lowerCAmelCase: Tuple = factorial(__SCREAMING_SNAKE_CASE ) __lowerCAmelCase: Optional[int] = split_and_add(__SCREAMING_SNAKE_CASE ) return result if __name__ == "__main__": print(solution(int(input("Enter the Number: ").strip())))
217
1
'''simple docstring''' import requests from bsa import BeautifulSoup def UpperCamelCase__ ( lowerCAmelCase = "AAPL" ): """simple docstring""" _lowerCAmelCase = f"https://in.finance.yahoo.com/quote/{symbol}?s={symbol}" _lowerCAmelCase = BeautifulSoup(requests.get(lowerCAmelCase ).text , """html.parser""" ) _lowerCAmelCase = """My(6px) Pos(r) smartphone_Mt(6px)""" return soup.find("""div""" , class_=class_ ).find("""span""" ).text if __name__ == "__main__": for symbol in "AAPL AMZN IBM GOOG MSFT ORCL".split(): print(F"""Current {symbol:<4} stock price is {stock_price(symbol):>8}""")
220
'''simple docstring''' import collections import inspect import unittest from typing import Dict, List, Tuple from transformers import MaskFormerSwinConfig from transformers.testing_utils import require_torch, require_torch_multi_gpu, torch_device from transformers.utils import is_torch_available from ...test_backbone_common import BackboneTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import MaskFormerSwinBackbone from transformers.models.maskformer import MaskFormerSwinModel class UpperCAmelCase : def __init__( self : str , __snake_case : Optional[int] , __snake_case : Dict=13 , __snake_case : Dict=32 , __snake_case : List[str]=2 , __snake_case : str=3 , __snake_case : str=16 , __snake_case : int=[1, 2, 1] , __snake_case : Dict=[2, 2, 4] , __snake_case : int=2 , __snake_case : str=2.0 , __snake_case : List[str]=True , __snake_case : Optional[Any]=0.0 , __snake_case : Optional[Any]=0.0 , __snake_case : Dict=0.1 , __snake_case : Tuple="gelu" , __snake_case : str=False , __snake_case : Any=True , __snake_case : Union[str, Any]=0.02 , __snake_case : Union[str, Any]=1E-5 , __snake_case : Optional[Any]=True , __snake_case : Union[str, Any]=None , __snake_case : Any=True , __snake_case : Optional[Any]=10 , __snake_case : Tuple=8 , __snake_case : List[Any]=["stage1", "stage2", "stage3"] , __snake_case : Dict=[1, 2, 3] , ) -> List[str]: _lowerCAmelCase = parent _lowerCAmelCase = batch_size _lowerCAmelCase = image_size _lowerCAmelCase = patch_size _lowerCAmelCase = num_channels _lowerCAmelCase = embed_dim _lowerCAmelCase = depths _lowerCAmelCase = num_heads _lowerCAmelCase = window_size _lowerCAmelCase = mlp_ratio _lowerCAmelCase = qkv_bias _lowerCAmelCase = hidden_dropout_prob _lowerCAmelCase = attention_probs_dropout_prob _lowerCAmelCase = drop_path_rate _lowerCAmelCase = hidden_act _lowerCAmelCase = use_absolute_embeddings _lowerCAmelCase = patch_norm _lowerCAmelCase = layer_norm_eps _lowerCAmelCase = initializer_range _lowerCAmelCase = is_training _lowerCAmelCase = scope _lowerCAmelCase = use_labels _lowerCAmelCase = type_sequence_label_size _lowerCAmelCase = encoder_stride _lowerCAmelCase = out_features _lowerCAmelCase = out_indices def lowercase__ ( self : Union[str, Any] ) -> List[str]: _lowerCAmelCase = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) _lowerCAmelCase = None if self.use_labels: _lowerCAmelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size ) _lowerCAmelCase = self.get_config() return config, pixel_values, labels def lowercase__ ( self : int ) -> Any: return MaskFormerSwinConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , embed_dim=self.embed_dim , depths=self.depths , num_heads=self.num_heads , window_size=self.window_size , mlp_ratio=self.mlp_ratio , qkv_bias=self.qkv_bias , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , drop_path_rate=self.drop_path_rate , hidden_act=self.hidden_act , use_absolute_embeddings=self.use_absolute_embeddings , path_norm=self.patch_norm , layer_norm_eps=self.layer_norm_eps , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , out_features=self.out_features , out_indices=self.out_indices , ) def lowercase__ ( self : List[str] , __snake_case : Tuple , __snake_case : Optional[Any] , __snake_case : Optional[Any] ) -> Dict: _lowerCAmelCase = MaskFormerSwinModel(config=__snake_case ) model.to(__snake_case ) model.eval() _lowerCAmelCase = model(__snake_case ) _lowerCAmelCase = ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths ) - 1)) _lowerCAmelCase = int(config.embed_dim * 2 ** (len(config.depths ) - 1) ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, expected_seq_len, expected_dim) ) def lowercase__ ( self : Optional[Any] , __snake_case : Any , __snake_case : List[Any] , __snake_case : Optional[int] ) -> Union[str, Any]: _lowerCAmelCase = MaskFormerSwinBackbone(config=__snake_case ) model.to(__snake_case ) model.eval() _lowerCAmelCase = model(__snake_case ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) , len(config.out_features ) ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [13, 16, 16, 16] ) # verify channels self.parent.assertEqual(len(model.channels ) , len(config.out_features ) ) self.parent.assertListEqual(model.channels , [16, 32, 64] ) # verify ValueError with self.parent.assertRaises(__snake_case ): _lowerCAmelCase = ["""stem"""] _lowerCAmelCase = MaskFormerSwinBackbone(config=__snake_case ) def lowercase__ ( self : Union[str, Any] ) -> int: _lowerCAmelCase = self.prepare_config_and_inputs() _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase = config_and_inputs _lowerCAmelCase = {"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class UpperCAmelCase ( snake_case_ , snake_case_ , unittest.TestCase ): _lowercase: str = ( ( MaskFormerSwinModel, MaskFormerSwinBackbone, ) if is_torch_available() else () ) _lowercase: List[Any] = {'''feature-extraction''': MaskFormerSwinModel} if is_torch_available() else {} _lowercase: Optional[Any] = False _lowercase: List[str] = False _lowercase: Optional[Any] = False _lowercase: str = False _lowercase: Union[str, Any] = False def lowercase__ ( self : Optional[Any] ) -> str: _lowerCAmelCase = MaskFormerSwinModelTester(self ) _lowerCAmelCase = ConfigTester(self , config_class=__snake_case , embed_dim=37 ) @require_torch_multi_gpu @unittest.skip( reason=( """`MaskFormerSwinModel` outputs `hidden_states_spatial_dimensions` which doesn't work well with""" """ `nn.DataParallel`""" ) ) def lowercase__ ( self : Tuple ) -> str: pass def lowercase__ ( self : str ) -> 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 lowercase__ ( self : str ) -> Any: return def lowercase__ ( self : Tuple ) -> Tuple: _lowerCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__snake_case ) def lowercase__ ( self : Optional[int] ) -> str: _lowerCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_backbone(*__snake_case ) @unittest.skip("""Swin does not use inputs_embeds""" ) def lowercase__ ( self : str ) -> List[str]: pass @unittest.skip("""Swin does not support feedforward chunking""" ) def lowercase__ ( self : Any ) -> Union[str, Any]: pass def lowercase__ ( self : Optional[Any] ) -> List[str]: _lowerCAmelCase , _lowerCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _lowerCAmelCase = model_class(__snake_case ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) _lowerCAmelCase = model.get_output_embeddings() self.assertTrue(x is None or isinstance(__snake_case , nn.Linear ) ) def lowercase__ ( self : str ) -> Any: _lowerCAmelCase , _lowerCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _lowerCAmelCase = model_class(__snake_case ) _lowerCAmelCase = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic _lowerCAmelCase = [*signature.parameters.keys()] _lowerCAmelCase = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , __snake_case ) @unittest.skip(reason="""MaskFormerSwin is only used as backbone and doesn't support output_attentions""" ) def lowercase__ ( self : Union[str, Any] ) -> Any: pass @unittest.skip(reason="""MaskFormerSwin is only used as an internal backbone""" ) def lowercase__ ( self : List[str] ) -> Any: pass def lowercase__ ( self : Tuple , __snake_case : Optional[int] , __snake_case : str , __snake_case : str , __snake_case : Optional[int] ) -> Optional[int]: _lowerCAmelCase = model_class(__snake_case ) model.to(__snake_case ) model.eval() with torch.no_grad(): _lowerCAmelCase = model(**self._prepare_for_class(__snake_case , __snake_case ) ) _lowerCAmelCase = outputs.hidden_states _lowerCAmelCase = getattr( self.model_tester , """expected_num_hidden_layers""" , len(self.model_tester.depths ) + 1 ) self.assertEqual(len(__snake_case ) , __snake_case ) # Swin has a different seq_length _lowerCAmelCase = ( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) _lowerCAmelCase = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [num_patches, self.model_tester.embed_dim] , ) def lowercase__ ( self : List[str] ) -> Any: _lowerCAmelCase , _lowerCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() _lowerCAmelCase = ( self.model_tester.image_size if isinstance(self.model_tester.image_size , collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) for model_class in self.all_model_classes: _lowerCAmelCase = True self.check_hidden_states_output(__snake_case , __snake_case , __snake_case , __snake_case ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] _lowerCAmelCase = True self.check_hidden_states_output(__snake_case , __snake_case , __snake_case , __snake_case ) def lowercase__ ( self : Any ) -> Any: _lowerCAmelCase , _lowerCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() _lowerCAmelCase = 3 _lowerCAmelCase = ( self.model_tester.image_size if isinstance(self.model_tester.image_size , collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) _lowerCAmelCase = ( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) _lowerCAmelCase = image_size[0] + patch_size[0] - (image_size[0] % patch_size[0]) _lowerCAmelCase = image_size[1] + patch_size[1] - (image_size[1] % patch_size[1]) for model_class in self.all_model_classes: _lowerCAmelCase = True self.check_hidden_states_output(__snake_case , __snake_case , __snake_case , (padded_height, padded_width) ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] _lowerCAmelCase = True self.check_hidden_states_output(__snake_case , __snake_case , __snake_case , (padded_height, padded_width) ) @unittest.skip(reason="""MaskFormerSwin doesn't have pretrained checkpoints""" ) def lowercase__ ( self : List[Any] ) -> Any: pass @unittest.skip(reason="""This will be fixed once MaskFormerSwin is replaced by native Swin""" ) def lowercase__ ( self : Any ) -> str: pass @unittest.skip(reason="""This will be fixed once MaskFormerSwin is replaced by native Swin""" ) def lowercase__ ( self : Dict ) -> Optional[int]: pass def lowercase__ ( self : List[str] ) -> Tuple: _lowerCAmelCase , _lowerCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() def set_nan_tensor_to_zero(__snake_case : List[str] ): _lowerCAmelCase = 0 return t def check_equivalence(__snake_case : Any , __snake_case : Optional[Any] , __snake_case : Tuple , __snake_case : Dict={} ): with torch.no_grad(): _lowerCAmelCase = model(**__snake_case , return_dict=__snake_case , **__snake_case ) _lowerCAmelCase = model(**__snake_case , return_dict=__snake_case , **__snake_case ).to_tuple() def recursive_check(__snake_case : int , __snake_case : Any ): if isinstance(__snake_case , (List, Tuple) ): for tuple_iterable_value, dict_iterable_value in zip(__snake_case , __snake_case ): recursive_check(__snake_case , __snake_case ) elif isinstance(__snake_case , __snake_case ): for tuple_iterable_value, dict_iterable_value in zip( tuple_object.values() , dict_object.values() ): recursive_check(__snake_case , __snake_case ) elif tuple_object is None: return else: self.assertTrue( torch.allclose( set_nan_tensor_to_zero(__snake_case ) , set_nan_tensor_to_zero(__snake_case ) , atol=1E-5 ) , msg=( """Tuple and dict output are not equal. Difference:""" f" {torch.max(torch.abs(tuple_object - dict_object ) )}. Tuple has `nan`:" f" {torch.isnan(__snake_case ).any()} and `inf`: {torch.isinf(__snake_case )}. Dict has" f" `nan`: {torch.isnan(__snake_case ).any()} and `inf`: {torch.isinf(__snake_case )}." ) , ) recursive_check(__snake_case , __snake_case ) for model_class in self.all_model_classes: _lowerCAmelCase = model_class(__snake_case ) model.to(__snake_case ) model.eval() _lowerCAmelCase = self._prepare_for_class(__snake_case , __snake_case ) _lowerCAmelCase = self._prepare_for_class(__snake_case , __snake_case ) check_equivalence(__snake_case , __snake_case , __snake_case ) _lowerCAmelCase = self._prepare_for_class(__snake_case , __snake_case , return_labels=__snake_case ) _lowerCAmelCase = self._prepare_for_class(__snake_case , __snake_case , return_labels=__snake_case ) check_equivalence(__snake_case , __snake_case , __snake_case ) _lowerCAmelCase = self._prepare_for_class(__snake_case , __snake_case ) _lowerCAmelCase = self._prepare_for_class(__snake_case , __snake_case ) check_equivalence(__snake_case , __snake_case , __snake_case , {"""output_hidden_states""": True} ) _lowerCAmelCase = self._prepare_for_class(__snake_case , __snake_case , return_labels=__snake_case ) _lowerCAmelCase = self._prepare_for_class(__snake_case , __snake_case , return_labels=__snake_case ) check_equivalence(__snake_case , __snake_case , __snake_case , {"""output_hidden_states""": True} ) @require_torch class UpperCAmelCase ( unittest.TestCase , snake_case_ ): _lowercase: int = (MaskFormerSwinBackbone,) if is_torch_available() else () _lowercase: Dict = MaskFormerSwinConfig def lowercase__ ( self : Union[str, Any] ) -> str: _lowerCAmelCase = MaskFormerSwinModelTester(self ) def lowercase__ ( self : str ) -> Tuple: _lowerCAmelCase , _lowerCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() _lowerCAmelCase = inputs_dict["""pixel_values"""].shape[0] for backbone_class in self.all_model_classes: _lowerCAmelCase = backbone_class(__snake_case ) backbone.to(__snake_case ) backbone.eval() _lowerCAmelCase = backbone(**__snake_case ) # Test default outputs and verify feature maps self.assertIsInstance(outputs.feature_maps , __snake_case ) self.assertTrue(len(outputs.feature_maps ) == len(backbone.channels ) ) for feature_map, n_channels in zip(outputs.feature_maps , backbone.channels ): self.assertTrue(feature_map.shape[:2] , (batch_size, n_channels) ) self.assertIsNone(outputs.hidden_states ) self.assertIsNone(outputs.attentions ) # Test output_hidden_states=True _lowerCAmelCase = backbone(**__snake_case , output_hidden_states=__snake_case ) self.assertIsNotNone(outputs.hidden_states ) self.assertTrue(len(outputs.hidden_states ) , len(backbone.stage_names ) ) # We skip the stem layer for hidden_states, n_channels in zip(outputs.hidden_states[1:] , backbone.channels ): for hidden_state in hidden_states: # Hidden states are in the format (batch_size, (height * width), n_channels) _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase = hidden_state.shape self.assertTrue((h_batch_size, h_n_channels) , (batch_size, n_channels) ) # Test output_attentions=True if self.has_attentions: _lowerCAmelCase = backbone(**__snake_case , output_attentions=__snake_case ) self.assertIsNotNone(outputs.attentions )
220
1
import importlib import shutil import threading import warnings from typing import List import fsspec import fsspec.asyn from . import compression from .hffilesystem import HfFileSystem __UpperCAmelCase = importlib.util.find_spec('s3fs') is not None if _has_safs: from .safilesystem import SaFileSystem # noqa: F401 __UpperCAmelCase = [ compression.BzaFileSystem, compression.GzipFileSystem, compression.LzaFileSystem, compression.XzFileSystem, compression.ZstdFileSystem, ] # Register custom filesystems for fs_class in COMPRESSION_FILESYSTEMS + [HfFileSystem]: if fs_class.protocol in fsspec.registry and fsspec.registry[fs_class.protocol] is not fs_class: warnings.warn(F'A filesystem protocol was already set for {fs_class.protocol} and will be overwritten.') fsspec.register_implementation(fs_class.protocol, fs_class, clobber=True) def lowercase__ ( __snake_case : str ): '''simple docstring''' if "://" in dataset_path: UpperCAmelCase_ : int = dataset_path.split('://' )[1] return dataset_path def lowercase__ ( __snake_case : fsspec.AbstractFileSystem ): '''simple docstring''' if fs is not None and fs.protocol != "file": return True else: return False def lowercase__ ( __snake_case : fsspec.AbstractFileSystem , __snake_case : str , __snake_case : str ): '''simple docstring''' UpperCAmelCase_ : List[str] = not is_remote_filesystem(__snake_case ) if is_local: # LocalFileSystem.mv does copy + rm, it is more efficient to simply move a local directory shutil.move(fs._strip_protocol(__snake_case ) , fs._strip_protocol(__snake_case ) ) else: fs.mv(__snake_case , __snake_case , recursive=__snake_case ) def lowercase__ ( ): '''simple docstring''' if hasattr(fsspec.asyn , 'reset_lock' ): # for future fsspec>2022.05.0 fsspec.asyn.reset_lock() else: UpperCAmelCase_ : Optional[Any] = None UpperCAmelCase_ : Union[str, Any] = None UpperCAmelCase_ : int = threading.Lock()
29
'''simple docstring''' # This script creates a super tiny model that is useful inside tests, when we just want to test that # the machinery works, without needing to the check the quality of the outcomes. # # This version creates a tiny vocab first, and then a tiny model - so the outcome is truly tiny - # all files ~60KB. As compared to taking a full-size model, reducing to the minimum its layers and # emb dimensions, but keeping the full vocab + merges files, leading to ~3MB in total for all files. # The latter is done by `fsmt-make-super-tiny-model.py`. # # It will be used then as "stas/tiny-wmt19-en-ru" from pathlib import Path import json import tempfile from transformers import FSMTTokenizer, FSMTConfig, FSMTForConditionalGeneration from transformers.models.fsmt.tokenization_fsmt import VOCAB_FILES_NAMES _A : Dict ='''tiny-wmt19-en-ru''' # Build # borrowed from a test _A : List[str] =[ '''l''', '''o''', '''w''', '''e''', '''r''', '''s''', '''t''', '''i''', '''d''', '''n''', '''w</w>''', '''r</w>''', '''t</w>''', '''lo''', '''low''', '''er</w>''', '''low</w>''', '''lowest</w>''', '''newer</w>''', '''wider</w>''', '''<unk>''', ] _A : str =dict(zip(vocab, range(len(vocab)))) _A : List[str] =['''l o 123''', '''lo w 1456''', '''e r</w> 1789''', ''''''] with tempfile.TemporaryDirectory() as tmpdirname: _A : Union[str, Any] =Path(tmpdirname) _A : str =build_dir / VOCAB_FILES_NAMES['''src_vocab_file'''] _A : int =build_dir / VOCAB_FILES_NAMES['''tgt_vocab_file'''] _A : List[Any] =build_dir / VOCAB_FILES_NAMES['''merges_file'''] with open(src_vocab_file, '''w''') as fp: fp.write(json.dumps(vocab_tokens)) with open(tgt_vocab_file, '''w''') as fp: fp.write(json.dumps(vocab_tokens)) with open(merges_file, '''w''') as fp: fp.write('''\n'''.join(merges)) _A : int =FSMTTokenizer( langs=['''en''', '''ru'''], src_vocab_size=len(vocab), tgt_vocab_size=len(vocab), src_vocab_file=src_vocab_file, tgt_vocab_file=tgt_vocab_file, merges_file=merges_file, ) _A : List[str] =FSMTConfig( langs=['''ru''', '''en'''], src_vocab_size=1_000, tgt_vocab_size=1_000, d_model=4, encoder_layers=1, decoder_layers=1, encoder_ffn_dim=4, decoder_ffn_dim=4, encoder_attention_heads=1, decoder_attention_heads=1, ) _A : Union[str, Any] =FSMTForConditionalGeneration(config) print(F'num of params {tiny_model.num_parameters()}') # Test _A : List[str] =tokenizer(['''Making tiny model'''], return_tensors='''pt''') _A : Tuple =tiny_model(**batch) print('''test output:''', len(outputs.logits[0])) # Save tiny_model.half() # makes it smaller tiny_model.save_pretrained(mname_tiny) tokenizer.save_pretrained(mname_tiny) print(F'Generated {mname_tiny}') # Upload # transformers-cli upload tiny-wmt19-en-ru
41
0
import os import unittest from transformers import BatchEncoding from transformers.models.bert.tokenization_bert import ( BasicTokenizer, WordpieceTokenizer, _is_control, _is_punctuation, _is_whitespace, ) from transformers.models.prophetnet.tokenization_prophetnet import VOCAB_FILES_NAMES, ProphetNetTokenizer from transformers.testing_utils import require_torch, slow from ...test_tokenization_common import TokenizerTesterMixin class SCREAMING_SNAKE_CASE_ ( __lowerCAmelCase , unittest.TestCase ): __lowerCAmelCase = ProphetNetTokenizer __lowerCAmelCase = False def lowerCamelCase_ ( self : Tuple ): """simple docstring""" super().setUp() UpperCamelCase = [ """[UNK]""", """[CLS]""", """[SEP]""", """[PAD]""", """[MASK]""", """want""", """##want""", """##ed""", """wa""", """un""", """runn""", """##ing""", """,""", """low""", """lowest""", ] UpperCamelCase = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as vocab_writer: vocab_writer.write("""""".join([x + """\n""" for x in vocab_tokens] ) ) def lowerCamelCase_ ( self : str , lowerCamelCase_ : str ): """simple docstring""" UpperCamelCase = """UNwant\u00E9d,running""" UpperCamelCase = """unwanted, running""" return input_text, output_text def lowerCamelCase_ ( self : Optional[int] ): """simple docstring""" UpperCamelCase = self.tokenizer_class(self.vocab_file ) UpperCamelCase = tokenizer.tokenize("""UNwant\u00E9d,running""" ) self.assertListEqual(lowerCamelCase_ , ["""un""", """##want""", """##ed""", """,""", """runn""", """##ing"""] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(lowerCamelCase_ ) , [9, 6, 7, 12, 10, 11] ) def lowerCamelCase_ ( self : Any ): """simple docstring""" UpperCamelCase = BasicTokenizer() self.assertListEqual(tokenizer.tokenize("""ah\u535A\u63A8zz""" ) , ["""ah""", """\u535A""", """\u63A8""", """zz"""] ) def lowerCamelCase_ ( self : List[Any] ): """simple docstring""" UpperCamelCase = BasicTokenizer(do_lower_case=lowerCamelCase_ ) self.assertListEqual( tokenizer.tokenize(""" \tHeLLo!how \n Are yoU? """ ) , ["""hello""", """!""", """how""", """are""", """you""", """?"""] ) self.assertListEqual(tokenizer.tokenize("""H\u00E9llo""" ) , ["""hello"""] ) def lowerCamelCase_ ( self : Union[str, Any] ): """simple docstring""" UpperCamelCase = BasicTokenizer(do_lower_case=lowerCamelCase_ , strip_accents=lowerCamelCase_ ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""hällo""", """!""", """how""", """are""", """you""", """?"""] ) self.assertListEqual(tokenizer.tokenize("""H\u00E9llo""" ) , ["""h\u00E9llo"""] ) def lowerCamelCase_ ( self : int ): """simple docstring""" UpperCamelCase = BasicTokenizer(do_lower_case=lowerCamelCase_ , strip_accents=lowerCamelCase_ ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""hallo""", """!""", """how""", """are""", """you""", """?"""] ) self.assertListEqual(tokenizer.tokenize("""H\u00E9llo""" ) , ["""hello"""] ) def lowerCamelCase_ ( self : Optional[Any] ): """simple docstring""" UpperCamelCase = BasicTokenizer(do_lower_case=lowerCamelCase_ ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""hallo""", """!""", """how""", """are""", """you""", """?"""] ) self.assertListEqual(tokenizer.tokenize("""H\u00E9llo""" ) , ["""hello"""] ) def lowerCamelCase_ ( self : List[Any] ): """simple docstring""" UpperCamelCase = BasicTokenizer(do_lower_case=lowerCamelCase_ ) self.assertListEqual( tokenizer.tokenize(""" \tHeLLo!how \n Are yoU? """ ) , ["""HeLLo""", """!""", """how""", """Are""", """yoU""", """?"""] ) def lowerCamelCase_ ( self : List[str] ): """simple docstring""" UpperCamelCase = BasicTokenizer(do_lower_case=lowerCamelCase_ , strip_accents=lowerCamelCase_ ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""HäLLo""", """!""", """how""", """Are""", """yoU""", """?"""] ) def lowerCamelCase_ ( self : List[str] ): """simple docstring""" UpperCamelCase = BasicTokenizer(do_lower_case=lowerCamelCase_ , strip_accents=lowerCamelCase_ ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""HaLLo""", """!""", """how""", """Are""", """yoU""", """?"""] ) def lowerCamelCase_ ( self : Any ): """simple docstring""" UpperCamelCase = BasicTokenizer(do_lower_case=lowerCamelCase_ , never_split=["""[UNK]"""] ) self.assertListEqual( tokenizer.tokenize(""" \tHeLLo!how \n Are yoU? [UNK]""" ) , ["""HeLLo""", """!""", """how""", """Are""", """yoU""", """?""", """[UNK]"""] ) def lowerCamelCase_ ( self : List[Any] ): """simple docstring""" UpperCamelCase = ["""[UNK]""", """[CLS]""", """[SEP]""", """want""", """##want""", """##ed""", """wa""", """un""", """runn""", """##ing"""] UpperCamelCase = {} for i, token in enumerate(lowerCamelCase_ ): UpperCamelCase = i UpperCamelCase = WordpieceTokenizer(vocab=lowerCamelCase_ , unk_token="""[UNK]""" ) self.assertListEqual(tokenizer.tokenize("""""" ) , [] ) self.assertListEqual(tokenizer.tokenize("""unwanted running""" ) , ["""un""", """##want""", """##ed""", """runn""", """##ing"""] ) self.assertListEqual(tokenizer.tokenize("""unwantedX running""" ) , ["""[UNK]""", """runn""", """##ing"""] ) @require_torch def lowerCamelCase_ ( self : Dict ): """simple docstring""" UpperCamelCase = self.tokenizer_class.from_pretrained("""microsoft/prophetnet-large-uncased""" ) UpperCamelCase = ["""A long paragraph for summarization.""", """Another paragraph for summarization."""] UpperCamelCase = [1037, 2146, 2_0423, 2005, 7680, 7849, 3989, 1012, 102] UpperCamelCase = tokenizer(lowerCamelCase_ , padding=lowerCamelCase_ , return_tensors="""pt""" ) self.assertIsInstance(lowerCamelCase_ , lowerCamelCase_ ) UpperCamelCase = list(batch.input_ids.numpy()[0] ) self.assertListEqual(lowerCamelCase_ , lowerCamelCase_ ) self.assertEqual((2, 9) , batch.input_ids.shape ) self.assertEqual((2, 9) , batch.attention_mask.shape ) def lowerCamelCase_ ( self : Union[str, Any] ): """simple docstring""" self.assertTrue(_is_whitespace(""" """ ) ) self.assertTrue(_is_whitespace("""\t""" ) ) self.assertTrue(_is_whitespace("""\r""" ) ) self.assertTrue(_is_whitespace("""\n""" ) ) self.assertTrue(_is_whitespace("""\u00A0""" ) ) self.assertFalse(_is_whitespace("""A""" ) ) self.assertFalse(_is_whitespace("""-""" ) ) def lowerCamelCase_ ( self : List[str] ): """simple docstring""" self.assertTrue(_is_control("""\u0005""" ) ) self.assertFalse(_is_control("""A""" ) ) self.assertFalse(_is_control(""" """ ) ) self.assertFalse(_is_control("""\t""" ) ) self.assertFalse(_is_control("""\r""" ) ) def lowerCamelCase_ ( self : Optional[Any] ): """simple docstring""" self.assertTrue(_is_punctuation("""-""" ) ) self.assertTrue(_is_punctuation("""$""" ) ) self.assertTrue(_is_punctuation("""`""" ) ) self.assertTrue(_is_punctuation(""".""" ) ) self.assertFalse(_is_punctuation("""A""" ) ) self.assertFalse(_is_punctuation(""" """ ) ) @slow def lowerCamelCase_ ( self : Optional[Any] ): """simple docstring""" UpperCamelCase = self.tokenizer_class.from_pretrained("""microsoft/prophetnet-large-uncased""" ) UpperCamelCase = tokenizer.encode("""sequence builders""" , add_special_tokens=lowerCamelCase_ ) UpperCamelCase = tokenizer.encode("""multi-sequence build""" , add_special_tokens=lowerCamelCase_ ) UpperCamelCase = tokenizer.build_inputs_with_special_tokens(lowerCamelCase_ ) UpperCamelCase = tokenizer.build_inputs_with_special_tokens(lowerCamelCase_ , lowerCamelCase_ ) assert encoded_sentence == text + [102] assert encoded_pair == text + [102] + text_a + [102]
165
import os try: from .build_directory_md import good_file_paths except ImportError: from build_directory_md import good_file_paths # type: ignore _SCREAMING_SNAKE_CASE = list(good_file_paths()) assert filepaths, "good_file_paths() failed!" _SCREAMING_SNAKE_CASE = [file for file in filepaths if file != file.lower()] if upper_files: print(F'''{len(upper_files)} files contain uppercase characters:''') print("""\n""".join(upper_files) + """\n""") _SCREAMING_SNAKE_CASE = [file for file in filepaths if """ """ in file] if space_files: print(F'''{len(space_files)} files contain space characters:''') print("""\n""".join(space_files) + """\n""") _SCREAMING_SNAKE_CASE = [file for file in filepaths if """-""" in file] if hyphen_files: print(F'''{len(hyphen_files)} files contain hyphen characters:''') print("""\n""".join(hyphen_files) + """\n""") _SCREAMING_SNAKE_CASE = [file for file in filepaths if os.sep not in file] if nodir_files: print(F'''{len(nodir_files)} files are not in a directory:''') print("""\n""".join(nodir_files) + """\n""") _SCREAMING_SNAKE_CASE = len(upper_files + space_files + hyphen_files + nodir_files) if bad_files: import sys sys.exit(bad_files)
165
1
"""simple docstring""" import unittest import numpy as np from transformers.testing_utils import require_pytesseract, require_torch from transformers.utils import is_pytesseract_available, is_torch_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_pytesseract_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class snake_case__ ( unittest.TestCase ): def __init__( self , lowerCamelCase , lowerCamelCase=7 , lowerCamelCase=3 , lowerCamelCase=18 , lowerCamelCase=30 , lowerCamelCase=400 , lowerCamelCase=True , lowerCamelCase=None , lowerCamelCase=True , ): __a = size if size is not None else {"height": 18, "width": 18} __a = parent __a = batch_size __a = num_channels __a = image_size __a = min_resolution __a = max_resolution __a = do_resize __a = size __a = apply_ocr def a__ ( self ): return {"do_resize": self.do_resize, "size": self.size, "apply_ocr": self.apply_ocr} @require_torch @require_pytesseract class snake_case__ ( snake_case_, unittest.TestCase ): _snake_case : int = LayoutLMvaImageProcessor if is_pytesseract_available() else None def a__ ( self ): __a = LayoutLMvaImageProcessingTester(self ) @property def a__ ( self ): return self.image_processor_tester.prepare_image_processor_dict() def a__ ( self ): __a = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(lowerCamelCase , "do_resize" ) ) self.assertTrue(hasattr(lowerCamelCase , "size" ) ) self.assertTrue(hasattr(lowerCamelCase , "apply_ocr" ) ) def a__ ( self ): __a = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"height": 18, "width": 18} ) __a = self.image_processing_class.from_dict(self.image_processor_dict , size=42 ) self.assertEqual(image_processor.size , {"height": 42, "width": 42} ) def a__ ( self ): pass def a__ ( self ): # Initialize image_processing __a = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __a = prepare_image_inputs(self.image_processor_tester , equal_resolution=lowerCamelCase ) for image in image_inputs: self.assertIsInstance(lowerCamelCase , Image.Image ) # Test not batched input __a = image_processing(image_inputs[0] , return_tensors="pt" ) self.assertEqual( encoding.pixel_values.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) , ) self.assertIsInstance(encoding.words , lowerCamelCase ) self.assertIsInstance(encoding.boxes , lowerCamelCase ) # Test batched __a = image_processing(lowerCamelCase , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) , ) def a__ ( self ): # Initialize image_processing __a = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __a = prepare_image_inputs(self.image_processor_tester , equal_resolution=lowerCamelCase , numpify=lowerCamelCase ) for image in image_inputs: self.assertIsInstance(lowerCamelCase , np.ndarray ) # Test not batched input __a = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) , ) # Test batched __a = image_processing(lowerCamelCase , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) , ) def a__ ( self ): # Initialize image_processing __a = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __a = prepare_image_inputs(self.image_processor_tester , equal_resolution=lowerCamelCase , torchify=lowerCamelCase ) for image in image_inputs: self.assertIsInstance(lowerCamelCase , torch.Tensor ) # Test not batched input __a = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) , ) # Test batched __a = image_processing(lowerCamelCase , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) , ) def a__ ( self ): # with apply_OCR = True __a = LayoutLMvaImageProcessor() from datasets import load_dataset __a = load_dataset("hf-internal-testing/fixtures_docvqa" , split="test" ) __a = Image.open(ds[0]["file"] ).convert("RGB" ) __a = image_processing(lowerCamelCase , return_tensors="pt" ) self.assertEqual(encoding.pixel_values.shape , (1, 3, 224, 224) ) self.assertEqual(len(encoding.words ) , len(encoding.boxes ) ) # fmt: off # the words and boxes were obtained with Tesseract 4.1.1 __a = [["11:14", "to", "11:39", "a.m", "11:39", "to", "11:44", "a.m.", "11:44", "a.m.", "to", "12:25", "p.m.", "12:25", "to", "12:58", "p.m.", "12:58", "to", "4:00", "p.m.", "2:00", "to", "5:00", "p.m.", "Coffee", "Break", "Coffee", "will", "be", "served", "for", "men", "and", "women", "in", "the", "lobby", "adjacent", "to", "exhibit", "area.", "Please", "move", "into", "exhibit", "area.", "(Exhibits", "Open)", "TRRF", "GENERAL", "SESSION", "(PART", "|)", "Presiding:", "Lee", "A.", "Waller", "TRRF", "Vice", "President", "“Introductory", "Remarks”", "Lee", "A.", "Waller,", "TRRF", "Vice", "Presi-", "dent", "Individual", "Interviews", "with", "TRRF", "Public", "Board", "Members", "and", "Sci-", "entific", "Advisory", "Council", "Mem-", "bers", "Conducted", "by", "TRRF", "Treasurer", "Philip", "G.", "Kuehn", "to", "get", "answers", "which", "the", "public", "refrigerated", "warehousing", "industry", "is", "looking", "for.", "Plus", "questions", "from", "the", "floor.", "Dr.", "Emil", "M.", "Mrak,", "University", "of", "Cal-", "ifornia,", "Chairman,", "TRRF", "Board;", "Sam", "R.", "Cecil,", "University", "of", "Georgia", "College", "of", "Agriculture;", "Dr.", "Stanley", "Charm,", "Tufts", "University", "School", "of", "Medicine;", "Dr.", "Robert", "H.", "Cotton,", "ITT", "Continental", "Baking", "Company;", "Dr.", "Owen", "Fennema,", "University", "of", "Wis-", "consin;", "Dr.", "Robert", "E.", "Hardenburg,", "USDA.", "Questions", "and", "Answers", "Exhibits", "Open", "Capt.", "Jack", "Stoney", "Room", "TRRF", "Scientific", "Advisory", "Council", "Meeting", "Ballroom", "Foyer"]] # noqa: E231 __a = [[[141, 57, 214, 69], [228, 58, 252, 69], [141, 75, 216, 88], [230, 79, 280, 88], [142, 260, 218, 273], [230, 261, 255, 273], [143, 279, 218, 290], [231, 282, 290, 291], [143, 342, 218, 354], [231, 345, 289, 355], [202, 362, 227, 373], [143, 379, 220, 392], [231, 382, 291, 394], [144, 714, 220, 726], [231, 715, 256, 726], [144, 732, 220, 745], [232, 736, 291, 747], [144, 769, 218, 782], [231, 770, 256, 782], [141, 788, 202, 801], [215, 791, 274, 804], [143, 826, 204, 838], [215, 826, 240, 838], [142, 844, 202, 857], [215, 847, 274, 859], [334, 57, 427, 69], [440, 57, 522, 69], [369, 75, 461, 88], [469, 75, 516, 88], [528, 76, 562, 88], [570, 76, 667, 88], [675, 75, 711, 87], [721, 79, 778, 88], [789, 75, 840, 88], [369, 97, 470, 107], [484, 94, 507, 106], [518, 94, 562, 107], [576, 94, 655, 110], [668, 94, 792, 109], [804, 95, 829, 107], [369, 113, 465, 125], [477, 116, 547, 125], [562, 113, 658, 125], [671, 116, 748, 125], [761, 113, 811, 125], [369, 131, 465, 143], [477, 133, 548, 143], [563, 130, 698, 145], [710, 130, 802, 146], [336, 171, 412, 183], [423, 171, 572, 183], [582, 170, 716, 184], [728, 171, 817, 187], [829, 171, 844, 186], [338, 197, 482, 212], [507, 196, 557, 209], [569, 196, 595, 208], [610, 196, 702, 209], [505, 214, 583, 226], [595, 214, 656, 227], [670, 215, 807, 227], [335, 259, 543, 274], [556, 259, 708, 272], [372, 279, 422, 291], [435, 279, 460, 291], [474, 279, 574, 292], [587, 278, 664, 291], [676, 278, 738, 291], [751, 279, 834, 291], [372, 298, 434, 310], [335, 341, 483, 354], [497, 341, 655, 354], [667, 341, 728, 354], [740, 341, 825, 354], [335, 360, 430, 372], [442, 360, 534, 372], [545, 359, 687, 372], [697, 360, 754, 372], [765, 360, 823, 373], [334, 378, 428, 391], [440, 378, 577, 394], [590, 378, 705, 391], [720, 378, 801, 391], [334, 397, 400, 409], [370, 416, 529, 429], [544, 416, 576, 432], [587, 416, 665, 428], [677, 416, 814, 429], [372, 435, 452, 450], [465, 434, 495, 447], [511, 434, 600, 447], [611, 436, 637, 447], [649, 436, 694, 451], [705, 438, 824, 447], [369, 453, 452, 466], [464, 454, 509, 466], [522, 453, 611, 469], [625, 453, 792, 469], [370, 472, 556, 488], [570, 472, 684, 487], [697, 472, 718, 485], [732, 472, 835, 488], [369, 490, 411, 503], [425, 490, 484, 503], [496, 490, 635, 506], [645, 490, 707, 503], [718, 491, 761, 503], [771, 490, 840, 503], [336, 510, 374, 521], [388, 510, 447, 522], [460, 510, 489, 521], [503, 510, 580, 522], [592, 509, 736, 525], [745, 509, 770, 522], [781, 509, 840, 522], [338, 528, 434, 541], [448, 528, 596, 541], [609, 527, 687, 540], [700, 528, 792, 541], [336, 546, 397, 559], [407, 546, 431, 559], [443, 546, 525, 560], [537, 546, 680, 562], [688, 546, 714, 559], [722, 546, 837, 562], [336, 565, 449, 581], [461, 565, 485, 577], [497, 565, 665, 581], [681, 565, 718, 577], [732, 565, 837, 580], [337, 584, 438, 597], [452, 583, 521, 596], [535, 584, 677, 599], [690, 583, 787, 596], [801, 583, 825, 596], [338, 602, 478, 615], [492, 602, 530, 614], [543, 602, 638, 615], [650, 602, 676, 614], [688, 602, 788, 615], [802, 602, 843, 614], [337, 621, 502, 633], [516, 621, 615, 637], [629, 621, 774, 636], [789, 621, 827, 633], [337, 639, 418, 652], [432, 640, 571, 653], [587, 639, 731, 655], [743, 639, 769, 652], [780, 639, 841, 652], [338, 658, 440, 673], [455, 658, 491, 670], [508, 658, 602, 671], [616, 658, 638, 670], [654, 658, 835, 674], [337, 677, 429, 689], [337, 714, 482, 726], [495, 714, 548, 726], [561, 714, 683, 726], [338, 770, 461, 782], [474, 769, 554, 785], [489, 788, 562, 803], [576, 788, 643, 801], [656, 787, 751, 804], [764, 788, 844, 801], [334, 825, 421, 838], [430, 824, 574, 838], [584, 824, 723, 841], [335, 844, 450, 857], [464, 843, 583, 860], [628, 862, 755, 875], [769, 861, 848, 878]]] # noqa: E231 # fmt: on self.assertListEqual(encoding.words , lowerCamelCase ) self.assertListEqual(encoding.boxes , lowerCamelCase ) # with apply_OCR = False __a = LayoutLMvaImageProcessor(apply_ocr=lowerCamelCase ) __a = image_processing(lowerCamelCase , return_tensors="pt" ) self.assertEqual(encoding.pixel_values.shape , (1, 3, 224, 224) )
261
"""simple docstring""" from __future__ import annotations from typing import Any class snake_case__ : def __init__( self , lowerCamelCase , lowerCamelCase , lowerCamelCase = 0 ): __a , __a = row, column __a = [[default_value for c in range(lowerCamelCase )] for r in range(lowerCamelCase )] def __str__( self ): __a = F"Matrix consist of {self.row} rows and {self.column} columns\n" # Make string identifier __a = 0 for row_vector in self.array: for obj in row_vector: __a = max(lowerCamelCase , len(str(lowerCamelCase ) ) ) __a = F"%{max_element_length}s" # Make string and return def single_line(lowerCamelCase ) -> str: nonlocal string_format_identifier __a = "[" line += ", ".join(string_format_identifier % (obj,) for obj in row_vector ) line += "]" return line s += "\n".join(single_line(lowerCamelCase ) for row_vector in self.array ) return s def __repr__( self ): return str(self ) def a__ ( self , lowerCamelCase ): if not (isinstance(lowerCamelCase , (list, tuple) ) and len(lowerCamelCase ) == 2): return False elif not (0 <= loc[0] < self.row and 0 <= loc[1] < self.column): return False else: return True def __getitem__( self , lowerCamelCase ): assert self.validate_indicies(lowerCamelCase ) return self.array[loc[0]][loc[1]] def __setitem__( self , lowerCamelCase , lowerCamelCase ): assert self.validate_indicies(lowerCamelCase ) __a = value def __add__( self , lowerCamelCase ): assert isinstance(lowerCamelCase , lowerCamelCase ) assert self.row == another.row and self.column == another.column # Add __a = Matrix(self.row , self.column ) for r in range(self.row ): for c in range(self.column ): __a = self[r, c] + another[r, c] return result def __neg__( self ): __a = Matrix(self.row , self.column ) for r in range(self.row ): for c in range(self.column ): __a = -self[r, c] return result def __sub__( self , lowerCamelCase ): return self + (-another) def __mul__( self , lowerCamelCase ): if isinstance(lowerCamelCase , (int, float) ): # Scalar multiplication __a = Matrix(self.row , self.column ) for r in range(self.row ): for c in range(self.column ): __a = self[r, c] * another return result elif isinstance(lowerCamelCase , lowerCamelCase ): # Matrix multiplication assert self.column == another.row __a = Matrix(self.row , another.column ) for r in range(self.row ): for c in range(another.column ): for i in range(self.column ): result[r, c] += self[r, i] * another[i, c] return result else: __a = F"Unsupported type given for another ({type(lowerCamelCase )})" raise TypeError(lowerCamelCase ) def a__ ( self ): __a = Matrix(self.column , self.row ) for r in range(self.row ): for c in range(self.column ): __a = self[r, c] return result def a__ ( self , lowerCamelCase , lowerCamelCase ): assert isinstance(lowerCamelCase , lowerCamelCase ) and isinstance(lowerCamelCase , lowerCamelCase ) assert self.row == self.column == u.row == v.row # u, v should be column vector assert u.column == v.column == 1 # u, v should be column vector # Calculate __a = v.transpose() __a = (v_t * self * u)[0, 0] + 1 if numerator_factor == 0: return None # It's not invertable return self - ((self * u) * (v_t * self) * (1.0 / numerator_factor)) # Testing if __name__ == "__main__": def _lowerCamelCase( ): # a^(-1) __a = Matrix(3 , 3 , 0 ) for i in range(3 ): __a = 1 print(F"a^(-1) is {ainv}" ) # u, v __a = Matrix(3 , 1 , 0 ) __a , __a , __a = 1, 2, -3 __a = Matrix(3 , 1 , 0 ) __a , __a , __a = 4, -2, 5 print(F"u is {u}" ) print(F"v is {v}" ) print(F"uv^T is {u * v.transpose()}" ) # Sherman Morrison print(F"(a + uv^T)^(-1) is {ainv.sherman_morrison(a , a )}" ) def _lowerCamelCase( ): import doctest doctest.testmod() testa()
261
1
import json import logging import os import re import sys from dataclasses import dataclass, field from typing import Any, Dict, List, Optional, Union import datasets import numpy as np import torch import torchaudio from packaging import version from torch import nn import transformers from transformers import ( HfArgumentParser, Trainer, TrainingArguments, WavaVecaCTCTokenizer, WavaVecaFeatureExtractor, WavaVecaForCTC, WavaVecaProcessor, is_apex_available, set_seed, ) from transformers.trainer_utils import get_last_checkpoint, is_main_process if is_apex_available(): from apex import amp if version.parse(version.parse(torch.__version__).base_version) >= version.parse("1.6"): lowercase__ : List[str] = True from torch.cuda.amp import autocast lowercase__ : Any = logging.getLogger(__name__) def SCREAMING_SNAKE_CASE ( __UpperCamelCase=None , __UpperCamelCase=None) -> Tuple: return field(default_factory=lambda: default , metadata=a__) @dataclass class a__ : a : str = field( metadata={"""help""": """Path to pretrained model or model identifier from huggingface.co/models"""} ) a : Optional[str] = field( default=_a , metadata={"""help""": """Where do you want to store the pretrained models downloaded from huggingface.co"""} , ) a : Optional[bool] = field( default=_a , metadata={"""help""": """Whether to freeze the feature extractor layers of the model."""} ) a : Optional[float] = field( default=0.1 , metadata={"""help""": """The dropout ratio for the attention probabilities."""} ) a : Optional[float] = field( default=0.1 , metadata={"""help""": """The dropout ratio for activations inside the fully connected layer."""} ) a : Optional[float] = field( default=0.1 , metadata={ """help""": """The dropout probabilitiy for all fully connected layers in the embeddings, encoder, and pooler.""" } , ) a : Optional[float] = field( default=0.1 , metadata={"""help""": """The dropout probabilitiy for all 1D convolutional layers in feature extractor."""} , ) a : Optional[float] = field( default=0.0_5 , metadata={ """help""": ( """Propability of each feature vector along the time axis to be chosen as the start of the vector""" """span to be masked. Approximately ``mask_time_prob * sequence_length // mask_time_length`` feature""" """vectors will be masked along the time axis. This is only relevant if ``apply_spec_augment is True``.""" ) } , ) a : Optional[float] = field(default=0.0 , metadata={"""help""": """The LayerDrop probability."""} ) @dataclass class a__ : a : Optional[str] = field( default=_a , metadata={"""help""": """The configuration name of the dataset to use (via the datasets library)."""} ) a : Optional[str] = field( default="""train+validation""" , metadata={ """help""": """The name of the training data set split to use (via the datasets library). Defaults to 'train'""" } , ) a : bool = field( default=_a , metadata={"""help""": """Overwrite the cached preprocessed datasets or not."""} ) a : Optional[int] = field( default=_a , metadata={"""help""": """The number of processes to use for the preprocessing."""} , ) a : Optional[int] = field( default=_a , metadata={ """help""": ( """For debugging purposes or quicker training, truncate the number of training examples to this """ """value if set.""" ) } , ) a : Optional[int] = field( default=_a , metadata={ """help""": ( """For debugging purposes or quicker training, truncate the number of validation examples to this """ """value if set.""" ) } , ) a : List[str] = list_field( default=[""",""", """?""", """.""", """!""", """-""", """;""", """:""", """\"\"""", """%""", """'""", """\"""", """�"""] , metadata={"""help""": """A list of characters to remove from the transcripts."""} , ) @dataclass class a__ : a : WavaVecaProcessor a : Union[bool, str] = True a : Optional[int] = None a : Optional[int] = None a : Optional[int] = None a : Optional[int] = None def __call__( self , A ) -> int: '''simple docstring''' a = [{"input_values": feature["input_values"]} for feature in features] a = [{"input_ids": feature["labels"]} for feature in features] a = self.processor.pad( __lowerCAmelCase , padding=self.padding , max_length=self.max_length , pad_to_multiple_of=self.pad_to_multiple_of , return_tensors="pt" , ) a = self.processor.pad( labels=__lowerCAmelCase , padding=self.padding , max_length=self.max_length_labels , pad_to_multiple_of=self.pad_to_multiple_of_labels , return_tensors="pt" , ) # replace padding with -100 to ignore loss correctly a = labels_batch["input_ids"].masked_fill(labels_batch.attention_mask.ne(1 ) , -100 ) a = labels return batch class a__ ( _a ): def lowerCAmelCase_ ( self , A , A ) -> List[Any]: '''simple docstring''' model.train() a = self._prepare_inputs(__lowerCAmelCase ) if self.use_amp: with autocast(): a = self.compute_loss(__lowerCAmelCase , __lowerCAmelCase ) else: a = self.compute_loss(__lowerCAmelCase , __lowerCAmelCase ) if self.args.n_gpu > 1: if model.module.config.ctc_loss_reduction == "mean": a = loss.mean() elif model.module.config.ctc_loss_reduction == "sum": a = loss.sum() / (inputs["labels"] >= 0).sum() else: raise ValueError(F'''{model.config.ctc_loss_reduction} is not valid. Choose one of [\'mean\', \'sum\']''' ) if self.args.gradient_accumulation_steps > 1: a = loss / self.args.gradient_accumulation_steps if self.use_amp: self.scaler.scale(__lowerCAmelCase ).backward() elif self.use_apex: with amp.scale_loss(__lowerCAmelCase , self.optimizer ) as scaled_loss: scaled_loss.backward() elif self.deepspeed: self.deepspeed.backward(__lowerCAmelCase ) else: loss.backward() return loss.detach() def SCREAMING_SNAKE_CASE ( ) -> List[Any]: a = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)) if len(sys.argv) == 2 and sys.argv[1].endswith(".json"): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. a , a , a = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1])) else: a , a , a = parser.parse_args_into_dataclasses() # Detecting last checkpoint. a = None if os.path.isdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir: a = get_last_checkpoint(training_args.output_dir) if last_checkpoint is None and len(os.listdir(training_args.output_dir)) > 0: raise ValueError( f'''Output directory ({training_args.output_dir}) already exists and is not empty. ''' "Use --overwrite_output_dir to overcome.") elif last_checkpoint is not None: logger.info( f'''Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change ''' "the `--output_dir` or add `--overwrite_output_dir` to train from scratch.") # Setup logging logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s" , datefmt="%m/%d/%Y %H:%M:%S" , handlers=[logging.StreamHandler(sys.stdout)] , ) logger.setLevel(logging.INFO if is_main_process(training_args.local_rank) else logging.WARN) # Log on each process the small summary: logger.warning( f'''Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}''' + f'''distributed training: {bool(training_args.local_rank != -1)}, 16-bits training: {training_args.fpaa}''') # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank): transformers.utils.logging.set_verbosity_info() logger.info("Training/evaluation parameters %s" , a__) # Set seed before initializing model. set_seed(training_args.seed) # Get the datasets: a = datasets.load_dataset( "common_voice" , data_args.dataset_config_name , split=data_args.train_split_name) a = datasets.load_dataset("common_voice" , data_args.dataset_config_name , split="test") # Create and save tokenizer a = f'''[{"".join(data_args.chars_to_ignore)}]''' def remove_special_characters(__UpperCamelCase): a = re.sub(a__ , "" , batch["sentence"]).lower() + " " return batch a = train_dataset.map(a__ , remove_columns=["sentence"]) a = eval_dataset.map(a__ , remove_columns=["sentence"]) def extract_all_chars(__UpperCamelCase): a = " ".join(batch["text"]) a = list(set(a__)) return {"vocab": [vocab], "all_text": [all_text]} a = train_dataset.map( a__ , batched=a__ , batch_size=-1 , keep_in_memory=a__ , remove_columns=train_dataset.column_names , ) a = train_dataset.map( a__ , batched=a__ , batch_size=-1 , keep_in_memory=a__ , remove_columns=eval_dataset.column_names , ) a = list(set(vocab_train["vocab"][0]) | set(vocab_test["vocab"][0])) a = {v: k for k, v in enumerate(a__)} a = vocab_dict[" "] del vocab_dict[" "] a = len(a__) a = len(a__) with open("vocab.json" , "w") as vocab_file: json.dump(a__ , a__) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. a = WavaVecaCTCTokenizer( "vocab.json" , unk_token="[UNK]" , pad_token="[PAD]" , word_delimiter_token="|" , ) a = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=1_60_00 , padding_value=0.0 , do_normalize=a__ , return_attention_mask=a__) a = WavaVecaProcessor(feature_extractor=a__ , tokenizer=a__) a = WavaVecaForCTC.from_pretrained( model_args.model_name_or_path , cache_dir=model_args.cache_dir , activation_dropout=model_args.activation_dropout , attention_dropout=model_args.attention_dropout , hidden_dropout=model_args.hidden_dropout , feat_proj_dropout=model_args.feat_proj_dropout , mask_time_prob=model_args.mask_time_prob , gradient_checkpointing=training_args.gradient_checkpointing , layerdrop=model_args.layerdrop , ctc_loss_reduction="mean" , pad_token_id=processor.tokenizer.pad_token_id , vocab_size=len(processor.tokenizer) , ) if data_args.max_train_samples is not None: a = min(len(a__) , data_args.max_train_samples) a = train_dataset.select(range(a__)) if data_args.max_val_samples is not None: a = eval_dataset.select(range(data_args.max_val_samples)) a = torchaudio.transforms.Resample(4_80_00 , 1_60_00) # Preprocessing the datasets. # We need to read the aduio files as arrays and tokenize the targets. def speech_file_to_array_fn(__UpperCamelCase): a , a = torchaudio.load(batch["path"]) a = resampler(a__).squeeze().numpy() a = 1_60_00 a = batch["text"] return batch a = train_dataset.map( a__ , remove_columns=train_dataset.column_names , num_proc=data_args.preprocessing_num_workers , ) a = eval_dataset.map( a__ , remove_columns=eval_dataset.column_names , num_proc=data_args.preprocessing_num_workers , ) def prepare_dataset(__UpperCamelCase): # check that all files have the correct sampling rate assert ( len(set(batch["sampling_rate"])) == 1 ), f'''Make sure all inputs have the same sampling rate of {processor.feature_extractor.sampling_rate}.''' a = processor( audio=batch["speech"] , text=batch["target_text"] , sampling_rate=batch["sampling_rate"][0]) batch.update(a__) return batch a = train_dataset.map( a__ , remove_columns=train_dataset.column_names , batch_size=training_args.per_device_train_batch_size , batched=a__ , num_proc=data_args.preprocessing_num_workers , ) a = eval_dataset.map( a__ , remove_columns=eval_dataset.column_names , batch_size=training_args.per_device_train_batch_size , batched=a__ , num_proc=data_args.preprocessing_num_workers , ) # Metric a = datasets.load_metric("wer") def compute_metrics(__UpperCamelCase): a = pred.predictions a = np.argmax(a__ , axis=-1) a = processor.tokenizer.pad_token_id a = processor.batch_decode(a__) # we do not want to group tokens when computing the metrics a = processor.batch_decode(pred.label_ids , group_tokens=a__) a = wer_metric.compute(predictions=a__ , references=a__) return {"wer": wer} if model_args.freeze_feature_extractor: model.freeze_feature_extractor() # Data collator a = DataCollatorCTCWithPadding(processor=a__ , padding=a__) # Initialize our Trainer a = CTCTrainer( model=a__ , data_collator=a__ , args=a__ , compute_metrics=a__ , train_dataset=train_dataset if training_args.do_train else None , eval_dataset=eval_dataset if training_args.do_eval else None , tokenizer=processor.feature_extractor , ) # Training if training_args.do_train: if last_checkpoint is not None: a = last_checkpoint elif os.path.isdir(model_args.model_name_or_path): a = model_args.model_name_or_path else: a = None # Save the feature_extractor and the tokenizer if is_main_process(training_args.local_rank): processor.save_pretrained(training_args.output_dir) a = trainer.train(resume_from_checkpoint=a__) trainer.save_model() a = train_result.metrics a = ( data_args.max_train_samples if data_args.max_train_samples is not None else len(a__) ) a = min(a__ , len(a__)) trainer.log_metrics("train" , a__) trainer.save_metrics("train" , a__) trainer.save_state() # Evaluation a = {} if training_args.do_eval: logger.info("*** Evaluate ***") a = trainer.evaluate() a = data_args.max_val_samples if data_args.max_val_samples is not None else len(a__) a = min(a__ , len(a__)) trainer.log_metrics("eval" , a__) trainer.save_metrics("eval" , a__) return results if __name__ == "__main__": main()
371
import math def SCREAMING_SNAKE_CASE ( __UpperCamelCase) -> bool: 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(__UpperCamelCase) + 1) , 6): if number % i == 0 or number % (i + 2) == 0: return False return True def SCREAMING_SNAKE_CASE ( __UpperCamelCase = 0.1) -> int: a = 3 a = 3 while primes / (2 * j - 1) >= ratio: for i in range(j * j + j + 1 , (j + 2) * (j + 2) , j + 1): primes += is_prime(__UpperCamelCase) j += 2 return j if __name__ == "__main__": import doctest doctest.testmod()
180
0
"""simple docstring""" import inspect import unittest from transformers import MobileNetVaConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MobileNetVaForImageClassification, MobileNetVaForSemanticSegmentation, MobileNetVaModel from transformers.models.mobilenet_va.modeling_mobilenet_va import MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import MobileNetVaImageProcessor class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __UpperCAmelCase ( self ): __a = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(_a , '''tf_padding''' ) ) self.parent.assertTrue(hasattr(_a , '''depth_multiplier''' ) ) class __lowerCAmelCase : '''simple docstring''' def __init__( self , _a , _a=13 , _a=3 , _a=32 , _a=0.25 , _a=8 , _a=8 , _a=6 , _a=32 , _a=True , _a=True , _a=True , _a="relu6" , _a=1_280 , _a=0.1 , _a=0.02 , _a=True , _a=True , _a=10 , _a=None , ): __a = parent __a = batch_size __a = num_channels __a = image_size __a = depth_multiplier __a = depth_divisible_by __a = min_depth __a = expand_ratio __a = tf_padding __a = output_stride __a = first_layer_is_expansion __a = finegrained_output __a = hidden_act __a = last_hidden_size if finegrained_output else int(last_hidden_size * depth_multiplier ) __a = classifier_dropout_prob __a = use_labels __a = is_training __a = num_labels __a = initializer_range __a = scope def __UpperCAmelCase ( self ): __a = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __a = None __a = None if self.use_labels: __a = ids_tensor([self.batch_size] , self.num_labels ) __a = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels ) __a = self.get_config() return config, pixel_values, labels, pixel_labels def __UpperCAmelCase ( self ): return MobileNetVaConfig( num_channels=self.num_channels , image_size=self.image_size , depth_multiplier=self.depth_multiplier , depth_divisible_by=self.depth_divisible_by , min_depth=self.min_depth , expand_ratio=self.expand_ratio , output_stride=self.output_stride , first_layer_is_expansion=self.first_layer_is_expansion , finegrained_output=self.finegrained_output , hidden_act=self.hidden_act , tf_padding=self.tf_padding , classifier_dropout_prob=self.classifier_dropout_prob , initializer_range=self.initializer_range , ) def __UpperCAmelCase ( self , _a , _a , _a , _a ): __a = MobileNetVaModel(config=_a ) model.to(_a ) model.eval() __a = model(_a ) self.parent.assertEqual( result.last_hidden_state.shape , ( self.batch_size, self.last_hidden_size, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) self.parent.assertEqual( result.pooler_output.shape , (self.batch_size, self.last_hidden_size) , ) def __UpperCAmelCase ( self , _a , _a , _a , _a ): __a = self.num_labels __a = MobileNetVaForImageClassification(_a ) model.to(_a ) model.eval() __a = model(_a , labels=_a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __UpperCAmelCase ( self , _a , _a , _a , _a ): __a = self.num_labels __a = MobileNetVaForSemanticSegmentation(_a ) model.to(_a ) model.eval() __a = model(_a ) self.parent.assertEqual( result.logits.shape , ( self.batch_size, self.num_labels, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) __a = model(_a , labels=_a ) self.parent.assertEqual( result.logits.shape , ( self.batch_size, self.num_labels, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) def __UpperCAmelCase ( self ): __a = self.prepare_config_and_inputs() __a , __a , __a , __a = config_and_inputs __a = {'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' __UpperCAmelCase : int = ( (MobileNetVaModel, MobileNetVaForImageClassification, MobileNetVaForSemanticSegmentation) if is_torch_available() else () ) __UpperCAmelCase : str = ( { 'feature-extraction': MobileNetVaModel, 'image-classification': MobileNetVaForImageClassification, 'image-segmentation': MobileNetVaForSemanticSegmentation, } if is_torch_available() else {} ) __UpperCAmelCase : List[str] = False __UpperCAmelCase : Optional[Any] = False __UpperCAmelCase : Optional[Any] = False __UpperCAmelCase : str = False def __UpperCAmelCase ( self ): __a = MobileNetVaModelTester(self ) __a = MobileNetVaConfigTester(self , config_class=_a , has_text_modality=_a ) def __UpperCAmelCase ( self ): self.config_tester.run_common_tests() @unittest.skip(reason='''MobileNetV2 does not use inputs_embeds''' ) def __UpperCAmelCase ( self ): pass @unittest.skip(reason='''MobileNetV2 does not support input and output embeddings''' ) def __UpperCAmelCase ( self ): pass @unittest.skip(reason='''MobileNetV2 does not output attentions''' ) def __UpperCAmelCase ( self ): pass def __UpperCAmelCase ( self ): __a , __a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a = model_class(_a ) __a = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __a = [*signature.parameters.keys()] __a = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , _a ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_a ) def __UpperCAmelCase ( self ): def check_hidden_states_output(_a , _a , _a ): __a = model_class(_a ) model.to(_a ) model.eval() with torch.no_grad(): __a = model(**self._prepare_for_class(_a , _a ) ) __a = outputs.hidden_states __a = 16 self.assertEqual(len(_a ) , _a ) __a , __a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a = True check_hidden_states_output(_a , _a , _a ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __a = True check_hidden_states_output(_a , _a , _a ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_a ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*_a ) @slow def __UpperCAmelCase ( self ): for model_name in MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __a = MobileNetVaModel.from_pretrained(_a ) self.assertIsNotNone(_a ) def lowercase ( ) -> Dict: __a = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_torch @require_vision class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' @cached_property def __UpperCAmelCase ( self ): return ( MobileNetVaImageProcessor.from_pretrained('''google/mobilenet_v2_1.0_224''' ) if is_vision_available() else None ) @slow def __UpperCAmelCase ( self ): __a = MobileNetVaForImageClassification.from_pretrained('''google/mobilenet_v2_1.0_224''' ).to(_a ) __a = self.default_image_processor __a = prepare_img() __a = image_processor(images=_a , return_tensors='''pt''' ).to(_a ) # forward pass with torch.no_grad(): __a = model(**_a ) # verify the logits __a = torch.Size((1, 1_001) ) self.assertEqual(outputs.logits.shape , _a ) __a = torch.tensor([0.2445, -1.1993, 0.1905] ).to(_a ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , _a , atol=1E-4 ) ) @slow def __UpperCAmelCase ( self ): __a = MobileNetVaForSemanticSegmentation.from_pretrained('''google/deeplabv3_mobilenet_v2_1.0_513''' ) __a = model.to(_a ) __a = MobileNetVaImageProcessor.from_pretrained('''google/deeplabv3_mobilenet_v2_1.0_513''' ) __a = prepare_img() __a = image_processor(images=_a , return_tensors='''pt''' ).to(_a ) # forward pass with torch.no_grad(): __a = model(**_a ) __a = outputs.logits # verify the logits __a = torch.Size((1, 21, 65, 65) ) self.assertEqual(logits.shape , _a ) __a = torch.tensor( [ [[17.5790, 17.7581, 18.3355], [18.3257, 18.4230, 18.8973], [18.6169, 18.8650, 19.2187]], [[-2.1595, -2.0977, -2.3741], [-2.4226, -2.3028, -2.6835], [-2.7819, -2.5991, -2.7706]], [[4.2058, 4.8317, 4.7638], [4.4136, 5.0361, 4.9383], [4.5028, 4.9644, 4.8734]], ] , device=_a , ) self.assertTrue(torch.allclose(logits[0, :3, :3, :3] , _a , atol=1E-4 ) )
45
"""simple docstring""" import unittest from transformers import AutoTokenizer, FalconConfig, 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 ( FalconForCausalLM, FalconForQuestionAnswering, FalconForSequenceClassification, FalconForTokenClassification, FalconModel, ) class __a : '''simple docstring''' def __init__( self , _a , _a=3 , _a=7 , _a=True , _a=True , _a=False , _a=True , _a=99 , _a=32 , _a=5 , _a=4 , _a=37 , _a="gelu" , _a=0.1 , _a=0.1 , _a=512 , _a=16 , _a=2 , _a=0.02 , _a=3 , _a=4 , _a=None , ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = parent SCREAMING_SNAKE_CASE__ : int = batch_size SCREAMING_SNAKE_CASE__ : Dict = seq_length SCREAMING_SNAKE_CASE__ : int = is_training SCREAMING_SNAKE_CASE__ : Optional[int] = use_input_mask SCREAMING_SNAKE_CASE__ : Optional[Any] = use_token_type_ids SCREAMING_SNAKE_CASE__ : Optional[Any] = use_labels SCREAMING_SNAKE_CASE__ : Tuple = vocab_size SCREAMING_SNAKE_CASE__ : List[Any] = hidden_size SCREAMING_SNAKE_CASE__ : Optional[int] = num_hidden_layers SCREAMING_SNAKE_CASE__ : int = num_attention_heads SCREAMING_SNAKE_CASE__ : Union[str, Any] = intermediate_size SCREAMING_SNAKE_CASE__ : int = hidden_act SCREAMING_SNAKE_CASE__ : List[str] = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : List[str] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : Dict = max_position_embeddings SCREAMING_SNAKE_CASE__ : Union[str, Any] = type_vocab_size SCREAMING_SNAKE_CASE__ : List[str] = type_sequence_label_size SCREAMING_SNAKE_CASE__ : Optional[int] = initializer_range SCREAMING_SNAKE_CASE__ : Dict = num_labels SCREAMING_SNAKE_CASE__ : Optional[Any] = num_choices SCREAMING_SNAKE_CASE__ : Optional[int] = scope def _a ( self ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE__ : int = None if self.use_input_mask: SCREAMING_SNAKE_CASE__ : Optional[int] = random_attention_mask([self.batch_size, self.seq_length] ) SCREAMING_SNAKE_CASE__ : int = None SCREAMING_SNAKE_CASE__ : Optional[Any] = None SCREAMING_SNAKE_CASE__ : Union[str, Any] = None SCREAMING_SNAKE_CASE__ : Dict = None if self.use_labels: SCREAMING_SNAKE_CASE__ : int = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) SCREAMING_SNAKE_CASE__ : str = ids_tensor([self.batch_size] , self.num_choices ) SCREAMING_SNAKE_CASE__ : Optional[Any] = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def _a ( self ) -> str: """simple docstring""" return FalconConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=_a , initializer_range=self.initializer_range , pad_token_id=1 , new_decoder_architecture=_a , ) def _a ( self , _a , _a , _a , _a , _a , _a , _a ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = FalconModel(config=_a ) model.to(_a ) model.eval() SCREAMING_SNAKE_CASE__ : str = model(_a , attention_mask=_a ) SCREAMING_SNAKE_CASE__ : Any = model(_a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _a ( self , _a , _a , _a , _a , _a , _a , _a , _a , _a , ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = True SCREAMING_SNAKE_CASE__ : Dict = FalconModel(_a ) model.to(_a ) model.eval() SCREAMING_SNAKE_CASE__ : int = model( _a , attention_mask=_a , encoder_hidden_states=_a , encoder_attention_mask=_a , ) SCREAMING_SNAKE_CASE__ : List[str] = model( _a , attention_mask=_a , encoder_hidden_states=_a , ) SCREAMING_SNAKE_CASE__ : Optional[Any] = model(_a , attention_mask=_a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _a ( self , _a , _a , _a , _a , _a , _a , _a , _a , _a , ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = FalconForCausalLM(config=_a ) model.to(_a ) model.eval() SCREAMING_SNAKE_CASE__ : Union[str, Any] = model(_a , attention_mask=_a , labels=_a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def _a ( self , _a , _a , _a , _a , _a , _a , _a , _a , _a , ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = True SCREAMING_SNAKE_CASE__ : Dict = True SCREAMING_SNAKE_CASE__ : Optional[int] = FalconForCausalLM(config=_a ) model.to(_a ) model.eval() # first forward pass SCREAMING_SNAKE_CASE__ : int = model( _a , attention_mask=_a , encoder_hidden_states=_a , encoder_attention_mask=_a , use_cache=_a , ) SCREAMING_SNAKE_CASE__ : str = outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids SCREAMING_SNAKE_CASE__ : Any = ids_tensor((self.batch_size, 3) , config.vocab_size ) SCREAMING_SNAKE_CASE__ : List[Any] = ids_tensor((self.batch_size, 3) , vocab_size=2 ) # append to next input_ids and SCREAMING_SNAKE_CASE__ : Tuple = torch.cat([input_ids, next_tokens] , dim=-1 ) SCREAMING_SNAKE_CASE__ : Optional[int] = torch.cat([input_mask, next_mask] , dim=-1 ) SCREAMING_SNAKE_CASE__ : Tuple = model( _a , attention_mask=_a , encoder_hidden_states=_a , encoder_attention_mask=_a , output_hidden_states=_a , )["""hidden_states"""][0] SCREAMING_SNAKE_CASE__ : Tuple = model( _a , attention_mask=_a , encoder_hidden_states=_a , encoder_attention_mask=_a , past_key_values=_a , output_hidden_states=_a , )["""hidden_states"""][0] # select random slice SCREAMING_SNAKE_CASE__ : List[Any] = ids_tensor((1,) , output_from_past.shape[-1] ).item() SCREAMING_SNAKE_CASE__ : Optional[int] = output_from_no_past[:, -3:, random_slice_idx].detach() SCREAMING_SNAKE_CASE__ : str = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(_a , _a , atol=1E-3 ) ) def _a ( self ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ) : Tuple = config_and_inputs SCREAMING_SNAKE_CASE__ : Optional[Any] = {"""input_ids""": input_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class __a (UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase): '''simple docstring''' _SCREAMING_SNAKE_CASE :List[Any] = ( ( FalconModel, FalconForCausalLM, FalconForSequenceClassification, FalconForTokenClassification, FalconForQuestionAnswering, ) if is_torch_available() else () ) _SCREAMING_SNAKE_CASE :Any = (FalconForCausalLM,) if is_torch_available() else () _SCREAMING_SNAKE_CASE :List[Any] = ( { """feature-extraction""": FalconModel, """text-classification""": FalconForSequenceClassification, """text-generation""": FalconForCausalLM, """question-answering""": FalconForQuestionAnswering, """token-classification""": FalconForTokenClassification, """zero-shot""": FalconForSequenceClassification, } if is_torch_available() else {} ) _SCREAMING_SNAKE_CASE :List[str] = False _SCREAMING_SNAKE_CASE :str = False def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = FalconModelTester(self ) SCREAMING_SNAKE_CASE__ : List[str] = ConfigTester(self , config_class=_a , hidden_size=37 ) def _a ( self ) -> int: """simple docstring""" self.config_tester.run_common_tests() def _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_a ) def _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ , *SCREAMING_SNAKE_CASE__ : Any = self.model_tester.prepare_config_and_inputs() for alibi in [True, False]: SCREAMING_SNAKE_CASE__ : str = alibi self.model_tester.create_and_check_model(_a , *_a ) def _a ( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : List[Any] = 3 SCREAMING_SNAKE_CASE__ : Optional[Any] = input_dict["""input_ids"""] SCREAMING_SNAKE_CASE__ : str = input_ids.ne(1 ).to(_a ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = FalconForSequenceClassification(_a ) model.to(_a ) model.eval() SCREAMING_SNAKE_CASE__ : List[str] = model(_a , attention_mask=_a , labels=_a ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def _a ( self ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Any = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : Union[str, Any] = 3 SCREAMING_SNAKE_CASE__ : Optional[Any] = """single_label_classification""" SCREAMING_SNAKE_CASE__ : List[str] = input_dict["""input_ids"""] SCREAMING_SNAKE_CASE__ : Tuple = input_ids.ne(1 ).to(_a ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ : List[Any] = FalconForSequenceClassification(_a ) model.to(_a ) model.eval() SCREAMING_SNAKE_CASE__ : str = model(_a , attention_mask=_a , labels=_a ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def _a ( self ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Any = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : Optional[int] = input_dict["""input_ids"""] SCREAMING_SNAKE_CASE__ : int = FalconForCausalLM(_a ) model.to(_a ) model.eval() SCREAMING_SNAKE_CASE__ : Dict = model(_a , use_cache=_a ) SCREAMING_SNAKE_CASE__ : str = input_ids.shape[0] SCREAMING_SNAKE_CASE__ : Union[str, Any] = model._convert_to_rw_cache(result.past_key_values ) SCREAMING_SNAKE_CASE__ : Any = model._convert_cache_to_standard_format(_a , _a ) for layer in range(len(_a ) ): for tensor_idx in range(2 ): self.assertTrue(rw_cache[layer][tensor_idx].ndim == 3 ) self.assertTrue(result.past_key_values[layer][tensor_idx].ndim == 4 ) self.assertTrue( torch.all(result.past_key_values[layer][tensor_idx] == standard_cache[layer][tensor_idx] ) ) def _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : List[str] = 3 SCREAMING_SNAKE_CASE__ : str = """multi_label_classification""" SCREAMING_SNAKE_CASE__ : int = input_dict["""input_ids"""] SCREAMING_SNAKE_CASE__ : List[str] = input_ids.ne(1 ).to(_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = ids_tensor( [self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size ).to(torch.float ) SCREAMING_SNAKE_CASE__ : int = FalconForSequenceClassification(_a ) model.to(_a ) model.eval() SCREAMING_SNAKE_CASE__ : List[Any] = model(_a , attention_mask=_a , labels=_a ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def _a ( self ) -> List[str]: """simple docstring""" for model_class in self.all_generative_model_classes: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() # If it doesn't support cache, pass the test if not hasattr(_a , """use_cache""" ): return SCREAMING_SNAKE_CASE__ : Optional[int] = model_class(_a ).to(_a ) if "use_cache" not in inputs: SCREAMING_SNAKE_CASE__ : Optional[Any] = True SCREAMING_SNAKE_CASE__ : Tuple = model(**_a ) # If "past_key_values" is not returned, pass the test (e.g. RWKV uses a different cache name and format) if "past_key_values" not in outputs: return SCREAMING_SNAKE_CASE__ : Dict = ( getattr(_a , """decoder_layers""" , _a ) or getattr(_a , """num_decoder_layers""" , _a ) or config.num_hidden_layers ) SCREAMING_SNAKE_CASE__ : Any = getattr(_a , """num_kv_heads""" , config.num_attention_heads ) SCREAMING_SNAKE_CASE__ : str = getattr(_a , """d_model""" , config.hidden_size ) SCREAMING_SNAKE_CASE__ : str = embed_dim // num_attention_heads SCREAMING_SNAKE_CASE__ : List[Any] = outputs["""past_key_values"""] self.assertEqual(len(_a ) , _a ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Tuple = inputs["""input_ids"""].shape for i in range(_a ): if config.new_decoder_architecture: SCREAMING_SNAKE_CASE__ : Any = config.num_attention_heads elif config.multi_query: SCREAMING_SNAKE_CASE__ : Optional[Any] = 1 self.assertEqual(len(past_kv[0] ) , 2 ) # K V for the decoder = 2 self.assertEqual( past_kv[i][0].shape , (batch_size, num_attention_heads, seq_length, per_head_embed_dim) ) self.assertEqual( past_kv[i][1].shape , (batch_size, num_attention_heads, seq_length, per_head_embed_dim) ) @require_torch class __a (unittest.TestCase): '''simple docstring''' @slow def _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = AutoTokenizer.from_pretrained("""Rocketknight1/falcon-rw-1b""" ) SCREAMING_SNAKE_CASE__ : Tuple = FalconForCausalLM.from_pretrained("""Rocketknight1/falcon-rw-1b""" ) model.eval() model.to(_a ) SCREAMING_SNAKE_CASE__ : Tuple = tokenizer("""My favorite food is""" , return_tensors="""pt""" ).to(_a ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = ( """My favorite food is pizza. I love it so much that I have a pizza party every year for my birthday.""" ) SCREAMING_SNAKE_CASE__ : Any = model.generate(**_a , do_sample=_a , max_new_tokens=19 ) SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer.batch_decode(_a )[0] self.assertEqual(_a , _a ) @slow def _a ( self ) -> Union[str, Any]: """simple docstring""" for repo in ["Rocketknight1/tiny-random-falcon-7b", "Rocketknight1/tiny-random-falcon-40b"]: SCREAMING_SNAKE_CASE__ : Any = AutoTokenizer.from_pretrained(_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = FalconForCausalLM.from_pretrained(_a ) model.eval() model.to(_a ) SCREAMING_SNAKE_CASE__ : str = tokenizer("""My favorite food is""" , return_tensors="""pt""" ).to(_a ) # We just test that these run without errors - the models are randomly initialized # and so the actual text outputs will be garbage model.generate(**_a , do_sample=_a , max_new_tokens=4 ) model.generate(**_a , do_sample=_a , max_new_tokens=4 ) model.generate(**_a , num_beams=2 , max_new_tokens=4 ) @slow def _a ( self ) -> Optional[int]: """simple docstring""" with torch.no_grad(): for repo in [ "Rocketknight1/falcon-rw-1b", "Rocketknight1/tiny-random-falcon-7b", "Rocketknight1/tiny-random-falcon-40b", ]: SCREAMING_SNAKE_CASE__ : Optional[int] = AutoTokenizer.from_pretrained(_a ) SCREAMING_SNAKE_CASE__ : int = FalconForCausalLM.from_pretrained(_a ) model.eval() model.to(device=_a ) SCREAMING_SNAKE_CASE__ : List[str] = tokenizer("""My favorite food is""" , return_tensors="""pt""" ).to(_a ) # Test results are the same with and without cache SCREAMING_SNAKE_CASE__ : Tuple = model.generate(**_a , do_sample=_a , max_new_tokens=20 , use_cache=_a ) SCREAMING_SNAKE_CASE__ : Tuple = model.generate(**_a , do_sample=_a , max_new_tokens=20 , use_cache=_a ) self.assertTrue((outputs_cache - outputs_no_cache).sum().item() == 0 )
132
0
'''simple docstring''' import os import unittest from transformers import FunnelTokenizer, FunnelTokenizerFast from transformers.models.funnel.tokenization_funnel import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class A__ ( A__ , unittest.TestCase ): A__ = FunnelTokenizer A__ = FunnelTokenizerFast A__ = True A__ = True def A ( self : Union[str, Any] ) -> Optional[Any]: '''simple docstring''' super().setUp() _SCREAMING_SNAKE_CASE =[ '<unk>', '<cls>', '<sep>', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing', ',', 'low', 'lowest', ] _SCREAMING_SNAKE_CASE =os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in vocab_tokens] ) ) def A ( self : Tuple , **_a : Tuple ) -> Optional[Any]: '''simple docstring''' return FunnelTokenizer.from_pretrained(self.tmpdirname , **_a ) def A ( self : List[str] , **_a : List[Any] ) -> str: '''simple docstring''' return FunnelTokenizerFast.from_pretrained(self.tmpdirname , **_a ) def A ( self : Tuple , _a : Union[str, Any] ) -> Any: '''simple docstring''' _SCREAMING_SNAKE_CASE ='UNwant\u00E9d,running' _SCREAMING_SNAKE_CASE ='unwanted, running' return input_text, output_text def A ( self : str ) -> List[Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.tokenizer_class(self.vocab_file ) _SCREAMING_SNAKE_CASE =tokenizer.tokenize('UNwant\u00E9d,running' ) self.assertListEqual(_a , ['un', '##want', '##ed', ',', 'runn', '##ing'] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(_a ) , [7, 4, 5, 10, 8, 9] ) def A ( self : str ) -> List[Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.get_tokenizers(do_lower_case=_a ) for tokenizer in tokenizers: _SCREAMING_SNAKE_CASE =tokenizer('UNwant\u00E9d,running' ) _SCREAMING_SNAKE_CASE =len(inputs['input_ids'] ) - 1 self.assertListEqual(inputs['token_type_ids'] , [2] + [0] * sentence_len ) _SCREAMING_SNAKE_CASE =tokenizer('UNwant\u00E9d,running' , 'UNwant\u00E9d,running' ) self.assertListEqual(inputs['token_type_ids'] , [2] + [0] * sentence_len + [1] * sentence_len )
114
'''simple docstring''' import os def _lowerCAmelCase ( ) -> List[str]: """simple docstring""" _SCREAMING_SNAKE_CASE =os.path.dirname(os.path.realpath(_UpperCamelCase ) ) _SCREAMING_SNAKE_CASE =os.path.join(_UpperCamelCase , 'triangle.txt' ) with open(_UpperCamelCase ) as f: _SCREAMING_SNAKE_CASE =f.readlines() _SCREAMING_SNAKE_CASE =[] for line in triangle: _SCREAMING_SNAKE_CASE =[] for number in line.strip().split(' ' ): numbers_from_line.append(int(_UpperCamelCase ) ) a.append(_UpperCamelCase ) for i in range(1 , len(_UpperCamelCase ) ): for j in range(len(a[i] ) ): _SCREAMING_SNAKE_CASE =a[i - 1][j] if j != len(a[i - 1] ) else 0 _SCREAMING_SNAKE_CASE =a[i - 1][j - 1] if j > 0 else 0 a[i][j] += max(_UpperCamelCase , _UpperCamelCase ) return max(a[-1] ) if __name__ == "__main__": print(solution())
114
1
"""simple docstring""" from math import sqrt def __UpperCAmelCase ( __UpperCamelCase ): if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(sqrt(lowerCamelCase__ ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def __UpperCAmelCase ( __UpperCamelCase = 1_00_01 ): __lowercase : List[Any] = 0 __lowercase : Tuple = 1 while count != nth and number < 3: number += 1 if is_prime(lowerCamelCase__ ): count += 1 while count != nth: number += 2 if is_prime(lowerCamelCase__ ): count += 1 return number if __name__ == "__main__": print(F"{solution() = }")
249
"""simple docstring""" def _snake_case ( lowerCamelCase__ : str , lowerCamelCase__ : str , lowerCamelCase__ : List[Any] , lowerCamelCase__ : str ) -> str: global f # a global dp table for knapsack if f[i][j] < 0: if j < wt[i - 1]: lowerCamelCase_ : Optional[Any] =mf_knapsack(i - 1 , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) else: lowerCamelCase_ : Union[str, Any] =max( mf_knapsack(i - 1 , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) , mf_knapsack(i - 1 , lowerCamelCase__ , lowerCamelCase__ , j - wt[i - 1] ) + val[i - 1] , ) lowerCamelCase_ : int =val return f[i][j] def _snake_case ( lowerCamelCase__ : Optional[int] , lowerCamelCase__ : Dict , lowerCamelCase__ : Any , lowerCamelCase__ : int ) -> Dict: lowerCamelCase_ : List[Any] =[[0] * (w + 1) for _ in range(n + 1 )] for i in range(1 , n + 1 ): for w_ in range(1 , w + 1 ): if wt[i - 1] <= w_: lowerCamelCase_ : Union[str, Any] =max(val[i - 1] + dp[i - 1][w_ - wt[i - 1]] , dp[i - 1][w_] ) else: lowerCamelCase_ : Optional[int] =dp[i - 1][w_] return dp[n][w_], dp def _snake_case ( lowerCamelCase__ : int , lowerCamelCase__ : list , lowerCamelCase__ : list ) -> Tuple: if not (isinstance(lowerCamelCase__ , (list, tuple) ) and isinstance(lowerCamelCase__ , (list, tuple) )): raise ValueError( "Both the weights and values vectors must be either lists or tuples" ) lowerCamelCase_ : Optional[int] =len(lowerCamelCase__ ) if num_items != len(lowerCamelCase__ ): lowerCamelCase_ : Optional[Any] =( "The number of weights must be the same as the number of values.\n" F"""But got {num_items} weights and {len(lowerCamelCase__ )} values""" ) raise ValueError(lowerCamelCase__ ) for i in range(lowerCamelCase__ ): if not isinstance(wt[i] , lowerCamelCase__ ): lowerCamelCase_ : Optional[Any] =( "All weights must be integers but got weight of " F"""type {type(wt[i] )} at index {i}""" ) raise TypeError(lowerCamelCase__ ) lowerCamelCase_ , lowerCamelCase_ : Optional[int] =knapsack(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) lowerCamelCase_ : set =set() _construct_solution(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) return optimal_val, example_optional_set def _snake_case ( lowerCamelCase__ : list , lowerCamelCase__ : list , lowerCamelCase__ : int , lowerCamelCase__ : int , lowerCamelCase__ : set ) -> Optional[int]: # for the current item i at a maximum weight j to be part of an optimal subset, # the optimal value at (i, j) must be greater than the optimal value at (i-1, j). # where i - 1 means considering only the previous items at the given maximum weight if i > 0 and j > 0: if dp[i - 1][j] == dp[i][j]: _construct_solution(lowerCamelCase__ , lowerCamelCase__ , i - 1 , lowerCamelCase__ , lowerCamelCase__ ) else: optimal_set.add(lowerCamelCase__ ) _construct_solution(lowerCamelCase__ , lowerCamelCase__ , i - 1 , j - wt[i - 1] , lowerCamelCase__ ) if __name__ == "__main__": A__ : Optional[Any] = [3, 2, 4, 4] A__ : str = [4, 3, 2, 3] A__ : List[Any] = 4 A__ : Union[str, Any] = 6 A__ : List[str] = [[0] * (w + 1)] + [[0] + [-1] * (w + 1) for _ in range(n + 1)] A__ , A__ : Any = knapsack(w, wt, val, n) print(optimal_solution) print(mf_knapsack(n, wt, val, w)) # switched the n and w # testing the dynamic programming problem with example # the optimal subset for the above example are items 3 and 4 A__ , A__ : str = knapsack_with_example_solution(w, wt, val) assert optimal_solution == 8 assert optimal_subset == {3, 4} print('optimal_value = ', optimal_solution) print('An optimal subset corresponding to the optimal value', optimal_subset)
144
0
'''simple docstring''' import os import unittest from transformers import FunnelTokenizer, FunnelTokenizerFast from transformers.models.funnel.tokenization_funnel import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class a__ ( _UpperCAmelCase , unittest.TestCase ): _SCREAMING_SNAKE_CASE : Dict = FunnelTokenizer _SCREAMING_SNAKE_CASE : Union[str, Any] = FunnelTokenizerFast _SCREAMING_SNAKE_CASE : Union[str, Any] = True _SCREAMING_SNAKE_CASE : Tuple = True def _lowerCamelCase ( self ): """simple docstring""" super().setUp() _lowercase : Optional[Any] = [ '''<unk>''', '''<cls>''', '''<sep>''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest''', ] _lowercase : int = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as vocab_writer: vocab_writer.write("".join([x + "\n" for x in vocab_tokens] ) ) def _lowerCamelCase ( self , **_UpperCamelCase ): """simple docstring""" return FunnelTokenizer.from_pretrained(self.tmpdirname , **_UpperCAmelCase ) def _lowerCamelCase ( self , **_UpperCamelCase ): """simple docstring""" return FunnelTokenizerFast.from_pretrained(self.tmpdirname , **_UpperCAmelCase ) def _lowerCamelCase ( self , _UpperCamelCase ): """simple docstring""" _lowercase : Tuple = '''UNwant\u00E9d,running''' _lowercase : Optional[int] = '''unwanted, running''' return input_text, output_text def _lowerCamelCase ( self ): """simple docstring""" _lowercase : List[str] = self.tokenizer_class(self.vocab_file ) _lowercase : Tuple = tokenizer.tokenize("UNwant\u00E9d,running" ) self.assertListEqual(_UpperCAmelCase , ["un", "##want", "##ed", ",", "runn", "##ing"] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(_UpperCAmelCase ) , [7, 4, 5, 10, 8, 9] ) def _lowerCamelCase ( self ): """simple docstring""" _lowercase : Union[str, Any] = self.get_tokenizers(do_lower_case=_UpperCAmelCase ) for tokenizer in tokenizers: _lowercase : int = tokenizer("UNwant\u00E9d,running" ) _lowercase : Union[str, Any] = len(inputs["input_ids"] ) - 1 self.assertListEqual(inputs["token_type_ids"] , [2] + [0] * sentence_len ) _lowercase : Union[str, Any] = tokenizer("UNwant\u00E9d,running" , "UNwant\u00E9d,running" ) self.assertListEqual(inputs["token_type_ids"] , [2] + [0] * sentence_len + [1] * sentence_len )
352
'''simple docstring''' import logging from transformers import PretrainedConfig _snake_case = logging.getLogger(__name__) _snake_case = { 'bertabs-finetuned-cnndm': 'https://huggingface.co/remi/bertabs-finetuned-cnndm-extractive-abstractive-summarization/resolve/main/config.json', } class a__ ( lowerCamelCase_ ): _SCREAMING_SNAKE_CASE : List[str] = 'bertabs' def __init__( self , _UpperCamelCase=30522 , _UpperCamelCase=512 , _UpperCamelCase=6 , _UpperCamelCase=512 , _UpperCamelCase=8 , _UpperCamelCase=512 , _UpperCamelCase=0.2 , _UpperCamelCase=6 , _UpperCamelCase=768 , _UpperCamelCase=8 , _UpperCamelCase=2048 , _UpperCamelCase=0.2 , **_UpperCamelCase , ): """simple docstring""" super().__init__(**_UpperCamelCase ) _lowercase : List[str] = vocab_size _lowercase : Tuple = max_pos _lowercase : int = enc_layers _lowercase : str = enc_hidden_size _lowercase : Optional[Any] = enc_heads _lowercase : Union[str, Any] = enc_ff_size _lowercase : Tuple = enc_dropout _lowercase : Dict = dec_layers _lowercase : List[str] = dec_hidden_size _lowercase : List[str] = dec_heads _lowercase : str = dec_ff_size _lowercase : str = dec_dropout
199
0
'''simple docstring''' import warnings from ...utils import logging from .image_processing_donut import DonutImageProcessor SCREAMING_SNAKE_CASE_: int =logging.get_logger(__name__) class __A ( UpperCamelCase__ ): def __init__(self : Optional[int] , *__a : Optional[Any] , **__a : Dict ): warnings.warn( "The class DonutFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please" " use DonutImageProcessor instead." , __a , ) super().__init__(*__a , **__a )
1
"""simple docstring""" # flake8: noqa # Lint as: python3 _UpperCAmelCase = [ """VerificationMode""", """Version""", """disable_progress_bar""", """enable_progress_bar""", """is_progress_bar_enabled""", """experimental""", ] from .info_utils import VerificationMode from .logging import disable_progress_bar, enable_progress_bar, is_progress_bar_enabled from .version import Version from .experimental import experimental
173
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available snake_case_ : str = { 'configuration_poolformer': [ 'POOLFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'PoolFormerConfig', 'PoolFormerOnnxConfig', ] } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case_ : Tuple = ['PoolFormerFeatureExtractor'] snake_case_ : int = ['PoolFormerImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case_ : Union[str, Any] = [ 'POOLFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'PoolFormerForImageClassification', 'PoolFormerModel', 'PoolFormerPreTrainedModel', ] if TYPE_CHECKING: from .configuration_poolformer import ( POOLFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, PoolFormerConfig, PoolFormerOnnxConfig, ) try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_poolformer import PoolFormerFeatureExtractor from .image_processing_poolformer import PoolFormerImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_poolformer import ( POOLFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, PoolFormerForImageClassification, PoolFormerModel, PoolFormerPreTrainedModel, ) else: import sys snake_case_ : Any = _LazyModule(__name__, globals()['__file__'], _import_structure)
370
'''simple docstring''' class lowercase__ : def __init__( self : List[str] ,lowerCamelCase__ : List[Any] ,lowerCamelCase__ : Optional[int] ,lowerCamelCase__ : Any ): '''simple docstring''' _UpperCamelCase : Dict = None _UpperCamelCase : List[Any] = None _UpperCamelCase : int = graph self._normalize_graph(lowerCamelCase__ ,lowerCamelCase__ ) _UpperCamelCase : List[str] = len(lowerCamelCase__ ) _UpperCamelCase : Tuple = None def UpperCamelCase_ ( self : Any ,lowerCamelCase__ : Optional[Any] ,lowerCamelCase__ : Any ): '''simple docstring''' if sources is int: _UpperCamelCase : Optional[int] = [sources] if sinks is int: _UpperCamelCase : Union[str, Any] = [sinks] if len(lowerCamelCase__ ) == 0 or len(lowerCamelCase__ ) == 0: return _UpperCamelCase : List[str] = sources[0] _UpperCamelCase : str = sinks[0] # make fake vertex if there are more # than one source or sink if len(lowerCamelCase__ ) > 1 or len(lowerCamelCase__ ) > 1: _UpperCamelCase : Dict = 0 for i in sources: max_input_flow += sum(self.graph[i] ) _UpperCamelCase : Tuple = len(self.graph ) + 1 for room in self.graph: room.insert(0 ,0 ) self.graph.insert(0 ,[0] * size ) for i in sources: _UpperCamelCase : List[Any] = max_input_flow _UpperCamelCase : Tuple = 0 _UpperCamelCase : int = len(self.graph ) + 1 for room in self.graph: room.append(0 ) self.graph.append([0] * size ) for i in sinks: _UpperCamelCase : Optional[int] = max_input_flow _UpperCamelCase : Optional[int] = size - 1 def UpperCamelCase_ ( self : List[str] ): '''simple docstring''' if self.maximum_flow_algorithm is None: raise Exception('You need to set maximum flow algorithm before.' ) if self.source_index is None or self.sink_index is None: return 0 self.maximum_flow_algorithm.execute() return self.maximum_flow_algorithm.getMaximumFlow() def UpperCamelCase_ ( self : Any ,lowerCamelCase__ : Any ): '''simple docstring''' _UpperCamelCase : str = algorithm(self ) class lowercase__ : def __init__( self : List[str] ,lowerCamelCase__ : Optional[int] ): '''simple docstring''' _UpperCamelCase : Optional[Any] = flow_network _UpperCamelCase : List[str] = flow_network.verticesCount _UpperCamelCase : List[str] = flow_network.sourceIndex _UpperCamelCase : Any = flow_network.sinkIndex # it's just a reference, so you shouldn't change # it in your algorithms, use deep copy before doing that _UpperCamelCase : List[Any] = flow_network.graph _UpperCamelCase : Any = False def UpperCamelCase_ ( self : str ): '''simple docstring''' if not self.executed: self._algorithm() _UpperCamelCase : Any = True def UpperCamelCase_ ( self : Any ): '''simple docstring''' pass class lowercase__ ( lowercase ): def __init__( self : Union[str, Any] ,lowerCamelCase__ : List[str] ): '''simple docstring''' super().__init__(lowerCamelCase__ ) # use this to save your result _UpperCamelCase : Tuple = -1 def UpperCamelCase_ ( self : Dict ): '''simple docstring''' if not self.executed: raise Exception('You should execute algorithm before using its result!' ) return self.maximum_flow class lowercase__ ( lowercase ): def __init__( self : Optional[Any] ,lowerCamelCase__ : Dict ): '''simple docstring''' super().__init__(lowerCamelCase__ ) _UpperCamelCase : Dict = [[0] * self.verticies_count for i in range(self.verticies_count )] _UpperCamelCase : Optional[Any] = [0] * self.verticies_count _UpperCamelCase : List[str] = [0] * self.verticies_count def UpperCamelCase_ ( self : Union[str, Any] ): '''simple docstring''' _UpperCamelCase : Dict = self.verticies_count # push some substance to graph for nextvertex_index, bandwidth in enumerate(self.graph[self.source_index] ): self.preflow[self.source_index][nextvertex_index] += bandwidth self.preflow[nextvertex_index][self.source_index] -= bandwidth self.excesses[nextvertex_index] += bandwidth # Relabel-to-front selection rule _UpperCamelCase : List[str] = [ i for i in range(self.verticies_count ) if i != self.source_index and i != self.sink_index ] # move through list _UpperCamelCase : int = 0 while i < len(lowerCamelCase__ ): _UpperCamelCase : List[Any] = vertices_list[i] _UpperCamelCase : str = self.heights[vertex_index] self.process_vertex(lowerCamelCase__ ) if self.heights[vertex_index] > previous_height: # if it was relabeled, swap elements # and start from 0 index vertices_list.insert(0 ,vertices_list.pop(lowerCamelCase__ ) ) _UpperCamelCase : Dict = 0 else: i += 1 _UpperCamelCase : Optional[Any] = sum(self.preflow[self.source_index] ) def UpperCamelCase_ ( self : Union[str, Any] ,lowerCamelCase__ : Dict ): '''simple docstring''' while self.excesses[vertex_index] > 0: for neighbour_index in range(self.verticies_count ): # if it's neighbour and current vertex is higher if ( self.graph[vertex_index][neighbour_index] - self.preflow[vertex_index][neighbour_index] > 0 and self.heights[vertex_index] > self.heights[neighbour_index] ): self.push(lowerCamelCase__ ,lowerCamelCase__ ) self.relabel(lowerCamelCase__ ) def UpperCamelCase_ ( self : Tuple ,lowerCamelCase__ : List[Any] ,lowerCamelCase__ : List[str] ): '''simple docstring''' _UpperCamelCase : Union[str, Any] = min( self.excesses[from_index] ,self.graph[from_index][to_index] - self.preflow[from_index][to_index] ,) self.preflow[from_index][to_index] += preflow_delta self.preflow[to_index][from_index] -= preflow_delta self.excesses[from_index] -= preflow_delta self.excesses[to_index] += preflow_delta def UpperCamelCase_ ( self : List[str] ,lowerCamelCase__ : Optional[int] ): '''simple docstring''' _UpperCamelCase : Tuple = None for to_index in range(self.verticies_count ): if ( self.graph[vertex_index][to_index] - self.preflow[vertex_index][to_index] > 0 ) and (min_height is None or self.heights[to_index] < min_height): _UpperCamelCase : List[Any] = self.heights[to_index] if min_height is not None: _UpperCamelCase : Any = min_height + 1 if __name__ == "__main__": snake_case_ : List[str] = [0] snake_case_ : int = [3] # graph = [ # [0, 0, 4, 6, 0, 0], # [0, 0, 5, 2, 0, 0], # [0, 0, 0, 0, 4, 4], # [0, 0, 0, 0, 6, 6], # [0, 0, 0, 0, 0, 0], # [0, 0, 0, 0, 0, 0], # ] snake_case_ : int = [[0, 7, 0, 0], [0, 0, 6, 0], [0, 0, 0, 8], [9, 0, 0, 0]] # prepare our network snake_case_ : List[Any] = FlowNetwork(graph, entrances, exits) # set algorithm flow_network.set_maximum_flow_algorithm(PushRelabelExecutor) # and calculate snake_case_ : Tuple = flow_network.find_maximum_flow() print(F"""maximum flow is {maximum_flow}""")
236
0
import flax.linen as nn import jax import jax.numpy as jnp class __lowerCAmelCase ( nn.Module ): _a = 42 _a = jnp.floataa def A__ ( self ) -> Any: '''simple docstring''' _lowercase =nn.Conv( self.out_channels , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) def __call__( self , lowerCAmelCase ) -> Any: '''simple docstring''' _lowercase , _lowercase , _lowercase , _lowercase =hidden_states.shape _lowercase =jax.image.resize( lowerCAmelCase , shape=(batch, height * 2, width * 2, channels) , method='nearest' , ) _lowercase =self.conv(lowerCAmelCase ) return hidden_states class __lowerCAmelCase ( nn.Module ): _a = 42 _a = jnp.floataa def A__ ( self ) -> Optional[int]: '''simple docstring''' _lowercase =nn.Conv( self.out_channels , kernel_size=(3, 3) , strides=(2, 2) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) def __call__( self , lowerCAmelCase ) -> List[str]: '''simple docstring''' _lowercase =self.conv(lowerCAmelCase ) return hidden_states class __lowerCAmelCase ( nn.Module ): _a = 42 _a = None _a = 0.0 _a = None _a = jnp.floataa def A__ ( self ) -> Union[str, Any]: '''simple docstring''' _lowercase =self.in_channels if self.out_channels is None else self.out_channels _lowercase =nn.GroupNorm(num_groups=32 , epsilon=1e-5 ) _lowercase =nn.Conv( lowerCAmelCase , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) _lowercase =nn.Dense(lowerCAmelCase , dtype=self.dtype ) _lowercase =nn.GroupNorm(num_groups=32 , epsilon=1e-5 ) _lowercase =nn.Dropout(self.dropout_prob ) _lowercase =nn.Conv( lowerCAmelCase , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) _lowercase =self.in_channels != out_channels if self.use_nin_shortcut is None else self.use_nin_shortcut _lowercase =None if use_nin_shortcut: _lowercase =nn.Conv( lowerCAmelCase , kernel_size=(1, 1) , strides=(1, 1) , padding='VALID' , dtype=self.dtype , ) def __call__( self , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase=True ) -> Optional[Any]: '''simple docstring''' _lowercase =hidden_states _lowercase =self.norma(lowerCAmelCase ) _lowercase =nn.swish(lowerCAmelCase ) _lowercase =self.conva(lowerCAmelCase ) _lowercase =self.time_emb_proj(nn.swish(lowerCAmelCase ) ) _lowercase =jnp.expand_dims(jnp.expand_dims(lowerCAmelCase , 1 ) , 1 ) _lowercase =hidden_states + temb _lowercase =self.norma(lowerCAmelCase ) _lowercase =nn.swish(lowerCAmelCase ) _lowercase =self.dropout(lowerCAmelCase , lowerCAmelCase ) _lowercase =self.conva(lowerCAmelCase ) if self.conv_shortcut is not None: _lowercase =self.conv_shortcut(lowerCAmelCase ) return hidden_states + residual
205
import io import json import unittest from parameterized import parameterized from transformers import FSMTForConditionalGeneration, FSMTTokenizer from transformers.testing_utils import get_tests_dir, require_torch, slow, torch_device from utils import calculate_bleu lowerCAmelCase__ = get_tests_dir() + """/test_data/fsmt/fsmt_val_data.json""" with io.open(filename, """r""", encoding="""utf-8""") as f: lowerCAmelCase__ = json.load(f) @require_torch class a__ ( unittest.TestCase ): """simple docstring""" def UpperCamelCase ( self , lowercase ) -> int: '''simple docstring''' return FSMTTokenizer.from_pretrained(lowercase ) def UpperCamelCase ( self , lowercase ) -> Optional[int]: '''simple docstring''' A__ = FSMTForConditionalGeneration.from_pretrained(lowercase ).to(lowercase ) if torch_device == "cuda": model.half() return model @parameterized.expand( [ ["en-ru", 26.0], ["ru-en", 22.0], ["en-de", 22.0], ["de-en", 29.0], ] ) @slow def UpperCamelCase ( self , lowercase , lowercase ) -> List[Any]: '''simple docstring''' A__ = F'facebook/wmt19-{pair}' A__ = self.get_tokenizer(lowercase ) A__ = self.get_model(lowercase ) A__ = bleu_data[pair]["src"] A__ = bleu_data[pair]["tgt"] A__ = tokenizer(lowercase , return_tensors="pt" , truncation=lowercase , padding="longest" ).to(lowercase ) A__ = model.generate( input_ids=batch.input_ids , num_beams=8 , ) A__ = tokenizer.batch_decode( lowercase , skip_special_tokens=lowercase , clean_up_tokenization_spaces=lowercase ) A__ = calculate_bleu(lowercase , lowercase ) print(lowercase ) self.assertGreaterEqual(scores["bleu"] , lowercase )
68
0
"""simple docstring""" import importlib import os from dataclasses import dataclass from enum import Enum from typing import Any, Dict, Optional, Union import torch from ..utils import BaseOutput a : Any = """scheduler_config.json""" class __UpperCAmelCase( SCREAMING_SNAKE_CASE__ ): """simple docstring""" __lowerCamelCase = 1 __lowerCamelCase = 2 __lowerCamelCase = 3 __lowerCamelCase = 4 __lowerCamelCase = 5 __lowerCamelCase = 6 __lowerCamelCase = 7 __lowerCamelCase = 8 __lowerCamelCase = 9 __lowerCamelCase = 10 __lowerCamelCase = 11 __lowerCamelCase = 12 __lowerCamelCase = 13 __lowerCamelCase = 14 @dataclass class __UpperCAmelCase( SCREAMING_SNAKE_CASE__ ): """simple docstring""" __lowerCamelCase = 42 class __UpperCAmelCase: """simple docstring""" __lowerCamelCase = SCHEDULER_CONFIG_NAME __lowerCamelCase = [] __lowerCamelCase = True @classmethod def UpperCAmelCase_ ( cls , snake_case__ = None , snake_case__ = None , snake_case__=False , **snake_case__ , ): '''simple docstring''' lowercase__ : List[Any]= cls.load_config( pretrained_model_name_or_path=snake_case__ , subfolder=snake_case__ , return_unused_kwargs=snake_case__ , return_commit_hash=snake_case__ , **snake_case__ , ) return cls.from_config(snake_case__ , return_unused_kwargs=snake_case__ , **snake_case__ ) def UpperCAmelCase_ ( self , snake_case__ , snake_case__ = False , **snake_case__ ): '''simple docstring''' self.save_config(save_directory=snake_case__ , push_to_hub=snake_case__ , **snake_case__ ) @property def UpperCAmelCase_ ( self ): '''simple docstring''' return self._get_compatibles() @classmethod def UpperCAmelCase_ ( cls ): '''simple docstring''' lowercase__ : Union[str, Any]= list(set([cls.__name__] + cls._compatibles ) ) lowercase__ : Optional[Any]= importlib.import_module(__name__.split("." )[0] ) lowercase__ : List[Any]= [ getattr(snake_case__ , snake_case__ ) for c in compatible_classes_str if hasattr(snake_case__ , snake_case__ ) ] return compatible_classes
354
"""simple docstring""" import os from pathlib import Path def lowercase__() ->List[Any]: """simple docstring""" from torch.utils.cpp_extension import load lowercase__ : Any= Path(A ).resolve().parent.parent.parent / "kernels" / "deformable_detr" lowercase__ : Any= [ root / filename for filename in [ "vision.cpp", os.path.join("cpu" , "ms_deform_attn_cpu.cpp" ), os.path.join("cuda" , "ms_deform_attn_cuda.cu" ), ] ] load( "MultiScaleDeformableAttention" , A , with_cuda=A , extra_include_paths=[str(A )] , extra_cflags=["-DWITH_CUDA=1"] , extra_cuda_cflags=[ "-DCUDA_HAS_FP16=1", "-D__CUDA_NO_HALF_OPERATORS__", "-D__CUDA_NO_HALF_CONVERSIONS__", "-D__CUDA_NO_HALF2_OPERATORS__", ] , ) import MultiScaleDeformableAttention as MSDA return MSDA
150
0
_UpperCamelCase = "\n# Installazione di Transformers\n! pip install transformers datasets\n# Per installare dalla fonte invece dell'ultima versione rilasciata, commenta il comando sopra e\n# rimuovi la modalità commento al comando seguente.\n# ! pip install git+https://github.com/huggingface/transformers.git\n" _UpperCamelCase = [{"type": "code", "content": INSTALL_CONTENT}] _UpperCamelCase = { "{processor_class}": "FakeProcessorClass", "{model_class}": "FakeModelClass", "{object_class}": "FakeObjectClass", }
275
A__ = [0, 2, 4, 6, 8] A__ = [1, 3, 5, 7, 9] def _UpperCAmelCase ( snake_case , snake_case , snake_case , snake_case ): """simple docstring""" if remaining_length == 0: if digits[0] == 0 or digits[-1] == 0: return 0 for i in range(length // 2 - 1 , -1 , -1 ): remainder += digits[i] + digits[length - i - 1] if remainder % 2 == 0: return 0 remainder //= 10 return 1 if remaining_length == 1: if remainder % 2 == 0: return 0 _lowerCAmelCase = 0 for digit in range(10 ): _lowerCAmelCase = digit result += reversible_numbers( 0 , (remainder + 2 * digit) // 10 , snake_case , snake_case ) return result _lowerCAmelCase = 0 for digita in range(10 ): _lowerCAmelCase = digita if (remainder + digita) % 2 == 0: _lowerCAmelCase = ODD_DIGITS else: _lowerCAmelCase = EVEN_DIGITS for digita in other_parity_digits: _lowerCAmelCase = digita result += reversible_numbers( remaining_length - 2 , (remainder + digita + digita) // 10 , snake_case , snake_case , ) return result def _UpperCAmelCase ( snake_case = 9 ): """simple docstring""" _lowerCAmelCase = 0 for length in range(1 , max_power + 1 ): result += reversible_numbers(snake_case , 0 , [0] * length , snake_case ) return result if __name__ == "__main__": print(f"{solution() = }")
82
0
import argparse import importlib from pathlib import Path # Test all the extensions added in the setup SCREAMING_SNAKE_CASE :Union[str, Any] = [ 'kernels/rwkv/wkv_cuda.cu', 'kernels/rwkv/wkv_op.cpp', 'kernels/deformable_detr/ms_deform_attn.h', 'kernels/deformable_detr/cuda/ms_deform_im2col_cuda.cuh', 'models/graphormer/algos_graphormer.pyx', ] def UpperCAmelCase ( a_ ) -> Dict: """simple docstring""" for file in FILES_TO_FIND: if not (transformers_path / file).exists(): return False return True if __name__ == "__main__": SCREAMING_SNAKE_CASE :int = argparse.ArgumentParser() parser.add_argument('--check_lib', action='store_true', help='Whether to check the build or the actual package.') SCREAMING_SNAKE_CASE :str = parser.parse_args() if args.check_lib: SCREAMING_SNAKE_CASE :Tuple = importlib.import_module('transformers') SCREAMING_SNAKE_CASE :Union[str, Any] = Path(transformers_module.__file__).parent else: SCREAMING_SNAKE_CASE :List[str] = Path.cwd() / 'build/lib/transformers' if not test_custom_files_are_present(transformers_path): raise ValueError('The built release does not contain the custom files. Fix this before going further!')
124
import copy import re class UpperCAmelCase : '''simple docstring''' snake_case_ = "hp" snake_case_ = {} snake_case_ = None @classmethod def UpperCamelCase_ ( cls : Dict ,A : Dict ,A : Any ): __A = prefix __A = defaults cls.build_naming_info() @staticmethod def UpperCamelCase_ ( A : Dict ,A : int ): if len(A ) == 0: return "" __A = None if any(char.isdigit() for char in word ): raise Exception(f'''Parameters should not contain numbers: \'{word}\' contains a number''' ) if word in info["short_word"]: return info["short_word"][word] for prefix_len in range(1 ,len(A ) + 1 ): __A = word[:prefix_len] if prefix in info["reverse_short_word"]: continue else: __A = prefix break if short_word is None: # Paranoid fallback def int_to_alphabetic(A : str ): __A = "" while integer != 0: __A = chr(ord("A" ) + integer % 10 ) + s integer //= 10 return s __A = 0 while True: __A = word + "#" + int_to_alphabetic(A ) if sword in info["reverse_short_word"]: continue else: __A = sword break __A = short_word __A = word return short_word @staticmethod def UpperCamelCase_ ( A : int ,A : Tuple ): __A = param_name.split("_" ) __A = [TrialShortNamer.shortname_for_word(A ,A ) for word in words] # We try to create a separatorless short name, but if there is a collision we have to fallback # to a separated short name __A = ["", "_"] for separator in separators: __A = separator.join(A ) if shortname not in info["reverse_short_param"]: __A = shortname __A = param_name return shortname return param_name @staticmethod def UpperCamelCase_ ( A : Optional[Any] ,A : Tuple ): __A = TrialShortNamer.shortname_for_key(A ,A ) __A = short_name __A = param_name @classmethod def UpperCamelCase_ ( cls : Dict ): if cls.NAMING_INFO is not None: return __A = { "short_word": {}, "reverse_short_word": {}, "short_param": {}, "reverse_short_param": {}, } __A = list(cls.DEFAULTS.keys() ) for k in field_keys: cls.add_new_param_name(A ,A ) __A = info @classmethod def UpperCamelCase_ ( cls : Dict ,A : List[str] ): cls.build_naming_info() assert cls.PREFIX is not None __A = [copy.copy(cls.PREFIX )] for k, v in params.items(): if k not in cls.DEFAULTS: raise Exception(f'''You should provide a default value for the param name {k} with value {v}''' ) if v == cls.DEFAULTS[k]: # The default value is not added to the name continue __A = cls.NAMING_INFO["short_param"][k] if isinstance(A ,A ): __A = 1 if v else 0 __A = "" if isinstance(A ,(int, float) ) else "-" __A = f'''{key}{sep}{v}''' name.append(A ) return "_".join(A ) @classmethod def UpperCamelCase_ ( cls : Tuple ,A : Tuple ): __A = repr[len(cls.PREFIX ) + 1 :] if repr == "": __A = [] else: __A = repr.split("_" ) __A = {} for value in values: if "-" in value: __A , __A = value.split("-" ) else: __A = re.sub("[0-9.]" ,"" ,A ) __A = float(re.sub("[^0-9.]" ,"" ,A ) ) __A = cls.NAMING_INFO["reverse_short_param"][p_k] __A = p_v for k in cls.DEFAULTS: if k not in parameters: __A = cls.DEFAULTS[k] return parameters
124
1
"""simple docstring""" import argparse import json from collections import OrderedDict import torch from huggingface_hub import cached_download, hf_hub_url from transformers import AutoImageProcessor, CvtConfig, CvtForImageClassification def _SCREAMING_SNAKE_CASE ( __snake_case : List[Any] ): '''simple docstring''' lowercase = [] embed.append( ( f'cvt.encoder.stages.{idx}.embedding.convolution_embeddings.projection.weight', f'stage{idx}.patch_embed.proj.weight', ) ) embed.append( ( f'cvt.encoder.stages.{idx}.embedding.convolution_embeddings.projection.bias', f'stage{idx}.patch_embed.proj.bias', ) ) embed.append( ( f'cvt.encoder.stages.{idx}.embedding.convolution_embeddings.normalization.weight', f'stage{idx}.patch_embed.norm.weight', ) ) embed.append( ( f'cvt.encoder.stages.{idx}.embedding.convolution_embeddings.normalization.bias', f'stage{idx}.patch_embed.norm.bias', ) ) return embed def _SCREAMING_SNAKE_CASE ( __snake_case : Union[str, Any] , __snake_case : List[str] ): '''simple docstring''' lowercase = [] attention_weights.append( ( f'cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.convolution.weight', f'stage{idx}.blocks.{cnt}.attn.conv_proj_q.conv.weight', ) ) attention_weights.append( ( f'cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.weight', f'stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.weight', ) ) attention_weights.append( ( f'cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.bias', f'stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.bias', ) ) attention_weights.append( ( f'cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.running_mean', f'stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.running_mean', ) ) attention_weights.append( ( f'cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.running_var', f'stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.running_var', ) ) attention_weights.append( ( f'cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.num_batches_tracked', f'stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.num_batches_tracked', ) ) attention_weights.append( ( f'cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.convolution.weight', f'stage{idx}.blocks.{cnt}.attn.conv_proj_k.conv.weight', ) ) attention_weights.append( ( f'cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.weight', f'stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.weight', ) ) attention_weights.append( ( f'cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.bias', f'stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.bias', ) ) attention_weights.append( ( f'cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.running_mean', f'stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.running_mean', ) ) attention_weights.append( ( f'cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.running_var', f'stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.running_var', ) ) attention_weights.append( ( f'cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.num_batches_tracked', f'stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.num_batches_tracked', ) ) attention_weights.append( ( f'cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.convolution.weight', f'stage{idx}.blocks.{cnt}.attn.conv_proj_v.conv.weight', ) ) attention_weights.append( ( f'cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.weight', f'stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.weight', ) ) attention_weights.append( ( f'cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.bias', f'stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.bias', ) ) attention_weights.append( ( f'cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.running_mean', f'stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.running_mean', ) ) attention_weights.append( ( f'cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.running_var', f'stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.running_var', ) ) attention_weights.append( ( f'cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.num_batches_tracked', f'stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.num_batches_tracked', ) ) attention_weights.append( ( f'cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_query.weight', f'stage{idx}.blocks.{cnt}.attn.proj_q.weight', ) ) attention_weights.append( ( f'cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_query.bias', f'stage{idx}.blocks.{cnt}.attn.proj_q.bias', ) ) attention_weights.append( ( f'cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_key.weight', f'stage{idx}.blocks.{cnt}.attn.proj_k.weight', ) ) attention_weights.append( ( f'cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_key.bias', f'stage{idx}.blocks.{cnt}.attn.proj_k.bias', ) ) attention_weights.append( ( f'cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_value.weight', f'stage{idx}.blocks.{cnt}.attn.proj_v.weight', ) ) attention_weights.append( ( f'cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_value.bias', f'stage{idx}.blocks.{cnt}.attn.proj_v.bias', ) ) attention_weights.append( ( f'cvt.encoder.stages.{idx}.layers.{cnt}.attention.output.dense.weight', f'stage{idx}.blocks.{cnt}.attn.proj.weight', ) ) attention_weights.append( ( f'cvt.encoder.stages.{idx}.layers.{cnt}.attention.output.dense.bias', f'stage{idx}.blocks.{cnt}.attn.proj.bias', ) ) attention_weights.append( (f'cvt.encoder.stages.{idx}.layers.{cnt}.intermediate.dense.weight', f'stage{idx}.blocks.{cnt}.mlp.fc1.weight') ) attention_weights.append( (f'cvt.encoder.stages.{idx}.layers.{cnt}.intermediate.dense.bias', f'stage{idx}.blocks.{cnt}.mlp.fc1.bias') ) attention_weights.append( (f'cvt.encoder.stages.{idx}.layers.{cnt}.output.dense.weight', f'stage{idx}.blocks.{cnt}.mlp.fc2.weight') ) attention_weights.append( (f'cvt.encoder.stages.{idx}.layers.{cnt}.output.dense.bias', f'stage{idx}.blocks.{cnt}.mlp.fc2.bias') ) attention_weights.append( (f'cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_before.weight', f'stage{idx}.blocks.{cnt}.norm1.weight') ) attention_weights.append( (f'cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_before.bias', f'stage{idx}.blocks.{cnt}.norm1.bias') ) attention_weights.append( (f'cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_after.weight', f'stage{idx}.blocks.{cnt}.norm2.weight') ) attention_weights.append( (f'cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_after.bias', f'stage{idx}.blocks.{cnt}.norm2.bias') ) return attention_weights def _SCREAMING_SNAKE_CASE ( __snake_case : List[str] ): '''simple docstring''' lowercase = [] token.append((f'cvt.encoder.stages.{idx}.cls_token', 'stage2.cls_token') ) return token def _SCREAMING_SNAKE_CASE ( ): '''simple docstring''' lowercase = [] head.append(('layernorm.weight', 'norm.weight') ) head.append(('layernorm.bias', 'norm.bias') ) head.append(('classifier.weight', 'head.weight') ) head.append(('classifier.bias', 'head.bias') ) return head def _SCREAMING_SNAKE_CASE ( __snake_case : List[Any] , __snake_case : Dict , __snake_case : List[str] , __snake_case : Union[str, Any] ): '''simple docstring''' lowercase = 'imagenet-1k-id2label.json' lowercase = 10_00 lowercase = 'huggingface/label-files' lowercase = num_labels lowercase = json.load(open(cached_download(hf_hub_url(__snake_case , __snake_case , repo_type='dataset' ) ) , 'r' ) ) lowercase = {int(__snake_case ): v for k, v in idalabel.items()} lowercase = idalabel lowercase = {v: k for k, v in idalabel.items()} lowercase = lowercase = CvtConfig(num_labels=__snake_case , idalabel=__snake_case , labelaid=__snake_case ) # For depth size 13 (13 = 1+2+10) if cvt_model.rsplit('/' , 1 )[-1][4:6] == "13": lowercase = [1, 2, 10] # For depth size 21 (21 = 1+4+16) elif cvt_model.rsplit('/' , 1 )[-1][4:6] == "21": lowercase = [1, 4, 16] # For wide cvt (similar to wide-resnet) depth size 24 (w24 = 2 + 2 20) else: lowercase = [2, 2, 20] lowercase = [3, 12, 16] lowercase = [1_92, 7_68, 10_24] lowercase = CvtForImageClassification(__snake_case ) lowercase = AutoImageProcessor.from_pretrained('facebook/convnext-base-224-22k-1k' ) lowercase = image_size lowercase = torch.load(__snake_case , map_location=torch.device('cpu' ) ) lowercase = OrderedDict() lowercase = [] for idx in range(len(config.depth ) ): if config.cls_token[idx]: lowercase = list_of_state_dict + cls_token(__snake_case ) lowercase = list_of_state_dict + embeddings(__snake_case ) for cnt in range(config.depth[idx] ): lowercase = list_of_state_dict + attention(__snake_case , __snake_case ) lowercase = list_of_state_dict + final() for gg in list_of_state_dict: print(__snake_case ) for i in range(len(__snake_case ) ): lowercase = original_weights[list_of_state_dict[i][1]] model.load_state_dict(__snake_case ) model.save_pretrained(__snake_case ) image_processor.save_pretrained(__snake_case ) # Download the weights from zoo: https://1drv.ms/u/s!AhIXJn_J-blW9RzF3rMW7SsLHa8h?e=blQ0Al if __name__ == "__main__": _UpperCamelCase : Optional[Any] = argparse.ArgumentParser() parser.add_argument( '--cvt_model', default='cvt-w24', type=str, help='Name of the cvt model you\'d like to convert.', ) parser.add_argument( '--image_size', default=3_8_4, type=int, help='Input Image Size', ) parser.add_argument( '--cvt_file_name', default=R'cvtmodels\CvT-w24-384x384-IN-22k.pth', type=str, help='Input Image Size', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model directory.' ) _UpperCamelCase : Tuple = parser.parse_args() convert_cvt_checkpoint(args.cvt_model, args.image_size, args.cvt_file_name, args.pytorch_dump_folder_path)
220
"""simple docstring""" from __future__ import annotations from collections.abc import Iterator from typing import Generic, TypeVar _UpperCamelCase : Any = TypeVar('T') class a ( Generic[T] ): def __init__( self , _lowerCamelCase ): lowercase = data lowercase = None def __str__( self ): return F'{self.data}' class a ( Generic[T] ): def __init__( self ): lowercase = None def __iter__( self ): lowercase = self.top while node: yield node.data lowercase = node.next def __str__( self ): return "->".join([str(_lowerCamelCase ) for item in self] ) def __len__( self ): return len(tuple(iter(self ) ) ) def UpperCamelCase_ ( self ): return self.top is None def UpperCamelCase_ ( self , _lowerCamelCase ): lowercase = Node(_lowerCamelCase ) if not self.is_empty(): lowercase = self.top lowercase = node def UpperCamelCase_ ( self ): if self.is_empty(): raise IndexError('pop from empty stack' ) assert isinstance(self.top , _lowerCamelCase ) lowercase = self.top lowercase = self.top.next return pop_node.data def UpperCamelCase_ ( self ): if self.is_empty(): raise IndexError('peek from empty stack' ) assert self.top is not None return self.top.data def UpperCamelCase_ ( self ): lowercase = None if __name__ == "__main__": from doctest import testmod testmod()
220
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 from ..auto import CONFIG_MAPPING __lowerCamelCase = logging.get_logger(__name__) __lowerCamelCase = { '''microsoft/table-transformer-detection''': ( '''https://huggingface.co/microsoft/table-transformer-detection/resolve/main/config.json''' ), } class A__ ( _snake_case ): lowercase = "table-transformer" lowercase = ["past_key_values"] lowercase = { "hidden_size": "d_model", "num_attention_heads": "encoder_attention_heads", } def __init__( self , UpperCamelCase__=True , UpperCamelCase__=None , UpperCamelCase__=3 , UpperCamelCase__=100 , UpperCamelCase__=6 , UpperCamelCase__=2048 , UpperCamelCase__=8 , UpperCamelCase__=6 , UpperCamelCase__=2048 , UpperCamelCase__=8 , UpperCamelCase__=0.0 , UpperCamelCase__=0.0 , UpperCamelCase__=True , UpperCamelCase__="relu" , UpperCamelCase__=256 , UpperCamelCase__=0.1 , UpperCamelCase__=0.0 , UpperCamelCase__=0.0 , UpperCamelCase__=0.02 , UpperCamelCase__=1.0 , UpperCamelCase__=False , UpperCamelCase__="sine" , UpperCamelCase__="resnet50" , UpperCamelCase__=True , UpperCamelCase__=False , UpperCamelCase__=1 , UpperCamelCase__=5 , UpperCamelCase__=2 , UpperCamelCase__=1 , UpperCamelCase__=1 , UpperCamelCase__=5 , UpperCamelCase__=2 , UpperCamelCase__=0.1 , **UpperCamelCase__ , ) -> str: '''simple docstring''' 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(UpperCamelCase__ , UpperCamelCase__ ): A_ = backbone_config.get("""model_type""" ) A_ = CONFIG_MAPPING[backbone_model_type] A_ = config_class.from_dict(UpperCamelCase__ ) # set timm attributes to None A_ , A_ , A_ = None, None, None 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_ = bbox_loss_coefficient A_ = giou_loss_coefficient A_ = eos_coefficient super().__init__(is_encoder_decoder=UpperCamelCase__ , **UpperCamelCase__ ) @property def snake_case_ ( self ) -> int: '''simple docstring''' return self.encoder_attention_heads @property def snake_case_ ( self ) -> int: '''simple docstring''' return self.d_model class A__ ( _snake_case ): lowercase = version.parse("1.11" ) @property def snake_case_ ( self ) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' return OrderedDict( [ ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}), ("""pixel_mask""", {0: """batch"""}), ] ) @property def snake_case_ ( self ) -> float: '''simple docstring''' return 1e-5 @property def snake_case_ ( self ) -> int: '''simple docstring''' return 12
101
'''simple docstring''' def UpperCAmelCase__ ( UpperCAmelCase__ = 10_00 ) -> int: return sum(2 * a * ((a - 1) // 2) for a in range(3, n + 1 ) ) if __name__ == "__main__": print(solution())
101
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 A ( snake_case__ , snake_case__=0.9_99 , snake_case__="cosine" , ): '''simple docstring''' if alpha_transform_type == "cosine": def alpha_bar_fn(snake_case__ ): return math.cos((t + 0.0_08) / 1.0_08 * math.pi / 2 ) ** 2 elif alpha_transform_type == "exp": def alpha_bar_fn(snake_case__ ): return math.exp(t * -12.0 ) else: raise ValueError(f"""Unsupported alpha_tranform_type: {alpha_transform_type}""" ) SCREAMING_SNAKE_CASE__ = [] for i in range(snake_case__ ): SCREAMING_SNAKE_CASE__ = i / num_diffusion_timesteps SCREAMING_SNAKE_CASE__ = (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 (A__ ,A__ ): lowerCamelCase__ : int = [e.name for e in KarrasDiffusionSchedulers] lowerCamelCase__ : List[str] = 2 @register_to_config def __init__( self : int , __UpperCAmelCase : int = 1_0_0_0 , __UpperCAmelCase : float = 0.00_085 , __UpperCAmelCase : float = 0.012 , __UpperCAmelCase : str = "linear" , __UpperCAmelCase : Optional[Union[np.ndarray, List[float]]] = None , __UpperCAmelCase : str = "epsilon" , __UpperCAmelCase : str = "linspace" , __UpperCAmelCase : int = 0 , ) -> int: if trained_betas is not None: SCREAMING_SNAKE_CASE__ = torch.tensor(__UpperCAmelCase , dtype=torch.floataa ) elif beta_schedule == "linear": SCREAMING_SNAKE_CASE__ = torch.linspace(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , dtype=torch.floataa ) elif beta_schedule == "scaled_linear": # this schedule is very specific to the latent diffusion model. SCREAMING_SNAKE_CASE__ = ( torch.linspace(beta_start**0.5 , beta_end**0.5 , __UpperCAmelCase , dtype=torch.floataa ) ** 2 ) elif beta_schedule == "squaredcos_cap_v2": # Glide cosine schedule SCREAMING_SNAKE_CASE__ = betas_for_alpha_bar(__UpperCAmelCase ) else: raise NotImplementedError(F"""{beta_schedule} does is not implemented for {self.__class__}""" ) SCREAMING_SNAKE_CASE__ = 1.0 - self.betas SCREAMING_SNAKE_CASE__ = torch.cumprod(self.alphas , dim=0 ) # set all values self.set_timesteps(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) def SCREAMING_SNAKE_CASE ( self : List[str] , __UpperCAmelCase : List[Any] , __UpperCAmelCase : Optional[int]=None ) -> Optional[Any]: if schedule_timesteps is None: SCREAMING_SNAKE_CASE__ = self.timesteps SCREAMING_SNAKE_CASE__ = (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: SCREAMING_SNAKE_CASE__ = 1 if len(__UpperCAmelCase ) > 1 else 0 else: SCREAMING_SNAKE_CASE__ = timestep.cpu().item() if torch.is_tensor(__UpperCAmelCase ) else timestep SCREAMING_SNAKE_CASE__ = self._index_counter[timestep_int] return indices[pos].item() @property def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> str: # 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 : Optional[Any] , __UpperCAmelCase : torch.FloatTensor , __UpperCAmelCase : Union[float, torch.FloatTensor] , ) -> torch.FloatTensor: SCREAMING_SNAKE_CASE__ = self.index_for_timestep(__UpperCAmelCase ) if self.state_in_first_order: SCREAMING_SNAKE_CASE__ = self.sigmas[step_index] else: SCREAMING_SNAKE_CASE__ = self.sigmas_interpol[step_index] SCREAMING_SNAKE_CASE__ = sample / ((sigma**2 + 1) ** 0.5) return sample def SCREAMING_SNAKE_CASE ( self : Optional[int] , __UpperCAmelCase : int , __UpperCAmelCase : Union[str, torch.device] = None , __UpperCAmelCase : Optional[int] = None , ) -> str: SCREAMING_SNAKE_CASE__ = num_inference_steps SCREAMING_SNAKE_CASE__ = 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": SCREAMING_SNAKE_CASE__ = np.linspace(0 , num_train_timesteps - 1 , __UpperCAmelCase , dtype=__UpperCAmelCase )[::-1].copy() elif self.config.timestep_spacing == "leading": SCREAMING_SNAKE_CASE__ = 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 SCREAMING_SNAKE_CASE__ = (np.arange(0 , __UpperCAmelCase ) * step_ratio).round()[::-1].copy().astype(__UpperCAmelCase ) timesteps += self.config.steps_offset elif self.config.timestep_spacing == "trailing": SCREAMING_SNAKE_CASE__ = 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 SCREAMING_SNAKE_CASE__ = (np.arange(__UpperCAmelCase , 0 , -step_ratio )).round().copy().astype(__UpperCAmelCase ) timesteps -= 1 else: raise ValueError( F"""{self.config.timestep_spacing} is not supported. Please make sure to choose one of 'linspace', 'leading' or 'trailing'.""" ) SCREAMING_SNAKE_CASE__ = np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5 ) SCREAMING_SNAKE_CASE__ = torch.from_numpy(np.log(__UpperCAmelCase ) ).to(__UpperCAmelCase ) SCREAMING_SNAKE_CASE__ = np.interp(__UpperCAmelCase , np.arange(0 , len(__UpperCAmelCase ) ) , __UpperCAmelCase ) SCREAMING_SNAKE_CASE__ = np.concatenate([sigmas, [0.0]] ).astype(np.floataa ) SCREAMING_SNAKE_CASE__ = torch.from_numpy(__UpperCAmelCase ).to(device=__UpperCAmelCase ) # interpolate sigmas SCREAMING_SNAKE_CASE__ = sigmas.log().lerp(sigmas.roll(1 ).log() , 0.5 ).exp() SCREAMING_SNAKE_CASE__ = torch.cat([sigmas[:1], sigmas[1:].repeat_interleave(2 ), sigmas[-1:]] ) SCREAMING_SNAKE_CASE__ = torch.cat( [sigmas_interpol[:1], sigmas_interpol[1:].repeat_interleave(2 ), sigmas_interpol[-1:]] ) if str(__UpperCAmelCase ).startswith("""mps""" ): # mps does not support float64 SCREAMING_SNAKE_CASE__ = torch.from_numpy(__UpperCAmelCase ).to(__UpperCAmelCase , dtype=torch.floataa ) else: SCREAMING_SNAKE_CASE__ = torch.from_numpy(__UpperCAmelCase ).to(__UpperCAmelCase ) # interpolate timesteps SCREAMING_SNAKE_CASE__ = self.sigma_to_t(__UpperCAmelCase ).to(__UpperCAmelCase , dtype=timesteps.dtype ) SCREAMING_SNAKE_CASE__ = torch.stack((timesteps_interpol[1:-1, None], timesteps[1:, None]) , dim=-1 ).flatten() SCREAMING_SNAKE_CASE__ = torch.cat([timesteps[:1], interleaved_timesteps] ) SCREAMING_SNAKE_CASE__ = None # for exp beta schedules, such as the one for `pipeline_shap_e.py` # we need an index counter SCREAMING_SNAKE_CASE__ = defaultdict(__UpperCAmelCase ) def SCREAMING_SNAKE_CASE ( self : Union[str, Any] , __UpperCAmelCase : Tuple ) -> Dict: # get log sigma SCREAMING_SNAKE_CASE__ = sigma.log() # get distribution SCREAMING_SNAKE_CASE__ = log_sigma - self.log_sigmas[:, None] # get sigmas range SCREAMING_SNAKE_CASE__ = dists.ge(0 ).cumsum(dim=0 ).argmax(dim=0 ).clamp(max=self.log_sigmas.shape[0] - 2 ) SCREAMING_SNAKE_CASE__ = low_idx + 1 SCREAMING_SNAKE_CASE__ = self.log_sigmas[low_idx] SCREAMING_SNAKE_CASE__ = self.log_sigmas[high_idx] # interpolate sigmas SCREAMING_SNAKE_CASE__ = (low - log_sigma) / (low - high) SCREAMING_SNAKE_CASE__ = w.clamp(0 , 1 ) # transform interpolation to time range SCREAMING_SNAKE_CASE__ = (1 - w) * low_idx + w * high_idx SCREAMING_SNAKE_CASE__ = t.view(sigma.shape ) return t @property def SCREAMING_SNAKE_CASE ( self : str ) -> str: return self.sample is None def SCREAMING_SNAKE_CASE ( self : Optional[int] , __UpperCAmelCase : Union[torch.FloatTensor, np.ndarray] , __UpperCAmelCase : Union[float, torch.FloatTensor] , __UpperCAmelCase : Union[torch.FloatTensor, np.ndarray] , __UpperCAmelCase : bool = True , ) -> Union[SchedulerOutput, Tuple]: SCREAMING_SNAKE_CASE__ = self.index_for_timestep(__UpperCAmelCase ) # advance index counter by 1 SCREAMING_SNAKE_CASE__ = timestep.cpu().item() if torch.is_tensor(__UpperCAmelCase ) else timestep self._index_counter[timestep_int] += 1 if self.state_in_first_order: SCREAMING_SNAKE_CASE__ = self.sigmas[step_index] SCREAMING_SNAKE_CASE__ = self.sigmas_interpol[step_index + 1] SCREAMING_SNAKE_CASE__ = self.sigmas[step_index + 1] else: # 2nd order / KDPM2's method SCREAMING_SNAKE_CASE__ = self.sigmas[step_index - 1] SCREAMING_SNAKE_CASE__ = self.sigmas_interpol[step_index] SCREAMING_SNAKE_CASE__ = 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 SCREAMING_SNAKE_CASE__ = 0 SCREAMING_SNAKE_CASE__ = 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": SCREAMING_SNAKE_CASE__ = sigma_hat if self.state_in_first_order else sigma_interpol SCREAMING_SNAKE_CASE__ = sample - sigma_input * model_output elif self.config.prediction_type == "v_prediction": SCREAMING_SNAKE_CASE__ = sigma_hat if self.state_in_first_order else sigma_interpol SCREAMING_SNAKE_CASE__ = model_output * (-sigma_input / (sigma_input**2 + 1) ** 0.5) + ( sample / (sigma_input**2 + 1) ) elif self.config.prediction_type == "sample": raise NotImplementedError("""prediction_type not implemented yet: sample""" ) else: raise ValueError( F"""prediction_type given as {self.config.prediction_type} must be one of `epsilon`, or `v_prediction`""" ) if self.state_in_first_order: # 2. Convert to an ODE derivative for 1st order SCREAMING_SNAKE_CASE__ = (sample - pred_original_sample) / sigma_hat # 3. delta timestep SCREAMING_SNAKE_CASE__ = sigma_interpol - sigma_hat # store for 2nd order step SCREAMING_SNAKE_CASE__ = sample else: # DPM-Solver-2 # 2. Convert to an ODE derivative for 2nd order SCREAMING_SNAKE_CASE__ = (sample - pred_original_sample) / sigma_interpol # 3. delta timestep SCREAMING_SNAKE_CASE__ = sigma_next - sigma_hat SCREAMING_SNAKE_CASE__ = self.sample SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = sample + derivative * dt if not return_dict: return (prev_sample,) return SchedulerOutput(prev_sample=__UpperCAmelCase ) def SCREAMING_SNAKE_CASE ( self : str , __UpperCAmelCase : torch.FloatTensor , __UpperCAmelCase : torch.FloatTensor , __UpperCAmelCase : torch.FloatTensor , ) -> torch.FloatTensor: # Make sure sigmas and timesteps have the same device and dtype as original_samples SCREAMING_SNAKE_CASE__ = self.sigmas.to(device=original_samples.device , dtype=original_samples.dtype ) if original_samples.device.type == "mps" and torch.is_floating_point(__UpperCAmelCase ): # mps does not support float64 SCREAMING_SNAKE_CASE__ = self.timesteps.to(original_samples.device , dtype=torch.floataa ) SCREAMING_SNAKE_CASE__ = timesteps.to(original_samples.device , dtype=torch.floataa ) else: SCREAMING_SNAKE_CASE__ = self.timesteps.to(original_samples.device ) SCREAMING_SNAKE_CASE__ = timesteps.to(original_samples.device ) SCREAMING_SNAKE_CASE__ = [self.index_for_timestep(__UpperCAmelCase , __UpperCAmelCase ) for t in timesteps] SCREAMING_SNAKE_CASE__ = sigmas[step_indices].flatten() while len(sigma.shape ) < len(original_samples.shape ): SCREAMING_SNAKE_CASE__ = sigma.unsqueeze(-1 ) SCREAMING_SNAKE_CASE__ = original_samples + noise * sigma return noisy_samples def __len__( self : Union[str, Any] ) -> List[str]: return self.config.num_train_timesteps
165
"""simple docstring""" from collections import defaultdict class lowerCamelCase : def __init__( self : List[str] , __UpperCAmelCase : Dict , __UpperCAmelCase : Any ) -> Any: SCREAMING_SNAKE_CASE__ = total # total no of tasks (N) # DP table will have a dimension of (2^M)*N # initially all values are set to -1 SCREAMING_SNAKE_CASE__ = [ [-1 for i in range(total + 1 )] for j in range(2 ** len(__UpperCAmelCase ) ) ] SCREAMING_SNAKE_CASE__ = defaultdict(__UpperCAmelCase ) # stores the list of persons for each task # final_mask is used to check if all persons are included by setting all bits # to 1 SCREAMING_SNAKE_CASE__ = (1 << len(__UpperCAmelCase )) - 1 def SCREAMING_SNAKE_CASE ( self : str , __UpperCAmelCase : Optional[Any] , __UpperCAmelCase : Optional[int] ) -> Optional[int]: # if mask == self.finalmask all persons are distributed tasks, return 1 if mask == self.final_mask: return 1 # if not everyone gets the task and no more tasks are available, return 0 if task_no > self.total_tasks: return 0 # if case already considered if self.dp[mask][task_no] != -1: return self.dp[mask][task_no] # Number of ways when we don't this task in the arrangement SCREAMING_SNAKE_CASE__ = self.count_ways_until(__UpperCAmelCase , task_no + 1 ) # now assign the tasks one by one to all possible persons and recursively # assign for the remaining tasks. if task_no in self.task: for p in self.task[task_no]: # if p is already given a task if mask & (1 << p): continue # assign this task to p and change the mask value. And recursively # assign tasks with the new mask value. total_ways_util += self.count_ways_until(mask | (1 << p) , task_no + 1 ) # save the value. SCREAMING_SNAKE_CASE__ = total_ways_util return self.dp[mask][task_no] def SCREAMING_SNAKE_CASE ( self : Optional[int] , __UpperCAmelCase : Union[str, Any] ) -> List[str]: # Store the list of persons for each task for i in range(len(__UpperCAmelCase ) ): for j in task_performed[i]: self.task[j].append(__UpperCAmelCase ) # call the function to fill the DP table, final answer is stored in dp[0][1] return self.count_ways_until(0 , 1 ) if __name__ == "__main__": A_ : Any = 5 # total no of tasks (the value of N) # the list of tasks that can be done by M persons. A_ : Any = [[1, 3, 4], [1, 2, 5], [3, 4]] print( AssignmentUsingBitmask(task_performed, total_tasks).count_no_of_ways( task_performed ) )
165
1
import collections import inspect import unittest from transformers import SwinvaConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import SwinvaForImageClassification, SwinvaForMaskedImageModeling, SwinvaModel from transformers.models.swinva.modeling_swinva import SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class UpperCAmelCase : '''simple docstring''' def __init__( self : Dict , lowerCAmelCase_ : str , lowerCAmelCase_ : List[Any]=1_3 , lowerCAmelCase_ : Any=3_2 , lowerCAmelCase_ : List[Any]=2 , lowerCAmelCase_ : Optional[int]=3 , lowerCAmelCase_ : List[Any]=1_6 , lowerCAmelCase_ : Optional[Any]=[1, 2, 1] , lowerCAmelCase_ : List[Any]=[2, 2, 4] , lowerCAmelCase_ : Tuple=2 , lowerCAmelCase_ : Optional[int]=2.0 , lowerCAmelCase_ : Tuple=True , lowerCAmelCase_ : List[str]=0.0 , lowerCAmelCase_ : List[Any]=0.0 , lowerCAmelCase_ : List[Any]=0.1 , lowerCAmelCase_ : Optional[Any]="gelu" , lowerCAmelCase_ : Optional[int]=False , lowerCAmelCase_ : Tuple=True , lowerCAmelCase_ : Dict=0.02 , lowerCAmelCase_ : List[Any]=1e-5 , lowerCAmelCase_ : str=True , lowerCAmelCase_ : Tuple=None , lowerCAmelCase_ : Optional[int]=True , lowerCAmelCase_ : Optional[Any]=1_0 , lowerCAmelCase_ : Tuple=8 , ): """simple docstring""" _A: Tuple = parent _A: Optional[Any] = batch_size _A: Optional[Any] = image_size _A: Union[str, Any] = patch_size _A: Any = num_channels _A: Optional[int] = embed_dim _A: Any = depths _A: List[str] = num_heads _A: int = window_size _A: List[str] = mlp_ratio _A: Union[str, Any] = qkv_bias _A: int = hidden_dropout_prob _A: Any = attention_probs_dropout_prob _A: str = drop_path_rate _A: Union[str, Any] = hidden_act _A: List[str] = use_absolute_embeddings _A: List[Any] = patch_norm _A: Any = layer_norm_eps _A: Tuple = initializer_range _A: str = is_training _A: Dict = scope _A: str = use_labels _A: List[Any] = type_sequence_label_size _A: Optional[Any] = encoder_stride def __magic_name__ ( self : str ): """simple docstring""" _A: List[Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) _A: str = None if self.use_labels: _A: int = ids_tensor([self.batch_size] , self.type_sequence_label_size ) _A: Dict = self.get_config() return config, pixel_values, labels def __magic_name__ ( self : Dict ): """simple docstring""" return SwinvaConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , embed_dim=self.embed_dim , depths=self.depths , num_heads=self.num_heads , window_size=self.window_size , mlp_ratio=self.mlp_ratio , qkv_bias=self.qkv_bias , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , drop_path_rate=self.drop_path_rate , hidden_act=self.hidden_act , use_absolute_embeddings=self.use_absolute_embeddings , path_norm=self.patch_norm , layer_norm_eps=self.layer_norm_eps , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , ) def __magic_name__ ( self : int , lowerCAmelCase_ : Tuple , lowerCAmelCase_ : Union[str, Any] , lowerCAmelCase_ : Tuple ): """simple docstring""" _A: List[Any] = SwinvaModel(config=lowerCAmelCase_ ) model.to(lowerCAmelCase_ ) model.eval() _A: List[str] = model(lowerCAmelCase_ ) _A: Union[str, Any] = ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths ) - 1)) _A: str = int(config.embed_dim * 2 ** (len(config.depths ) - 1) ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, expected_seq_len, expected_dim) ) def __magic_name__ ( self : Union[str, Any] , lowerCAmelCase_ : Tuple , lowerCAmelCase_ : Any , lowerCAmelCase_ : Union[str, Any] ): """simple docstring""" _A: List[Any] = SwinvaForMaskedImageModeling(config=lowerCAmelCase_ ) model.to(lowerCAmelCase_ ) model.eval() _A: Any = model(lowerCAmelCase_ ) self.parent.assertEqual( result.logits.shape , (self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images _A: Dict = 1 _A: Tuple = SwinvaForMaskedImageModeling(lowerCAmelCase_ ) model.to(lowerCAmelCase_ ) model.eval() _A: str = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) _A: Optional[Any] = model(lowerCAmelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, 1, self.image_size, self.image_size) ) def __magic_name__ ( self : Dict , lowerCAmelCase_ : int , lowerCAmelCase_ : Optional[int] , lowerCAmelCase_ : Tuple ): """simple docstring""" _A: List[str] = self.type_sequence_label_size _A: List[str] = SwinvaForImageClassification(lowerCAmelCase_ ) model.to(lowerCAmelCase_ ) model.eval() _A: int = model(lowerCAmelCase_ , labels=lowerCAmelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def __magic_name__ ( self : List[Any] ): """simple docstring""" _A: Any = self.prepare_config_and_inputs() _A , _A , _A: int = config_and_inputs _A: int = {'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , unittest.TestCase ): '''simple docstring''' __UpperCamelCase : List[str] = ( (SwinvaModel, SwinvaForImageClassification, SwinvaForMaskedImageModeling) if is_torch_available() else () ) __UpperCamelCase : Tuple = ( {'''feature-extraction''': SwinvaModel, '''image-classification''': SwinvaForImageClassification} if is_torch_available() else {} ) __UpperCamelCase : List[Any] = False __UpperCamelCase : Tuple = False __UpperCamelCase : int = False __UpperCamelCase : Any = False def __magic_name__ ( self : int ): """simple docstring""" _A: Union[str, Any] = SwinvaModelTester(self ) _A: List[str] = ConfigTester(self , config_class=lowerCAmelCase_ , embed_dim=3_7 ) def __magic_name__ ( self : Optional[Any] ): """simple docstring""" 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 __magic_name__ ( self : str ): """simple docstring""" _A: Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowerCAmelCase_ ) @unittest.skip(reason='''Got `CUDA error: misaligned address` with PyTorch 2.0.0.''' ) def __magic_name__ ( self : str ): """simple docstring""" pass @unittest.skip(reason='''Swinv2 does not use inputs_embeds''' ) def __magic_name__ ( self : Optional[int] ): """simple docstring""" pass def __magic_name__ ( self : List[str] ): """simple docstring""" _A , _A: Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _A: List[str] = model_class(lowerCAmelCase_ ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) _A: List[str] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(lowerCAmelCase_ , nn.Linear ) ) def __magic_name__ ( self : List[Any] ): """simple docstring""" _A , _A: Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _A: Dict = model_class(lowerCAmelCase_ ) _A: Union[str, Any] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic _A: int = [*signature.parameters.keys()] _A: int = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , lowerCAmelCase_ ) def __magic_name__ ( self : Dict ): """simple docstring""" _A , _A: Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() _A: int = True for model_class in self.all_model_classes: _A: Union[str, Any] = True _A: Optional[int] = False _A: List[str] = True _A: str = model_class(lowerCAmelCase_ ) model.to(lowerCAmelCase_ ) model.eval() with torch.no_grad(): _A: Any = model(**self._prepare_for_class(lowerCAmelCase_ , lowerCAmelCase_ ) ) _A: int = outputs.attentions _A: Any = len(self.model_tester.depths ) self.assertEqual(len(lowerCAmelCase_ ) , lowerCAmelCase_ ) # check that output_attentions also work using config del inputs_dict["output_attentions"] _A: List[str] = True _A: Optional[int] = config.window_size**2 _A: Optional[int] = model_class(lowerCAmelCase_ ) model.to(lowerCAmelCase_ ) model.eval() with torch.no_grad(): _A: List[Any] = model(**self._prepare_for_class(lowerCAmelCase_ , lowerCAmelCase_ ) ) _A: Any = outputs.attentions self.assertEqual(len(lowerCAmelCase_ ) , lowerCAmelCase_ ) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_heads[0], window_size_squared, window_size_squared] , ) _A: List[Any] = len(lowerCAmelCase_ ) # Check attention is always last and order is fine _A: Dict = True _A: Dict = True _A: Dict = model_class(lowerCAmelCase_ ) model.to(lowerCAmelCase_ ) model.eval() with torch.no_grad(): _A: Dict = model(**self._prepare_for_class(lowerCAmelCase_ , lowerCAmelCase_ ) ) if hasattr(self.model_tester , '''num_hidden_states_types''' ): _A: Union[str, Any] = self.model_tester.num_hidden_states_types else: # also another +1 for reshaped_hidden_states _A: Dict = 2 self.assertEqual(out_len + added_hidden_states , len(lowerCAmelCase_ ) ) _A: List[str] = outputs.attentions self.assertEqual(len(lowerCAmelCase_ ) , lowerCAmelCase_ ) self.assertListEqual( list(self_attentions[0].shape[-3:] ) , [self.model_tester.num_heads[0], window_size_squared, window_size_squared] , ) def __magic_name__ ( self : Any , lowerCAmelCase_ : Union[str, Any] , lowerCAmelCase_ : Optional[int] , lowerCAmelCase_ : Dict , lowerCAmelCase_ : Tuple ): """simple docstring""" _A: str = model_class(lowerCAmelCase_ ) model.to(lowerCAmelCase_ ) model.eval() with torch.no_grad(): _A: Any = model(**self._prepare_for_class(lowerCAmelCase_ , lowerCAmelCase_ ) ) _A: List[Any] = outputs.hidden_states _A: str = getattr( self.model_tester , '''expected_num_hidden_layers''' , len(self.model_tester.depths ) + 1 ) self.assertEqual(len(lowerCAmelCase_ ) , lowerCAmelCase_ ) # Swinv2 has a different seq_length _A: Any = ( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) _A: Union[str, Any] = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [num_patches, self.model_tester.embed_dim] , ) _A: Dict = outputs.reshaped_hidden_states self.assertEqual(len(lowerCAmelCase_ ) , lowerCAmelCase_ ) _A , _A , _A , _A: Optional[Any] = reshaped_hidden_states[0].shape _A: Optional[int] = ( reshaped_hidden_states[0].view(lowerCAmelCase_ , lowerCAmelCase_ , height * width ).permute(0 , 2 , 1 ) ) self.assertListEqual( list(reshaped_hidden_states.shape[-2:] ) , [num_patches, self.model_tester.embed_dim] , ) def __magic_name__ ( self : List[str] ): """simple docstring""" _A , _A: Any = self.model_tester.prepare_config_and_inputs_for_common() _A: Tuple = ( self.model_tester.image_size if isinstance(self.model_tester.image_size , collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) for model_class in self.all_model_classes: _A: Any = True self.check_hidden_states_output(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] _A: Any = True self.check_hidden_states_output(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) def __magic_name__ ( self : Optional[Any] ): """simple docstring""" _A , _A: Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() _A: Any = 3 _A: str = ( self.model_tester.image_size if isinstance(self.model_tester.image_size , collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) _A: Tuple = ( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) _A: Optional[int] = image_size[0] + patch_size[0] - (image_size[0] % patch_size[0]) _A: Tuple = image_size[1] + patch_size[1] - (image_size[1] % patch_size[1]) for model_class in self.all_model_classes: _A: List[str] = True self.check_hidden_states_output(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , (padded_height, padded_width) ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] _A: str = True self.check_hidden_states_output(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , (padded_height, padded_width) ) def __magic_name__ ( self : Tuple ): """simple docstring""" _A: int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*lowerCAmelCase_ ) def __magic_name__ ( self : Any ): """simple docstring""" _A: Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*lowerCAmelCase_ ) @slow def __magic_name__ ( self : Any ): """simple docstring""" for model_name in SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _A: Optional[Any] = SwinvaModel.from_pretrained(lowerCAmelCase_ ) self.assertIsNotNone(lowerCAmelCase_ ) def __magic_name__ ( self : List[Any] ): """simple docstring""" _A , _A: Dict = self.model_tester.prepare_config_and_inputs_for_common() _A: int = _config_zero_init(lowerCAmelCase_ ) for model_class in self.all_model_classes: _A: Optional[int] = model_class(config=lowerCAmelCase_ ) for name, param in model.named_parameters(): if "embeddings" not in name and "logit_scale" not in name and param.requires_grad: self.assertIn( ((param.data.mean() * 1e9).round() / 1e9).item() , [0.0, 1.0] , msg=F"""Parameter {name} of model {model_class} seems not properly initialized""" , ) @require_vision @require_torch class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' @cached_property def __magic_name__ ( self : Any ): """simple docstring""" return ( AutoImageProcessor.from_pretrained('''microsoft/swinv2-tiny-patch4-window8-256''' ) if is_vision_available() else None ) @slow def __magic_name__ ( self : int ): """simple docstring""" _A: Any = SwinvaForImageClassification.from_pretrained('''microsoft/swinv2-tiny-patch4-window8-256''' ).to( lowerCAmelCase_ ) _A: int = self.default_image_processor _A: Union[str, Any] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) _A: Optional[Any] = image_processor(images=lowerCAmelCase_ , return_tensors='''pt''' ).to(lowerCAmelCase_ ) # forward pass with torch.no_grad(): _A: Dict = model(**lowerCAmelCase_ ) # verify the logits _A: int = torch.Size((1, 1_0_0_0) ) self.assertEqual(outputs.logits.shape , lowerCAmelCase_ ) _A: Union[str, Any] = torch.tensor([-0.3947, -0.4306, 0.0026] ).to(lowerCAmelCase_ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , lowerCAmelCase_ , atol=1e-4 ) )
301
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available UpperCAmelCase__ : Union[str, Any] = { 'configuration_roc_bert': ['ROC_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'RoCBertConfig'], 'tokenization_roc_bert': ['RoCBertTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: pass try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ : Optional[Any] = [ 'ROC_BERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'RoCBertForCausalLM', 'RoCBertForMaskedLM', 'RoCBertForMultipleChoice', 'RoCBertForPreTraining', 'RoCBertForQuestionAnswering', 'RoCBertForSequenceClassification', 'RoCBertForTokenClassification', 'RoCBertLayer', 'RoCBertModel', 'RoCBertPreTrainedModel', 'load_tf_weights_in_roc_bert', ] if TYPE_CHECKING: from .configuration_roc_bert import ROC_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, RoCBertConfig from .tokenization_roc_bert import RoCBertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: raise OptionalDependencyNotAvailable() try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_roc_bert import ( ROC_BERT_PRETRAINED_MODEL_ARCHIVE_LIST, RoCBertForCausalLM, RoCBertForMaskedLM, RoCBertForMultipleChoice, RoCBertForPreTraining, RoCBertForQuestionAnswering, RoCBertForSequenceClassification, RoCBertForTokenClassification, RoCBertLayer, RoCBertModel, RoCBertPreTrainedModel, load_tf_weights_in_roc_bert, ) else: import sys UpperCAmelCase__ : Any = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
301
1
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging snake_case_ : Union[str, Any] = logging.get_logger(__name__) snake_case_ : int = { 'uclanlp/visualbert-vqa': 'https://huggingface.co/uclanlp/visualbert-vqa/resolve/main/config.json', 'uclanlp/visualbert-vqa-pre': 'https://huggingface.co/uclanlp/visualbert-vqa-pre/resolve/main/config.json', 'uclanlp/visualbert-vqa-coco-pre': ( 'https://huggingface.co/uclanlp/visualbert-vqa-coco-pre/resolve/main/config.json' ), 'uclanlp/visualbert-vcr': 'https://huggingface.co/uclanlp/visualbert-vcr/resolve/main/config.json', 'uclanlp/visualbert-vcr-pre': 'https://huggingface.co/uclanlp/visualbert-vcr-pre/resolve/main/config.json', 'uclanlp/visualbert-vcr-coco-pre': ( 'https://huggingface.co/uclanlp/visualbert-vcr-coco-pre/resolve/main/config.json' ), 'uclanlp/visualbert-nlvr2': 'https://huggingface.co/uclanlp/visualbert-nlvr2/resolve/main/config.json', 'uclanlp/visualbert-nlvr2-pre': 'https://huggingface.co/uclanlp/visualbert-nlvr2-pre/resolve/main/config.json', 'uclanlp/visualbert-nlvr2-coco-pre': ( 'https://huggingface.co/uclanlp/visualbert-nlvr2-coco-pre/resolve/main/config.json' ) # See all VisualBERT models at https://huggingface.co/models?filter=visual_bert } class lowercase__ ( lowercase ): lowercase__ = """visual_bert""" def __init__( self : List[Any] ,lowerCamelCase__ : Tuple=30522 ,lowerCamelCase__ : str=768 ,lowerCamelCase__ : List[str]=512 ,lowerCamelCase__ : Any=12 ,lowerCamelCase__ : Any=12 ,lowerCamelCase__ : Dict=3072 ,lowerCamelCase__ : List[str]="gelu" ,lowerCamelCase__ : Optional[int]=0.1 ,lowerCamelCase__ : List[Any]=0.1 ,lowerCamelCase__ : Optional[Any]=512 ,lowerCamelCase__ : Optional[int]=2 ,lowerCamelCase__ : Dict=0.0_2 ,lowerCamelCase__ : Optional[int]=1E-12 ,lowerCamelCase__ : Any=False ,lowerCamelCase__ : int=True ,lowerCamelCase__ : Optional[int]=1 ,lowerCamelCase__ : List[str]=0 ,lowerCamelCase__ : List[str]=2 ,**lowerCamelCase__ : str ,): '''simple docstring''' super().__init__(pad_token_id=lowerCamelCase__ ,bos_token_id=lowerCamelCase__ ,eos_token_id=lowerCamelCase__ ,**lowerCamelCase__ ) _UpperCamelCase : Tuple = vocab_size _UpperCamelCase : str = max_position_embeddings _UpperCamelCase : Dict = hidden_size _UpperCamelCase : Union[str, Any] = visual_embedding_dim _UpperCamelCase : List[Any] = num_hidden_layers _UpperCamelCase : str = num_attention_heads _UpperCamelCase : Any = intermediate_size _UpperCamelCase : Optional[int] = hidden_act _UpperCamelCase : int = hidden_dropout_prob _UpperCamelCase : Any = attention_probs_dropout_prob _UpperCamelCase : Optional[Any] = initializer_range _UpperCamelCase : Tuple = type_vocab_size _UpperCamelCase : Optional[Any] = layer_norm_eps _UpperCamelCase : List[Any] = bypass_transformer _UpperCamelCase : Optional[Any] = special_visual_initialize
83
from ...configuration_utils import PretrainedConfig from ...utils import logging _SCREAMING_SNAKE_CASE = logging.get_logger(__name__) _SCREAMING_SNAKE_CASE = { 'microsoft/biogpt': 'https://huggingface.co/microsoft/biogpt/resolve/main/config.json', # See all BioGPT models at https://huggingface.co/models?filter=biogpt } class a ( __lowerCAmelCase ): """simple docstring""" lowerCamelCase :Any = '''biogpt''' def __init__( self , lowerCAmelCase_=4_23_84 , lowerCAmelCase_=10_24 , lowerCAmelCase_=24 , lowerCAmelCase_=16 , lowerCAmelCase_=40_96 , lowerCAmelCase_="gelu" , lowerCAmelCase_=0.1 , lowerCAmelCase_=0.1 , lowerCAmelCase_=10_24 , lowerCAmelCase_=0.02 , lowerCAmelCase_=1E-12 , lowerCAmelCase_=True , lowerCAmelCase_=True , lowerCAmelCase_=0.0 , lowerCAmelCase_=0.0 , lowerCAmelCase_=1 , lowerCAmelCase_=0 , lowerCAmelCase_=2 , **lowerCAmelCase_ , ) -> Tuple: _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 = hidden_dropout_prob _A = attention_probs_dropout_prob _A = initializer_range _A = layer_norm_eps _A = scale_embedding _A = use_cache _A = layerdrop _A = activation_dropout super().__init__(pad_token_id=lowerCAmelCase_ , bos_token_id=lowerCAmelCase_ , eos_token_id=lowerCAmelCase_ , **lowerCAmelCase_ )
180
0
"""simple docstring""" from ..utils import DummyObject, requires_backends class _lowerCAmelCase ( metaclass=__lowercase ): """simple docstring""" __UpperCAmelCase : Union[str, Any] = ['''transformers''', '''torch''', '''note_seq'''] def __init__( self : Dict, *UpperCAmelCase__ : List[str], **UpperCAmelCase__ : Union[str, Any] ): requires_backends(self, ["transformers", "torch", "note_seq"] ) @classmethod def _lowercase ( cls : Any, *UpperCAmelCase__ : Optional[Any], **UpperCAmelCase__ : Any ): requires_backends(cls, ["transformers", "torch", "note_seq"] ) @classmethod def _lowercase ( cls : Union[str, Any], *UpperCAmelCase__ : Dict, **UpperCAmelCase__ : Optional[int] ): requires_backends(cls, ["transformers", "torch", "note_seq"] )
363
"""simple docstring""" from __future__ import annotations from typing import Any class _lowerCAmelCase : """simple docstring""" def __init__( self : Union[str, Any], UpperCAmelCase__ : int ): __lowercase = num_of_nodes __lowercase = [] __lowercase = {} def _lowercase ( self : Tuple, UpperCAmelCase__ : int, UpperCAmelCase__ : int, UpperCAmelCase__ : int ): self.m_edges.append([u_node, v_node, weight] ) def _lowercase ( self : Dict, UpperCAmelCase__ : int ): if self.m_component[u_node] == u_node: return u_node return self.find_component(self.m_component[u_node] ) def _lowercase ( self : Dict, UpperCAmelCase__ : int ): if self.m_component[u_node] != u_node: for k in self.m_component: __lowercase = self.find_component(UpperCAmelCase__ ) def _lowercase ( self : str, UpperCAmelCase__ : list[int], UpperCAmelCase__ : int, UpperCAmelCase__ : int ): if component_size[u_node] <= component_size[v_node]: __lowercase = v_node component_size[v_node] += component_size[u_node] self.set_component(UpperCAmelCase__ ) elif component_size[u_node] >= component_size[v_node]: __lowercase = self.find_component(UpperCAmelCase__ ) component_size[u_node] += component_size[v_node] self.set_component(UpperCAmelCase__ ) def _lowercase ( self : Tuple ): __lowercase = [] __lowercase = 0 __lowercase = [-1] * self.m_num_of_nodes # A list of components (initialized to all of the nodes) for node in range(self.m_num_of_nodes ): self.m_component.update({node: node} ) component_size.append(1 ) __lowercase = self.m_num_of_nodes while num_of_components > 1: for edge in self.m_edges: __lowercase ,__lowercase ,__lowercase = edge __lowercase = self.m_component[u] __lowercase = self.m_component[v] if u_component != v_component: for component in (u_component, v_component): if ( minimum_weight_edge[component] == -1 or minimum_weight_edge[component][2] > w ): __lowercase = [u, v, w] for edge in minimum_weight_edge: if isinstance(UpperCAmelCase__, UpperCAmelCase__ ): __lowercase ,__lowercase ,__lowercase = edge __lowercase = self.m_component[u] __lowercase = self.m_component[v] if u_component != v_component: mst_weight += w self.union(UpperCAmelCase__, UpperCAmelCase__, UpperCAmelCase__ ) print(F"""Added edge [{u} - {v}]\nAdded weight: {w}\n""" ) num_of_components -= 1 __lowercase = [-1] * self.m_num_of_nodes print(F"""The total weight of the minimal spanning tree is: {mst_weight}""" ) def _A ( ) -> None: '''simple docstring''' if __name__ == "__main__": import doctest doctest.testmod()
144
0
def lowerCamelCase__ ( __lowerCamelCase : Dict , __lowerCamelCase : List[Any] ): __UpperCAmelCase : Any = 0 while b > 0: if b & 1: res += a a += a b >>= 1 return res def lowerCamelCase__ ( __lowerCamelCase : Union[str, Any] , __lowerCamelCase : int , __lowerCamelCase : Optional[int] ): __UpperCAmelCase : Dict = 0 while b > 0: if b & 1: __UpperCAmelCase : Tuple = ((res % c) + (a % c)) % c a += a b >>= 1 return res
114
# 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 from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available a : Union[str, Any] = {"configuration_timm_backbone": ["TimmBackboneConfig"]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a : Tuple = ["TimmBackbone"] if TYPE_CHECKING: from .configuration_timm_backbone import TimmBackboneConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_timm_backbone import TimmBackbone else: import sys a : List[Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
114
1
import argparse import torch from transformers import GPTaConfig, GPTaModel, load_tf_weights_in_gpta from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging logging.set_verbosity_info() def A_ ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ): # Construct model if gpta_config_file == "": SCREAMING_SNAKE_CASE_: Tuple = GPTaConfig() else: SCREAMING_SNAKE_CASE_: List[str] = GPTaConfig.from_json_file(_UpperCAmelCase ) SCREAMING_SNAKE_CASE_: Union[str, Any] = GPTaModel(_UpperCAmelCase ) # Load weights from numpy load_tf_weights_in_gpta(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) # Save pytorch-model SCREAMING_SNAKE_CASE_: Dict = pytorch_dump_folder_path + "/" + WEIGHTS_NAME SCREAMING_SNAKE_CASE_: List[str] = pytorch_dump_folder_path + "/" + CONFIG_NAME print(f"Save PyTorch model to {pytorch_weights_dump_path}" ) torch.save(model.state_dict() , _UpperCAmelCase ) print(f"Save configuration file to {pytorch_config_dump_path}" ) with open(_UpperCAmelCase , "w" , encoding="utf-8" ) as f: f.write(config.to_json_string() ) if __name__ == "__main__": lowerCAmelCase : Union[str, Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( """--gpt2_checkpoint_path""", default=None, type=str, required=True, help="""Path to the TensorFlow checkpoint path.""" ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model.""" ) parser.add_argument( """--gpt2_config_file""", default="""""", type=str, help=( """An optional config json file corresponding to the pre-trained OpenAI model. \n""" """This specifies the model architecture.""" ), ) lowerCAmelCase : Optional[Any] = parser.parse_args() convert_gpta_checkpoint_to_pytorch(args.gpta_checkpoint_path, args.gpta_config_file, args.pytorch_dump_folder_path)
127
import json import pathlib import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import DeformableDetrImageProcessor class __lowercase ( unittest.TestCase ): """simple docstring""" def __init__( self : Any , lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Optional[Any]=7 , lowerCAmelCase__ : Tuple=3 , lowerCAmelCase__ : Optional[int]=30 , lowerCAmelCase__ : Dict=400 , lowerCAmelCase__ : int=True , lowerCAmelCase__ : Dict=None , lowerCAmelCase__ : Union[str, Any]=True , lowerCAmelCase__ : Any=[0.5, 0.5, 0.5] , lowerCAmelCase__ : Optional[Any]=[0.5, 0.5, 0.5] , lowerCAmelCase__ : List[Any]=True , lowerCAmelCase__ : Tuple=1 / 255 , lowerCAmelCase__ : int=True , ): # by setting size["longest_edge"] > max_resolution we're effectively not testing this :p SCREAMING_SNAKE_CASE_: Optional[Any] = size if size is not None else {"shortest_edge": 18, "longest_edge": 1333} SCREAMING_SNAKE_CASE_: str = parent SCREAMING_SNAKE_CASE_: Tuple = batch_size SCREAMING_SNAKE_CASE_: Tuple = num_channels SCREAMING_SNAKE_CASE_: Union[str, Any] = min_resolution SCREAMING_SNAKE_CASE_: Tuple = max_resolution SCREAMING_SNAKE_CASE_: List[Any] = do_resize SCREAMING_SNAKE_CASE_: Optional[int] = size SCREAMING_SNAKE_CASE_: Optional[int] = do_normalize SCREAMING_SNAKE_CASE_: Any = image_mean SCREAMING_SNAKE_CASE_: Dict = image_std SCREAMING_SNAKE_CASE_: Tuple = do_rescale SCREAMING_SNAKE_CASE_: int = rescale_factor SCREAMING_SNAKE_CASE_: int = do_pad def _SCREAMING_SNAKE_CASE ( self : Optional[int]): return { "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_pad": self.do_pad, } def _SCREAMING_SNAKE_CASE ( self : str , lowerCAmelCase__ : Dict , lowerCAmelCase__ : int=False): if not batched: SCREAMING_SNAKE_CASE_: List[str] = image_inputs[0] if isinstance(lowerCAmelCase__ , Image.Image): SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Union[str, Any] = image.size else: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Union[str, Any] = image.shape[1], image.shape[2] if w < h: SCREAMING_SNAKE_CASE_: List[Any] = int(self.size["shortest_edge"] * h / w) SCREAMING_SNAKE_CASE_: Union[str, Any] = self.size["shortest_edge"] elif w > h: SCREAMING_SNAKE_CASE_: Any = self.size["shortest_edge"] SCREAMING_SNAKE_CASE_: Union[str, Any] = int(self.size["shortest_edge"] * w / h) else: SCREAMING_SNAKE_CASE_: int = self.size["shortest_edge"] SCREAMING_SNAKE_CASE_: Dict = self.size["shortest_edge"] else: SCREAMING_SNAKE_CASE_: int = [] for image in image_inputs: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Optional[int] = self.get_expected_values([image]) expected_values.append((expected_height, expected_width)) SCREAMING_SNAKE_CASE_: Tuple = max(lowerCAmelCase__ , key=lambda lowerCAmelCase__: item[0])[0] SCREAMING_SNAKE_CASE_: Optional[Any] = max(lowerCAmelCase__ , key=lambda lowerCAmelCase__: item[1])[1] return expected_height, expected_width @require_torch @require_vision class __lowercase ( UpperCAmelCase_ , unittest.TestCase ): """simple docstring""" _UpperCAmelCase : Any = DeformableDetrImageProcessor if is_vision_available() else None def _SCREAMING_SNAKE_CASE ( self : Optional[int]): SCREAMING_SNAKE_CASE_: int = DeformableDetrImageProcessingTester(self) @property def _SCREAMING_SNAKE_CASE ( self : Optional[int]): return self.image_processor_tester.prepare_image_processor_dict() def _SCREAMING_SNAKE_CASE ( self : List[str]): SCREAMING_SNAKE_CASE_: Dict = self.image_processing_class(**self.image_processor_dict) self.assertTrue(hasattr(lowerCAmelCase__ , "image_mean")) self.assertTrue(hasattr(lowerCAmelCase__ , "image_std")) self.assertTrue(hasattr(lowerCAmelCase__ , "do_normalize")) self.assertTrue(hasattr(lowerCAmelCase__ , "do_resize")) self.assertTrue(hasattr(lowerCAmelCase__ , "do_rescale")) self.assertTrue(hasattr(lowerCAmelCase__ , "do_pad")) self.assertTrue(hasattr(lowerCAmelCase__ , "size")) def _SCREAMING_SNAKE_CASE ( self : Tuple): SCREAMING_SNAKE_CASE_: Dict = self.image_processing_class.from_dict(self.image_processor_dict) self.assertEqual(image_processor.size , {"shortest_edge": 18, "longest_edge": 1333}) self.assertEqual(image_processor.do_pad , lowerCAmelCase__) SCREAMING_SNAKE_CASE_: Dict = self.image_processing_class.from_dict( self.image_processor_dict , size=42 , max_size=84 , pad_and_return_pixel_mask=lowerCAmelCase__) self.assertEqual(image_processor.size , {"shortest_edge": 42, "longest_edge": 84}) self.assertEqual(image_processor.do_pad , lowerCAmelCase__) def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): pass def _SCREAMING_SNAKE_CASE ( self : List[Any]): # Initialize image_processing SCREAMING_SNAKE_CASE_: List[Any] = self.image_processing_class(**self.image_processor_dict) # create random PIL images SCREAMING_SNAKE_CASE_: Optional[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=lowerCAmelCase__) for image in image_inputs: self.assertIsInstance(lowerCAmelCase__ , Image.Image) # Test not batched input SCREAMING_SNAKE_CASE_: Union[str, Any] = image_processing(image_inputs[0] , return_tensors="pt").pixel_values SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: List[str] = self.image_processor_tester.get_expected_values(lowerCAmelCase__) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Optional[Any] = self.image_processor_tester.get_expected_values(lowerCAmelCase__ , batched=lowerCAmelCase__) SCREAMING_SNAKE_CASE_: List[str] = image_processing(lowerCAmelCase__ , return_tensors="pt").pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def _SCREAMING_SNAKE_CASE ( self : str): # Initialize image_processing SCREAMING_SNAKE_CASE_: Optional[Any] = self.image_processing_class(**self.image_processor_dict) # create random numpy tensors SCREAMING_SNAKE_CASE_: List[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=lowerCAmelCase__ , numpify=lowerCAmelCase__) for image in image_inputs: self.assertIsInstance(lowerCAmelCase__ , np.ndarray) # Test not batched input SCREAMING_SNAKE_CASE_: str = image_processing(image_inputs[0] , return_tensors="pt").pixel_values SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: List[str] = self.image_processor_tester.get_expected_values(lowerCAmelCase__) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched SCREAMING_SNAKE_CASE_: Any = image_processing(lowerCAmelCase__ , return_tensors="pt").pixel_values SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: int = self.image_processor_tester.get_expected_values(lowerCAmelCase__ , batched=lowerCAmelCase__) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def _SCREAMING_SNAKE_CASE ( self : List[Any]): # Initialize image_processing SCREAMING_SNAKE_CASE_: List[Any] = self.image_processing_class(**self.image_processor_dict) # create random PyTorch tensors SCREAMING_SNAKE_CASE_: int = prepare_image_inputs(self.image_processor_tester , equal_resolution=lowerCAmelCase__ , torchify=lowerCAmelCase__) for image in image_inputs: self.assertIsInstance(lowerCAmelCase__ , torch.Tensor) # Test not batched input SCREAMING_SNAKE_CASE_: Dict = image_processing(image_inputs[0] , return_tensors="pt").pixel_values SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Any = self.image_processor_tester.get_expected_values(lowerCAmelCase__) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched SCREAMING_SNAKE_CASE_: Optional[Any] = image_processing(lowerCAmelCase__ , return_tensors="pt").pixel_values SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Optional[Any] = self.image_processor_tester.get_expected_values(lowerCAmelCase__ , batched=lowerCAmelCase__) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) @slow def _SCREAMING_SNAKE_CASE ( self : Tuple): # prepare image and target SCREAMING_SNAKE_CASE_: Optional[Any] = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png") with open("./tests/fixtures/tests_samples/COCO/coco_annotations.txt" , "r") as f: SCREAMING_SNAKE_CASE_: str = json.loads(f.read()) SCREAMING_SNAKE_CASE_: Optional[int] = {"image_id": 3_9769, "annotations": target} # encode them SCREAMING_SNAKE_CASE_: str = DeformableDetrImageProcessor() SCREAMING_SNAKE_CASE_: Dict = image_processing(images=lowerCAmelCase__ , annotations=lowerCAmelCase__ , return_tensors="pt") # verify pixel values SCREAMING_SNAKE_CASE_: Optional[Any] = torch.Size([1, 3, 800, 1066]) self.assertEqual(encoding["pixel_values"].shape , lowerCAmelCase__) SCREAMING_SNAKE_CASE_: str = torch.tensor([0.2796, 0.3138, 0.3481]) self.assertTrue(torch.allclose(encoding["pixel_values"][0, 0, 0, :3] , lowerCAmelCase__ , atol=1E-4)) # verify area SCREAMING_SNAKE_CASE_: int = torch.tensor([5887.9600, 1_1250.2061, 48_9353.8438, 83_7122.7500, 14_7967.5156, 16_5732.3438]) self.assertTrue(torch.allclose(encoding["labels"][0]["area"] , lowerCAmelCase__)) # verify boxes SCREAMING_SNAKE_CASE_: str = torch.Size([6, 4]) self.assertEqual(encoding["labels"][0]["boxes"].shape , lowerCAmelCase__) SCREAMING_SNAKE_CASE_: Dict = torch.tensor([0.5503, 0.2765, 0.0604, 0.2215]) self.assertTrue(torch.allclose(encoding["labels"][0]["boxes"][0] , lowerCAmelCase__ , atol=1E-3)) # verify image_id SCREAMING_SNAKE_CASE_: str = torch.tensor([3_9769]) self.assertTrue(torch.allclose(encoding["labels"][0]["image_id"] , lowerCAmelCase__)) # verify is_crowd SCREAMING_SNAKE_CASE_: int = torch.tensor([0, 0, 0, 0, 0, 0]) self.assertTrue(torch.allclose(encoding["labels"][0]["iscrowd"] , lowerCAmelCase__)) # verify class_labels SCREAMING_SNAKE_CASE_: Tuple = torch.tensor([75, 75, 63, 65, 17, 17]) self.assertTrue(torch.allclose(encoding["labels"][0]["class_labels"] , lowerCAmelCase__)) # verify orig_size SCREAMING_SNAKE_CASE_: Union[str, Any] = torch.tensor([480, 640]) self.assertTrue(torch.allclose(encoding["labels"][0]["orig_size"] , lowerCAmelCase__)) # verify size SCREAMING_SNAKE_CASE_: str = torch.tensor([800, 1066]) self.assertTrue(torch.allclose(encoding["labels"][0]["size"] , lowerCAmelCase__)) @slow def _SCREAMING_SNAKE_CASE ( self : Tuple): # prepare image, target and masks_path SCREAMING_SNAKE_CASE_: Union[str, Any] = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png") with open("./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt" , "r") as f: SCREAMING_SNAKE_CASE_: List[Any] = json.loads(f.read()) SCREAMING_SNAKE_CASE_: Optional[Any] = {"file_name": "000000039769.png", "image_id": 3_9769, "segments_info": target} SCREAMING_SNAKE_CASE_: int = pathlib.Path("./tests/fixtures/tests_samples/COCO/coco_panoptic") # encode them SCREAMING_SNAKE_CASE_: Any = DeformableDetrImageProcessor(format="coco_panoptic") SCREAMING_SNAKE_CASE_: Optional[Any] = image_processing(images=lowerCAmelCase__ , annotations=lowerCAmelCase__ , masks_path=lowerCAmelCase__ , return_tensors="pt") # verify pixel values SCREAMING_SNAKE_CASE_: Dict = torch.Size([1, 3, 800, 1066]) self.assertEqual(encoding["pixel_values"].shape , lowerCAmelCase__) SCREAMING_SNAKE_CASE_: List[Any] = torch.tensor([0.2796, 0.3138, 0.3481]) self.assertTrue(torch.allclose(encoding["pixel_values"][0, 0, 0, :3] , lowerCAmelCase__ , atol=1E-4)) # verify area SCREAMING_SNAKE_CASE_: Optional[Any] = torch.tensor([14_7979.6875, 16_5527.0469, 48_4638.5938, 1_1292.9375, 5879.6562, 7634.1147]) self.assertTrue(torch.allclose(encoding["labels"][0]["area"] , lowerCAmelCase__)) # verify boxes SCREAMING_SNAKE_CASE_: List[str] = torch.Size([6, 4]) self.assertEqual(encoding["labels"][0]["boxes"].shape , lowerCAmelCase__) SCREAMING_SNAKE_CASE_: Optional[Any] = torch.tensor([0.2625, 0.5437, 0.4688, 0.8625]) self.assertTrue(torch.allclose(encoding["labels"][0]["boxes"][0] , lowerCAmelCase__ , atol=1E-3)) # verify image_id SCREAMING_SNAKE_CASE_: Any = torch.tensor([3_9769]) self.assertTrue(torch.allclose(encoding["labels"][0]["image_id"] , lowerCAmelCase__)) # verify is_crowd SCREAMING_SNAKE_CASE_: Union[str, Any] = torch.tensor([0, 0, 0, 0, 0, 0]) self.assertTrue(torch.allclose(encoding["labels"][0]["iscrowd"] , lowerCAmelCase__)) # verify class_labels SCREAMING_SNAKE_CASE_: List[Any] = torch.tensor([17, 17, 63, 75, 75, 93]) self.assertTrue(torch.allclose(encoding["labels"][0]["class_labels"] , lowerCAmelCase__)) # verify masks SCREAMING_SNAKE_CASE_: Tuple = 82_2873 self.assertEqual(encoding["labels"][0]["masks"].sum().item() , lowerCAmelCase__) # verify orig_size SCREAMING_SNAKE_CASE_: str = torch.tensor([480, 640]) self.assertTrue(torch.allclose(encoding["labels"][0]["orig_size"] , lowerCAmelCase__)) # verify size SCREAMING_SNAKE_CASE_: Optional[int] = torch.tensor([800, 1066]) self.assertTrue(torch.allclose(encoding["labels"][0]["size"] , lowerCAmelCase__))
127
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowerCamelCase = { 'configuration_luke': ['LUKE_PRETRAINED_CONFIG_ARCHIVE_MAP', 'LukeConfig'], 'tokenization_luke': ['LukeTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase = [ 'LUKE_PRETRAINED_MODEL_ARCHIVE_LIST', 'LukeForEntityClassification', 'LukeForEntityPairClassification', 'LukeForEntitySpanClassification', 'LukeForMultipleChoice', 'LukeForQuestionAnswering', 'LukeForSequenceClassification', 'LukeForTokenClassification', 'LukeForMaskedLM', 'LukeModel', 'LukePreTrainedModel', ] if TYPE_CHECKING: from .configuration_luke import LUKE_PRETRAINED_CONFIG_ARCHIVE_MAP, LukeConfig from .tokenization_luke import LukeTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_luke import ( LUKE_PRETRAINED_MODEL_ARCHIVE_LIST, LukeForEntityClassification, LukeForEntityPairClassification, LukeForEntitySpanClassification, LukeForMaskedLM, LukeForMultipleChoice, LukeForQuestionAnswering, LukeForSequenceClassification, LukeForTokenClassification, LukeModel, LukePreTrainedModel, ) else: import sys lowerCamelCase = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
199
import os import pytest from attr import dataclass lowerCamelCase = 'us-east-1' # defaults region @dataclass class A : UpperCamelCase__ : str UpperCamelCase__ : Dict ='arn:aws:iam::558105141721:role/sagemaker_execution_role' UpperCamelCase__ : int ={ 'task_name': 'mnli', 'per_device_train_batch_size': 16, 'per_device_eval_batch_size': 16, 'do_train': True, 'do_eval': True, 'do_predict': True, 'output_dir': '/opt/ml/model', 'overwrite_output_dir': True, 'max_steps': 500, 'save_steps': 5500, } UpperCamelCase__ : Optional[Any] ={**hyperparameters, 'max_steps': 1000} @property def lowerCamelCase ( self : List[Any] ) -> str: """simple docstring""" if self.framework == "pytorch": return [ {"Name": "train_runtime", "Regex": r"train_runtime.*=\D*(.*?)$"}, {"Name": "eval_accuracy", "Regex": r"eval_accuracy.*=\D*(.*?)$"}, {"Name": "eval_loss", "Regex": r"eval_loss.*=\D*(.*?)$"}, ] else: return [ {"Name": "train_runtime", "Regex": r"train_runtime.*=\D*(.*?)$"}, {"Name": "eval_accuracy", "Regex": r"loss.*=\D*(.*?)]?$"}, {"Name": "eval_loss", "Regex": r"sparse_categorical_accuracy.*=\D*(.*?)]?$"}, ] @property def lowerCamelCase ( self : List[Any] ) -> str: """simple docstring""" return F'''{self.framework}-transfromers-test''' @property def lowerCamelCase ( self : Union[str, Any] ) -> str: """simple docstring""" return F'''./tests/sagemaker/scripts/{self.framework}''' @property def lowerCamelCase ( self : Union[str, Any] ) -> str: """simple docstring""" if self.framework == "pytorch": return "763104351884.dkr.ecr.us-east-1.amazonaws.com/huggingface-pytorch-training:1.7.1-transformers4.6.1-gpu-py36-cu110-ubuntu18.04" else: return "763104351884.dkr.ecr.us-east-1.amazonaws.com/huggingface-tensorflow-training:2.4.1-transformers4.6.1-gpu-py37-cu110-ubuntu18.04" @pytest.fixture(scope='class' ) def a_ ( SCREAMING_SNAKE_CASE__ : Tuple ): '''simple docstring''' _lowerCamelCase : List[Any] =SageMakerTestEnvironment(framework=request.cls.framework )
199
1
def __lowerCamelCase ( lowerCamelCase__ ): """simple docstring""" if not isinstance(lowerCamelCase__ , lowerCamelCase__ ): raise TypeError("only integers accepted as input" ) else: lowercase__ : int = str(abs(lowerCamelCase__ ) ) lowercase__ : List[Any] = [list(lowerCamelCase__ ) for char in range(len(lowerCamelCase__ ) )] for index in range(len(lowerCamelCase__ ) ): num_transpositions[index].pop(lowerCamelCase__ ) return max( int("".join(list(lowerCamelCase__ ) ) ) for transposition in num_transpositions ) if __name__ == "__main__": __import__('''doctest''').testmod()
121
import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase__ = logging.get_logger(__name__) lowerCAmelCase__ = { '''BridgeTower/bridgetower-base''': '''https://huggingface.co/BridgeTower/bridgetower-base/blob/main/config.json''', '''BridgeTower/bridgetower-base-itm-mlm''': ( '''https://huggingface.co/BridgeTower/bridgetower-base-itm-mlm/blob/main/config.json''' ), } class snake_case__(_UpperCamelCase ): """simple docstring""" lowercase_ = """bridgetower_vision_model""" def __init__( self : str , SCREAMING_SNAKE_CASE : Dict=768 , SCREAMING_SNAKE_CASE : Union[str, Any]=12 , SCREAMING_SNAKE_CASE : Dict=3 , SCREAMING_SNAKE_CASE : Dict=16 , SCREAMING_SNAKE_CASE : List[Any]=288 , SCREAMING_SNAKE_CASE : List[Any]=1 , SCREAMING_SNAKE_CASE : List[str]=1E-0_5 , SCREAMING_SNAKE_CASE : str=False , SCREAMING_SNAKE_CASE : Any=True , SCREAMING_SNAKE_CASE : Tuple=False , **SCREAMING_SNAKE_CASE : List[str] , ): super().__init__(**SCREAMING_SNAKE_CASE ) lowercase__ : Union[str, Any] = hidden_size lowercase__ : str = num_hidden_layers lowercase__ : str = num_channels lowercase__ : Optional[int] = patch_size lowercase__ : Dict = image_size lowercase__ : List[Any] = initializer_factor lowercase__ : int = layer_norm_eps lowercase__ : List[str] = stop_gradient lowercase__ : Optional[int] = share_layernorm lowercase__ : Optional[int] = remove_last_layer @classmethod def snake_case ( cls : Tuple , SCREAMING_SNAKE_CASE : Union[str, os.PathLike] , **SCREAMING_SNAKE_CASE : str ): lowercase__ , lowercase__ : Optional[Any] = cls.get_config_dict(SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) if config_dict.get("model_type" ) == "bridgetower": lowercase__ : Optional[int] = 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 snake_case__(_UpperCamelCase ): """simple docstring""" lowercase_ = """bridgetower_text_model""" def __init__( self : Tuple , SCREAMING_SNAKE_CASE : Union[str, Any]=50_265 , SCREAMING_SNAKE_CASE : Optional[int]=768 , SCREAMING_SNAKE_CASE : List[str]=12 , SCREAMING_SNAKE_CASE : Union[str, Any]=12 , SCREAMING_SNAKE_CASE : List[Any]=1 , SCREAMING_SNAKE_CASE : Any=3_072 , SCREAMING_SNAKE_CASE : Union[str, Any]="gelu" , SCREAMING_SNAKE_CASE : Optional[int]=0.1 , SCREAMING_SNAKE_CASE : List[str]=0.1 , SCREAMING_SNAKE_CASE : Tuple=514 , SCREAMING_SNAKE_CASE : List[str]=1 , SCREAMING_SNAKE_CASE : Dict=1E-0_5 , SCREAMING_SNAKE_CASE : List[str]=1 , SCREAMING_SNAKE_CASE : str=0 , SCREAMING_SNAKE_CASE : List[Any]=2 , SCREAMING_SNAKE_CASE : Optional[Any]="absolute" , SCREAMING_SNAKE_CASE : int=True , **SCREAMING_SNAKE_CASE : int , ): super().__init__(**SCREAMING_SNAKE_CASE ) lowercase__ : Any = vocab_size lowercase__ : Optional[Any] = hidden_size lowercase__ : Optional[int] = num_hidden_layers lowercase__ : Optional[int] = num_attention_heads lowercase__ : int = hidden_act lowercase__ : Optional[Any] = initializer_factor lowercase__ : Dict = intermediate_size lowercase__ : Tuple = hidden_dropout_prob lowercase__ : List[Any] = attention_probs_dropout_prob lowercase__ : Optional[int] = max_position_embeddings lowercase__ : str = type_vocab_size lowercase__ : str = layer_norm_eps lowercase__ : Dict = position_embedding_type lowercase__ : Optional[Any] = use_cache lowercase__ : List[str] = pad_token_id lowercase__ : Optional[Any] = bos_token_id lowercase__ : Optional[Any] = eos_token_id @classmethod def snake_case ( cls : Optional[int] , SCREAMING_SNAKE_CASE : Union[str, os.PathLike] , **SCREAMING_SNAKE_CASE : str ): lowercase__ , lowercase__ : Optional[Any] = cls.get_config_dict(SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) if config_dict.get("model_type" ) == "bridgetower": lowercase__ : List[Any] = 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 snake_case__(_UpperCamelCase ): """simple docstring""" lowercase_ = """bridgetower""" def __init__( self : Tuple , SCREAMING_SNAKE_CASE : Optional[int]=True , SCREAMING_SNAKE_CASE : Dict="gelu" , SCREAMING_SNAKE_CASE : Any=768 , SCREAMING_SNAKE_CASE : Dict=1 , SCREAMING_SNAKE_CASE : Union[str, Any]=1E-0_5 , SCREAMING_SNAKE_CASE : Tuple=False , SCREAMING_SNAKE_CASE : List[Any]="add" , SCREAMING_SNAKE_CASE : Any=12 , SCREAMING_SNAKE_CASE : Any=6 , SCREAMING_SNAKE_CASE : Any=False , SCREAMING_SNAKE_CASE : List[Any]=False , SCREAMING_SNAKE_CASE : str=None , SCREAMING_SNAKE_CASE : Dict=None , **SCREAMING_SNAKE_CASE : List[Any] , ): # TODO: remove this once the Hub files are updated. lowercase__ : int = kwargs.pop("text_config_dict" , SCREAMING_SNAKE_CASE ) lowercase__ : int = kwargs.pop("vision_config_dict" , SCREAMING_SNAKE_CASE ) super().__init__(**SCREAMING_SNAKE_CASE ) lowercase__ : Dict = share_cross_modal_transformer_layers lowercase__ : int = hidden_act lowercase__ : int = hidden_size lowercase__ : Optional[int] = initializer_factor lowercase__ : Optional[int] = layer_norm_eps lowercase__ : str = share_link_tower_layers lowercase__ : Optional[int] = link_tower_type lowercase__ : List[Any] = num_attention_heads lowercase__ : Dict = num_hidden_layers lowercase__ : Dict = tie_word_embeddings lowercase__ : Optional[Any] = init_layernorm_from_vision_encoder if text_config is None: lowercase__ : Optional[Any] = {} logger.info("`text_config` is `None`. Initializing the `BridgeTowerTextConfig` with default values." ) if vision_config is None: lowercase__ : List[Any] = {} logger.info("`vision_config` is `None`. Initializing the `BridgeTowerVisionConfig` with default values." ) lowercase__ : Any = BridgeTowerTextConfig(**SCREAMING_SNAKE_CASE ) lowercase__ : Dict = BridgeTowerVisionConfig(**SCREAMING_SNAKE_CASE ) @classmethod def snake_case ( cls : Optional[int] , SCREAMING_SNAKE_CASE : BridgeTowerTextConfig , SCREAMING_SNAKE_CASE : BridgeTowerVisionConfig , **SCREAMING_SNAKE_CASE : List[str] ): return cls(text_config=text_config.to_dict() , vision_config=vision_config.to_dict() , **SCREAMING_SNAKE_CASE ) def snake_case ( self : Optional[int] ): lowercase__ : List[str] = copy.deepcopy(self.__dict__ ) lowercase__ : Dict = self.text_config.to_dict() lowercase__ : Tuple = self.vision_config.to_dict() lowercase__ : Optional[Any] = self.__class__.model_type return output
121
1
'''simple docstring''' import unittest from transformers import EsmConfig, is_torch_available from transformers.testing_utils import TestCasePlus, require_torch, slow, torch_device 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.models.esm.modeling_esmfold import EsmForProteinFolding class __a : def __init__( self : List[str] , __magic_name__ : Tuple , __magic_name__ : Any=13 , __magic_name__ : List[Any]=7 , __magic_name__ : Tuple=False , __magic_name__ : List[str]=True , __magic_name__ : int=False , __magic_name__ : Any=False , __magic_name__ : List[str]=19 , __magic_name__ : Any=32 , __magic_name__ : Tuple=5 , __magic_name__ : Tuple=4 , __magic_name__ : Tuple=37 , __magic_name__ : str="gelu" , __magic_name__ : int=0.1 , __magic_name__ : Optional[Any]=0.1 , __magic_name__ : List[str]=5_12 , __magic_name__ : Optional[Any]=16 , __magic_name__ : Tuple=2 , __magic_name__ : List[Any]=0.0_2 , __magic_name__ : List[str]=3 , __magic_name__ : Any=4 , __magic_name__ : int=None , ) -> str: """simple docstring""" UpperCAmelCase_ : Any = parent UpperCAmelCase_ : int = batch_size UpperCAmelCase_ : List[Any] = seq_length UpperCAmelCase_ : int = is_training UpperCAmelCase_ : Any = use_input_mask UpperCAmelCase_ : List[str] = use_token_type_ids UpperCAmelCase_ : Optional[int] = use_labels UpperCAmelCase_ : List[str] = vocab_size UpperCAmelCase_ : Dict = hidden_size UpperCAmelCase_ : Optional[Any] = num_hidden_layers UpperCAmelCase_ : Any = num_attention_heads UpperCAmelCase_ : Optional[int] = intermediate_size UpperCAmelCase_ : Optional[Any] = hidden_act UpperCAmelCase_ : List[Any] = hidden_dropout_prob UpperCAmelCase_ : List[Any] = attention_probs_dropout_prob UpperCAmelCase_ : Union[str, Any] = max_position_embeddings UpperCAmelCase_ : Any = type_vocab_size UpperCAmelCase_ : Union[str, Any] = type_sequence_label_size UpperCAmelCase_ : Dict = initializer_range UpperCAmelCase_ : Dict = num_labels UpperCAmelCase_ : Union[str, Any] = num_choices UpperCAmelCase_ : List[str] = scope def UpperCAmelCase__ ( self : Optional[Any] ) -> str: """simple docstring""" UpperCAmelCase_ : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCAmelCase_ : Tuple = None if self.use_input_mask: UpperCAmelCase_ : Optional[Any] = random_attention_mask([self.batch_size, self.seq_length] ) UpperCAmelCase_ : str = None UpperCAmelCase_ : Union[str, Any] = None UpperCAmelCase_ : Any = None if self.use_labels: UpperCAmelCase_ : Any = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCAmelCase_ : List[str] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) UpperCAmelCase_ : List[str] = ids_tensor([self.batch_size] , self.num_choices ) UpperCAmelCase_ : Any = self.get_config() return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCAmelCase__ ( self : List[str] ) -> str: """simple docstring""" UpperCAmelCase_ : Any = EsmConfig( vocab_size=33 , hidden_size=self.hidden_size , pad_token_id=1 , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , is_folding_model=_lowerCAmelCase , esmfold_config={'''trunk''': {'''num_blocks''': 2}, '''fp16_esm''': False} , ) return config def UpperCAmelCase__ ( self : str , __magic_name__ : Union[str, Any] , __magic_name__ : Optional[int] , __magic_name__ : Dict , __magic_name__ : int , __magic_name__ : Any , __magic_name__ : Union[str, Any] ) -> Optional[int]: """simple docstring""" UpperCAmelCase_ : List[Any] = EsmForProteinFolding(config=_lowerCAmelCase ).float() model.to(_lowerCAmelCase ) model.eval() UpperCAmelCase_ : List[Any] = model(_lowerCAmelCase , attention_mask=_lowerCAmelCase ) UpperCAmelCase_ : int = model(_lowerCAmelCase ) UpperCAmelCase_ : Optional[Any] = model(_lowerCAmelCase ) self.parent.assertEqual(result.positions.shape , (8, self.batch_size, self.seq_length, 14, 3) ) self.parent.assertEqual(result.angles.shape , (8, self.batch_size, self.seq_length, 7, 2) ) def UpperCAmelCase__ ( self : Optional[Any] ) -> Optional[int]: """simple docstring""" UpperCAmelCase_ : Tuple = self.prepare_config_and_inputs() ( UpperCAmelCase_ ) : str = config_and_inputs UpperCAmelCase_ : Dict = {"input_ids": input_ids, "attention_mask": input_mask} return config, inputs_dict @require_torch class __a (lowerCamelCase , lowerCamelCase , unittest.TestCase ): __a : Any = False __a : Optional[Any] = (EsmForProteinFolding,) if is_torch_available() else () __a : Optional[Any] = () __a : List[Any] = {} if is_torch_available() else {} __a : List[str] = False def UpperCAmelCase__ ( self : List[str] ) -> Optional[int]: """simple docstring""" UpperCAmelCase_ : Union[str, Any] = EsmFoldModelTester(self ) UpperCAmelCase_ : List[str] = ConfigTester(self , config_class=_lowerCAmelCase , hidden_size=37 ) def UpperCAmelCase__ ( self : Any ) -> int: """simple docstring""" self.config_tester.run_common_tests() def UpperCAmelCase__ ( self : Union[str, Any] ) -> Optional[Any]: """simple docstring""" UpperCAmelCase_ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_lowerCAmelCase ) @unittest.skip('''Does not support attention outputs''' ) def UpperCAmelCase__ ( self : Union[str, Any] ) -> Union[str, Any]: """simple docstring""" pass @unittest.skip def UpperCAmelCase__ ( self : Optional[int] ) -> Union[str, Any]: """simple docstring""" pass @unittest.skip('''Esm does not support embedding resizing''' ) def UpperCAmelCase__ ( self : Tuple ) -> Tuple: """simple docstring""" pass @unittest.skip('''Esm does not support embedding resizing''' ) def UpperCAmelCase__ ( self : Dict ) -> int: """simple docstring""" pass @unittest.skip('''ESMFold does not support passing input embeds!''' ) def UpperCAmelCase__ ( self : List[Any] ) -> List[Any]: """simple docstring""" pass @unittest.skip('''ESMFold does not support head pruning.''' ) def UpperCAmelCase__ ( self : Optional[int] ) -> Dict: """simple docstring""" pass @unittest.skip('''ESMFold does not support head pruning.''' ) def UpperCAmelCase__ ( self : List[Any] ) -> Dict: """simple docstring""" pass @unittest.skip('''ESMFold does not support head pruning.''' ) def UpperCAmelCase__ ( self : List[Any] ) -> List[str]: """simple docstring""" pass @unittest.skip('''ESMFold does not support head pruning.''' ) def UpperCAmelCase__ ( self : Union[str, Any] ) -> int: """simple docstring""" pass @unittest.skip('''ESMFold does not support head pruning.''' ) def UpperCAmelCase__ ( self : Dict ) -> List[str]: """simple docstring""" pass @unittest.skip('''ESMFold does not output hidden states in the normal way.''' ) def UpperCAmelCase__ ( self : List[str] ) -> Optional[Any]: """simple docstring""" pass @unittest.skip('''ESMfold does not output hidden states in the normal way.''' ) def UpperCAmelCase__ ( self : Union[str, Any] ) -> int: """simple docstring""" pass @unittest.skip('''ESMFold only has one output format.''' ) def UpperCAmelCase__ ( self : Any ) -> Tuple: """simple docstring""" pass @unittest.skip('''This test doesn\'t work for ESMFold and doesn\'t test core functionality''' ) def UpperCAmelCase__ ( self : Tuple ) -> Dict: """simple docstring""" pass @unittest.skip('''ESMFold does not support input chunking.''' ) def UpperCAmelCase__ ( self : int ) -> Optional[int]: """simple docstring""" pass @unittest.skip('''ESMFold doesn\'t respect you and it certainly doesn\'t respect your initialization arguments.''' ) def UpperCAmelCase__ ( self : str ) -> List[str]: """simple docstring""" pass @unittest.skip('''ESMFold doesn\'t support torchscript compilation.''' ) def UpperCAmelCase__ ( self : List[str] ) -> Dict: """simple docstring""" pass @unittest.skip('''ESMFold doesn\'t support torchscript compilation.''' ) def UpperCAmelCase__ ( self : List[Any] ) -> int: """simple docstring""" pass @unittest.skip('''ESMFold doesn\'t support torchscript compilation.''' ) def UpperCAmelCase__ ( self : Optional[Any] ) -> Optional[int]: """simple docstring""" pass @unittest.skip('''ESMFold doesn\'t support data parallel.''' ) def UpperCAmelCase__ ( self : int ) -> Dict: """simple docstring""" pass @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' ) def UpperCAmelCase__ ( self : Tuple ) -> int: """simple docstring""" pass @require_torch class __a (lowerCamelCase ): @slow def UpperCAmelCase__ ( self : Tuple ) -> Any: """simple docstring""" UpperCAmelCase_ : List[Any] = EsmForProteinFolding.from_pretrained('''facebook/esmfold_v1''' ).float() model.eval() UpperCAmelCase_ : str = torch.tensor([[0, 6, 4, 13, 5, 4, 16, 12, 11, 7, 2]] ) UpperCAmelCase_ : List[str] = model(_lowerCAmelCase )["positions"] UpperCAmelCase_ : List[str] = torch.tensor([2.5_8_2_8, 0.7_9_9_3, -1_0.9_3_3_4] , dtype=torch.floataa ) self.assertTrue(torch.allclose(position_outputs[0, 0, 0, 0] , _lowerCAmelCase , atol=1E-4 ) )
125
import os import pytest from attr import dataclass _UpperCAmelCase : List[str] = "us-east-1" # defaults region @dataclass class __lowerCAmelCase : _a = 42 _a = '''arn:aws:iam::558105141721:role/sagemaker_execution_role''' _a = { '''task_name''': '''mnli''', '''per_device_train_batch_size''': 16, '''per_device_eval_batch_size''': 16, '''do_train''': True, '''do_eval''': True, '''do_predict''': True, '''output_dir''': '''/opt/ml/model''', '''overwrite_output_dir''': True, '''max_steps''': 500, '''save_steps''': 5500, } _a = {**hyperparameters, '''max_steps''': 1000} @property def SCREAMING_SNAKE_CASE ( self: str ): if self.framework == "pytorch": return [ {"Name": "train_runtime", "Regex": r"train_runtime.*=\D*(.*?)$"}, {"Name": "eval_accuracy", "Regex": r"eval_accuracy.*=\D*(.*?)$"}, {"Name": "eval_loss", "Regex": r"eval_loss.*=\D*(.*?)$"}, ] else: return [ {"Name": "train_runtime", "Regex": r"train_runtime.*=\D*(.*?)$"}, {"Name": "eval_accuracy", "Regex": r"loss.*=\D*(.*?)]?$"}, {"Name": "eval_loss", "Regex": r"sparse_categorical_accuracy.*=\D*(.*?)]?$"}, ] @property def SCREAMING_SNAKE_CASE ( self: Dict ): return F"{self.framework}-transfromers-test" @property def SCREAMING_SNAKE_CASE ( self: Any ): return F"./tests/sagemaker/scripts/{self.framework}" @property def SCREAMING_SNAKE_CASE ( self: Optional[int] ): if self.framework == "pytorch": return "763104351884.dkr.ecr.us-east-1.amazonaws.com/huggingface-pytorch-training:1.7.1-transformers4.6.1-gpu-py36-cu110-ubuntu18.04" else: return "763104351884.dkr.ecr.us-east-1.amazonaws.com/huggingface-tensorflow-training:2.4.1-transformers4.6.1-gpu-py37-cu110-ubuntu18.04" @pytest.fixture(scope="class" ) def UpperCAmelCase__ ( lowerCamelCase ): lowercase :Union[str, Any] = SageMakerTestEnvironment(framework=request.cls.framework )
236
0
from typing import Optional, Tuple, Union import flax import flax.linen as nn import jax import jax.numpy as jnp from flax.core.frozen_dict import FrozenDict from ..configuration_utils import ConfigMixin, flax_register_to_config from ..utils import BaseOutput from .embeddings_flax import FlaxTimestepEmbedding, FlaxTimesteps from .modeling_flax_utils import FlaxModelMixin from .unet_ad_blocks_flax import ( FlaxCrossAttnDownBlockaD, FlaxCrossAttnUpBlockaD, FlaxDownBlockaD, FlaxUNetMidBlockaDCrossAttn, FlaxUpBlockaD, ) @flax.struct.dataclass class __lowerCAmelCase ( __magic_name__ ): UpperCamelCase__ = 42 @flax_register_to_config class __lowerCAmelCase ( nn.Module , __magic_name__ , __magic_name__ ): UpperCamelCase__ = 32 UpperCamelCase__ = 4 UpperCamelCase__ = 4 UpperCamelCase__ = ( '''CrossAttnDownBlock2D''', '''CrossAttnDownBlock2D''', '''CrossAttnDownBlock2D''', '''DownBlock2D''', ) UpperCamelCase__ = ('''UpBlock2D''', '''CrossAttnUpBlock2D''', '''CrossAttnUpBlock2D''', '''CrossAttnUpBlock2D''') UpperCamelCase__ = False UpperCamelCase__ = (320, 640, 1280, 1280) UpperCamelCase__ = 2 UpperCamelCase__ = 8 UpperCamelCase__ = None UpperCamelCase__ = 1280 UpperCamelCase__ = 0.0 UpperCamelCase__ = False UpperCamelCase__ = jnp.floataa UpperCamelCase__ = True UpperCamelCase__ = 0 UpperCamelCase__ = False def lowerCamelCase__ ( self :List[str] , __magic_name__ :jax.random.KeyArray ): '''simple docstring''' a = (1, self.in_channels, self.sample_size, self.sample_size) a = jnp.zeros(__magic_name__ , dtype=jnp.floataa ) a = jnp.ones((1,) , dtype=jnp.intaa ) a = jnp.zeros((1, 1, self.cross_attention_dim) , dtype=jnp.floataa ) a , a = jax.random.split(__magic_name__ ) a = {"""params""": params_rng, """dropout""": dropout_rng} return self.init(__magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ )["params"] def lowerCamelCase__ ( self :Optional[Any] ): '''simple docstring''' a = self.block_out_channels a = block_out_channels[0] * 4 if self.num_attention_heads is not None: raise ValueError( """At the moment it is not possible to define the number of attention heads via `num_attention_heads` because of a naming issue as described in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131. Passing `num_attention_heads` will only be supported in diffusers v0.19.""" ) # If `num_attention_heads` is not defined (which is the case for most models) # it will default to `attention_head_dim`. This looks weird upon first reading it and it is. # The reason for this behavior is to correct for incorrectly named variables that were introduced # when this library was created. The incorrect naming was only discovered much later in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131 # Changing `attention_head_dim` to `num_attention_heads` for 40,000+ configurations is too backwards breaking # which is why we correct for the naming here. a = self.num_attention_heads or self.attention_head_dim # input a = nn.Conv( block_out_channels[0] , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) # time a = FlaxTimesteps( block_out_channels[0] , flip_sin_to_cos=self.flip_sin_to_cos , freq_shift=self.config.freq_shift ) a = FlaxTimestepEmbedding(__magic_name__ , dtype=self.dtype ) a = self.only_cross_attention if isinstance(__magic_name__ , __magic_name__ ): a = (only_cross_attention,) * len(self.down_block_types ) if isinstance(__magic_name__ , __magic_name__ ): a = (num_attention_heads,) * len(self.down_block_types ) # down a = [] a = block_out_channels[0] for i, down_block_type in enumerate(self.down_block_types ): a = output_channel a = block_out_channels[i] a = i == len(__magic_name__ ) - 1 if down_block_type == "CrossAttnDownBlock2D": a = FlaxCrossAttnDownBlockaD( in_channels=__magic_name__ , out_channels=__magic_name__ , dropout=self.dropout , num_layers=self.layers_per_block , num_attention_heads=num_attention_heads[i] , add_downsample=not is_final_block , use_linear_projection=self.use_linear_projection , only_cross_attention=only_cross_attention[i] , use_memory_efficient_attention=self.use_memory_efficient_attention , dtype=self.dtype , ) else: a = FlaxDownBlockaD( in_channels=__magic_name__ , out_channels=__magic_name__ , dropout=self.dropout , num_layers=self.layers_per_block , add_downsample=not is_final_block , dtype=self.dtype , ) down_blocks.append(__magic_name__ ) a = down_blocks # mid a = FlaxUNetMidBlockaDCrossAttn( in_channels=block_out_channels[-1] , dropout=self.dropout , num_attention_heads=num_attention_heads[-1] , use_linear_projection=self.use_linear_projection , use_memory_efficient_attention=self.use_memory_efficient_attention , dtype=self.dtype , ) # up a = [] a = list(reversed(__magic_name__ ) ) a = list(reversed(__magic_name__ ) ) a = list(reversed(__magic_name__ ) ) a = reversed_block_out_channels[0] for i, up_block_type in enumerate(self.up_block_types ): a = output_channel a = reversed_block_out_channels[i] a = reversed_block_out_channels[min(i + 1 , len(__magic_name__ ) - 1 )] a = i == len(__magic_name__ ) - 1 if up_block_type == "CrossAttnUpBlock2D": a = FlaxCrossAttnUpBlockaD( in_channels=__magic_name__ , out_channels=__magic_name__ , prev_output_channel=__magic_name__ , num_layers=self.layers_per_block + 1 , num_attention_heads=reversed_num_attention_heads[i] , add_upsample=not is_final_block , dropout=self.dropout , use_linear_projection=self.use_linear_projection , only_cross_attention=only_cross_attention[i] , use_memory_efficient_attention=self.use_memory_efficient_attention , dtype=self.dtype , ) else: a = FlaxUpBlockaD( in_channels=__magic_name__ , out_channels=__magic_name__ , prev_output_channel=__magic_name__ , num_layers=self.layers_per_block + 1 , add_upsample=not is_final_block , dropout=self.dropout , dtype=self.dtype , ) up_blocks.append(__magic_name__ ) a = output_channel a = up_blocks # out a = nn.GroupNorm(num_groups=32 , epsilon=1E-5 ) a = nn.Conv( self.out_channels , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) def __call__( self :List[str] , __magic_name__ :Union[str, Any] , __magic_name__ :Optional[Any] , __magic_name__ :str , __magic_name__ :Tuple=None , __magic_name__ :List[str]=None , __magic_name__ :bool = True , __magic_name__ :bool = False , ): '''simple docstring''' if not isinstance(__magic_name__ , jnp.ndarray ): a = jnp.array([timesteps] , dtype=jnp.intaa ) elif isinstance(__magic_name__ , jnp.ndarray ) and len(timesteps.shape ) == 0: a = timesteps.astype(dtype=jnp.floataa ) a = jnp.expand_dims(__magic_name__ , 0 ) a = self.time_proj(__magic_name__ ) a = self.time_embedding(__magic_name__ ) # 2. pre-process a = jnp.transpose(__magic_name__ , (0, 2, 3, 1) ) a = self.conv_in(__magic_name__ ) # 3. down a = (sample,) for down_block in self.down_blocks: if isinstance(__magic_name__ , __magic_name__ ): a , a = down_block(__magic_name__ , __magic_name__ , __magic_name__ , deterministic=not train ) else: a , a = down_block(__magic_name__ , __magic_name__ , deterministic=not train ) down_block_res_samples += res_samples if down_block_additional_residuals is not None: a = () for down_block_res_sample, down_block_additional_residual in zip( __magic_name__ , __magic_name__ ): down_block_res_sample += down_block_additional_residual new_down_block_res_samples += (down_block_res_sample,) a = new_down_block_res_samples # 4. mid a = self.mid_block(__magic_name__ , __magic_name__ , __magic_name__ , deterministic=not train ) if mid_block_additional_residual is not None: sample += mid_block_additional_residual # 5. up for up_block in self.up_blocks: a = down_block_res_samples[-(self.layers_per_block + 1) :] a = down_block_res_samples[: -(self.layers_per_block + 1)] if isinstance(__magic_name__ , __magic_name__ ): a = up_block( __magic_name__ , temb=__magic_name__ , encoder_hidden_states=__magic_name__ , res_hidden_states_tuple=__magic_name__ , deterministic=not train , ) else: a = up_block(__magic_name__ , temb=__magic_name__ , res_hidden_states_tuple=__magic_name__ , deterministic=not train ) # 6. post-process a = self.conv_norm_out(__magic_name__ ) a = nn.silu(__magic_name__ ) a = self.conv_out(__magic_name__ ) a = jnp.transpose(__magic_name__ , (0, 3, 1, 2) ) if not return_dict: return (sample,) return FlaxUNetaDConditionOutput(sample=__magic_name__ )
363
def __A ( __lowerCamelCase ) -> int: if not numbers: return 0 if not isinstance(__lowerCamelCase , (list, tuple) ) or not all( isinstance(__lowerCamelCase , __lowerCamelCase ) for number in numbers ): raise ValueError("""numbers must be an iterable of integers""" ) a = a = a = numbers[0] for i in range(1 , len(__lowerCamelCase ) ): # update the maximum and minimum subarray products a = numbers[i] if number < 0: a , a = min_till_now, max_till_now a = max(__lowerCamelCase , max_till_now * number ) a = min(__lowerCamelCase , min_till_now * number ) # update the maximum product found till now a = max(__lowerCamelCase , __lowerCamelCase ) return max_prod
347
0
"""simple docstring""" import argparse 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 ######################################################################## # This is a fully working simple example to use Accelerate, # specifically showcasing the experiment tracking capability, # and builds off the `nlp_example.py` script. # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # To help focus on the differences in the code, building `DataLoaders` # was refactored into its own function. # New additions from the base script can be found quickly by # looking for the # New Code # tags # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## __A = 16 __A = 32 def lowercase_ ( _lowerCamelCase: Accelerator , _lowerCamelCase: int = 16 ) -> str: '''simple docstring''' __lowerCamelCase : Optional[Any] = AutoTokenizer.from_pretrained("bert-base-cased" ) __lowerCamelCase : Optional[Any] = load_dataset("glue" , "mrpc" ) def tokenize_function(_lowerCamelCase: str ): # max_length=None => use the model max length (it's actually the default) __lowerCamelCase : Any = tokenizer(examples["sentence1"] , examples["sentence2"] , truncation=_UpperCamelCase , max_length=_UpperCamelCase ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): __lowerCamelCase : Optional[Any] = datasets.map( _UpperCamelCase , batched=_UpperCamelCase , remove_columns=["idx", "sentence1", "sentence2"] , ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library __lowerCamelCase : int = tokenized_datasets.rename_column("label" , "labels" ) def collate_fn(_lowerCamelCase: int ): # On TPU it's best to pad everything to the same length or training will be very slow. __lowerCamelCase : Optional[Any] = 128 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": __lowerCamelCase : Optional[int] = 16 elif accelerator.mixed_precision != "no": __lowerCamelCase : Optional[Any] = 8 else: __lowerCamelCase : Tuple = None return tokenizer.pad( _UpperCamelCase , padding="longest" , max_length=_UpperCamelCase , pad_to_multiple_of=_UpperCamelCase , return_tensors="pt" , ) # Instantiate dataloaders. __lowerCamelCase : List[str] = DataLoader( tokenized_datasets["train"] , shuffle=_UpperCamelCase , collate_fn=_UpperCamelCase , batch_size=_UpperCamelCase ) __lowerCamelCase : int = DataLoader( tokenized_datasets["validation"] , shuffle=_UpperCamelCase , collate_fn=_UpperCamelCase , batch_size=_UpperCamelCase ) return train_dataloader, eval_dataloader # For testing only if os.environ.get('''TESTING_MOCKED_DATALOADERS''', None) == "1": from accelerate.test_utils.training import mocked_dataloaders __A = mocked_dataloaders # noqa: F811 def lowercase_ ( _lowerCamelCase: Dict , _lowerCamelCase: List[Any] ) -> int: '''simple docstring''' if os.environ.get("TESTING_MOCKED_DATALOADERS" , _UpperCamelCase ) == "1": __lowerCamelCase : str = 2 # Initialize Accelerator # New Code # # We pass in "all" to `log_with` to grab all available trackers in the environment # Note: If using a custom `Tracker` class, should be passed in here such as: # >>> log_with = ["all", MyCustomTrackerClassInstance()] if args.with_tracking: __lowerCamelCase : Optional[Any] = Accelerator( cpu=args.cpu , mixed_precision=args.mixed_precision , log_with="all" , project_dir=args.project_dir ) else: __lowerCamelCase : Dict = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs __lowerCamelCase : int = config["lr"] __lowerCamelCase : Optional[Any] = int(config["num_epochs"] ) __lowerCamelCase : Dict = int(config["seed"] ) __lowerCamelCase : Union[str, Any] = int(config["batch_size"] ) set_seed(_UpperCamelCase ) __lowerCamelCase , __lowerCamelCase : List[Any] = get_dataloaders(_UpperCamelCase , _UpperCamelCase ) __lowerCamelCase : Tuple = evaluate.load("glue" , "mrpc" ) # If the batch size is too big we use gradient accumulation __lowerCamelCase : int = 1 if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU: __lowerCamelCase : Tuple = batch_size // MAX_GPU_BATCH_SIZE __lowerCamelCase : int = MAX_GPU_BATCH_SIZE # Instantiate the model (we build the model here so that the seed also control new weights initialization) __lowerCamelCase : List[str] = AutoModelForSequenceClassification.from_pretrained("bert-base-cased" , return_dict=_UpperCamelCase ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). __lowerCamelCase : List[Any] = model.to(accelerator.device ) # Instantiate optimizer __lowerCamelCase : List[Any] = AdamW(params=model.parameters() , lr=_UpperCamelCase ) # Instantiate scheduler __lowerCamelCase : Tuple = get_linear_schedule_with_warmup( optimizer=_UpperCamelCase , num_warmup_steps=100 , num_training_steps=(len(_UpperCamelCase ) * num_epochs) // gradient_accumulation_steps , ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : Union[str, Any] = accelerator.prepare( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) # New Code # # We need to initialize the trackers we use. Overall configurations can also be stored if args.with_tracking: __lowerCamelCase : int = os.path.split(_UpperCamelCase )[-1].split("." )[0] accelerator.init_trackers(_UpperCamelCase , _UpperCamelCase ) # Now we train the model for epoch in range(_UpperCamelCase ): model.train() # New Code # # For our tracking example, we will log the total loss of each epoch if args.with_tracking: __lowerCamelCase : Dict = 0 for step, batch in enumerate(_UpperCamelCase ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) __lowerCamelCase : Optional[Any] = model(**_UpperCamelCase ) __lowerCamelCase : Optional[int] = outputs.loss # New Code # if args.with_tracking: total_loss += loss.detach().float() __lowerCamelCase : Dict = loss / gradient_accumulation_steps accelerator.backward(_UpperCamelCase ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(_UpperCamelCase ): # We could avoid this line since we set the accelerator with `device_placement=True` (the default). batch.to(accelerator.device ) with torch.no_grad(): __lowerCamelCase : Tuple = model(**_UpperCamelCase ) __lowerCamelCase : str = outputs.logits.argmax(dim=-1 ) __lowerCamelCase , __lowerCamelCase : int = accelerator.gather_for_metrics((predictions, batch["labels"]) ) metric.add_batch( predictions=_UpperCamelCase , references=_UpperCamelCase , ) __lowerCamelCase : Dict = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F"""epoch {epoch}:""" , _UpperCamelCase ) # New Code # # To actually log, we call `Accelerator.log` # The values passed can be of `str`, `int`, `float` or `dict` of `str` to `float`/`int` if args.with_tracking: accelerator.log( { "accuracy": eval_metric["accuracy"], "f1": eval_metric["f1"], "train_loss": total_loss.item() / len(_UpperCamelCase ), "epoch": epoch, } , step=_UpperCamelCase , ) # New Code # # When a run is finished, you should call `accelerator.end_training()` # to close all of the open trackers if args.with_tracking: accelerator.end_training() def lowercase_ ( ) -> int: '''simple docstring''' __lowerCamelCase : Union[str, Any] = argparse.ArgumentParser(description="Simple example of training script." ) parser.add_argument( "--mixed_precision" , type=_UpperCamelCase , default=_UpperCamelCase , choices=["no", "fp16", "bf16", "fp8"] , help="Whether to use mixed precision. Choose" "between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10." "and an Nvidia Ampere GPU." , ) parser.add_argument("--cpu" , action="store_true" , help="If passed, will train on the CPU." ) parser.add_argument( "--with_tracking" , action="store_true" , help="Whether to load in all available experiment trackers from the environment and use them for logging." , ) parser.add_argument( "--project_dir" , type=_UpperCamelCase , default="logs" , help="Location on where to store experiment tracking logs` and relevent project information" , ) __lowerCamelCase : str = parser.parse_args() __lowerCamelCase : Optional[Any] = {"lr": 2E-5, "num_epochs": 3, "seed": 42, "batch_size": 16} training_function(_UpperCamelCase , _UpperCamelCase ) if __name__ == "__main__": main()
135
"""simple docstring""" from __future__ import annotations def lowerCAmelCase__ ( _UpperCamelCase : list[list[int]] ) -> int: """simple docstring""" for i in range(1 , len(matrix[0] ) ): matrix[0][i] += matrix[0][i - 1] # preprocessing the first column for i in range(1 , len(_UpperCamelCase ) ): matrix[i][0] += matrix[i - 1][0] # updating the path cost for current position for i in range(1 , len(_UpperCamelCase ) ): for j in range(1 , len(matrix[0] ) ): matrix[i][j] += min(matrix[i - 1][j] , matrix[i][j - 1] ) return matrix[-1][-1] if __name__ == "__main__": import doctest doctest.testmod()
150
0
'''simple docstring''' from typing import List from .keymap import KEYMAP, get_character def __magic_name__ ( A ) -> str: def decorator(A ): snake_case = getattr(A , 'handle_key' , [] ) handle += [key] setattr(A , 'handle_key' , A ) return func return decorator def __magic_name__ ( *A ) -> Any: def decorator(A ): snake_case = getattr(A , 'handle_key' , [] ) handle += keys setattr(A , 'handle_key' , A ) return func return decorator class lowerCamelCase ( __lowerCAmelCase ): def __new__( cls, lowercase_, lowercase_, lowercase_ ) -> Dict: snake_case = super().__new__(cls, lowercase_, lowercase_, lowercase_ ) if not hasattr(lowercase_, 'key_handler' ): setattr(lowercase_, 'key_handler', {} ) setattr(lowercase_, 'handle_input', KeyHandler.handle_input ) for value in attrs.values(): snake_case = getattr(lowercase_, 'handle_key', [] ) for key in handled_keys: snake_case = value return new_cls @staticmethod def _lowerCamelCase ( cls ) -> Union[str, Any]: snake_case = get_character() if char != KEYMAP["undefined"]: snake_case = ord(lowercase_ ) snake_case = cls.key_handler.get(lowercase_ ) if handler: snake_case = char return handler(cls ) else: return None def __magic_name__ ( cls ) -> List[str]: return KeyHandler(cls.__name__ , cls.__bases__ , cls.__dict__.copy() )
350
'''simple docstring''' from __future__ import annotations def __magic_name__ ( A , A , A ) -> int | float: if len(A ) == 0: raise ValueError('find_max() arg is an empty sequence' ) if ( left >= len(A ) or left < -len(A ) or right >= len(A ) or right < -len(A ) ): raise IndexError('list index out of range' ) if left == right: return nums[left] snake_case = (left + right) >> 1 # the middle snake_case = find_max(A , A , A ) # find max in range[left, mid] snake_case = find_max(A , mid + 1 , A ) # find max in range[mid + 1, right] return left_max if left_max >= right_max else right_max if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
332
0
lowerCamelCase : int = 'Tobias Carryer' from time import time class __lowercase : """simple docstring""" def __init__( self , A , A , A , A=int(time() ) ) -> int: # noqa: B008 snake_case : List[str] = multiplier snake_case : int = increment snake_case : Optional[Any] = modulo snake_case : Optional[Any] = seed def UpperCAmelCase ( self ) -> Optional[int]: snake_case : List[Any] = (self.multiplier * self.seed + self.increment) % self.modulo return self.seed if __name__ == "__main__": # Show the LCG in action. lowerCamelCase : Optional[int] = LinearCongruentialGenerator(1_6_6_4_5_2_5, 1_0_1_3_9_0_4_2_2_3, 2 << 3_1) while True: print(lcg.next_number())
124
import argparse import importlib from pathlib import Path # Test all the extensions added in the setup lowerCamelCase : Any = [ 'kernels/rwkv/wkv_cuda.cu', 'kernels/rwkv/wkv_op.cpp', 'kernels/deformable_detr/ms_deform_attn.h', 'kernels/deformable_detr/cuda/ms_deform_im2col_cuda.cuh', 'models/graphormer/algos_graphormer.pyx', ] def SCREAMING_SNAKE_CASE__ ( lowercase ) -> str: # Test all the extensions added in the setup for file in FILES_TO_FIND: if not (transformers_path / file).exists(): return False return True if __name__ == "__main__": lowerCamelCase : Tuple = argparse.ArgumentParser() parser.add_argument('--check_lib', action='store_true', help='Whether to check the build or the actual package.') lowerCamelCase : int = parser.parse_args() if args.check_lib: lowerCamelCase : Optional[int] = importlib.import_module('transformers') lowerCamelCase : List[str] = Path(transformers_module.__file__).parent else: lowerCamelCase : Optional[int] = Path.cwd() / 'build/lib/transformers' if not test_custom_files_are_present(transformers_path): raise ValueError('The built release does not contain the custom files. Fix this before going further!')
124
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _snake_case = { '''configuration_clap''': [ '''CLAP_PRETRAINED_MODEL_ARCHIVE_LIST''', '''ClapAudioConfig''', '''ClapConfig''', '''ClapTextConfig''', ], '''processing_clap''': ['''ClapProcessor'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _snake_case = [ '''CLAP_PRETRAINED_MODEL_ARCHIVE_LIST''', '''ClapModel''', '''ClapPreTrainedModel''', '''ClapTextModel''', '''ClapTextModelWithProjection''', '''ClapAudioModel''', '''ClapAudioModelWithProjection''', ] _snake_case = ['''ClapFeatureExtractor'''] if TYPE_CHECKING: from .configuration_clap import ( CLAP_PRETRAINED_MODEL_ARCHIVE_LIST, ClapAudioConfig, ClapConfig, ClapTextConfig, ) from .processing_clap import ClapProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_clap import ClapFeatureExtractor from .modeling_clap import ( CLAP_PRETRAINED_MODEL_ARCHIVE_LIST, ClapAudioModel, ClapAudioModelWithProjection, ClapModel, ClapPreTrainedModel, ClapTextModel, ClapTextModelWithProjection, ) else: import sys _snake_case = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
354
from ...configuration_utils import PretrainedConfig from ...utils import logging _snake_case = logging.get_logger(__name__) _snake_case = { "MIT/ast-finetuned-audioset-10-10-0.4593": ( "https://huggingface.co/MIT/ast-finetuned-audioset-10-10-0.4593/resolve/main/config.json" ), } class lowercase ( UpperCamelCase__ ): _a = "audio-spectrogram-transformer" def __init__( self , _a=768 , _a=12 , _a=12 , _a=3072 , _a="gelu" , _a=0.0 , _a=0.0 , _a=0.02 , _a=1e-12 , _a=16 , _a=True , _a=10 , _a=10 , _a=1024 , _a=128 , **_a , ) -> List[Any]: super().__init__(**_a ) _A : Any = hidden_size _A : Tuple = num_hidden_layers _A : List[str] = num_attention_heads _A : Any = intermediate_size _A : Optional[Any] = hidden_act _A : Optional[Any] = hidden_dropout_prob _A : Any = attention_probs_dropout_prob _A : Optional[Any] = initializer_range _A : Optional[Any] = layer_norm_eps _A : str = patch_size _A : Tuple = qkv_bias _A : Dict = frequency_stride _A : Union[str, Any] = time_stride _A : Any = max_length _A : Tuple = num_mel_bins
343
0
from collections import namedtuple import requests from lxml import html # type: ignore lowercase__ :int = namedtuple("covid_data", "cases deaths recovered") def UpperCamelCase ( lowerCAmelCase__ = "https://www.worldometers.info/coronavirus/" ): '''simple docstring''' lowercase = '''//div[@class = "maincounter-number"]/span/text()''' return covid_data(*html.fromstring(requests.get(lowerCAmelCase__ ).content ).xpath(lowerCAmelCase__ ) ) lowercase__ :str = "Total COVID-19 cases in the world: {}\nTotal deaths due to COVID-19 in the world: {}\nTotal COVID-19 patients recovered in the world: {}" print(fmt.format(*covid_stats()))
101
import unittest from transformers import SPIECE_UNDERLINE, XLNetTokenizer, XLNetTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin lowercase__ :List[Any] = get_tests_dir("fixtures/test_sentencepiece.model") @require_sentencepiece @require_tokenizers class lowercase ( SCREAMING_SNAKE_CASE__ , unittest.TestCase ): lowercase_ : str =XLNetTokenizer lowercase_ : Dict =XLNetTokenizerFast lowercase_ : str =True lowercase_ : str =True def A__ ( self): super().setUp() # We have a SentencePiece fixture for testing lowercase = XLNetTokenizer(A__ ,keep_accents=A__) tokenizer.sanitize_special_tokens() tokenizer.save_pretrained(self.tmpdirname) def A__ ( self): lowercase = '''<s>''' lowercase = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(A__) ,A__) self.assertEqual(self.get_tokenizer()._convert_id_to_token(A__) ,A__) def A__ ( self): lowercase = list(self.get_tokenizer().get_vocab().keys()) self.assertEqual(vocab_keys[0] ,'''<unk>''') self.assertEqual(vocab_keys[1] ,'''<s>''') self.assertEqual(vocab_keys[-1] ,'''<eod>''') self.assertEqual(len(A__) ,1_0_0_6) def A__ ( self): self.assertEqual(self.get_tokenizer().vocab_size ,1_0_0_0) def A__ ( self): lowercase = XLNetTokenizer(A__ ,keep_accents=A__) lowercase = tokenizer.tokenize('''This is a test''') self.assertListEqual(A__ ,['''▁This''', '''▁is''', '''▁a''', '''▁t''', '''est''']) self.assertListEqual(tokenizer.convert_tokens_to_ids(A__) ,[2_8_5, 4_6, 1_0, 1_7_0, 3_8_2]) lowercase = 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''', '''é''', '''.''', ] ,) lowercase = tokenizer.convert_tokens_to_ids(A__) self.assertListEqual(A__ ,[8, 2_1, 8_4, 5_5, 2_4, 1_9, 7, 0, 6_0_2, 3_4_7, 3_4_7, 3_4_7, 3, 1_2, 6_6, 4_6, 7_2, 8_0, 6, 0, 4]) lowercase = 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>''', '''.''', ] ,) def A__ ( self): lowercase = XLNetTokenizer(A__ ,do_lower_case=A__) lowercase = 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''', '''se''', '''.''', ] ,) self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''') ,['''▁he''', '''ll''', '''o''']) def A__ ( self): lowercase = XLNetTokenizer(A__ ,do_lower_case=A__) lowercase = 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''', '''se''', '''.''', ] ,) @slow def A__ ( self): lowercase = XLNetTokenizer.from_pretrained('''xlnet-base-cased''') lowercase = tokenizer.encode('''sequence builders''' ,add_special_tokens=A__) lowercase = tokenizer.encode('''multi-sequence build''' ,add_special_tokens=A__) lowercase = tokenizer.build_inputs_with_special_tokens(A__) lowercase = tokenizer.build_inputs_with_special_tokens(A__ ,A__) assert encoded_sentence == text + [4, 3] assert encoded_pair == text + [4] + text_a + [4, 3] @slow def A__ ( self): # fmt: off lowercase = {'''input_ids''': [[1_7, 2_1_4_4_2, 2_7_0, 1_7, 1_0, 1_4_6_4_5, 3_1_8, 3_4, 1_7, 4_5_4_6, 3_1_4_5, 7_8_7, 1_3, 7_7_5_2, 2_2_0_1_8, 2_3, 2_1, 1_7, 4_5_4_6, 3_1_4_5, 7_8_7, 1_3, 3_3_5_2, 1_4_4_3_1, 1_3, 5_5_0_0, 1_1, 1_1_7_6, 5_8_0, 1_3, 1_6_8_1_9, 4_7_9_7, 2_3, 1_7, 1_0, 1_7_1_3_5, 6_5_8, 1_9, 4_5_7, 7_9_3_2, 1_3, 1_8_4, 1_9, 3_1_5_4, 1_7_1_3_5, 6_4_6_8, 1_9, 1_4_0_4, 1_2_2_6_9, 1_9, 4_2_2_9, 5_3_5_6, 1_6_2_6_4, 4_6, 1_9, 1_7, 2_0_5_4_5, 1_0_3_9_5, 9, 9, 9, 1_1, 2_8, 6_4_2_1, 9_5_3_1, 2_0_7_2_9, 1_7, 1_0, 3_5_3, 1_7_0_2_2, 1_1, 2_1, 6_4_2_1, 9_5_3_1, 1_6_9_4_9, 1_7, 1_0, 1_1_5_0_9, 7_5_3, 1_1, 3_3, 9_5, 2_4_2_1, 7_3_8_5, 9_5_6, 1_4_4_3_1, 2_6_2_6, 2_5, 8_4_2, 7_3_8_5, 4_8_3_6, 2_1, 1_4_2_9, 2_2_7_2, 9_8_5_5, 3_1_2_0, 1_6_1, 2_4_7_3_8, 1_9, 1_3_2_0_3, 6_5_8, 2_1_8, 7_8_7, 2_1, 4_3_0, 1_8_4_8_2, 8_4_7, 2_6_3_7, 9, 4, 3], [5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 3_2_2, 2_2_1_7_8, 2_7, 1_0_6_4, 2_2, 9_5_6, 1_3, 1_1_1_0_1, 1_4_2_9, 5_8_5_4, 2_4_3_1_3, 1_8_9_5_3, 4_0, 4_2_2, 2_4_3_6_6, 6_8, 1_7_5_8, 3_7, 1_0_4_8_3, 1_4_2_5_7, 3_1, 2_0_7, 2_6_3, 2_1, 2_0_3, 3_7_7_3, 2_5, 7_1, 9_7_3_5, 9, 4, 3], [5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 3_2, 2_0_4_9, 3_4_4_2, 1_7, 1_3_8_9_4, 3_3_8_0, 2_3, 9_5, 1_8, 1_7_6_3_4, 2_2_8_8, 9, 4, 3]], '''token_type_ids''': [[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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2], [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 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, 2], [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2]], '''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], [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, 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, 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]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=A__ ,model_name='''xlnet-base-cased''' ,revision='''c841166438c31ec7ca9a106dee7bb312b73ae511''' ,)
101
1
"""simple docstring""" _a : str = frozenset( [ 'prompt', 'height', 'width', 'guidance_scale', 'negative_prompt', 'prompt_embeds', 'negative_prompt_embeds', 'cross_attention_kwargs', ] ) _a : Any = frozenset(['prompt', 'negative_prompt']) _a : str = frozenset([]) _a : Optional[Any] = frozenset(['image']) _a : List[str] = frozenset( [ 'image', 'height', 'width', 'guidance_scale', ] ) _a : List[str] = frozenset(['image']) _a : int = frozenset( [ 'prompt', 'image', 'height', 'width', 'guidance_scale', 'negative_prompt', 'prompt_embeds', 'negative_prompt_embeds', ] ) _a : Optional[int] = frozenset(['prompt', 'image', 'negative_prompt']) _a : Optional[Any] = frozenset( [ # Text guided image variation with an image mask 'prompt', 'image', 'mask_image', 'height', 'width', 'guidance_scale', 'negative_prompt', 'prompt_embeds', 'negative_prompt_embeds', ] ) _a : Tuple = frozenset(['prompt', 'image', 'mask_image', 'negative_prompt']) _a : List[Any] = frozenset( [ # image variation with an image mask 'image', 'mask_image', 'height', 'width', 'guidance_scale', ] ) _a : int = frozenset(['image', 'mask_image']) _a : Optional[int] = frozenset( [ 'example_image', 'image', 'mask_image', 'height', 'width', 'guidance_scale', ] ) _a : List[str] = frozenset(['example_image', 'image', 'mask_image']) _a : Any = frozenset(['class_labels']) _a : Union[str, Any] = frozenset(['class_labels']) _a : Any = frozenset(['batch_size']) _a : List[Any] = frozenset([]) _a : Optional[int] = frozenset(['batch_size']) _a : List[str] = frozenset([]) _a : int = frozenset( [ 'prompt', 'audio_length_in_s', 'guidance_scale', 'negative_prompt', 'prompt_embeds', 'negative_prompt_embeds', 'cross_attention_kwargs', ] ) _a : Optional[int] = frozenset(['prompt', 'negative_prompt']) _a : int = frozenset(['input_tokens']) _a : List[str] = frozenset(['input_tokens'])
363
"""simple docstring""" from __future__ import annotations def SCREAMING_SNAKE_CASE ( _lowerCamelCase : list ) -> float: if not nums: raise ValueError("""List is empty""" ) return sum(_lowerCamelCase ) / len(_lowerCamelCase ) if __name__ == "__main__": import doctest doctest.testmod()
126
0
"""simple docstring""" def lowercase (_lowerCAmelCase ): if len(_lowerCAmelCase ) <= 1: return lst __lowerCAmelCase = 1 while i < len(_lowerCAmelCase ): if lst[i - 1] <= lst[i]: i += 1 else: __lowerCAmelCase , __lowerCAmelCase = lst[i], lst[i - 1] i -= 1 if i == 0: __lowerCAmelCase = 1 return lst if __name__ == "__main__": SCREAMING_SNAKE_CASE_ = input('''Enter numbers separated by a comma:\n''').strip() SCREAMING_SNAKE_CASE_ = [int(item) for item in user_input.split(''',''')] print(gnome_sort(unsorted))
301
"""simple docstring""" from __future__ import annotations from statistics import mean def lowercase (_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ): __lowerCAmelCase = [0] * no_of_processes __lowerCAmelCase = [0] * no_of_processes # Initialize remaining_time to waiting_time. for i in range(_lowerCAmelCase ): __lowerCAmelCase = burst_time[i] __lowerCAmelCase = [] __lowerCAmelCase = 0 __lowerCAmelCase = 0 # When processes are not completed, # A process whose arrival time has passed \ # and has remaining execution time is put into the ready_process. # The shortest process in the ready_process, target_process is executed. while completed != no_of_processes: __lowerCAmelCase = [] __lowerCAmelCase = -1 for i in range(_lowerCAmelCase ): if (arrival_time[i] <= total_time) and (remaining_time[i] > 0): ready_process.append(_lowerCAmelCase ) if len(_lowerCAmelCase ) > 0: __lowerCAmelCase = ready_process[0] for i in ready_process: if remaining_time[i] < remaining_time[target_process]: __lowerCAmelCase = i total_time += burst_time[target_process] completed += 1 __lowerCAmelCase = 0 __lowerCAmelCase = ( total_time - arrival_time[target_process] - burst_time[target_process] ) else: total_time += 1 return waiting_time def lowercase (_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ): __lowerCAmelCase = [0] * no_of_processes for i in range(_lowerCAmelCase ): __lowerCAmelCase = burst_time[i] + waiting_time[i] return turn_around_time if __name__ == "__main__": print('''[TEST CASE 01]''') SCREAMING_SNAKE_CASE_ = 4 SCREAMING_SNAKE_CASE_ = [2, 5, 3, 7] SCREAMING_SNAKE_CASE_ = [0, 0, 0, 0] SCREAMING_SNAKE_CASE_ = calculate_waitingtime(arrival_time, burst_time, no_of_processes) SCREAMING_SNAKE_CASE_ = calculate_turnaroundtime( burst_time, no_of_processes, waiting_time ) # Printing the Result print('''PID\tBurst Time\tArrival Time\tWaiting Time\tTurnaround Time''') for i, process_id in enumerate(list(range(1, 5))): print( F"{process_id}\t{burst_time[i]}\t\t\t{arrival_time[i]}\t\t\t\t" F"{waiting_time[i]}\t\t\t\t{turn_around_time[i]}" ) print(F"\nAverage waiting time = {mean(waiting_time):.5f}") print(F"Average turnaround time = {mean(turn_around_time):.5f}")
301
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available _SCREAMING_SNAKE_CASE = { """configuration_poolformer""": [ """POOLFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP""", """PoolFormerConfig""", """PoolFormerOnnxConfig""", ] } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE = ["""PoolFormerFeatureExtractor"""] _SCREAMING_SNAKE_CASE = ["""PoolFormerImageProcessor"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE = [ """POOLFORMER_PRETRAINED_MODEL_ARCHIVE_LIST""", """PoolFormerForImageClassification""", """PoolFormerModel""", """PoolFormerPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_poolformer import ( POOLFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, PoolFormerConfig, PoolFormerOnnxConfig, ) try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_poolformer import PoolFormerFeatureExtractor from .image_processing_poolformer import PoolFormerImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_poolformer import ( POOLFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, PoolFormerForImageClassification, PoolFormerModel, PoolFormerPreTrainedModel, ) else: import sys _SCREAMING_SNAKE_CASE = _LazyModule(__name__, globals()["""__file__"""], _import_structure)
359
def lowercase( UpperCamelCase_ ) -> list[list]: '''simple docstring''' UpperCamelCase = current_set.copy() for row_index, row in enumerate(UpperCamelCase_ ): UpperCamelCase = row[0] for column_index, column in enumerate(UpperCamelCase_ ): if magnitude == 0: UpperCamelCase = column continue UpperCamelCase = column / magnitude # Subtract to cancel term UpperCamelCase = current_set[0] UpperCamelCase = [first_row] UpperCamelCase = current_set[1::] for row in current_set: UpperCamelCase = [] # If first term is 0, it is already in form we want, so we preserve it if row[0] == 0: final_set.append(UpperCamelCase_ ) continue for column_index in range(len(UpperCamelCase_ ) ): temp_row.append(first_row[column_index] - row[column_index] ) final_set.append(UpperCamelCase_ ) # Create next recursion iteration set if len(final_set[0] ) != 3: UpperCamelCase = final_set[0] UpperCamelCase = [] UpperCamelCase = [] for row in final_set[1::]: current_first_column.append(row[0] ) next_iteration.append(row[1::] ) UpperCamelCase = simplify(UpperCamelCase_ ) for i in range(len(UpperCamelCase_ ) ): resultant[i].insert(0 , current_first_column[i] ) resultant.insert(0 , UpperCamelCase_ ) UpperCamelCase = resultant return final_set def lowercase( UpperCamelCase_ ) -> list: '''simple docstring''' if len(UpperCamelCase_ ) == 0: raise IndexError("""solve_simultaneous() requires n lists of length n+1""" ) UpperCamelCase = len(UpperCamelCase_ ) + 1 if any(len(UpperCamelCase_ ) != _length for item in equations ): raise IndexError("""solve_simultaneous() requires n lists of length n+1""" ) for row in equations: if any(not isinstance(UpperCamelCase_ , (int, float) ) for column in row ): raise ValueError("""solve_simultaneous() requires lists of integers""" ) if len(UpperCamelCase_ ) == 1: return [equations[0][-1] / equations[0][0]] UpperCamelCase = equations.copy() if any(0 in row for row in data_set ): UpperCamelCase = data_set.copy() UpperCamelCase = [] for row_index, row in enumerate(UpperCamelCase_ ): if 0 not in row: UpperCamelCase = data_set.pop(UpperCamelCase_ ) break if not full_row: raise ValueError("""solve_simultaneous() requires at least 1 full equation""" ) data_set.insert(0 , UpperCamelCase_ ) UpperCamelCase = data_set.copy() UpperCamelCase = simplify(UpperCamelCase_ ) UpperCamelCase = simplified[::-1] UpperCamelCase = [] for row in simplified: UpperCamelCase = row[-1] if not solutions: if row[-2] == 0: solutions.append(0 ) continue solutions.append(current_solution / row[-2] ) continue UpperCamelCase = row.copy()[: len(UpperCamelCase_ ) - 1 :] while temp_row[0] == 0: temp_row.pop(0 ) if len(UpperCamelCase_ ) == 0: solutions.append(0 ) continue UpperCamelCase = temp_row[1::] UpperCamelCase = temp_row[::-1] for column_index, column in enumerate(UpperCamelCase_ ): current_solution -= column * solutions[column_index] solutions.append(UpperCamelCase_ ) UpperCamelCase = [] for item in solutions: final.append(float(round(UpperCamelCase_ , 5 ) ) ) return final[::-1] if __name__ == "__main__": import doctest doctest.testmod() _SCREAMING_SNAKE_CASE = [ [2, 1, 1, 1, 1, 4], [1, 2, 1, 1, 1, 5], [1, 1, 2, 1, 1, 6], [1, 1, 1, 2, 1, 7], [1, 1, 1, 1, 2, 8], ] print(solve_simultaneous(eq)) print(solve_simultaneous([[4, 2]]))
165
0
from abc import ABC, abstractmethod from argparse import ArgumentParser class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' @staticmethod @abstractmethod def SCREAMING_SNAKE_CASE_ (UpperCAmelCase_ : ArgumentParser) ->int: '''simple docstring''' raise NotImplementedError() @abstractmethod def SCREAMING_SNAKE_CASE_ (self : int) ->Tuple: '''simple docstring''' raise NotImplementedError()
10
"""simple docstring""" from typing import Optional, Tuple, Union import flax import flax.linen as nn import jax import jax.numpy as jnp from flax.core.frozen_dict import FrozenDict from ..configuration_utils import ConfigMixin, flax_register_to_config from ..utils import BaseOutput from .embeddings_flax import FlaxTimestepEmbedding, FlaxTimesteps from .modeling_flax_utils import FlaxModelMixin from .unet_ad_blocks_flax import ( FlaxCrossAttnDownBlockaD, FlaxDownBlockaD, FlaxUNetMidBlockaDCrossAttn, ) @flax.struct.dataclass class lowercase__ ( snake_case__ ): _UpperCAmelCase :jnp.ndarray _UpperCAmelCase :jnp.ndarray class lowercase__ ( nn.Module ): _UpperCAmelCase :int _UpperCAmelCase :Tuple[int] = (16, 32, 96, 256) _UpperCAmelCase :jnp.dtype = jnp.floataa def UpperCAmelCase__ ( self : List[Any] ): lowerCamelCase_ : Optional[int] =nn.Conv( self.block_out_channels[0] , kernel_size=(3, 3) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) lowerCamelCase_ : Any =[] for i in range(len(self.block_out_channels ) - 1 ): lowerCamelCase_ : Union[str, Any] =self.block_out_channels[i] lowerCamelCase_ : Any =self.block_out_channels[i + 1] lowerCamelCase_ : List[str] =nn.Conv( snake_case__ , kernel_size=(3, 3) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) blocks.append(snake_case__ ) lowerCamelCase_ : List[str] =nn.Conv( snake_case__ , kernel_size=(3, 3) , strides=(2, 2) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) blocks.append(snake_case__ ) lowerCamelCase_ : Union[str, Any] =blocks lowerCamelCase_ : Optional[Any] =nn.Conv( self.conditioning_embedding_channels , kernel_size=(3, 3) , padding=((1, 1), (1, 1)) , kernel_init=nn.initializers.zeros_init() , bias_init=nn.initializers.zeros_init() , dtype=self.dtype , ) def __call__( self : Tuple , snake_case__ : Union[str, Any] ): lowerCamelCase_ : int =self.conv_in(snake_case__ ) lowerCamelCase_ : List[Any] =nn.silu(snake_case__ ) for block in self.blocks: lowerCamelCase_ : Union[str, Any] =block(snake_case__ ) lowerCamelCase_ : List[str] =nn.silu(snake_case__ ) lowerCamelCase_ : Tuple =self.conv_out(snake_case__ ) return embedding @flax_register_to_config class lowercase__ ( nn.Module, snake_case__, snake_case__ ): _UpperCAmelCase :int = 32 _UpperCAmelCase :int = 4 _UpperCAmelCase :Tuple[str] = ( "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "DownBlock2D", ) _UpperCAmelCase :Union[bool, Tuple[bool]] = False _UpperCAmelCase :Tuple[int] = (320, 640, 1280, 1280) _UpperCAmelCase :int = 2 _UpperCAmelCase :Union[int, Tuple[int]] = 8 _UpperCAmelCase :Optional[Union[int, Tuple[int]]] = None _UpperCAmelCase :int = 1280 _UpperCAmelCase :float = 0.0 _UpperCAmelCase :bool = False _UpperCAmelCase :jnp.dtype = jnp.floataa _UpperCAmelCase :bool = True _UpperCAmelCase :int = 0 _UpperCAmelCase :str = "rgb" _UpperCAmelCase :Tuple[int] = (16, 32, 96, 256) def UpperCAmelCase__ ( self : int , snake_case__ : jax.random.KeyArray ): # init input tensors lowerCamelCase_ : str =(1, self.in_channels, self.sample_size, self.sample_size) lowerCamelCase_ : List[Any] =jnp.zeros(snake_case__ , dtype=jnp.floataa ) lowerCamelCase_ : int =jnp.ones((1,) , dtype=jnp.intaa ) lowerCamelCase_ : Union[str, Any] =jnp.zeros((1, 1, self.cross_attention_dim) , dtype=jnp.floataa ) lowerCamelCase_ : Optional[int] =(1, 3, self.sample_size * 8, self.sample_size * 8) lowerCamelCase_ : Any =jnp.zeros(snake_case__ , dtype=jnp.floataa ) lowerCamelCase_ , lowerCamelCase_ : Any =jax.random.split(snake_case__ ) lowerCamelCase_ : Tuple ={"params": params_rng, "dropout": dropout_rng} return self.init(snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ )["params"] def UpperCAmelCase__ ( self : List[Any] ): lowerCamelCase_ : Union[str, Any] =self.block_out_channels lowerCamelCase_ : Optional[int] =block_out_channels[0] * 4 # If `num_attention_heads` is not defined (which is the case for most models) # it will default to `attention_head_dim`. This looks weird upon first reading it and it is. # The reason for this behavior is to correct for incorrectly named variables that were introduced # when this library was created. The incorrect naming was only discovered much later in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131 # Changing `attention_head_dim` to `num_attention_heads` for 40,000+ configurations is too backwards breaking # which is why we correct for the naming here. lowerCamelCase_ : int =self.num_attention_heads or self.attention_head_dim # input lowerCamelCase_ : Any =nn.Conv( block_out_channels[0] , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) # time lowerCamelCase_ : Union[str, Any] =FlaxTimesteps( block_out_channels[0] , flip_sin_to_cos=self.flip_sin_to_cos , freq_shift=self.config.freq_shift ) lowerCamelCase_ : List[Any] =FlaxTimestepEmbedding(snake_case__ , dtype=self.dtype ) lowerCamelCase_ : List[str] =FlaxControlNetConditioningEmbedding( conditioning_embedding_channels=block_out_channels[0] , block_out_channels=self.conditioning_embedding_out_channels , ) lowerCamelCase_ : Optional[int] =self.only_cross_attention if isinstance(snake_case__ , snake_case__ ): lowerCamelCase_ : str =(only_cross_attention,) * len(self.down_block_types ) if isinstance(snake_case__ , snake_case__ ): lowerCamelCase_ : Any =(num_attention_heads,) * len(self.down_block_types ) # down lowerCamelCase_ : Optional[int] =[] lowerCamelCase_ : Optional[Any] =[] lowerCamelCase_ : str =block_out_channels[0] lowerCamelCase_ : str =nn.Conv( snake_case__ , kernel_size=(1, 1) , padding="VALID" , kernel_init=nn.initializers.zeros_init() , bias_init=nn.initializers.zeros_init() , dtype=self.dtype , ) controlnet_down_blocks.append(snake_case__ ) for i, down_block_type in enumerate(self.down_block_types ): lowerCamelCase_ : Union[str, Any] =output_channel lowerCamelCase_ : Tuple =block_out_channels[i] lowerCamelCase_ : List[Any] =i == len(snake_case__ ) - 1 if down_block_type == "CrossAttnDownBlock2D": lowerCamelCase_ : Tuple =FlaxCrossAttnDownBlockaD( in_channels=snake_case__ , out_channels=snake_case__ , dropout=self.dropout , num_layers=self.layers_per_block , num_attention_heads=num_attention_heads[i] , add_downsample=not is_final_block , use_linear_projection=self.use_linear_projection , only_cross_attention=only_cross_attention[i] , dtype=self.dtype , ) else: lowerCamelCase_ : Union[str, Any] =FlaxDownBlockaD( in_channels=snake_case__ , out_channels=snake_case__ , dropout=self.dropout , num_layers=self.layers_per_block , add_downsample=not is_final_block , dtype=self.dtype , ) down_blocks.append(snake_case__ ) for _ in range(self.layers_per_block ): lowerCamelCase_ : List[Any] =nn.Conv( snake_case__ , kernel_size=(1, 1) , padding="VALID" , kernel_init=nn.initializers.zeros_init() , bias_init=nn.initializers.zeros_init() , dtype=self.dtype , ) controlnet_down_blocks.append(snake_case__ ) if not is_final_block: lowerCamelCase_ : Any =nn.Conv( snake_case__ , kernel_size=(1, 1) , padding="VALID" , kernel_init=nn.initializers.zeros_init() , bias_init=nn.initializers.zeros_init() , dtype=self.dtype , ) controlnet_down_blocks.append(snake_case__ ) lowerCamelCase_ : List[str] =down_blocks lowerCamelCase_ : int =controlnet_down_blocks # mid lowerCamelCase_ : int =block_out_channels[-1] lowerCamelCase_ : str =FlaxUNetMidBlockaDCrossAttn( in_channels=snake_case__ , dropout=self.dropout , num_attention_heads=num_attention_heads[-1] , use_linear_projection=self.use_linear_projection , dtype=self.dtype , ) lowerCamelCase_ : List[str] =nn.Conv( snake_case__ , kernel_size=(1, 1) , padding="VALID" , kernel_init=nn.initializers.zeros_init() , bias_init=nn.initializers.zeros_init() , dtype=self.dtype , ) def __call__( self : Tuple , snake_case__ : Dict , snake_case__ : str , snake_case__ : Union[str, Any] , snake_case__ : int , snake_case__ : float = 1.0 , snake_case__ : bool = True , snake_case__ : bool = False , ): lowerCamelCase_ : int =self.controlnet_conditioning_channel_order if channel_order == "bgr": lowerCamelCase_ : Optional[Any] =jnp.flip(snake_case__ , axis=1 ) # 1. time if not isinstance(snake_case__ , jnp.ndarray ): lowerCamelCase_ : Dict =jnp.array([timesteps] , dtype=jnp.intaa ) elif isinstance(snake_case__ , jnp.ndarray ) and len(timesteps.shape ) == 0: lowerCamelCase_ : Any =timesteps.astype(dtype=jnp.floataa ) lowerCamelCase_ : Optional[Any] =jnp.expand_dims(snake_case__ , 0 ) lowerCamelCase_ : Any =self.time_proj(snake_case__ ) lowerCamelCase_ : Union[str, Any] =self.time_embedding(snake_case__ ) # 2. pre-process lowerCamelCase_ : List[str] =jnp.transpose(snake_case__ , (0, 2, 3, 1) ) lowerCamelCase_ : Union[str, Any] =self.conv_in(snake_case__ ) lowerCamelCase_ : List[str] =jnp.transpose(snake_case__ , (0, 2, 3, 1) ) lowerCamelCase_ : str =self.controlnet_cond_embedding(snake_case__ ) sample += controlnet_cond # 3. down lowerCamelCase_ : List[str] =(sample,) for down_block in self.down_blocks: if isinstance(snake_case__ , snake_case__ ): lowerCamelCase_ , lowerCamelCase_ : Union[str, Any] =down_block(snake_case__ , snake_case__ , snake_case__ , deterministic=not train ) else: lowerCamelCase_ , lowerCamelCase_ : Optional[int] =down_block(snake_case__ , snake_case__ , deterministic=not train ) down_block_res_samples += res_samples # 4. mid lowerCamelCase_ : Optional[int] =self.mid_block(snake_case__ , snake_case__ , snake_case__ , deterministic=not train ) # 5. contronet blocks lowerCamelCase_ : Dict =() for down_block_res_sample, controlnet_block in zip(snake_case__ , self.controlnet_down_blocks ): lowerCamelCase_ : Dict =controlnet_block(snake_case__ ) controlnet_down_block_res_samples += (down_block_res_sample,) lowerCamelCase_ : List[Any] =controlnet_down_block_res_samples lowerCamelCase_ : Tuple =self.controlnet_mid_block(snake_case__ ) # 6. scaling lowerCamelCase_ : Dict =[sample * conditioning_scale for sample in down_block_res_samples] mid_block_res_sample *= conditioning_scale if not return_dict: return (down_block_res_samples, mid_block_res_sample) return FlaxControlNetOutput( down_block_res_samples=snake_case__ , mid_block_res_sample=snake_case__ )
144
0
"""simple docstring""" from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging UpperCAmelCase = logging.get_logger(__name__) UpperCAmelCase = { '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 UpperCAmelCase_ ( _lowerCamelCase): snake_case__ = '''deit''' def __init__( self : Optional[int] , __UpperCamelCase : List[Any]=768 , __UpperCamelCase : int=12 , __UpperCamelCase : List[str]=12 , __UpperCamelCase : Optional[Any]=3072 , __UpperCamelCase : List[str]="gelu" , __UpperCamelCase : Dict=0.0 , __UpperCamelCase : List[Any]=0.0 , __UpperCamelCase : str=0.0_2 , __UpperCamelCase : Optional[int]=1E-12 , __UpperCamelCase : Any=224 , __UpperCamelCase : Dict=16 , __UpperCamelCase : int=3 , __UpperCamelCase : List[str]=True , __UpperCamelCase : str=16 , **__UpperCamelCase : Any , ) -> Any: super().__init__(**__UpperCamelCase ) _UpperCamelCase = hidden_size _UpperCamelCase = num_hidden_layers _UpperCamelCase = num_attention_heads _UpperCamelCase = intermediate_size _UpperCamelCase = hidden_act _UpperCamelCase = hidden_dropout_prob _UpperCamelCase = attention_probs_dropout_prob _UpperCamelCase = initializer_range _UpperCamelCase = layer_norm_eps _UpperCamelCase = image_size _UpperCamelCase = patch_size _UpperCamelCase = num_channels _UpperCamelCase = qkv_bias _UpperCamelCase = encoder_stride class UpperCAmelCase_ ( _lowerCamelCase): snake_case__ = version.parse('''1.11''') @property def _UpperCamelCase ( self : Optional[Any] ) -> List[Any]: return OrderedDict( [ ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}), ] ) @property def _UpperCamelCase ( self : List[str] ) -> List[str]: return 1E-4
352
"""simple docstring""" import qiskit def lowercase ( a__ : int = 2 ) -> qiskit.result.counts.Counts: _UpperCamelCase = qubits # Using Aer's simulator _UpperCamelCase = qiskit.Aer.get_backend('''aer_simulator''' ) # Creating a Quantum Circuit acting on the q register _UpperCamelCase = qiskit.QuantumCircuit(a__ , a__ ) # Adding a H gate on qubit 0 (now q0 in superposition) circuit.h(0 ) for i in range(1 , a__ ): # Adding CX (CNOT) gate circuit.cx(i - 1 , a__ ) # Mapping the quantum measurement to the classical bits circuit.measure(list(range(a__ ) ) , list(range(a__ ) ) ) # Now measuring any one qubit would affect other qubits to collapse # their super position and have same state as the measured one. # Executing the circuit on the simulator _UpperCamelCase = qiskit.execute(a__ , a__ , shots=1000 ) return job.result().get_counts(a__ ) if __name__ == "__main__": print(F'''Total count for various states are: {quantum_entanglement(3)}''')
54
0
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging _SCREAMING_SNAKE_CASE : Union[str, Any] = logging.get_logger(__name__) _SCREAMING_SNAKE_CASE : List[Any] = { "camembert-base": "https://huggingface.co/camembert-base/resolve/main/config.json", "umberto-commoncrawl-cased-v1": ( "https://huggingface.co/Musixmatch/umberto-commoncrawl-cased-v1/resolve/main/config.json" ), "umberto-wikipedia-uncased-v1": ( "https://huggingface.co/Musixmatch/umberto-wikipedia-uncased-v1/resolve/main/config.json" ), } class A__ ( snake_case__ ): """simple docstring""" __magic_name__ = 'camembert' def __init__( self , __snake_case=3_0_5_2_2 , __snake_case=7_6_8 , __snake_case=1_2 , __snake_case=1_2 , __snake_case=3_0_7_2 , __snake_case="gelu" , __snake_case=0.1 , __snake_case=0.1 , __snake_case=5_1_2 , __snake_case=2 , __snake_case=0.02 , __snake_case=1E-12 , __snake_case=1 , __snake_case=0 , __snake_case=2 , __snake_case="absolute" , __snake_case=True , __snake_case=None , **__snake_case , ): super().__init__(pad_token_id=__snake_case , bos_token_id=__snake_case , eos_token_id=__snake_case , **__snake_case ) snake_case = vocab_size snake_case = hidden_size snake_case = num_hidden_layers snake_case = num_attention_heads snake_case = hidden_act snake_case = intermediate_size snake_case = hidden_dropout_prob snake_case = attention_probs_dropout_prob snake_case = max_position_embeddings snake_case = type_vocab_size snake_case = initializer_range snake_case = layer_norm_eps snake_case = position_embedding_type snake_case = use_cache snake_case = classifier_dropout class A__ ( snake_case__ ): """simple docstring""" @property def a_ ( self ): if self.task == "multiple-choice": snake_case = {0: '''batch''', 1: '''choice''', 2: '''sequence'''} else: snake_case = {0: '''batch''', 1: '''sequence'''} return OrderedDict( [ ('''input_ids''', dynamic_axis), ('''attention_mask''', dynamic_axis), ] )
127
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 _SCREAMING_SNAKE_CASE : List[Any] = logging.get_logger(__name__) _SCREAMING_SNAKE_CASE : Optional[Any] = { "google/mobilenet_v2_1.4_224": "https://huggingface.co/google/mobilenet_v2_1.4_224/resolve/main/config.json", "google/mobilenet_v2_1.0_224": "https://huggingface.co/google/mobilenet_v2_1.0_224/resolve/main/config.json", "google/mobilenet_v2_0.75_160": "https://huggingface.co/google/mobilenet_v2_0.75_160/resolve/main/config.json", "google/mobilenet_v2_0.35_96": "https://huggingface.co/google/mobilenet_v2_0.35_96/resolve/main/config.json", # See all MobileNetV2 models at https://huggingface.co/models?filter=mobilenet_v2 } class A__ ( snake_case__ ): """simple docstring""" __magic_name__ = 'mobilenet_v2' def __init__( self , __snake_case=3 , __snake_case=2_2_4 , __snake_case=1.0 , __snake_case=8 , __snake_case=8 , __snake_case=6 , __snake_case=3_2 , __snake_case=True , __snake_case=True , __snake_case="relu6" , __snake_case=True , __snake_case=0.8 , __snake_case=0.02 , __snake_case=0.001 , __snake_case=2_5_5 , **__snake_case , ): super().__init__(**__snake_case ) if depth_multiplier <= 0: raise ValueError('''depth_multiplier must be greater than zero.''' ) snake_case = num_channels snake_case = image_size snake_case = depth_multiplier snake_case = depth_divisible_by snake_case = min_depth snake_case = expand_ratio snake_case = output_stride snake_case = first_layer_is_expansion snake_case = finegrained_output snake_case = hidden_act snake_case = tf_padding snake_case = classifier_dropout_prob snake_case = initializer_range snake_case = layer_norm_eps snake_case = semantic_loss_ignore_index class A__ ( snake_case__ ): """simple docstring""" __magic_name__ = version.parse('1.11' ) @property def a_ ( self ): return OrderedDict([('''pixel_values''', {0: '''batch'''})] ) @property def a_ ( self ): if self.task == "image-classification": return OrderedDict([('''logits''', {0: '''batch'''})] ) else: return OrderedDict([('''last_hidden_state''', {0: '''batch'''}), ('''pooler_output''', {0: '''batch'''})] ) @property def a_ ( self ): return 1E-4
127
1
def lowerCamelCase__ ( a = 50 ) -> int: _A: int = [1] * (length + 1) for row_length in range(length + 1 ): for tile_length in range(2 , 5 ): for tile_start in range(row_length - tile_length + 1 ): ways_number[row_length] += ways_number[ row_length - tile_start - tile_length ] return ways_number[length] if __name__ == "__main__": print(F"""{solution() = }""")
301
from __future__ import annotations import unittest from transformers import AutoTokenizer, MBartConfig, is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFAutoModelForSeqaSeqLM, TFMBartForConditionalGeneration, TFMBartModel @require_tf class UpperCAmelCase : '''simple docstring''' __UpperCamelCase : Any = MBartConfig __UpperCamelCase : Tuple = {} __UpperCamelCase : Dict = '''gelu''' def __init__( self : Dict , lowerCAmelCase_ : Optional[int] , lowerCAmelCase_ : List[Any]=1_3 , lowerCAmelCase_ : Dict=7 , lowerCAmelCase_ : Optional[Any]=True , lowerCAmelCase_ : Optional[Any]=False , lowerCAmelCase_ : Union[str, Any]=9_9 , lowerCAmelCase_ : Dict=3_2 , lowerCAmelCase_ : str=2 , lowerCAmelCase_ : int=4 , lowerCAmelCase_ : Union[str, Any]=3_7 , lowerCAmelCase_ : Dict=0.1 , lowerCAmelCase_ : str=0.1 , lowerCAmelCase_ : List[str]=2_0 , lowerCAmelCase_ : str=2 , lowerCAmelCase_ : Optional[int]=1 , lowerCAmelCase_ : List[Any]=0 , ): """simple docstring""" _A: Union[str, Any] = parent _A: List[Any] = batch_size _A: Dict = seq_length _A: Dict = is_training _A: str = use_labels _A: int = vocab_size _A: str = hidden_size _A: Tuple = num_hidden_layers _A: Optional[Any] = num_attention_heads _A: Tuple = intermediate_size _A: int = hidden_dropout_prob _A: Tuple = attention_probs_dropout_prob _A: Tuple = max_position_embeddings _A: Dict = eos_token_id _A: int = pad_token_id _A: Any = bos_token_id def __magic_name__ ( self : Dict ): """simple docstring""" _A: Optional[int] = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) _A: Dict = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 ) _A: List[Any] = tf.concat([input_ids, eos_tensor] , axis=1 ) _A: Dict = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _A: int = self.config_cls( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_ids=[2] , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.pad_token_id , **self.config_updates , ) _A: Any = prepare_mbart_inputs_dict(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) return config, inputs_dict def __magic_name__ ( self : Union[str, Any] , lowerCAmelCase_ : Optional[Any] , lowerCAmelCase_ : List[str] ): """simple docstring""" _A: Tuple = TFMBartModel(config=lowerCAmelCase_ ).get_decoder() _A: List[str] = inputs_dict['''input_ids'''] _A: Tuple = input_ids[:1, :] _A: List[Any] = inputs_dict['''attention_mask'''][:1, :] _A: str = inputs_dict['''head_mask'''] _A: Optional[Any] = 1 # first forward pass _A: Any = model(lowerCAmelCase_ , attention_mask=lowerCAmelCase_ , head_mask=lowerCAmelCase_ , use_cache=lowerCAmelCase_ ) _A , _A: List[str] = outputs.to_tuple() _A: Dict = past_key_values[1] def lowerCamelCase__ ( a , a , a , a=None , a=None , a=None , a=None , a=None , ) -> Tuple: if attention_mask is None: _A: Union[str, Any] = tf.cast(tf.math.not_equal(a , config.pad_token_id ) , tf.inta ) if decoder_attention_mask is None: _A: Optional[int] = tf.concat( [ tf.ones(decoder_input_ids[:, :1].shape , dtype=tf.inta ), tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:] , config.pad_token_id ) , tf.inta ), ] , axis=-1 , ) if head_mask is None: _A: Tuple = tf.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: _A: Union[str, Any] = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) if cross_attn_head_mask is None: _A: Optional[Any] = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, "cross_attn_head_mask": cross_attn_head_mask, } @require_tf class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , unittest.TestCase ): '''simple docstring''' __UpperCamelCase : Union[str, Any] = (TFMBartForConditionalGeneration, TFMBartModel) if is_tf_available() else () __UpperCamelCase : int = (TFMBartForConditionalGeneration,) if is_tf_available() else () __UpperCamelCase : Tuple = ( { '''conversational''': TFMBartForConditionalGeneration, '''feature-extraction''': TFMBartModel, '''summarization''': TFMBartForConditionalGeneration, '''text2text-generation''': TFMBartForConditionalGeneration, '''translation''': TFMBartForConditionalGeneration, } if is_tf_available() else {} ) __UpperCamelCase : List[Any] = True __UpperCamelCase : int = False __UpperCamelCase : Optional[Any] = False def __magic_name__ ( self : int , lowerCAmelCase_ : Optional[Any] , lowerCAmelCase_ : int , lowerCAmelCase_ : str , lowerCAmelCase_ : Tuple , lowerCAmelCase_ : int ): """simple docstring""" if pipeline_test_casse_name != "FeatureExtractionPipelineTests": # Exception encountered when calling layer '...' return True return False def __magic_name__ ( self : Any ): """simple docstring""" _A: Dict = TFMBartModelTester(self ) _A: Tuple = ConfigTester(self , config_class=lowerCAmelCase_ ) def __magic_name__ ( self : List[str] ): """simple docstring""" self.config_tester.run_common_tests() def __magic_name__ ( self : Optional[Any] ): """simple docstring""" _A: str = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*lowerCAmelCase_ ) @require_sentencepiece @require_tokenizers @require_tf class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' __UpperCamelCase : Optional[int] = [ ''' UN Chief Says There Is No Military Solution in Syria''', ] __UpperCamelCase : List[str] = [ '''Şeful ONU declară că nu există o soluţie militară în Siria''', ] __UpperCamelCase : Union[str, Any] = '''facebook/mbart-large-en-ro''' @cached_property def __magic_name__ ( self : Tuple ): """simple docstring""" return AutoTokenizer.from_pretrained(self.model_name ) @cached_property def __magic_name__ ( self : str ): """simple docstring""" _A: Union[str, Any] = TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name ) return model def __magic_name__ ( self : Union[str, Any] , **lowerCAmelCase_ : Tuple ): """simple docstring""" _A: Optional[Any] = self.translate_src_text(**lowerCAmelCase_ ) self.assertListEqual(self.expected_text , lowerCAmelCase_ ) def __magic_name__ ( self : Dict , **lowerCAmelCase_ : Tuple ): """simple docstring""" _A: Any = self.tokenizer(self.src_text , **lowerCAmelCase_ , return_tensors='''tf''' ) _A: Any = self.model.generate( model_inputs.input_ids , attention_mask=model_inputs.attention_mask , num_beams=2 ) _A: Optional[Any] = self.tokenizer.batch_decode(lowerCAmelCase_ , skip_special_tokens=lowerCAmelCase_ ) return generated_words @slow def __magic_name__ ( self : List[str] ): """simple docstring""" self._assert_generated_batch_equal_expected()
301
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available UpperCAmelCase__ : Optional[Any] = { 'configuration_timesformer': ['TIMESFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'TimesformerConfig'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ : List[Any] = [ 'TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'TimesformerModel', 'TimesformerForVideoClassification', 'TimesformerPreTrainedModel', ] if TYPE_CHECKING: from .configuration_timesformer import TIMESFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, TimesformerConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_timesformer import ( TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TimesformerForVideoClassification, TimesformerModel, TimesformerPreTrainedModel, ) else: import sys UpperCAmelCase__ : List[str] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
121
from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import Features, Sequence, Value from .base import TaskTemplate @dataclass(frozen=SCREAMING_SNAKE_CASE__ ) class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' # `task` is not a ClassVar since we want it to be part of the `asdict` output for JSON serialization __UpperCamelCase : str = field(default='''question-answering-extractive''' , metadata={'''include_in_asdict_even_if_is_default''': True} ) __UpperCamelCase : ClassVar[Features] = Features({'''question''': Value('''string''' ), '''context''': Value('''string''' )} ) __UpperCamelCase : ClassVar[Features] = Features( { '''answers''': Sequence( { '''text''': Value('''string''' ), '''answer_start''': Value('''int32''' ), } ) } ) __UpperCamelCase : str = "question" __UpperCamelCase : str = "context" __UpperCamelCase : str = "answers" @property def __magic_name__ ( self : List[str] ): """simple docstring""" return {self.question_column: "question", self.context_column: "context", self.answers_column: "answers"}
121
1
"""simple docstring""" def lowerCamelCase_ ( _lowerCamelCase , _lowerCamelCase ): if discount_rate < 0: raise ValueError('Discount rate cannot be negative' ) if not cash_flows: raise ValueError('Cash flows list cannot be empty' ) lowerCamelCase__ : str = 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()
316
"""simple docstring""" # Lint as: python3 # pylint: enable=line-too-long # pylint: disable=g-import-not-at-top,g-bad-import-order,wrong-import-position A_ : Union[str, Any] = "2.13.1" import platform import pyarrow from packaging import version if version.parse(platform.python_version()) < version.parse("3.7"): raise ImportWarning( "To use `datasets`, Python>=3.7 is required, and the current version of Python doesn't match this condition." ) if version.parse(pyarrow.__version__).major < 8: raise ImportWarning( "To use `datasets`, the module `pyarrow>=8.0.0` is required, and the current version of `pyarrow` doesn't match this condition.\n" "If you are running this in a Google Colab, you should probably just restart the runtime to use the right version of `pyarrow`." ) del platform del pyarrow del version from .arrow_dataset import Dataset from .arrow_reader import ReadInstruction from .builder import ArrowBasedBuilder, BeamBasedBuilder, BuilderConfig, DatasetBuilder, GeneratorBasedBuilder from .combine import concatenate_datasets, interleave_datasets from .dataset_dict import DatasetDict, IterableDatasetDict from .download import * from .features import * from .fingerprint import disable_caching, enable_caching, is_caching_enabled, set_caching_enabled from .info import DatasetInfo, MetricInfo from .inspect import ( get_dataset_config_info, get_dataset_config_names, get_dataset_infos, get_dataset_split_names, inspect_dataset, inspect_metric, list_datasets, list_metrics, ) from .iterable_dataset import IterableDataset from .load import load_dataset, load_dataset_builder, load_from_disk, load_metric from .metric import Metric from .splits import ( NamedSplit, NamedSplitAll, Split, SplitBase, SplitDict, SplitGenerator, SplitInfo, SubSplitInfo, percent, ) from .tasks import * from .utils import * from .utils import logging # deprecated modules from datasets import arrow_dataset as _arrow_dataset # isort:skip from datasets import utils as _utils # isort:skip from datasets.utils import download_manager as _deprecated_download_manager # isort:skip A_ : int = concatenate_datasets A_ : Any = DownloadConfig A_ : List[Any] = DownloadManager A_ : Optional[Any] = DownloadMode A_ : List[str] = DownloadConfig A_ : Optional[int] = DownloadMode A_ : Dict = DownloadManager del _arrow_dataset, _utils, _deprecated_download_manager
316
1
"""simple docstring""" from __future__ import annotations def __UpperCAmelCase ( __lowerCamelCase ) -> int: # preprocessing the first row for i in range(1 , len(matrix[0] ) ): matrix[0][i] += matrix[0][i - 1] # preprocessing the first column for i in range(1 , len(_SCREAMING_SNAKE_CASE ) ): matrix[i][0] += matrix[i - 1][0] # updating the path cost for current position for i in range(1 , len(_SCREAMING_SNAKE_CASE ) ): for j in range(1 , len(matrix[0] ) ): matrix[i][j] += min(matrix[i - 1][j] , matrix[i][j - 1] ) return matrix[-1][-1] if __name__ == "__main__": import doctest doctest.testmod()
16
"""simple docstring""" import argparse import json import os import fairseq import torch from fairseq.data import Dictionary from transformers import ( WavaVecaConfig, WavaVecaCTCTokenizer, WavaVecaFeatureExtractor, WavaVecaForCTC, WavaVecaForPreTraining, WavaVecaProcessor, logging, ) from transformers.models.wavaveca.modeling_wavaveca import WavaVecaForSequenceClassification logging.set_verbosity_info() __SCREAMING_SNAKE_CASE : Tuple = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE : Tuple = { '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', 'adapter_layer': 'encoder.layers.*.adapter_layer', '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': 'lm_head', 'mask_emb': 'masked_spec_embed', 'pooling_layer.linear': 'projector', 'pooling_layer.projection': 'classifier', } __SCREAMING_SNAKE_CASE : List[Any] = [ 'lm_head', 'quantizer.weight_proj', 'quantizer.codevectors', 'project_q', 'project_hid', 'projector', 'classifier', ] def _a ( _SCREAMING_SNAKE_CASE ) -> List[str]: snake_case_ = {} with open(_SCREAMING_SNAKE_CASE , """r""" ) as file: for line_number, line in enumerate(_SCREAMING_SNAKE_CASE ): snake_case_ = line.strip() if line: snake_case_ = line.split() snake_case_ = line_number snake_case_ = words[0] snake_case_ = value return result def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Tuple: for attribute in key.split(""".""" ): snake_case_ = getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) snake_case_ = None for param_key in PARAM_MAPPING.keys(): if full_name.endswith(_SCREAMING_SNAKE_CASE ): snake_case_ = PARAM_MAPPING[full_name.split(""".""" )[-1]] snake_case_ = """param""" if weight_type is not None and weight_type != "param": snake_case_ = getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ).shape elif weight_type is not None and weight_type == "param": snake_case_ = hf_pointer for attribute in hf_param_name.split(""".""" ): snake_case_ = getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) snake_case_ = shape_pointer.shape # let's reduce dimension snake_case_ = value[0] else: snake_case_ = hf_pointer.shape if hf_shape != value.shape: raise ValueError( 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": snake_case_ = value elif weight_type == "weight_g": snake_case_ = value elif weight_type == "weight_v": snake_case_ = value elif weight_type == "bias": snake_case_ = value elif weight_type == "param": for attribute in hf_param_name.split(""".""" ): snake_case_ = getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) snake_case_ = value else: snake_case_ = value logger.info(f"""{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.""" ) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Tuple: snake_case_ = None for param_key in PARAM_MAPPING.keys(): if full_name.endswith(_SCREAMING_SNAKE_CASE ): snake_case_ = PARAM_MAPPING[full_name.split(""".""" )[-1]] snake_case_ = """param""" if weight_type is not None and weight_type != "param": snake_case_ = """.""".join([key, weight_type] ) elif weight_type is not None and weight_type == "param": snake_case_ = """.""".join([key, hf_param_name] ) else: snake_case_ = key snake_case_ = value if """lm_head""" in full_key else value[0] __SCREAMING_SNAKE_CASE : int = { 'W_a': 'linear_1.weight', 'W_b': 'linear_2.weight', 'b_a': 'linear_1.bias', 'b_b': 'linear_2.bias', 'ln_W': 'norm.weight', 'ln_b': 'norm.bias', } def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None ) -> List[str]: snake_case_ = False for key, mapped_key in MAPPING.items(): snake_case_ = """wav2vec2.""" + 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]: snake_case_ = True if "*" in mapped_key: snake_case_ = name.split(_SCREAMING_SNAKE_CASE )[0].split(""".""" )[-2] snake_case_ = mapped_key.replace("""*""" , _SCREAMING_SNAKE_CASE ) if "weight_g" in name: snake_case_ = """weight_g""" elif "weight_v" in name: snake_case_ = """weight_v""" elif "bias" in name: snake_case_ = """bias""" elif "weight" in name: # TODO: don't match quantizer.weight_proj snake_case_ = """weight""" else: snake_case_ = None if hf_dict is not None: rename_dict(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) else: set_recursively(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) return is_used return is_used def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Any: snake_case_ = [] snake_case_ = fairseq_model.state_dict() snake_case_ = hf_model.wavaveca.feature_extractor for name, value in fairseq_dict.items(): snake_case_ = False if "conv_layers" in name: load_conv_layer( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , hf_model.config.feat_extract_norm == """group""" , ) snake_case_ = True else: snake_case_ = load_wavaveca_layer(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if not is_used: unused_weights.append(_SCREAMING_SNAKE_CASE ) logger.warning(f"""Unused weights: {unused_weights}""" ) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Union[str, Any]: snake_case_ = full_name.split("""conv_layers.""" )[-1] snake_case_ = name.split(""".""" ) snake_case_ = int(items[0] ) snake_case_ = int(items[1] ) if type_id == 0: if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.bias.data.shape: raise ValueError( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.""" ) snake_case_ = value logger.info(f"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.weight.data.shape: raise ValueError( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.""" ) snake_case_ = 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: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape: raise ValueError( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape} was found.""" ) snake_case_ = value logger.info(f"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape: raise ValueError( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape} was found.""" ) snake_case_ = value logger.info(f"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) else: unused_weights.append(_SCREAMING_SNAKE_CASE ) @torch.no_grad() def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=False ) -> int: if config_path is not None: snake_case_ = WavaVecaConfig.from_pretrained(_SCREAMING_SNAKE_CASE ) else: snake_case_ = WavaVecaConfig() if is_seq_class: snake_case_ = read_txt_into_dict(_SCREAMING_SNAKE_CASE ) snake_case_ = idalabel snake_case_ = WavaVecaForSequenceClassification(_SCREAMING_SNAKE_CASE ) snake_case_ = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=16_000 , padding_value=0 , do_normalize=_SCREAMING_SNAKE_CASE , return_attention_mask=_SCREAMING_SNAKE_CASE , ) feature_extractor.save_pretrained(_SCREAMING_SNAKE_CASE ) elif is_finetuned: if dict_path: snake_case_ = Dictionary.load(_SCREAMING_SNAKE_CASE ) # important change bos & pad token id since CTC symbol is <pad> and # not <s> as in fairseq snake_case_ = target_dict.pad_index snake_case_ = target_dict.bos_index snake_case_ = target_dict.eos_index snake_case_ = len(target_dict.symbols ) snake_case_ = os.path.join(_SCREAMING_SNAKE_CASE , """vocab.json""" ) if not os.path.isdir(_SCREAMING_SNAKE_CASE ): logger.error("""--pytorch_dump_folder_path ({}) should be a directory""".format(_SCREAMING_SNAKE_CASE ) ) return os.makedirs(_SCREAMING_SNAKE_CASE , exist_ok=_SCREAMING_SNAKE_CASE ) snake_case_ = target_dict.indices # fairseq has the <pad> and <s> switched snake_case_ = 0 snake_case_ = 1 with open(_SCREAMING_SNAKE_CASE , """w""" , encoding="""utf-8""" ) as vocab_handle: json.dump(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) snake_case_ = WavaVecaCTCTokenizer( _SCREAMING_SNAKE_CASE , 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=_SCREAMING_SNAKE_CASE , ) snake_case_ = True if config.feat_extract_norm == """layer""" else False snake_case_ = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=16_000 , padding_value=0 , do_normalize=_SCREAMING_SNAKE_CASE , return_attention_mask=_SCREAMING_SNAKE_CASE , ) snake_case_ = WavaVecaProcessor(feature_extractor=_SCREAMING_SNAKE_CASE , tokenizer=_SCREAMING_SNAKE_CASE ) processor.save_pretrained(_SCREAMING_SNAKE_CASE ) snake_case_ = WavaVecaForCTC(_SCREAMING_SNAKE_CASE ) else: snake_case_ = WavaVecaForPreTraining(_SCREAMING_SNAKE_CASE ) if is_finetuned or is_seq_class: snake_case_ , snake_case_ , snake_case_ = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={"""data""": """/""".join(dict_path.split("""/""" )[:-1] )} ) else: snake_case_ = argparse.Namespace(task="""audio_pretraining""" ) snake_case_ = fairseq.tasks.setup_task(_SCREAMING_SNAKE_CASE ) snake_case_ , snake_case_ , snake_case_ = fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path] , task=_SCREAMING_SNAKE_CASE ) snake_case_ = model[0].eval() recursively_load_weights(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , not is_finetuned ) hf_wavavec.save_pretrained(_SCREAMING_SNAKE_CASE ) if __name__ == "__main__": __SCREAMING_SNAKE_CASE : str = 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' ) parser.add_argument( '--is_seq_class', action='store_true', help='Whether the model to convert is a fine-tuned sequence classification model or not', ) __SCREAMING_SNAKE_CASE : Any = parser.parse_args() __SCREAMING_SNAKE_CASE : List[Any] = not args.not_finetuned and not args.is_seq_class convert_wavaveca_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, is_finetuned, args.is_seq_class, )
347
0
import io import math from typing import Dict, Optional, Union import numpy as np from huggingface_hub import hf_hub_download from ...image_processing_utils import BaseImageProcessor, BatchFeature from ...image_transforms import convert_to_rgb, normalize, to_channel_dimension_format, to_pil_image from ...image_utils import ( ChannelDimension, ImageInput, get_image_size, infer_channel_dimension_format, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_torch_available, is_vision_available, logging from ...utils.import_utils import requires_backends if is_vision_available(): import textwrap from PIL import Image, ImageDraw, ImageFont if is_torch_available(): import torch from transformers.pytorch_utils import is_torch_greater_or_equal_than_1_11 else: _A = False _A = logging.get_logger(__name__) _A = '''ybelkada/fonts''' def lowerCamelCase__ ( ) -> Optional[int]: if is_torch_available() and not is_torch_greater_or_equal_than_1_11: raise ImportError( f'''You are using torch=={torch.__version__}, but torch>=1.11.0 is required to use ''' """Pix2StructImageProcessor. Please upgrade torch.""" ) def lowerCamelCase__ ( a__ : Optional[int] , a__ : Dict , a__ : List[str] ) -> List[str]: requires_backends(UpperCamelCase__ , ["""torch"""] ) _check_torch_version() UpperCamelCase_ = image_tensor.unsqueeze(0 ) UpperCamelCase_ = torch.nn.functional.unfold(UpperCamelCase__ , (patch_height, patch_width) , stride=(patch_height, patch_width) ) UpperCamelCase_ = patches.reshape(image_tensor.size(0 ) , image_tensor.size(1 ) , UpperCamelCase__ , UpperCamelCase__ , -1 ) UpperCamelCase_ = patches.permute(0 , 4 , 2 , 3 , 1 ).reshape( image_tensor.size(2 ) // patch_height , image_tensor.size(3 ) // patch_width , image_tensor.size(1 ) * patch_height * patch_width , ) return patches.unsqueeze(0 ) def lowerCamelCase__ ( a__ : str , a__ : int = 36 , a__ : str = "black" , a__ : str = "white" , a__ : int = 5 , a__ : int = 5 , a__ : int = 5 , a__ : int = 5 , a__ : Optional[bytes] = None , a__ : Optional[str] = None , ) -> Optional[int]: requires_backends(UpperCamelCase__ , """vision""" ) # Add new lines so that each line is no more than 80 characters. UpperCamelCase_ = textwrap.TextWrapper(width=80 ) UpperCamelCase_ = wrapper.wrap(text=UpperCamelCase__ ) UpperCamelCase_ = """\n""".join(UpperCamelCase__ ) if font_bytes is not None and font_path is None: UpperCamelCase_ = io.BytesIO(UpperCamelCase__ ) elif font_path is not None: UpperCamelCase_ = font_path else: UpperCamelCase_ = hf_hub_download(UpperCamelCase__ , """Arial.TTF""" ) UpperCamelCase_ = ImageFont.truetype(UpperCamelCase__ , encoding="""UTF-8""" , size=UpperCamelCase__ ) # Use a temporary canvas to determine the width and height in pixels when # rendering the text. UpperCamelCase_ = ImageDraw.Draw(Image.new("""RGB""" , (1, 1) , UpperCamelCase__ ) ) UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ = temp_draw.textbbox((0, 0) , UpperCamelCase__ , UpperCamelCase__ ) # Create the actual image with a bit of padding around the text. UpperCamelCase_ = text_width + left_padding + right_padding UpperCamelCase_ = text_height + top_padding + bottom_padding UpperCamelCase_ = Image.new("""RGB""" , (image_width, image_height) , UpperCamelCase__ ) UpperCamelCase_ = ImageDraw.Draw(UpperCamelCase__ ) draw.text(xy=(left_padding, top_padding) , text=UpperCamelCase__ , fill=UpperCamelCase__ , font=UpperCamelCase__ ) return image def lowerCamelCase__ ( a__ : np.ndarray , a__ : str , **a__ : Any ) -> int: requires_backends(UpperCamelCase__ , """vision""" ) # Convert to PIL image if necessary UpperCamelCase_ = to_pil_image(UpperCamelCase__ ) UpperCamelCase_ = render_text(UpperCamelCase__ , **UpperCamelCase__ ) UpperCamelCase_ = max(header_image.width , image.width ) UpperCamelCase_ = int(image.height * (new_width / image.width) ) UpperCamelCase_ = int(header_image.height * (new_width / header_image.width) ) UpperCamelCase_ = Image.new("""RGB""" , (new_width, new_height + new_header_height) , """white""" ) new_image.paste(header_image.resize((new_width, new_header_height) ) , (0, 0) ) new_image.paste(image.resize((new_width, new_height) ) , (0, new_header_height) ) # Convert back to the original framework if necessary UpperCamelCase_ = to_numpy_array(UpperCamelCase__ ) if infer_channel_dimension_format(UpperCamelCase__ ) == ChannelDimension.LAST: UpperCamelCase_ = to_channel_dimension_format(UpperCamelCase__ , ChannelDimension.LAST ) return new_image class lowercase_ ( __SCREAMING_SNAKE_CASE ): A__ : Union[str, Any] = ['''flattened_patches'''] def __init__( self , __UpperCamelCase = True , __UpperCamelCase = True , __UpperCamelCase = None , __UpperCamelCase = 2_0_4_8 , __UpperCamelCase = False , **__UpperCamelCase , ): """simple docstring""" super().__init__(**_a ) UpperCamelCase_ = patch_size if patch_size is not None else {"""height""": 1_6, """width""": 1_6} UpperCamelCase_ = do_normalize UpperCamelCase_ = do_convert_rgb UpperCamelCase_ = max_patches UpperCamelCase_ = is_vqa def lowerCamelCase_ ( self , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , **__UpperCamelCase ): """simple docstring""" requires_backends(self.extract_flattened_patches , """torch""" ) _check_torch_version() # convert to torch UpperCamelCase_ = to_channel_dimension_format(_a , ChannelDimension.FIRST ) UpperCamelCase_ = torch.from_numpy(_a ) UpperCamelCase_ , UpperCamelCase_ = patch_size["""height"""], patch_size["""width"""] UpperCamelCase_ , UpperCamelCase_ = get_image_size(_a ) # maximize scale s.t. UpperCamelCase_ = math.sqrt(max_patches * (patch_height / image_height) * (patch_width / image_width) ) UpperCamelCase_ = max(min(math.floor(scale * image_height / patch_height ) , _a ) , 1 ) UpperCamelCase_ = max(min(math.floor(scale * image_width / patch_width ) , _a ) , 1 ) UpperCamelCase_ = max(num_feasible_rows * patch_height , 1 ) UpperCamelCase_ = max(num_feasible_cols * patch_width , 1 ) UpperCamelCase_ = torch.nn.functional.interpolate( image.unsqueeze(0 ) , size=(resized_height, resized_width) , mode="""bilinear""" , align_corners=_a , antialias=_a , ).squeeze(0 ) # [1, rows, columns, patch_height * patch_width * image_channels] UpperCamelCase_ = torch_extract_patches(_a , _a , _a ) UpperCamelCase_ = patches.shape UpperCamelCase_ = patches_shape[1] UpperCamelCase_ = patches_shape[2] UpperCamelCase_ = patches_shape[3] # [rows * columns, patch_height * patch_width * image_channels] UpperCamelCase_ = patches.reshape([rows * columns, depth] ) # [rows * columns, 1] UpperCamelCase_ = torch.arange(_a ).reshape([rows, 1] ).repeat(1 , _a ).reshape([rows * columns, 1] ) UpperCamelCase_ = torch.arange(_a ).reshape([1, columns] ).repeat(_a , 1 ).reshape([rows * columns, 1] ) # Offset by 1 so the ids do not contain zeros, which represent padding. row_ids += 1 col_ids += 1 # Prepare additional patch features. # [rows * columns, 1] UpperCamelCase_ = row_ids.to(torch.floataa ) UpperCamelCase_ = col_ids.to(torch.floataa ) # [rows * columns, 2 + patch_height * patch_width * image_channels] UpperCamelCase_ = torch.cat([row_ids, col_ids, patches] , -1 ) # [max_patches, 2 + patch_height * patch_width * image_channels] UpperCamelCase_ = torch.nn.functional.pad(_a , [0, 0, 0, max_patches - (rows * columns)] ).float() UpperCamelCase_ = to_numpy_array(_a ) return result def lowerCamelCase_ ( self , __UpperCamelCase , __UpperCamelCase = None , **__UpperCamelCase ): """simple docstring""" if image.dtype == np.uinta: UpperCamelCase_ = image.astype(np.floataa ) # take mean across the whole `image` UpperCamelCase_ = np.mean(_a ) UpperCamelCase_ = np.std(_a ) UpperCamelCase_ = max(_a , 1.0 / math.sqrt(np.prod(image.shape ) ) ) return normalize(_a , mean=_a , std=_a , **_a ) def lowerCamelCase_ ( self , __UpperCamelCase , __UpperCamelCase = None , __UpperCamelCase = None , __UpperCamelCase = None , __UpperCamelCase = None , __UpperCamelCase = None , __UpperCamelCase = None , __UpperCamelCase = ChannelDimension.FIRST , **__UpperCamelCase , ): """simple docstring""" UpperCamelCase_ = do_normalize if do_normalize is not None else self.do_normalize UpperCamelCase_ = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb UpperCamelCase_ = patch_size if patch_size is not None else self.patch_size UpperCamelCase_ = max_patches if max_patches is not None else self.max_patches UpperCamelCase_ = self.is_vqa if kwargs.get("""data_format""" , _a ) is not None: raise ValueError("""data_format is not an accepted input as the outputs are """ ) UpperCamelCase_ = make_list_of_images(_a ) if not valid_images(_a ): raise ValueError( """Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """ """torch.Tensor, tf.Tensor or jax.ndarray.""" ) # PIL RGBA images are converted to RGB if do_convert_rgb: UpperCamelCase_ = [convert_to_rgb(_a ) for image in images] # All transformations expect numpy arrays. UpperCamelCase_ = [to_numpy_array(_a ) for image in images] if is_vqa: if header_text is None: raise ValueError("""A header text must be provided for VQA models.""" ) UpperCamelCase_ = kwargs.pop("""font_bytes""" , _a ) UpperCamelCase_ = kwargs.pop("""font_path""" , _a ) if isinstance(_a , _a ): UpperCamelCase_ = [header_text] * len(_a ) UpperCamelCase_ = [ render_header(_a , header_text[i] , font_bytes=_a , font_path=_a ) for i, image in enumerate(_a ) ] if do_normalize: UpperCamelCase_ = [self.normalize(image=_a ) for image in images] # convert to torch tensor and permute UpperCamelCase_ = [ self.extract_flattened_patches(image=_a , max_patches=_a , patch_size=_a ) for image in images ] # create attention mask in numpy UpperCamelCase_ = [(image.sum(axis=-1 ) != 0).astype(np.floataa ) for image in images] UpperCamelCase_ = BatchFeature( data={"""flattened_patches""": images, """attention_mask""": attention_masks} , tensor_type=_a ) return encoded_outputs
363
def lowerCamelCase__ ( a__ : list , a__ : list , a__ : int , a__ : int , a__ : int ) -> int: if index == number_of_items: return 0 UpperCamelCase_ = 0 UpperCamelCase_ = 0 UpperCamelCase_ = knapsack(a__ , a__ , a__ , a__ , index + 1 ) if weights[index] <= max_weight: UpperCamelCase_ = values[index] + knapsack( a__ , a__ , a__ , max_weight - weights[index] , index + 1 ) return max(a__ , a__ ) if __name__ == "__main__": import doctest doctest.testmod()
261
0
import importlib.metadata from typing import Union from packaging.version import Version, parse from .constants import STR_OPERATION_TO_FUNC _snake_case : Optional[Any] = parse(importlib.metadata.version('torch')) def a_ ( lowerCAmelCase_ : Union[str, Version], lowerCAmelCase_ : str, lowerCAmelCase_ : str ): if operation not in STR_OPERATION_TO_FUNC.keys(): raise ValueError(F"""`operation` must be one of {list(STR_OPERATION_TO_FUNC.keys() )}, received {operation}""" ) __lowerCAmelCase = STR_OPERATION_TO_FUNC[operation] if isinstance(__a, __a ): __lowerCAmelCase = parse(importlib.metadata.version(__a ) ) return operation(__a, parse(__a ) ) def a_ ( lowerCAmelCase_ : str, lowerCAmelCase_ : str ): return compare_versions(__a, __a, __a )
284
'''simple docstring''' from typing import Any, Dict, List, Optional, Tuple, Union import torch from torch import nn from torch.utils.data import DistributedSampler, RandomSampler from transformers import PreTrainedModel, Trainer, logging from transformers.integrations import is_fairscale_available from transformers.models.fsmt.configuration_fsmt import FSMTConfig from transformers.optimization import ( Adafactor, AdamW, get_constant_schedule, get_constant_schedule_with_warmup, get_cosine_schedule_with_warmup, get_cosine_with_hard_restarts_schedule_with_warmup, get_linear_schedule_with_warmup, get_polynomial_decay_schedule_with_warmup, ) from transformers.trainer_pt_utils import get_tpu_sampler from transformers.training_args import ParallelMode from transformers.utils import is_torch_tpu_available if is_fairscale_available(): from fairscale.optim import OSS __lowerCAmelCase = logging.get_logger(__name__) __lowerCAmelCase = { """linear""": get_linear_schedule_with_warmup, """cosine""": get_cosine_schedule_with_warmup, """cosine_w_restarts""": get_cosine_with_hard_restarts_schedule_with_warmup, """polynomial""": get_polynomial_decay_schedule_with_warmup, """constant""": get_constant_schedule, """constant_w_warmup""": get_constant_schedule_with_warmup, } class UpperCAmelCase__ ( lowercase__ ): """simple docstring""" def __init__( self : Optional[int] ,_a : Optional[Any]=None ,_a : Dict=None ,*_a : int ,**_a : str ): '''simple docstring''' super().__init__(*_a ,**_a ) if config is None: assert isinstance(self.model ,_a ), ( "If no `config` is passed the model to be trained has to be of type `PreTrainedModel`, but is" F""" {self.model.__class__}""" ) _a : List[Any] = self.model.config else: _a : Optional[int] = config _a : List[str] = data_args _a : List[Any] = self.config.tgt_vocab_size if isinstance(self.config ,_a ) else self.config.vocab_size if self.args.label_smoothing != 0 or (self.data_args is not None and self.data_args.ignore_pad_token_for_loss): assert self.config.pad_token_id is not None, ( "Make sure that `config.pad_token_id` is correcly defined when ignoring `pad_token` for loss" " calculation or doing label smoothing." ) if self.config.pad_token_id is None and self.config.eos_token_id is not None: logger.warning( F"""The `config.pad_token_id` is `None`. Using `config.eos_token_id` = {self.config.eos_token_id} for""" ' padding..' ) if self.args.label_smoothing == 0: _a : List[str] = torch.nn.CrossEntropyLoss(ignore_index=self.config.pad_token_id ) else: # dynamically import label_smoothed_nll_loss from utils import label_smoothed_nll_loss _a : Tuple = label_smoothed_nll_loss def __lowercase ( self : List[str] ,_a : int ): '''simple docstring''' if self.optimizer is None: _a : Union[str, Any] = ['bias', 'LayerNorm.weight'] _a : Tuple = [ { 'params': [p for n, p in self.model.named_parameters() if not any(nd in n for nd in no_decay )], 'weight_decay': self.args.weight_decay, }, { 'params': [p for n, p in self.model.named_parameters() if any(nd in n for nd in no_decay )], 'weight_decay': 0.0, }, ] _a : Optional[int] = Adafactor if self.args.adafactor else AdamW if self.args.adafactor: _a : Any = Adafactor _a : Dict = {'scale_parameter': False, 'relative_step': False} else: _a : Union[str, Any] = AdamW _a : str = { 'betas': (self.args.adam_betaa, self.args.adam_betaa), 'eps': self.args.adam_epsilon, } _a : Union[str, Any] = self.args.learning_rate if self.sharded_ddp: _a : str = OSS( params=_a ,optim=_a ,**_a ,) else: _a : Tuple = optimizer_cls(_a ,**_a ) if self.lr_scheduler is None: _a : List[Any] = self._get_lr_scheduler(_a ) else: # ignoring --lr_scheduler logger.warning('scheduler is passed to `Seq2SeqTrainer`, `--lr_scheduler` arg is ignored.' ) def __lowercase ( self : List[Any] ,_a : List[Any] ): '''simple docstring''' _a : str = arg_to_scheduler[self.args.lr_scheduler] if self.args.lr_scheduler == "constant": _a : int = schedule_func(self.optimizer ) elif self.args.lr_scheduler == "constant_w_warmup": _a : List[str] = schedule_func(self.optimizer ,num_warmup_steps=self.args.warmup_steps ) else: _a : Optional[int] = schedule_func( self.optimizer ,num_warmup_steps=self.args.warmup_steps ,num_training_steps=_a ) return scheduler def __lowercase ( self : Tuple ): '''simple docstring''' if isinstance(self.train_dataset ,torch.utils.data.IterableDataset ): return None elif is_torch_tpu_available(): return get_tpu_sampler(self.train_dataset ) else: if self.args.sortish_sampler: self.train_dataset.make_sortish_sampler( self.args.per_device_train_batch_size ,distributed=(self.args.parallel_mode == ParallelMode.DISTRIBUTED) ,) return ( RandomSampler(self.train_dataset ) if self.args.local_rank == -1 else DistributedSampler(self.train_dataset ) ) def __lowercase ( self : Dict ,_a : Dict ,_a : Any ,_a : Dict ): '''simple docstring''' if self.args.label_smoothing == 0: if self.data_args is not None and self.data_args.ignore_pad_token_for_loss: # force training to ignore pad token _a : List[Any] = model(**_a ,use_cache=_a )[0] _a : Union[str, Any] = self.loss_fn(logits.view(-1 ,logits.shape[-1] ) ,labels.view(-1 ) ) else: # compute usual loss via models _a, _a : Union[str, Any] = model(**_a ,labels=_a ,use_cache=_a )[:2] else: # compute label smoothed loss _a : List[Any] = model(**_a ,use_cache=_a )[0] _a : Any = torch.nn.functional.log_softmax(_a ,dim=-1 ) _a, _a : List[str] = self.loss_fn(_a ,_a ,self.args.label_smoothing ,ignore_index=self.config.pad_token_id ) return loss, logits def __lowercase ( self : Optional[int] ,_a : Union[str, Any] ,_a : List[Any] ): '''simple docstring''' _a : Optional[int] = inputs.pop('labels' ) _a, _a : int = self._compute_loss(_a ,_a ,_a ) return loss def __lowercase ( self : Optional[Any] ,_a : nn.Module ,_a : Dict[str, Union[torch.Tensor, Any]] ,_a : bool ,_a : Optional[List[str]] = None ,): '''simple docstring''' _a : int = self._prepare_inputs(_a ) _a : Any = { 'max_length': self.data_args.val_max_target_length if self.data_args is not None else self.config.max_length, 'num_beams': self.data_args.eval_beams if self.data_args is not None else self.config.num_beams, } if self.args.predict_with_generate and not self.args.prediction_loss_only: _a : int = self.model.generate( inputs['input_ids'] ,attention_mask=inputs['attention_mask'] ,**_a ,) # in case the batch is shorter than max length, the output should be padded if generated_tokens.shape[-1] < gen_kwargs["max_length"]: _a : int = self._pad_tensors_to_max_len(_a ,gen_kwargs['max_length'] ) _a : Union[str, Any] = inputs.pop('labels' ) with torch.no_grad(): # compute loss on predict data _a, _a : Optional[int] = self._compute_loss(_a ,_a ,_a ) _a : Optional[Any] = loss.mean().detach() if self.args.prediction_loss_only: return (loss, None, None) _a : Optional[Any] = generated_tokens if self.args.predict_with_generate else logits if labels.shape[-1] < gen_kwargs["max_length"]: _a : Dict = self._pad_tensors_to_max_len(_a ,gen_kwargs['max_length'] ) return (loss, logits, labels) def __lowercase ( self : str ,_a : Tuple ,_a : Tuple ): '''simple docstring''' _a : List[Any] = self.config.pad_token_id if self.config.pad_token_id is not None else self.config.eos_token_id if pad_token_id is None: raise ValueError( 'Make sure that either `config.pad_token_id` or `config.eos_token_id` is defined if tensor has to be' F""" padded to `max_length`={max_length}""" ) _a : int = pad_token_id * torch.ones( (tensor.shape[0], max_length) ,dtype=tensor.dtype ,device=tensor.device ) _a : Union[str, Any] = tensor return padded_tensor
271
0
"""simple docstring""" import json import os import unittest from transformers.models.gptsan_japanese.tokenization_gptsan_japanese import ( VOCAB_FILES_NAMES, GPTSanJapaneseTokenizer, ) from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class _lowercase ( __UpperCAmelCase , unittest.TestCase ): lowercase_ = GPTSanJapaneseTokenizer lowercase_ = False lowercase_ = {'do_clean_text': False, 'add_prefix_space': False} def _UpperCamelCase ( self ) -> Dict: super().setUp() # fmt: off lowerCamelCase : Tuple = ['こん', 'こんに', 'にちは', 'ばんは', '世界,㔺界', '、', '。', '<BR>', '<SP>', '<TAB>', '<URL>', '<EMAIL>', '<TEL>', '<DATE>', '<PRICE>', '<BLOCK>', '<KIGOU>', '<U2000U2BFF>', '<|emoji1|>', '<unk>', '<|bagoftoken|>', '<|endoftext|>'] # fmt: on lowerCamelCase : List[str] = {'emoji': {'\ud83d\ude00': '<|emoji1|>'}, 'emoji_inv': {'<|emoji1|>': '\ud83d\ude00'}} # 😀 lowerCamelCase : List[str] = {'unk_token': '<unk>'} lowerCamelCase : Dict = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) lowerCamelCase : int = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['emoji_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in vocab_tokens] ) ) with open(self.emoji_file , 'w' ) as emoji_writer: emoji_writer.write(json.dumps(UpperCAmelCase_ ) ) def _UpperCamelCase ( self , **UpperCAmelCase_ ) -> List[str]: kwargs.update(self.special_tokens_map ) return GPTSanJapaneseTokenizer.from_pretrained(self.tmpdirname , **UpperCAmelCase_ ) def _UpperCamelCase ( self , UpperCAmelCase_ ) -> List[str]: lowerCamelCase : Tuple = 'こんにちは、世界。 \nこんばんは、㔺界。😀' lowerCamelCase : List[str] = 'こんにちは、世界。 \nこんばんは、世界。😀' return input_text, output_text def _UpperCamelCase ( self , UpperCAmelCase_ ) -> Dict: lowerCamelCase , lowerCamelCase : List[Any] = self.get_input_output_texts(UpperCAmelCase_ ) lowerCamelCase : int = tokenizer.encode(UpperCAmelCase_ , add_special_tokens=UpperCAmelCase_ ) lowerCamelCase : Optional[Any] = tokenizer.decode(UpperCAmelCase_ , clean_up_tokenization_spaces=UpperCAmelCase_ ) return text, ids def _UpperCamelCase ( self ) -> int: pass # TODO add if relevant def _UpperCamelCase ( self ) -> Optional[int]: pass # TODO add if relevant def _UpperCamelCase ( self ) -> Tuple: pass # TODO add if relevant def _UpperCamelCase ( self ) -> Any: lowerCamelCase : Dict = self.get_tokenizer() # Testing tokenization lowerCamelCase : Any = 'こんにちは、世界。 こんばんは、㔺界。' lowerCamelCase : Any = ['こん', 'にちは', '、', '世界', '。', '<SP>', 'こん', 'ばんは', '、', '㔺界', '。'] lowerCamelCase : str = tokenizer.tokenize(UpperCAmelCase_ ) self.assertListEqual(UpperCAmelCase_ , UpperCAmelCase_ ) # Testing conversion to ids without special tokens lowerCamelCase : Optional[Any] = [0, 2, 5, 4, 6, 8, 0, 3, 5, 4, 6] lowerCamelCase : Union[str, Any] = tokenizer.convert_tokens_to_ids(UpperCAmelCase_ ) self.assertListEqual(UpperCAmelCase_ , UpperCAmelCase_ ) # Testing conversion to ids with special tokens lowerCamelCase : Union[str, Any] = tokens + [tokenizer.unk_token] lowerCamelCase : Optional[int] = [0, 2, 5, 4, 6, 8, 0, 3, 5, 4, 6, 19] lowerCamelCase : Union[str, Any] = tokenizer.convert_tokens_to_ids(UpperCAmelCase_ ) self.assertListEqual(UpperCAmelCase_ , UpperCAmelCase_ ) def _UpperCamelCase ( self ) -> int: lowerCamelCase : Optional[int] = self.get_tokenizer() # Testing tokenization lowerCamelCase : str = 'こんにちは、<|bagoftoken|>世界。こんばんは、<|bagoftoken|>㔺界。' lowerCamelCase : str = 'こんにちは、、、、世界。こんばんは、、、、世界。' lowerCamelCase : int = tokenizer.encode(UpperCAmelCase_ ) lowerCamelCase : List[Any] = tokenizer.decode(UpperCAmelCase_ ) self.assertEqual(UpperCAmelCase_ , UpperCAmelCase_ ) @slow def _UpperCamelCase ( self ) -> Optional[int]: lowerCamelCase : Any = self.tokenizer_class.from_pretrained('Tanrei/GPTSAN-japanese' ) # Testing tokenization lowerCamelCase : Optional[Any] = 'こんにちは、世界。' lowerCamelCase : str = 'こんばんは、㔺界。😀' lowerCamelCase : List[Any] = 'こんにちは、世界。こんばんは、世界。😀' lowerCamelCase : int = tokenizer.encode(prefix_text + input_text ) lowerCamelCase : Dict = tokenizer.encode('' , prefix_text=prefix_text + input_text ) lowerCamelCase : Union[str, Any] = tokenizer.encode(UpperCAmelCase_ , prefix_text=UpperCAmelCase_ ) lowerCamelCase : List[str] = tokenizer.decode(UpperCAmelCase_ ) lowerCamelCase : List[Any] = tokenizer.decode(UpperCAmelCase_ ) lowerCamelCase : List[str] = tokenizer.decode(UpperCAmelCase_ ) self.assertEqual(UpperCAmelCase_ , UpperCAmelCase_ ) self.assertEqual(UpperCAmelCase_ , UpperCAmelCase_ ) self.assertEqual(UpperCAmelCase_ , UpperCAmelCase_ ) @slow def _UpperCamelCase ( self ) -> Optional[Any]: lowerCamelCase : Optional[Any] = self.tokenizer_class.from_pretrained('Tanrei/GPTSAN-japanese' ) # Testing tokenization lowerCamelCase : Any = 'こんにちは、世界。' lowerCamelCase : int = 'こんばんは、㔺界。😀' lowerCamelCase : int = len(tokenizer.encode(UpperCAmelCase_ ) ) - 2 lowerCamelCase : int = len(tokenizer.encode(UpperCAmelCase_ ) ) - 2 lowerCamelCase : List[str] = [1] + [0] * (len_prefix + len_text + 1) lowerCamelCase : List[str] = [1] * (len_prefix + len_text + 1) + [0] lowerCamelCase : List[Any] = [1] + [1] * (len_prefix) + [0] * (len_text + 1) lowerCamelCase : List[Any] = tokenizer(prefix_text + input_text ).token_type_ids lowerCamelCase : List[str] = tokenizer('' , prefix_text=prefix_text + input_text ).token_type_ids lowerCamelCase : Dict = tokenizer(UpperCAmelCase_ , prefix_text=UpperCAmelCase_ ).token_type_ids self.assertListEqual(UpperCAmelCase_ , UpperCAmelCase_ ) self.assertListEqual(UpperCAmelCase_ , UpperCAmelCase_ ) self.assertListEqual(UpperCAmelCase_ , UpperCAmelCase_ ) @slow def _UpperCamelCase ( self ) -> int: lowerCamelCase : str = self.tokenizer_class.from_pretrained('Tanrei/GPTSAN-japanese' ) lowerCamelCase : List[str] = tokenizer.encode('あンいワ' ) lowerCamelCase : Optional[int] = tokenizer.encode('' , prefix_text='あンいワ' ) lowerCamelCase : Union[str, Any] = tokenizer.encode('いワ' , prefix_text='あン' ) self.assertEqual(tokenizer.decode(UpperCAmelCase_ ) , tokenizer.decode(UpperCAmelCase_ ) ) self.assertEqual(tokenizer.decode(UpperCAmelCase_ ) , tokenizer.decode(UpperCAmelCase_ ) ) self.assertNotEqual(UpperCAmelCase_ , UpperCAmelCase_ ) self.assertNotEqual(UpperCAmelCase_ , UpperCAmelCase_ ) self.assertEqual(x_token_a[1] , x_token_a[-1] ) # SEG token self.assertEqual(x_token_a[1] , x_token_a[3] ) # SEG token @slow def _UpperCamelCase ( self ) -> Dict: lowerCamelCase : Union[str, Any] = self.tokenizer_class.from_pretrained('Tanrei/GPTSAN-japanese' ) lowerCamelCase : Union[str, Any] = [['武田信玄', 'は、'], ['織田信長', 'の配下の、']] lowerCamelCase : int = tokenizer(UpperCAmelCase_ , padding=UpperCAmelCase_ ) lowerCamelCase : Union[str, Any] = tokenizer.batch_encode_plus(UpperCAmelCase_ , padding=UpperCAmelCase_ ) # fmt: off lowerCamelCase : Dict = [[35993, 8640, 25948, 35998, 30647, 35675, 35999, 35999], [35993, 10382, 9868, 35998, 30646, 9459, 30646, 35675]] lowerCamelCase : Dict = [[1, 1, 1, 0, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0, 0, 0]] lowerCamelCase : List[Any] = [[1, 1, 1, 1, 1, 1, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1]] # fmt: on self.assertListEqual(x_token.input_ids , UpperCAmelCase_ ) self.assertListEqual(x_token.token_type_ids , UpperCAmelCase_ ) self.assertListEqual(x_token.attention_mask , UpperCAmelCase_ ) self.assertListEqual(x_token_a.input_ids , UpperCAmelCase_ ) self.assertListEqual(x_token_a.token_type_ids , UpperCAmelCase_ ) self.assertListEqual(x_token_a.attention_mask , UpperCAmelCase_ ) def _UpperCamelCase ( self ) -> List[Any]: # Intentionally convert some words to accommodate character fluctuations unique to Japanese pass def _UpperCamelCase ( self ) -> List[Any]: # tokenizer has no padding token pass
205
"""simple docstring""" import copy from ...configuration_utils import PretrainedConfig from ...utils import logging _A = logging.get_logger(__name__) class _lowercase ( __UpperCAmelCase ): lowercase_ = 'encoder-decoder' lowercase_ = True def __init__( self , **UpperCAmelCase_ ) -> str: super().__init__(**UpperCAmelCase_ ) assert ( "encoder" in kwargs and "decoder" in kwargs ), "Config has to be initialized with encoder and decoder config" lowerCamelCase : List[Any] = kwargs.pop('encoder' ) lowerCamelCase : Optional[int] = encoder_config.pop('model_type' ) lowerCamelCase : str = kwargs.pop('decoder' ) lowerCamelCase : Dict = decoder_config.pop('model_type' ) from ..auto.configuration_auto import AutoConfig lowerCamelCase : int = AutoConfig.for_model(UpperCAmelCase_ , **UpperCAmelCase_ ) lowerCamelCase : List[str] = AutoConfig.for_model(UpperCAmelCase_ , **UpperCAmelCase_ ) lowerCamelCase : List[str] = True @classmethod def _UpperCamelCase ( cls , UpperCAmelCase_ , UpperCAmelCase_ , **UpperCAmelCase_ ) -> PretrainedConfig: logger.info('Set `config.is_decoder=True` and `config.add_cross_attention=True` for decoder_config' ) lowerCamelCase : str = True lowerCamelCase : Optional[Any] = True return cls(encoder=encoder_config.to_dict() , decoder=decoder_config.to_dict() , **UpperCAmelCase_ ) def _UpperCamelCase ( self ) -> Union[str, Any]: lowerCamelCase : Union[str, Any] = copy.deepcopy(self.__dict__ ) lowerCamelCase : Union[str, Any] = self.encoder.to_dict() lowerCamelCase : List[Any] = self.decoder.to_dict() lowerCamelCase : Tuple = self.__class__.model_type return output
205
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 from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices A__ : Dict =logging.get_logger(__name__) A__ : Tuple ={ '''microsoft/swin-tiny-patch4-window7-224''': ( '''https://huggingface.co/microsoft/swin-tiny-patch4-window7-224/resolve/main/config.json''' ), # See all Swin models at https://huggingface.co/models?filter=swin } class UpperCAmelCase ( snake_case_ , snake_case_ ): _lowercase: Optional[Any] = '''swin''' _lowercase: Union[str, Any] = { '''num_attention_heads''': '''num_heads''', '''num_hidden_layers''': '''num_layers''', } def __init__( self : List[Any] , __snake_case : Dict=2_24 , __snake_case : List[str]=4 , __snake_case : Optional[Any]=3 , __snake_case : Optional[int]=96 , __snake_case : Tuple=[2, 2, 6, 2] , __snake_case : Optional[int]=[3, 6, 12, 24] , __snake_case : Optional[Any]=7 , __snake_case : List[Any]=4.0 , __snake_case : List[Any]=True , __snake_case : Tuple=0.0 , __snake_case : Optional[int]=0.0 , __snake_case : Union[str, Any]=0.1 , __snake_case : Dict="gelu" , __snake_case : int=False , __snake_case : Optional[Any]=0.02 , __snake_case : Optional[Any]=1E-5 , __snake_case : str=32 , __snake_case : Any=None , __snake_case : Tuple=None , **__snake_case : Tuple , ) -> int: super().__init__(**__snake_case ) _lowerCAmelCase = image_size _lowerCAmelCase = patch_size _lowerCAmelCase = num_channels _lowerCAmelCase = embed_dim _lowerCAmelCase = depths _lowerCAmelCase = len(__snake_case ) _lowerCAmelCase = num_heads _lowerCAmelCase = window_size _lowerCAmelCase = mlp_ratio _lowerCAmelCase = qkv_bias _lowerCAmelCase = hidden_dropout_prob _lowerCAmelCase = attention_probs_dropout_prob _lowerCAmelCase = drop_path_rate _lowerCAmelCase = hidden_act _lowerCAmelCase = use_absolute_embeddings _lowerCAmelCase = layer_norm_eps _lowerCAmelCase = initializer_range _lowerCAmelCase = encoder_stride # we set the hidden_size attribute in order to make Swin work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model _lowerCAmelCase = int(embed_dim * 2 ** (len(__snake_case ) - 1) ) _lowerCAmelCase = ["""stem"""] + [f"stage{idx}" for idx in range(1 , len(__snake_case ) + 1 )] _lowerCAmelCase , _lowerCAmelCase = get_aligned_output_features_output_indices( out_features=__snake_case , out_indices=__snake_case , stage_names=self.stage_names ) class UpperCAmelCase ( snake_case_ ): _lowercase: Optional[Any] = version.parse('''1.11''' ) @property def lowercase__ ( self : List[Any] ) -> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}), ] ) @property def lowercase__ ( self : Union[str, Any] ) -> float: return 1E-4
70
from __future__ import annotations import inspect import unittest import numpy as np from transformers import ResNetConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFResNetForImageClassification, TFResNetModel from transformers.models.resnet.modeling_tf_resnet import TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class SCREAMING_SNAKE_CASE_ : def __init__( self : Optional[int] , lowerCamelCase_ : Optional[Any] , lowerCamelCase_ : str=3 , lowerCamelCase_ : Tuple=32 , lowerCamelCase_ : List[str]=3 , lowerCamelCase_ : Optional[int]=10 , lowerCamelCase_ : List[str]=[10, 20, 30, 40] , lowerCamelCase_ : Tuple=[1, 1, 2, 1] , lowerCamelCase_ : Dict=True , lowerCamelCase_ : str=True , lowerCamelCase_ : Tuple="relu" , lowerCamelCase_ : List[str]=3 , lowerCamelCase_ : Dict=None , ): """simple docstring""" UpperCamelCase = parent UpperCamelCase = batch_size UpperCamelCase = image_size UpperCamelCase = num_channels UpperCamelCase = embeddings_size UpperCamelCase = hidden_sizes UpperCamelCase = depths UpperCamelCase = is_training UpperCamelCase = use_labels UpperCamelCase = hidden_act UpperCamelCase = num_labels UpperCamelCase = scope UpperCamelCase = len(lowerCamelCase_ ) def lowerCamelCase_ ( self : Dict ): """simple docstring""" UpperCamelCase = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) UpperCamelCase = None if self.use_labels: UpperCamelCase = ids_tensor([self.batch_size] , self.num_labels ) UpperCamelCase = self.get_config() return config, pixel_values, labels def lowerCamelCase_ ( self : Optional[int] ): """simple docstring""" return ResNetConfig( 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 lowerCamelCase_ ( self : Any , lowerCamelCase_ : List[Any] , lowerCamelCase_ : Optional[int] , lowerCamelCase_ : Tuple ): """simple docstring""" UpperCamelCase = TFResNetModel(config=lowerCamelCase_ ) UpperCamelCase = model(lowerCamelCase_ ) # expected last hidden states: B, C, H // 32, W // 32 self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) , ) def lowerCamelCase_ ( self : List[Any] , lowerCamelCase_ : List[str] , lowerCamelCase_ : str , lowerCamelCase_ : Optional[int] ): """simple docstring""" UpperCamelCase = self.num_labels UpperCamelCase = TFResNetForImageClassification(lowerCamelCase_ ) UpperCamelCase = model(lowerCamelCase_ , labels=lowerCamelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def lowerCamelCase_ ( self : int ): """simple docstring""" UpperCamelCase = self.prepare_config_and_inputs() UpperCamelCase , UpperCamelCase , UpperCamelCase = config_and_inputs UpperCamelCase = {"""pixel_values""": pixel_values} return config, inputs_dict @require_tf class SCREAMING_SNAKE_CASE_ ( __lowerCAmelCase , __lowerCAmelCase , unittest.TestCase ): __lowerCAmelCase = (TFResNetModel, TFResNetForImageClassification) if is_tf_available() else () __lowerCAmelCase = ( {"""feature-extraction""": TFResNetModel, """image-classification""": TFResNetForImageClassification} if is_tf_available() else {} ) __lowerCAmelCase = False __lowerCAmelCase = False __lowerCAmelCase = False __lowerCAmelCase = False __lowerCAmelCase = False def lowerCamelCase_ ( self : Any ): """simple docstring""" UpperCamelCase = TFResNetModelTester(self ) UpperCamelCase = ConfigTester(self , config_class=lowerCamelCase_ , has_text_modality=lowerCamelCase_ ) def lowerCamelCase_ ( self : List[Any] ): """simple docstring""" 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 lowerCamelCase_ ( self : Union[str, Any] ): """simple docstring""" return @unittest.skip(reason="""ResNet does not use inputs_embeds""" ) def lowerCamelCase_ ( self : Dict ): """simple docstring""" pass @unittest.skip(reason="""ResNet does not support input and output embeddings""" ) def lowerCamelCase_ ( self : Optional[Any] ): """simple docstring""" pass def lowerCamelCase_ ( self : Optional[int] ): """simple docstring""" UpperCamelCase , UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase = model_class(lowerCamelCase_ ) UpperCamelCase = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic UpperCamelCase = [*signature.parameters.keys()] UpperCamelCase = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , lowerCamelCase_ ) def lowerCamelCase_ ( self : List[str] ): """simple docstring""" UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowerCamelCase_ ) def lowerCamelCase_ ( self : Union[str, Any] ): """simple docstring""" def check_hidden_states_output(lowerCamelCase_ : Tuple , lowerCamelCase_ : int , lowerCamelCase_ : str ): UpperCamelCase = model_class(lowerCamelCase_ ) UpperCamelCase = model(**self._prepare_for_class(lowerCamelCase_ , lowerCamelCase_ ) ) UpperCamelCase = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states UpperCamelCase = self.model_tester.num_stages self.assertEqual(len(lowerCamelCase_ ) , expected_num_stages + 1 ) # ResNet's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [self.model_tester.image_size // 4, self.model_tester.image_size // 4] , ) UpperCamelCase , UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase = ["""basic""", """bottleneck"""] for model_class in self.all_model_classes: for layer_type in layers_type: UpperCamelCase = layer_type UpperCamelCase = True check_hidden_states_output(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] UpperCamelCase = True check_hidden_states_output(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) def lowerCamelCase_ ( self : List[Any] ): """simple docstring""" UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*lowerCamelCase_ ) @slow def lowerCamelCase_ ( self : Any ): """simple docstring""" for model_name in TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCamelCase = TFResNetModel.from_pretrained(lowerCamelCase_ ) self.assertIsNotNone(lowerCamelCase_ ) def lowercase( ) -> Any: '''simple docstring''' UpperCamelCase = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_tf @require_vision class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): @cached_property def lowerCamelCase_ ( self : Dict ): """simple docstring""" return ( AutoImageProcessor.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) if is_vision_available() else None ) @slow def lowerCamelCase_ ( self : Dict ): """simple docstring""" UpperCamelCase = TFResNetForImageClassification.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) UpperCamelCase = self.default_image_processor UpperCamelCase = prepare_img() UpperCamelCase = image_processor(images=lowerCamelCase_ , return_tensors="""tf""" ) # forward pass UpperCamelCase = model(**lowerCamelCase_ ) # verify the logits UpperCamelCase = tf.TensorShape((1, 1000) ) self.assertEqual(outputs.logits.shape , lowerCamelCase_ ) UpperCamelCase = tf.constant([-1_1.1_0_6_9, -9.7_8_7_7, -8.3_7_7_7] ) self.assertTrue(np.allclose(outputs.logits[0, :3].numpy() , lowerCamelCase_ , atol=1E-4 ) )
343
0
SCREAMING_SNAKE_CASE :Optional[int] = '0.21.0' from .accelerator import Accelerator from .big_modeling import ( cpu_offload, cpu_offload_with_hook, disk_offload, dispatch_model, init_empty_weights, init_on_device, load_checkpoint_and_dispatch, ) from .data_loader import skip_first_batches from .launchers import debug_launcher, notebook_launcher from .state import PartialState from .utils import ( DeepSpeedPlugin, DistributedDataParallelKwargs, DistributedType, FullyShardedDataParallelPlugin, GradScalerKwargs, InitProcessGroupKwargs, find_executable_batch_size, infer_auto_device_map, is_rich_available, load_checkpoint_in_model, synchronize_rng_states, ) if is_rich_available(): from .utils import rich
124
from collections import OrderedDict from typing import TYPE_CHECKING, Any, List, Mapping, Optional from packaging import version if TYPE_CHECKING: from ... import PreTrainedTokenizer, TensorType from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfigWithPast, PatchingSpec from ...utils import is_torch_available, logging SCREAMING_SNAKE_CASE :Optional[Any] = logging.get_logger(__name__) SCREAMING_SNAKE_CASE :Union[str, Any] = { 'bigscience/bloom': 'https://huggingface.co/bigscience/bloom/resolve/main/config.json', 'bigscience/bloom-560m': 'https://huggingface.co/bigscience/bloom-560m/blob/main/config.json', 'bigscience/bloom-1b1': 'https://huggingface.co/bigscience/bloom-1b1/blob/main/config.json', 'bigscience/bloom-1b7': 'https://huggingface.co/bigscience/bloom-1b7/blob/main/config.json', 'bigscience/bloom-3b': 'https://huggingface.co/bigscience/bloom-3b/blob/main/config.json', 'bigscience/bloom-7b1': 'https://huggingface.co/bigscience/bloom-7b1/blob/main/config.json', } class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' snake_case_ = "bloom" snake_case_ = ["past_key_values"] snake_case_ = { "num_hidden_layers": "n_layer", "num_attention_heads": "n_head", } def __init__( self : Optional[Any] ,A : List[Any]=25_08_80 ,A : Optional[int]=64 ,A : List[Any]=2 ,A : Optional[int]=8 ,A : str=1E-5 ,A : str=0.02 ,A : int=True ,A : Optional[Any]=1 ,A : int=2 ,A : str=False ,A : Dict=0.0 ,A : List[Any]=0.0 ,A : str=1 ,A : List[Any]=False ,**A : List[Any] ,): __A = vocab_size # Backward compatibility with n_embed kwarg __A = kwargs.pop("n_embed" ,A ) __A = hidden_size if n_embed is None else n_embed __A = n_layer __A = n_head __A = layer_norm_epsilon __A = initializer_range __A = use_cache __A = pretraining_tp __A = apply_residual_connection_post_layernorm __A = hidden_dropout __A = attention_dropout __A = bos_token_id __A = eos_token_id __A = slow_but_exact super().__init__(bos_token_id=A ,eos_token_id=A ,**A ) class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' snake_case_ = version.parse("1.12" ) def __init__( self : str ,A : PretrainedConfig ,A : str = "default" ,A : List[PatchingSpec] = None ,A : bool = False ,): super().__init__(A ,task=A ,patching_specs=A ,use_past=A ) if not getattr(self._config ,"pad_token_id" ,A ): # TODO: how to do that better? __A = 0 @property def UpperCamelCase_ ( self : Union[str, Any] ): __A = OrderedDict({"input_ids": {0: "batch", 1: "sequence"}} ) if self.use_past: # BLOOM stores values on dynamic axis 2. For more details see: https://github.com/huggingface/transformers/pull/18344 self.fill_with_past_key_values_(A ,direction="inputs" ,inverted_values_shape=A ) __A = {0: "batch", 1: "past_sequence + sequence"} else: __A = {0: "batch", 1: "sequence"} return common_inputs @property def UpperCamelCase_ ( self : Optional[Any] ): return self._config.n_layer @property def UpperCamelCase_ ( self : List[Any] ): return self._config.n_head @property def UpperCamelCase_ ( self : Optional[int] ): return 1E-3 def UpperCamelCase_ ( self : Any ,A : "PreTrainedTokenizer" ,A : int = -1 ,A : int = -1 ,A : bool = False ,A : Optional["TensorType"] = None ,): __A = super(A ,self ).generate_dummy_inputs( A ,batch_size=A ,seq_length=A ,is_pair=A ,framework=A ) # We need to order the input in the way they appears in the forward() __A = OrderedDict({"input_ids": common_inputs["input_ids"]} ) # Need to add the past_keys if self.use_past: if not is_torch_available(): raise ValueError("Cannot generate dummy past_keys inputs without PyTorch installed." ) else: import torch __A , __A = common_inputs["input_ids"].shape # Not using the same length for past_key_values __A = seqlen + 2 __A = self._config.hidden_size // self.num_attention_heads __A = ( batch * self.num_attention_heads, head_dim, past_key_values_length, ) __A = ( batch * self.num_attention_heads, past_key_values_length, head_dim, ) __A = [ (torch.zeros(A ), torch.zeros(A )) for _ in range(self.num_layers ) ] __A = common_inputs["attention_mask"] if self.use_past: __A = ordered_inputs["attention_mask"].dtype __A = torch.cat( [ordered_inputs["attention_mask"], torch.ones(A ,A ,dtype=A )] ,dim=1 ) return ordered_inputs @property def UpperCamelCase_ ( self : int ): return 13
124
1
import json import os from datetime import date from pathlib import Path from tabulate import DataRow, TableFormat, tabulate UpperCAmelCase_ : Union[str, Any] = TableFormat( lineabove=None, linebelowheader=None, linebetweenrows=None, linebelow=None, headerrow=DataRow('', '|', '|'), datarow=DataRow('', '|', '|'), padding=1, with_header_hide=None, ) UpperCAmelCase_ : Optional[Any] = [] UpperCAmelCase_ : int = [] UpperCAmelCase_ : List[Any] = {'type': 'section', 'text': {'type': 'plain_text', 'text': 'No failed tests! 🤗', 'emoji': True}} UpperCAmelCase_ : str = [ { 'type': 'header', 'text': { 'type': 'plain_text', 'text': F'🤗 Accelerate nightly {os.environ.get("TEST_TYPE", "")} test results', 'emoji': True, }, } ] UpperCAmelCase_ : Any = 0 for log in Path().glob('*.log'): UpperCAmelCase_ : Dict = 0 with open(log, 'r') as f: for line in f: UpperCAmelCase_ : int = json.loads(line) if line.get('nodeid', '') != "": UpperCAmelCase_ : List[Any] = line['nodeid'] if line.get('duration', None) is not None: UpperCAmelCase_ : Any = F'{line["duration"]:.4f}' if line.get('outcome', '') == "failed": section_num_failed += 1 failed.append([test, duration, log.name.split('_')[0]]) total_num_failed += 1 group_info.append([str(log), section_num_failed, failed]) UpperCAmelCase_ : Any = [] log.unlink() UpperCAmelCase_ : Optional[int] = '' UpperCAmelCase_ : Optional[Any] = [] if total_num_failed > 0: for name, num_failed, failed_tests in group_info: if num_failed > 0: if num_failed == 1: message += F"*{name[1:]}: {num_failed} failed test*\n" else: message += F"*{name[1:]}: {num_failed} failed tests*\n" UpperCAmelCase_ : str = [] UpperCAmelCase_ : str = {} for test in failed_tests: UpperCAmelCase_ : List[str] = test[0].split('::') UpperCAmelCase_ : Union[str, Any] = data[0].split('/')[-1] if data[0] not in filesafailed: UpperCAmelCase_ : int = [data[1:]] else: filesafailed[data[0]] += [data[1:]] failed_table.append(data) UpperCAmelCase_ : List[str] = [test[0] for test in failed_table] UpperCAmelCase_ : List[Any] = list(set(files)) # Count number of instances in failed_tests UpperCAmelCase_ : Optional[int] = [] for file in individual_files: table.append([file, len(filesafailed[file])]) UpperCAmelCase_ : List[Any] = tabulate( table, headers=['Test Location', 'Num Failed'], tablefmt=hf_table_format, stralign='right', ) message += F"\n```\n{failed_table}\n```" all_filesafailed.append(filesafailed) if len(message) > 3000: UpperCAmelCase_ : Optional[Any] = 'Too many failed tests, please see the full report in the Action results.' UpperCAmelCase_ : int = len(err) + 10 UpperCAmelCase_ : int = message[: 3000 - offset] + F'\n...\n```\n{err}' print(F'### {message}') else: UpperCAmelCase_ : Union[str, Any] = 'No failed tests! 🤗' print(F'## {message}') payload.append(no_error_payload) if os.environ.get('TEST_TYPE', '') != "": from slack_sdk import WebClient UpperCAmelCase_ : Dict = WebClient(token=os.environ['SLACK_API_TOKEN']) if message != "No failed tests! 🤗": UpperCAmelCase_ : Any = { 'type': 'section', 'text': { 'type': 'mrkdwn', 'text': message, }, } payload.append(md_report) UpperCAmelCase_ : Optional[int] = { 'type': 'section', 'text': { 'type': 'mrkdwn', 'text': '*For more details:*', }, 'accessory': { 'type': 'button', 'text': { 'type': 'plain_text', 'text': 'Check Action results', 'emoji': True, }, 'url': F'https://github.com/{os.environ["GITHUB_REPOSITORY"]}/actions/runs/{os.environ["GITHUB_RUN_ID"]}', }, } payload.append(action_button) UpperCAmelCase_ : str = { 'type': 'context', 'elements': [ { 'type': 'plain_text', 'text': F'Nightly {os.environ.get("TEST_TYPE")} test results for {date.today()}', } ], } payload.append(date_report) UpperCAmelCase_ : str = client.chat_postMessage(channel='#accelerate-ci-daily', text=message, blocks=payload) UpperCAmelCase_ : str = response.data['ts'] for failed_file in all_filesafailed: for test_location, test_failures in failed_file.items(): # Keep only the first instance of the test name UpperCAmelCase_ : List[Any] = '' for i, row in enumerate(test_failures): if row[0] != test_class: UpperCAmelCase_ : Tuple = row[0] else: UpperCAmelCase_ : Union[str, Any] = '' UpperCAmelCase_ : int = { 'type': 'section', 'text': { 'type': 'mrkdwn', 'text': F'Test location: {test_location}\n```\n{tabulate(test_failures, headers=["Class", "Test"], tablefmt=hf_table_format, stralign="right")}\n```', }, } client.chat_postMessage( channel='#accelerate-ci-daily', thread_ts=ts, blocks=[payload], )
32
"""simple docstring""" import torch from transformers import AutoModel class A_ ( torch.nn.Module ): """simple docstring""" def __init__( self :Optional[Any] , lowerCamelCase_ :Dict="sayef/fsner-bert-base-uncased" ): """simple docstring""" super(lowerCamelCase_ , self ).__init__() lowerCamelCase__ : Dict =AutoModel.from_pretrained(lowerCamelCase_ , return_dict=lowerCamelCase_ ) lowerCamelCase__ : Union[str, Any] =torch.nn.CosineSimilarity(3 , 1e-08 ) lowerCamelCase__ : int =torch.nn.Softmax(dim=1 ) def UpperCAmelCase__ ( self :str , **lowerCamelCase_ :Optional[Any] ): """simple docstring""" return self.bert(**lowerCamelCase_ ).last_hidden_state def UpperCAmelCase__ ( self :Optional[Any] , lowerCamelCase_ :int ): """simple docstring""" return token_embeddings.sum(2 , keepdim=lowerCamelCase_ ) def UpperCAmelCase__ ( self :Optional[int] , lowerCamelCase_ :Any , lowerCamelCase_ :Optional[Any] , lowerCamelCase_ :int=1 ): """simple docstring""" return self.softmax(T * self.cos(lowerCamelCase_ , lowerCamelCase_ ) ) def UpperCAmelCase__ ( self :Optional[int] , lowerCamelCase_ :Optional[int] , lowerCamelCase_ :str ): """simple docstring""" lowerCamelCase__ : List[str] =W_supports['sizes'].tolist() lowerCamelCase__ : Tuple =W_supports['start_token_id'].item() lowerCamelCase__ : Optional[Any] =W_supports['end_token_id'].item() del W_supports["sizes"] del W_supports["start_token_id"] del W_supports["end_token_id"] lowerCamelCase__ : int =self.BERT(**lowerCamelCase_ ) lowerCamelCase__ : Dict =self.BERT(**lowerCamelCase_ ) lowerCamelCase__ : List[str] =None lowerCamelCase__ : Any =None lowerCamelCase__ : Any =W_supports['input_ids'] == start_token_id lowerCamelCase__ : Union[str, Any] =W_supports['input_ids'] == end_token_id for i, size in enumerate(lowerCamelCase_ ): if i == 0: lowerCamelCase__ : Optional[Any] =0 else: lowerCamelCase__ : Union[str, Any] =support_sizes[i - 1] lowerCamelCase__ : List[Any] =S[s : s + size][start_token_masks[s : s + size]] lowerCamelCase__ : Dict =S[s : s + size][end_token_masks[s : s + size]] lowerCamelCase__ : str =torch.matmul(q[i] , s_start.T ).sum(1 ).softmax(0 ) lowerCamelCase__ : Union[str, Any] =torch.matmul(q[i] , s_end.T ).sum(1 ).softmax(0 ) if p_starts is not None: lowerCamelCase__ : Optional[Any] =torch.vstack((p_starts, p_start) ) lowerCamelCase__ : List[Any] =torch.vstack((p_ends, p_end) ) else: lowerCamelCase__ : Any =p_start lowerCamelCase__ : Any =p_end return p_starts, p_ends
126
0
"""simple docstring""" import json from typing import TYPE_CHECKING, List, Optional, Tuple from tokenizers import pre_tokenizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation A_ = logging.get_logger(__name__) A_ = {'''vocab_file''': '''vocab.json''', '''merges_file''': '''merges.txt''', '''tokenizer_file''': '''tokenizer.json'''} A_ = { '''tokenizer_file''': { '''EleutherAI/gpt-neox-20b''': '''https://huggingface.co/EleutherAI/gpt-neox-20b/resolve/main/tokenizer.json''', }, } A_ = { '''gpt-neox-20b''': 2048, } class __SCREAMING_SNAKE_CASE ( __lowercase ): snake_case_ = VOCAB_FILES_NAMES snake_case_ = PRETRAINED_VOCAB_FILES_MAP snake_case_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES snake_case_ = ["input_ids", "attention_mask"] def __init__( self : List[Any] , snake_case : int=None , snake_case : int=None , snake_case : str=None , snake_case : Any="<|endoftext|>" , snake_case : List[Any]="<|endoftext|>" , snake_case : Union[str, Any]="<|endoftext|>" , snake_case : str=False , **snake_case : Any , ): '''simple docstring''' super().__init__( snake_case_ , snake_case_ , tokenizer_file=snake_case_ , unk_token=snake_case_ , bos_token=snake_case_ , eos_token=snake_case_ , add_prefix_space=snake_case_ , **snake_case_ , ) A__ : int = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get("""add_prefix_space""" , snake_case_ ) != add_prefix_space: A__ : Dict = getattr(snake_case_ , pre_tok_state.pop("""type""" ) ) A__ : Optional[int] = add_prefix_space A__ : int = pre_tok_class(**snake_case_ ) A__ : Optional[int] = add_prefix_space def _UpperCamelCase ( self : str , snake_case : str , snake_case : Optional[str] = None ): '''simple docstring''' A__ : List[Any] = self._tokenizer.model.save(snake_case_ , name=snake_case_ ) return tuple(snake_case_ ) def _UpperCamelCase ( self : Optional[int] , snake_case : "Conversation" ): '''simple docstring''' A__ : int = [] for is_user, text in conversation.iter_texts(): input_ids.extend(self.encode(snake_case_ , add_special_tokens=snake_case_ ) + [self.eos_token_id] ) if len(snake_case_ ) > self.model_max_length: A__ : Dict = input_ids[-self.model_max_length :] return input_ids
352
"""simple docstring""" from collections import defaultdict from math import gcd def _lowerCAmelCase ( UpperCAmelCase__ : int = 1_5_0_0_0_0_0 ) ->int: A__ : defaultdict = defaultdict(UpperCAmelCase__ ) A__ : Any = 2 while 2 * euclid_m * (euclid_m + 1) <= limit: for euclid_n in range((euclid_m % 2) + 1, UpperCAmelCase__, 2 ): if gcd(UpperCAmelCase__, UpperCAmelCase__ ) > 1: continue A__ : str = 2 * euclid_m * (euclid_m + euclid_n) for perimeter in range(UpperCAmelCase__, limit + 1, UpperCAmelCase__ ): frequencies[perimeter] += 1 euclid_m += 1 return sum(1 for frequency in frequencies.values() if frequency == 1 ) if __name__ == "__main__": print(F'{solution() = }')
296
0
'''simple docstring''' import re def _lowerCAmelCase ( _UpperCamelCase : Optional[int] ) -> str: """simple docstring""" if len(re.findall('[ATCG]' , snake_case__ ) ) != len(snake_case__ ): raise ValueError('Invalid Strand' ) return dna.translate(dna.maketrans('ATCG' , 'TAGC' ) ) if __name__ == "__main__": import doctest doctest.testmod()
47
"""simple docstring""" import os 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_ : List[Any] = logging.get_logger(__name__) A_ : List[Any] = "▁" A_ : str = {"vocab_file": "sentencepiece.bpe.model"} A_ : Union[str, Any] = { "vocab_file": { "xlm-roberta-base": "https://huggingface.co/xlm-roberta-base/resolve/main/sentencepiece.bpe.model", "xlm-roberta-large": "https://huggingface.co/xlm-roberta-large/resolve/main/sentencepiece.bpe.model", "xlm-roberta-large-finetuned-conll02-dutch": ( "https://huggingface.co/xlm-roberta-large-finetuned-conll02-dutch/resolve/main/sentencepiece.bpe.model" ), "xlm-roberta-large-finetuned-conll02-spanish": ( "https://huggingface.co/xlm-roberta-large-finetuned-conll02-spanish/resolve/main/sentencepiece.bpe.model" ), "xlm-roberta-large-finetuned-conll03-english": ( "https://huggingface.co/xlm-roberta-large-finetuned-conll03-english/resolve/main/sentencepiece.bpe.model" ), "xlm-roberta-large-finetuned-conll03-german": ( "https://huggingface.co/xlm-roberta-large-finetuned-conll03-german/resolve/main/sentencepiece.bpe.model" ), } } A_ : List[str] = { "xlm-roberta-base": 512, "xlm-roberta-large": 512, "xlm-roberta-large-finetuned-conll02-dutch": 512, "xlm-roberta-large-finetuned-conll02-spanish": 512, "xlm-roberta-large-finetuned-conll03-english": 512, "xlm-roberta-large-finetuned-conll03-german": 512, } class lowerCamelCase (A__ ): lowerCamelCase__ : Optional[int] = VOCAB_FILES_NAMES lowerCamelCase__ : Any = PRETRAINED_VOCAB_FILES_MAP lowerCamelCase__ : int = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCamelCase__ : Tuple = ['input_ids', 'attention_mask'] def __init__( self : Tuple , __UpperCAmelCase : List[Any] , __UpperCAmelCase : Tuple="<s>" , __UpperCAmelCase : str="</s>" , __UpperCAmelCase : int="</s>" , __UpperCAmelCase : Tuple="<s>" , __UpperCAmelCase : Union[str, Any]="<unk>" , __UpperCAmelCase : List[str]="<pad>" , __UpperCAmelCase : Dict="<mask>" , __UpperCAmelCase : Optional[Dict[str, Any]] = None , **__UpperCAmelCase : Optional[int] , ) -> None: # Mask token behave like a normal word, i.e. include the space before it SCREAMING_SNAKE_CASE__ = AddedToken(__UpperCAmelCase , lstrip=__UpperCAmelCase , rstrip=__UpperCAmelCase ) if isinstance(__UpperCAmelCase , __UpperCAmelCase ) else mask_token SCREAMING_SNAKE_CASE__ = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=__UpperCAmelCase , eos_token=__UpperCAmelCase , unk_token=__UpperCAmelCase , sep_token=__UpperCAmelCase , cls_token=__UpperCAmelCase , pad_token=__UpperCAmelCase , mask_token=__UpperCAmelCase , sp_model_kwargs=self.sp_model_kwargs , **__UpperCAmelCase , ) SCREAMING_SNAKE_CASE__ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(__UpperCAmelCase ) ) SCREAMING_SNAKE_CASE__ = vocab_file # Original fairseq vocab and spm vocab must be "aligned": # Vocab | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 # -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ---- # fairseq | '<s>' | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's' | '▁de' | '-' # spm | '<unk>' | '<s>' | '</s>' | ',' | '.' | '▁' | 's' | '▁de' | '-' | '▁a' # Mimic fairseq token-to-id alignment for the first 4 token SCREAMING_SNAKE_CASE__ = {"""<s>""": 0, """<pad>""": 1, """</s>""": 2, """<unk>""": 3} # The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab SCREAMING_SNAKE_CASE__ = 1 SCREAMING_SNAKE_CASE__ = len(self.sp_model ) + self.fairseq_offset SCREAMING_SNAKE_CASE__ = {v: k for k, v in self.fairseq_tokens_to_ids.items()} def __getstate__( self : List[Any] ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__ = self.__dict__.copy() SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = self.sp_model.serialized_model_proto() return state def __setstate__( self : Tuple , __UpperCAmelCase : Optional[int] ) -> List[str]: SCREAMING_SNAKE_CASE__ = d # for backward compatibility if not hasattr(self , """sp_model_kwargs""" ): SCREAMING_SNAKE_CASE__ = {} SCREAMING_SNAKE_CASE__ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.LoadFromSerializedProto(self.sp_model_proto ) def SCREAMING_SNAKE_CASE ( self : Dict , __UpperCAmelCase : List[int] , __UpperCAmelCase : Optional[List[int]] = None ) -> List[int]: if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] SCREAMING_SNAKE_CASE__ = [self.cls_token_id] SCREAMING_SNAKE_CASE__ = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def SCREAMING_SNAKE_CASE ( self : Dict , __UpperCAmelCase : List[int] , __UpperCAmelCase : Optional[List[int]] = None , __UpperCAmelCase : bool = False ) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__UpperCAmelCase , token_ids_a=__UpperCAmelCase , already_has_special_tokens=__UpperCAmelCase ) if token_ids_a is None: return [1] + ([0] * len(__UpperCAmelCase )) + [1] return [1] + ([0] * len(__UpperCAmelCase )) + [1, 1] + ([0] * len(__UpperCAmelCase )) + [1] def SCREAMING_SNAKE_CASE ( self : int , __UpperCAmelCase : List[int] , __UpperCAmelCase : Optional[List[int]] = None ) -> List[int]: SCREAMING_SNAKE_CASE__ = [self.sep_token_id] SCREAMING_SNAKE_CASE__ = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] @property def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Optional[int]: return len(self.sp_model ) + self.fairseq_offset + 1 # Add the <mask> token def SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Tuple: SCREAMING_SNAKE_CASE__ = {self.convert_ids_to_tokens(__UpperCAmelCase ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def SCREAMING_SNAKE_CASE ( self : List[Any] , __UpperCAmelCase : str ) -> List[str]: return self.sp_model.encode(__UpperCAmelCase , out_type=__UpperCAmelCase ) def SCREAMING_SNAKE_CASE ( self : Optional[Any] , __UpperCAmelCase : List[str] ) -> Tuple: if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] SCREAMING_SNAKE_CASE__ = self.sp_model.PieceToId(__UpperCAmelCase ) # Need to return unknown token if the SP model returned 0 return spm_id + self.fairseq_offset if spm_id else self.unk_token_id def SCREAMING_SNAKE_CASE ( self : List[Any] , __UpperCAmelCase : int ) -> Any: if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(index - self.fairseq_offset ) def SCREAMING_SNAKE_CASE ( self : Optional[Any] , __UpperCAmelCase : List[Any] ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__ = """""".join(__UpperCAmelCase ).replace(__UpperCAmelCase , """ """ ).strip() return out_string def SCREAMING_SNAKE_CASE ( self : int , __UpperCAmelCase : str , __UpperCAmelCase : Optional[str] = None ) -> Tuple[str]: if not os.path.isdir(__UpperCAmelCase ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return SCREAMING_SNAKE_CASE__ = os.path.join( __UpperCAmelCase , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__UpperCAmelCase ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , __UpperCAmelCase ) elif not os.path.isfile(self.vocab_file ): with open(__UpperCAmelCase , """wb""" ) as fi: SCREAMING_SNAKE_CASE__ = self.sp_model.serialized_model_proto() fi.write(__UpperCAmelCase ) return (out_vocab_file,)
165
0
'''simple docstring''' def _lowerCAmelCase ( lowercase ) -> Union[str, Any]: __lowerCAmelCase = [[0 for _ in range(_UpperCAmelCase )] for _ in range(m + 1 )] for i in range(m + 1 ): __lowerCAmelCase = 1 for n in range(m + 1 ): for k in range(1 , _UpperCAmelCase ): memo[n][k] += memo[n][k - 1] if n - k > 0: memo[n][k] += memo[n - k - 1][k] return memo[m][m - 1] if __name__ == "__main__": import sys if len(sys.argv) == 1: try: _a : Tuple = int(input("""Enter a number: """).strip()) print(partition(n)) except ValueError: print("""Please enter a number.""") else: try: _a : List[Any] = int(sys.argv[1]) print(partition(n)) except ValueError: print("""Please pass a number.""")
365
'''simple docstring''' import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging _a : List[str] = """▁""" _a : Optional[int] = {"""vocab_file""": """spiece.model"""} _a : int = { """vocab_file""": {"""google/pegasus-xsum""": """https://huggingface.co/google/pegasus-xsum/resolve/main/spiece.model"""} } _a : int = { """google/pegasus-xsum""": 5_1_2, } _a : List[Any] = logging.get_logger(__name__) class _UpperCAmelCase ( lowerCAmelCase_ ): a : List[Any] =VOCAB_FILES_NAMES a : Tuple =VOCAB_FILES_NAMES a : Any =PRETRAINED_VOCAB_FILES_MAP a : Dict =PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES a : List[Any] =["""input_ids""", """attention_mask"""] def __init__( self,__SCREAMING_SNAKE_CASE,__SCREAMING_SNAKE_CASE="<pad>",__SCREAMING_SNAKE_CASE="</s>",__SCREAMING_SNAKE_CASE="<unk>",__SCREAMING_SNAKE_CASE="<mask_2>",__SCREAMING_SNAKE_CASE="<mask_1>",__SCREAMING_SNAKE_CASE=None,__SCREAMING_SNAKE_CASE=1_03,__SCREAMING_SNAKE_CASE = None,**__SCREAMING_SNAKE_CASE,): '''simple docstring''' __lowerCAmelCase = offset if additional_special_tokens is not None: if not isinstance(__SCREAMING_SNAKE_CASE,__SCREAMING_SNAKE_CASE ): raise TypeError( f'additional_special_tokens should be of type {type(__SCREAMING_SNAKE_CASE )}, but is' f' {type(__SCREAMING_SNAKE_CASE )}' ) __lowerCAmelCase = ( ([mask_token_sent] + additional_special_tokens) if mask_token_sent not in additional_special_tokens and mask_token_sent is not None else additional_special_tokens ) # fill additional tokens with ..., <unk_token_102> in case not all additional tokens are already taken additional_special_tokens_extended += [ f'<unk_{i}>' for i in range(len(__SCREAMING_SNAKE_CASE ),self.offset - 1 ) ] if len(set(__SCREAMING_SNAKE_CASE ) ) != len(__SCREAMING_SNAKE_CASE ): raise ValueError( """Please make sure that the provided additional_special_tokens do not contain an incorrectly""" f' shifted list of <unk_x> tokens. Found {additional_special_tokens_extended}.' ) __lowerCAmelCase = additional_special_tokens_extended else: __lowerCAmelCase = [mask_token_sent] if mask_token_sent is not None else [] additional_special_tokens += [f'<unk_{i}>' for i in range(2,self.offset )] __lowerCAmelCase = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( eos_token=__SCREAMING_SNAKE_CASE,unk_token=__SCREAMING_SNAKE_CASE,mask_token=__SCREAMING_SNAKE_CASE,pad_token=__SCREAMING_SNAKE_CASE,mask_token_sent=__SCREAMING_SNAKE_CASE,offset=__SCREAMING_SNAKE_CASE,additional_special_tokens=__SCREAMING_SNAKE_CASE,sp_model_kwargs=self.sp_model_kwargs,**__SCREAMING_SNAKE_CASE,) __lowerCAmelCase = mask_token_sent __lowerCAmelCase = vocab_file __lowerCAmelCase = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(__SCREAMING_SNAKE_CASE ) # add special tokens to encoder dict __lowerCAmelCase = { 0: self.pad_token, 1: self.eos_token, } if self.mask_token_sent is not None: self.encoder.update( { 2: self.mask_token_sent, 3: self.mask_token, } ) if self.offset > 0: # entries 2-104 are only used for pretraining and called <mask_1>, <mask_2>, unk_2, ...unk_102 # mask_token_sent is already added to list -> so start at 1 self.encoder.update({i + 3: additional_special_tokens[i] for i in range(1,self.offset - 1 )} ) __lowerCAmelCase = {v: k for k, v in self.encoder.items()} @property def lowerCamelCase__ ( self ): '''simple docstring''' return len(self.sp_model ) + self.offset def lowerCamelCase__ ( self ): '''simple docstring''' __lowerCAmelCase = {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 ): '''simple docstring''' __lowerCAmelCase = self.__dict__.copy() __lowerCAmelCase = None return state def __setstate__( self,__SCREAMING_SNAKE_CASE ): '''simple docstring''' __lowerCAmelCase = d # for backward compatibility if not hasattr(self,"""sp_model_kwargs""" ): __lowerCAmelCase = {} __lowerCAmelCase = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def lowerCamelCase__ ( self,__SCREAMING_SNAKE_CASE ): '''simple docstring''' return self.sp_model.encode(__SCREAMING_SNAKE_CASE,out_type=__SCREAMING_SNAKE_CASE ) def lowerCamelCase__ ( self,__SCREAMING_SNAKE_CASE ): '''simple docstring''' if token in self.decoder: return self.decoder[token] elif token in self.added_tokens_decoder: return self.added_tokens_decoder[token] __lowerCAmelCase = self.sp_model.piece_to_id(__SCREAMING_SNAKE_CASE ) return sp_id + self.offset def lowerCamelCase__ ( self,__SCREAMING_SNAKE_CASE ): '''simple docstring''' if index in self.encoder: return self.encoder[index] elif index in self.added_tokens_encoder: return self.added_tokens_encoder[index] else: __lowerCAmelCase = self.sp_model.IdToPiece(index - self.offset ) return token def lowerCamelCase__ ( self,__SCREAMING_SNAKE_CASE ): '''simple docstring''' __lowerCAmelCase = [] __lowerCAmelCase = """""" for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: out_string += self.sp_model.decode(__SCREAMING_SNAKE_CASE ) + token __lowerCAmelCase = [] else: current_sub_tokens.append(__SCREAMING_SNAKE_CASE ) out_string += self.sp_model.decode(__SCREAMING_SNAKE_CASE ) return out_string.strip() def lowerCamelCase__ ( self,__SCREAMING_SNAKE_CASE=False ): '''simple docstring''' return 1 def lowerCamelCase__ ( self,__SCREAMING_SNAKE_CASE ): '''simple docstring''' __lowerCAmelCase = set(self.all_special_ids ) # call it once instead of inside list comp all_special_ids.remove(self.unk_token_id ) # <unk> is only sometimes special return [1 if x in all_special_ids else 0 for x in seq] def lowerCamelCase__ ( self,__SCREAMING_SNAKE_CASE,__SCREAMING_SNAKE_CASE = None,__SCREAMING_SNAKE_CASE = False ): '''simple docstring''' if already_has_special_tokens: return self._special_token_mask(__SCREAMING_SNAKE_CASE ) elif token_ids_a is None: return self._special_token_mask(__SCREAMING_SNAKE_CASE ) + [1] else: return self._special_token_mask(token_ids_a + token_ids_a ) + [1] def lowerCamelCase__ ( self,__SCREAMING_SNAKE_CASE,__SCREAMING_SNAKE_CASE=None ): '''simple docstring''' if token_ids_a is None: return token_ids_a + [self.eos_token_id] # We don't expect to process pairs, but leave the pair logic for API consistency return token_ids_a + token_ids_a + [self.eos_token_id] def lowerCamelCase__ ( self,__SCREAMING_SNAKE_CASE,__SCREAMING_SNAKE_CASE = None ): '''simple docstring''' if not os.path.isdir(__SCREAMING_SNAKE_CASE ): logger.error(f'Vocabulary path ({save_directory}) should be a directory' ) return __lowerCAmelCase = 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 = self.sp_model.serialized_model_proto() fi.write(__SCREAMING_SNAKE_CASE ) return (out_vocab_file,)
46
0
'''simple docstring''' import builtins import sys from ...utils.imports import _is_package_available from . import cursor, input from .helpers import Direction, clear_line, forceWrite, linebreak, move_cursor, reset_cursor, writeColor from .keymap import KEYMAP __UpperCAmelCase =False try: __UpperCAmelCase =_is_package_available("google.colab") except ModuleNotFoundError: pass @input.register class a__ : def __init__( self : Dict , a : str = None , a : list = [] ): """simple docstring""" __lowerCamelCase = 0 __lowerCamelCase = choices __lowerCamelCase = prompt if sys.platform == "win32": __lowerCamelCase = '''*''' else: __lowerCamelCase = '''➔ ''' def SCREAMING_SNAKE_CASE__ ( self : str , a : int , a : str = "" ): """simple docstring""" if sys.platform != "win32": writeColor(self.choices[index] , 32 , a ) else: forceWrite(self.choices[index] , a ) def SCREAMING_SNAKE_CASE__ ( self : List[Any] , a : int ): """simple docstring""" if index == self.position: forceWrite(f""" {self.arrow_char} """ ) self.write_choice(a ) else: forceWrite(f""" {self.choices[index]}""" ) reset_cursor() def SCREAMING_SNAKE_CASE__ ( self : Any , a : Direction , a : int = 1 ): """simple docstring""" __lowerCamelCase = self.position if direction == Direction.DOWN: if self.position + 1 >= len(self.choices ): return self.position += num_spaces else: if self.position - 1 < 0: return self.position -= num_spaces clear_line() self.print_choice(a ) move_cursor(a , direction.name ) self.print_choice(self.position ) @input.mark(KEYMAP['''up'''] ) def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ): """simple docstring""" self.move_direction(Direction.UP ) @input.mark(KEYMAP['''down'''] ) def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ): """simple docstring""" self.move_direction(Direction.DOWN ) @input.mark(KEYMAP['''newline'''] ) def SCREAMING_SNAKE_CASE__ ( self : List[str] ): """simple docstring""" move_cursor(len(self.choices ) - self.position , '''DOWN''' ) return self.position @input.mark(KEYMAP['''interrupt'''] ) def SCREAMING_SNAKE_CASE__ ( self : Tuple ): """simple docstring""" move_cursor(len(self.choices ) - self.position , '''DOWN''' ) raise KeyboardInterrupt @input.mark_multiple(*[KEYMAP[str(a )] for number in range(10 )] ) def SCREAMING_SNAKE_CASE__ ( self : Dict ): """simple docstring""" __lowerCamelCase = int(chr(self.current_selection ) ) __lowerCamelCase = index - self.position if index == self.position: return if index < len(self.choices ): if self.position > index: self.move_direction(Direction.UP , -movement ) elif self.position < index: self.move_direction(Direction.DOWN , a ) else: return else: return def SCREAMING_SNAKE_CASE__ ( self : List[str] , a : int = 0 ): """simple docstring""" if self.prompt: linebreak() forceWrite(self.prompt , '''\n''' ) if in_colab: forceWrite('''Please input a choice index (starting from 0), and press enter''' , '''\n''' ) else: forceWrite('''Please select a choice using the arrow or number keys, and selecting with enter''' , '''\n''' ) __lowerCamelCase = default_choice for i in range(len(self.choices ) ): self.print_choice(a ) forceWrite('''\n''' ) move_cursor(len(self.choices ) - self.position , '''UP''' ) with cursor.hide(): while True: if in_colab: try: __lowerCamelCase = int(builtins.input() ) except ValueError: __lowerCamelCase = default_choice else: __lowerCamelCase = self.handle_input() if choice is not None: reset_cursor() for _ in range(len(self.choices ) + 1 ): move_cursor(1 , '''UP''' ) clear_line() self.write_choice(a , '''\n''' ) return choice
67
"""simple docstring""" def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' if upper_limit < 0: raise ValueError("Limit for the Catalan sequence must be ≥ 0" ) __SCREAMING_SNAKE_CASE = [0] * (upper_limit + 1) # Base case: C(0) = C(1) = 1 __SCREAMING_SNAKE_CASE = 1 if upper_limit > 0: __SCREAMING_SNAKE_CASE = 1 # Recurrence relation: C(i) = sum(C(j).C(i-j-1)), from j = 0 to i for i in range(2 , upper_limit + 1 ): for j in range(lowerCAmelCase_ ): catalan_list[i] += catalan_list[j] * catalan_list[i - j - 1] return catalan_list if __name__ == "__main__": print('''\n********* Catalan Numbers Using Dynamic Programming ************\n''') print('''\n*** Enter -1 at any time to quit ***''') print('''\nEnter the upper limit (≥ 0) for the Catalan number sequence: ''', end='''''') try: while True: a__ : List[str] = int(input().strip()) if N < 0: print('''\n********* Goodbye!! ************''') break else: print(F"The Catalan numbers from 0 through {N} are:") print(catalan_numbers(N)) print('''Try another upper limit for the sequence: ''', end='''''') except (NameError, ValueError): print('''\n********* Invalid input, goodbye! ************\n''') import doctest doctest.testmod()
54
0
"""simple docstring""" def _lowerCAmelCase ( UpperCAmelCase__ : List[Any] ) ->Dict: A__ : Any = len(UpperCAmelCase__ ) while cur > 1: # Find the maximum number in arr A__ : int = arr.index(max(arr[0:cur] ) ) # Reverse from 0 to mi A__ : List[str] = arr[mi::-1] + arr[mi + 1 : len(UpperCAmelCase__ )] # Reverse whole list A__ : Tuple = arr[cur - 1 :: -1] + arr[cur : len(UpperCAmelCase__ )] cur -= 1 return arr if __name__ == "__main__": A_ = input('''Enter numbers separated by a comma:\n''').strip() A_ = [int(item) for item in user_input.split(''',''')] print(pancake_sort(unsorted))
296
"""simple docstring""" import cva import numpy as np class __SCREAMING_SNAKE_CASE : def __init__( self : Union[str, Any] , snake_case : float , snake_case : int ): '''simple docstring''' if k in (0.04, 0.06): A__ : Optional[int] = k A__ : int = window_size else: raise ValueError("""invalid k value""" ) def __str__( self : List[Any] ): '''simple docstring''' return str(self.k ) def _UpperCamelCase ( self : int , snake_case : str ): '''simple docstring''' A__ : List[str] = cva.imread(snake_case , 0 ) A__ , A__ : Union[str, Any] = img.shape A__ : list[list[int]] = [] A__ : Optional[Any] = img.copy() A__ : List[str] = cva.cvtColor(snake_case , cva.COLOR_GRAY2RGB ) A__ , A__ : List[Any] = np.gradient(snake_case ) A__ : List[Any] = dx**2 A__ : Any = dy**2 A__ : Dict = dx * dy A__ : Any = 0.04 A__ : Optional[Any] = self.window_size // 2 for y in range(snake_case , h - offset ): for x in range(snake_case , w - offset ): A__ : List[str] = ixx[ y - offset : y + offset + 1, x - offset : x + offset + 1 ].sum() A__ : Tuple = iyy[ y - offset : y + offset + 1, x - offset : x + offset + 1 ].sum() A__ : Optional[int] = ixy[ y - offset : y + offset + 1, x - offset : x + offset + 1 ].sum() A__ : int = (wxx * wyy) - (wxy**2) A__ : Any = wxx + wyy A__ : List[str] = det - k * (trace**2) # Can change the value if r > 0.5: corner_list.append([x, y, r] ) color_img.itemset((y, x, 0) , 0 ) color_img.itemset((y, x, 1) , 0 ) color_img.itemset((y, x, 2) , 255 ) return color_img, corner_list if __name__ == "__main__": A_ = HarrisCorner(0.04, 3) A_ , A_ = edge_detect.detect('''path_to_image''') cva.imwrite('''detect.png''', color_img)
296
1
"""simple docstring""" import json import os from typing import Optional, Tuple import regex as re from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging SCREAMING_SNAKE_CASE_ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE_ = { '''vocab_file''': '''vocab.json''', '''merges_file''': '''merges.txt''', } SCREAMING_SNAKE_CASE_ = { '''vocab_file''': {'''ctrl''': '''https://raw.githubusercontent.com/salesforce/ctrl/master/ctrl-vocab.json'''}, '''merges_file''': {'''ctrl''': '''https://raw.githubusercontent.com/salesforce/ctrl/master/ctrl-merges.txt'''}, } SCREAMING_SNAKE_CASE_ = { '''ctrl''': 256, } SCREAMING_SNAKE_CASE_ = { '''Pregnancy''': 168_629, '''Christianity''': 7_675, '''Explain''': 106_423, '''Fitness''': 63_440, '''Saving''': 63_163, '''Ask''': 27_171, '''Ass''': 95_985, '''Joke''': 163_509, '''Questions''': 45_622, '''Thoughts''': 49_605, '''Retail''': 52_342, '''Feminism''': 164_338, '''Writing''': 11_992, '''Atheism''': 192_263, '''Netflix''': 48_616, '''Computing''': 39_639, '''Opinion''': 43_213, '''Alone''': 44_967, '''Funny''': 58_917, '''Gaming''': 40_358, '''Human''': 4_088, '''India''': 1_331, '''Joker''': 77_138, '''Diet''': 36_206, '''Legal''': 11_859, '''Norman''': 4_939, '''Tip''': 72_689, '''Weight''': 52_343, '''Movies''': 46_273, '''Running''': 23_425, '''Science''': 2_090, '''Horror''': 37_793, '''Confession''': 60_572, '''Finance''': 12_250, '''Politics''': 16_360, '''Scary''': 191_985, '''Support''': 12_654, '''Technologies''': 32_516, '''Teenage''': 66_160, '''Event''': 32_769, '''Learned''': 67_460, '''Notion''': 182_770, '''Wikipedia''': 37_583, '''Books''': 6_665, '''Extract''': 76_050, '''Confessions''': 102_701, '''Conspiracy''': 75_932, '''Links''': 63_674, '''Narcissus''': 150_425, '''Relationship''': 54_766, '''Relationships''': 134_796, '''Reviews''': 41_671, '''News''': 4_256, '''Translation''': 26_820, '''multilingual''': 128_406, } def lowercase (_lowerCAmelCase ): __lowerCAmelCase = set() __lowerCAmelCase = word[0] for char in word[1:]: pairs.add((prev_char, char) ) __lowerCAmelCase = char __lowerCAmelCase = set(_lowerCAmelCase ) return pairs class lowerCAmelCase_ ( A__ ): '''simple docstring''' _snake_case = VOCAB_FILES_NAMES _snake_case = PRETRAINED_VOCAB_FILES_MAP _snake_case = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _snake_case = CONTROL_CODES def __init__( self , snake_case_ , snake_case_ , snake_case_="<unk>" , **snake_case_ ) -> Optional[int]: super().__init__(unk_token=snake_case_ , **snake_case_ ) with open(snake_case_ , encoding="""utf-8""" ) as vocab_handle: __lowerCAmelCase = json.load(snake_case_ ) __lowerCAmelCase = {v: k for k, v in self.encoder.items()} with open(snake_case_ , encoding="""utf-8""" ) as merges_handle: __lowerCAmelCase = merges_handle.read().split("""\n""" )[1:-1] __lowerCAmelCase = [tuple(merge.split() ) for merge in merges] __lowerCAmelCase = dict(zip(snake_case_ , range(len(snake_case_ ) ) ) ) __lowerCAmelCase = {} @property def A__ ( self ) -> List[Any]: return len(self.encoder ) def A__ ( self ) -> int: return dict(self.encoder , **self.added_tokens_encoder ) def A__ ( self , snake_case_ ) -> Tuple: if token in self.cache: return self.cache[token] __lowerCAmelCase = tuple(snake_case_ ) __lowerCAmelCase = tuple(list(word[:-1] ) + [word[-1] + """</w>"""] ) __lowerCAmelCase = get_pairs(snake_case_ ) if not pairs: return token while True: __lowerCAmelCase = min(snake_case_ , key=lambda snake_case_ : self.bpe_ranks.get(snake_case_ , float("""inf""" ) ) ) if bigram not in self.bpe_ranks: break __lowerCAmelCase , __lowerCAmelCase = bigram __lowerCAmelCase = [] __lowerCAmelCase = 0 while i < len(snake_case_ ): try: __lowerCAmelCase = word.index(snake_case_ , snake_case_ ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) __lowerCAmelCase = j if word[i] == first and i < len(snake_case_ ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 __lowerCAmelCase = tuple(snake_case_ ) __lowerCAmelCase = new_word if len(snake_case_ ) == 1: break else: __lowerCAmelCase = get_pairs(snake_case_ ) __lowerCAmelCase = """@@ """.join(snake_case_ ) __lowerCAmelCase = word[:-4] __lowerCAmelCase = word return word def A__ ( self , snake_case_ ) -> str: __lowerCAmelCase = [] __lowerCAmelCase = re.findall(r"""\S+\n?""" , snake_case_ ) for token in words: split_tokens.extend(list(self.bpe(snake_case_ ).split(""" """ ) ) ) return split_tokens def A__ ( self , snake_case_ ) -> Any: return self.encoder.get(snake_case_ , self.encoder.get(self.unk_token ) ) def A__ ( self , snake_case_ ) -> List[str]: return self.decoder.get(snake_case_ , self.unk_token ) def A__ ( self , snake_case_ ) -> List[Any]: __lowerCAmelCase = """ """.join(snake_case_ ).replace("""@@ """ , """""" ).strip() return out_string def A__ ( self , snake_case_ , snake_case_ = None ) -> Tuple[str]: if not os.path.isdir(snake_case_ ): logger.error(f"""Vocabulary path ({save_directory}) should be a directory""" ) return __lowerCAmelCase = os.path.join( snake_case_ , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) __lowerCAmelCase = os.path.join( snake_case_ , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""merges_file"""] ) with open(snake_case_ , """w""" , encoding="""utf-8""" ) as f: f.write(json.dumps(self.encoder , indent=2 , sort_keys=snake_case_ , ensure_ascii=snake_case_ ) + """\n""" ) __lowerCAmelCase = 0 with open(snake_case_ , """w""" , encoding="""utf-8""" ) as writer: writer.write("""#version: 0.2\n""" ) for bpe_tokens, token_index in sorted(self.bpe_ranks.items() , key=lambda snake_case_ : kv[1] ): if index != token_index: logger.warning( f"""Saving vocabulary to {merge_file}: BPE merge indices are not consecutive.""" """ Please check that the tokenizer is not corrupted!""" ) __lowerCAmelCase = token_index writer.write(""" """.join(snake_case_ ) + """\n""" ) index += 1 return vocab_file, merge_file # def decode(self, token_ids, skip_special_tokens=False, clean_up_tokenization_spaces=True): # filtered_tokens = ' '.join(self.convert_ids_to_tokens(token_ids, skip_special_tokens=skip_special_tokens)) # tokens_generated_so_far = re.sub('(@@ )', '', string=filtered_tokens) # tokens_generated_so_far = re.sub('(@@ ?$)', '', string=tokens_generated_so_far) # return ''.join(tokens_generated_so_far)
301
"""simple docstring""" import argparse import datetime import json import time import warnings from logging import getLogger from pathlib import Path from typing import Dict, List import torch from tqdm import tqdm from transformers import AutoModelForSeqaSeqLM, AutoTokenizer from utils import calculate_bleu, calculate_rouge, chunks, parse_numeric_n_bool_cl_kwargs, use_task_specific_params SCREAMING_SNAKE_CASE_ = getLogger(__name__) SCREAMING_SNAKE_CASE_ = '''cuda''' if torch.cuda.is_available() else '''cpu''' def lowercase (_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase = 8 , _lowerCAmelCase = DEFAULT_DEVICE , _lowerCAmelCase=False , _lowerCAmelCase="summarization" , _lowerCAmelCase=None , **_lowerCAmelCase , ): __lowerCAmelCase = Path(_lowerCAmelCase ).open("""w""" , encoding="""utf-8""" ) __lowerCAmelCase = str(_lowerCAmelCase ) __lowerCAmelCase = AutoModelForSeqaSeqLM.from_pretrained(_lowerCAmelCase ).to(_lowerCAmelCase ) if fpaa: __lowerCAmelCase = model.half() __lowerCAmelCase = AutoTokenizer.from_pretrained(_lowerCAmelCase ) logger.info(f"""Inferred tokenizer type: {tokenizer.__class__}""" ) # if this is wrong, check config.model_type. __lowerCAmelCase = time.time() # update config with task specific params use_task_specific_params(_lowerCAmelCase , _lowerCAmelCase ) if prefix is None: __lowerCAmelCase = prefix or getattr(model.config , """prefix""" , """""" ) or """""" for examples_chunk in tqdm(list(chunks(_lowerCAmelCase , _lowerCAmelCase ) ) ): __lowerCAmelCase = [prefix + text for text in examples_chunk] __lowerCAmelCase = tokenizer(_lowerCAmelCase , return_tensors="""pt""" , truncation=_lowerCAmelCase , padding="""longest""" ).to(_lowerCAmelCase ) __lowerCAmelCase = model.generate( input_ids=batch.input_ids , attention_mask=batch.attention_mask , **_lowerCAmelCase , ) __lowerCAmelCase = tokenizer.batch_decode(_lowerCAmelCase , skip_special_tokens=_lowerCAmelCase , clean_up_tokenization_spaces=_lowerCAmelCase ) for hypothesis in dec: fout.write(hypothesis + """\n""" ) fout.flush() fout.close() __lowerCAmelCase = int(time.time() - start_time ) # seconds __lowerCAmelCase = len(_lowerCAmelCase ) return {"n_obs": n_obs, "runtime": runtime, "seconds_per_sample": round(runtime / n_obs , 4 )} def lowercase (): return datetime.datetime.now().strftime("""%Y-%m-%d %H:%M:%S""" ) def lowercase (_lowerCAmelCase=True ): __lowerCAmelCase = argparse.ArgumentParser() parser.add_argument("""model_name""" , type=_lowerCAmelCase , help="""like facebook/bart-large-cnn,t5-base, etc.""" ) parser.add_argument("""input_path""" , type=_lowerCAmelCase , help="""like cnn_dm/test.source""" ) parser.add_argument("""save_path""" , type=_lowerCAmelCase , help="""where to save summaries""" ) parser.add_argument("""--reference_path""" , type=_lowerCAmelCase , required=_lowerCAmelCase , help="""like cnn_dm/test.target""" ) parser.add_argument("""--score_path""" , type=_lowerCAmelCase , required=_lowerCAmelCase , default="""metrics.json""" , help="""where to save metrics""" ) parser.add_argument("""--device""" , type=_lowerCAmelCase , required=_lowerCAmelCase , default=_lowerCAmelCase , help="""cuda, cuda:1, cpu etc.""" ) parser.add_argument( """--prefix""" , type=_lowerCAmelCase , required=_lowerCAmelCase , default=_lowerCAmelCase , help="""will be added to the begininng of src examples""" ) parser.add_argument("""--task""" , type=_lowerCAmelCase , default="""summarization""" , help="""used for task_specific_params + metrics""" ) parser.add_argument("""--bs""" , type=_lowerCAmelCase , default=8 , required=_lowerCAmelCase , help="""batch size""" ) parser.add_argument( """--n_obs""" , type=_lowerCAmelCase , default=-1 , required=_lowerCAmelCase , help="""How many observations. Defaults to all.""" ) parser.add_argument("""--fp16""" , action="""store_true""" ) parser.add_argument("""--dump-args""" , action="""store_true""" , help="""print the custom hparams with the results""" ) parser.add_argument( """--info""" , nargs="""?""" , type=_lowerCAmelCase , const=datetime_now() , help=( """use in conjunction w/ --dump-args to print with the results whatever other info you'd like, e.g.""" """ lang=en-ru. If no value is passed, the current datetime string will be used.""" ) , ) # Unspecified args like --num_beams=2 --decoder_start_token_id=4 are passed to model.generate __lowerCAmelCase , __lowerCAmelCase = parser.parse_known_args() __lowerCAmelCase = parse_numeric_n_bool_cl_kwargs(_lowerCAmelCase ) if parsed_args and verbose: print(f"""parsed the following generate kwargs: {parsed_args}""" ) __lowerCAmelCase = [""" """ + x.rstrip() if """t5""" in args.model_name else x.rstrip() for x in open(args.input_path ).readlines()] if args.n_obs > 0: __lowerCAmelCase = examples[: args.n_obs] Path(args.save_path ).parent.mkdir(exist_ok=_lowerCAmelCase ) if args.reference_path is None and Path(args.score_path ).exists(): warnings.warn(f"""score_path {args.score_path} will be overwritten unless you type ctrl-c.""" ) if args.device == "cpu" and args.fpaa: # this mix leads to RuntimeError: "threshold_cpu" not implemented for 'Half' raise ValueError("""Can't mix --fp16 and --device cpu""" ) __lowerCAmelCase = generate_summaries_or_translations( _lowerCAmelCase , args.save_path , args.model_name , batch_size=args.bs , device=args.device , fpaa=args.fpaa , task=args.task , prefix=args.prefix , **_lowerCAmelCase , ) if args.reference_path is None: return {} # Compute scores __lowerCAmelCase = calculate_bleu if """translation""" in args.task else calculate_rouge __lowerCAmelCase = [x.rstrip() for x in open(args.save_path ).readlines()] __lowerCAmelCase = [x.rstrip() for x in open(args.reference_path ).readlines()][: len(_lowerCAmelCase )] __lowerCAmelCase = score_fn(_lowerCAmelCase , _lowerCAmelCase ) scores.update(_lowerCAmelCase ) if args.dump_args: scores.update(_lowerCAmelCase ) if args.info: __lowerCAmelCase = args.info if verbose: print(_lowerCAmelCase ) if args.score_path is not None: json.dump(_lowerCAmelCase , open(args.score_path , """w""" ) ) return scores if __name__ == "__main__": # Usage for MT: # python run_eval.py MODEL_NAME $DATA_DIR/test.source $save_dir/test_translations.txt --reference_path $DATA_DIR/test.target --score_path $save_dir/test_bleu.json --task translation $@ run_generate(verbose=True)
301
1
def UpperCamelCase ( __lowerCamelCase : int , __lowerCamelCase : int ): if number < 0 or shift_amount < 0: raise ValueError("both inputs must be positive integers" ) snake_case : Any = str(bin(__lowerCamelCase ) ) binary_number += "0" * shift_amount return binary_number def UpperCamelCase ( __lowerCamelCase : int , __lowerCamelCase : int ): if number < 0 or shift_amount < 0: raise ValueError("both inputs must be positive integers" ) snake_case : Any = str(bin(__lowerCamelCase ) )[2:] if shift_amount >= len(__lowerCamelCase ): return "0b0" snake_case : Tuple = binary_number[: len(__lowerCamelCase ) - shift_amount] return "0b" + shifted_binary_number def UpperCamelCase ( __lowerCamelCase : int , __lowerCamelCase : int ): if number >= 0: # Get binary representation of positive number snake_case : List[str] = "0" + str(bin(__lowerCamelCase ) ).strip("-" )[2:] else: # Get binary (2's complement) representation of negative number snake_case : Optional[Any] = len(bin(__lowerCamelCase )[3:] ) # Find 2's complement of number snake_case : Dict = bin(abs(__lowerCamelCase ) - (1 << binary_number_length) )[3:] snake_case : Optional[int] = ( "1" + "0" * (binary_number_length - len(__lowerCamelCase )) + binary_number ) if shift_amount >= len(__lowerCamelCase ): return "0b" + binary_number[0] * len(__lowerCamelCase ) return ( "0b" + binary_number[0] * shift_amount + binary_number[: len(__lowerCamelCase ) - shift_amount] ) if __name__ == "__main__": import doctest doctest.testmod()
367
from __future__ import annotations def UpperCamelCase ( __lowerCamelCase : list[int] ): snake_case : Optional[int] = len(__lowerCamelCase ) // 2 # choose the middle 3 elements snake_case : str = lst[m - 1 : m + 2] # if middle element is peak if three[1] > three[0] and three[1] > three[2]: return three[1] # if increasing, recurse on right elif three[0] < three[2]: if len(lst[:m] ) == 2: m -= 1 return peak(lst[m:] ) # decreasing else: if len(lst[:m] ) == 2: m += 1 return peak(lst[:m] ) if __name__ == "__main__": import doctest doctest.testmod()
10
0
"""simple docstring""" def A ( snake_case :float , snake_case :list[float] ) -> float: if discount_rate < 0: raise ValueError('Discount rate cannot be negative' ) if not cash_flows: raise ValueError('Cash flows list cannot be empty' ) __UpperCamelCase = sum( cash_flow / ((1 + discount_rate) ** i) for i, cash_flow in enumerate(snake_case ) ) return round(snake_case , ndigits=2 ) if __name__ == "__main__": import doctest doctest.testmod()
316
"""simple docstring""" from typing import List, Optional, Tuple, Union import torch from ...models import UNetaDModel from ...schedulers import ScoreSdeVeScheduler from ...utils import randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): lowercase = 42 lowercase = 42 def __init__( self , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' super().__init__() self.register_modules(unet=__UpperCAmelCase , scheduler=__UpperCAmelCase ) @torch.no_grad() def __call__( self , __UpperCAmelCase = 1 , __UpperCAmelCase = 2000 , __UpperCAmelCase = None , __UpperCAmelCase = "pil" , __UpperCAmelCase = True , **__UpperCAmelCase , ): '''simple docstring''' __UpperCamelCase = self.unet.config.sample_size __UpperCamelCase = (batch_size, 3, img_size, img_size) __UpperCamelCase = self.unet __UpperCamelCase = randn_tensor(__UpperCAmelCase , generator=__UpperCAmelCase ) * self.scheduler.init_noise_sigma __UpperCamelCase = sample.to(self.device ) self.scheduler.set_timesteps(__UpperCAmelCase ) self.scheduler.set_sigmas(__UpperCAmelCase ) for i, t in enumerate(self.progress_bar(self.scheduler.timesteps ) ): __UpperCamelCase = self.scheduler.sigmas[i] * torch.ones(shape[0] , device=self.device ) # correction step for _ in range(self.scheduler.config.correct_steps ): __UpperCamelCase = self.unet(__UpperCAmelCase , __UpperCAmelCase ).sample __UpperCamelCase = self.scheduler.step_correct(__UpperCAmelCase , __UpperCAmelCase , generator=__UpperCAmelCase ).prev_sample # prediction step __UpperCamelCase = model(__UpperCAmelCase , __UpperCAmelCase ).sample __UpperCamelCase = self.scheduler.step_pred(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , generator=__UpperCAmelCase ) __UpperCamelCase , __UpperCamelCase = output.prev_sample, output.prev_sample_mean __UpperCamelCase = sample_mean.clamp(0 , 1 ) __UpperCamelCase = sample.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": __UpperCamelCase = self.numpy_to_pil(__UpperCAmelCase ) if not return_dict: return (sample,) return ImagePipelineOutput(images=__UpperCAmelCase )
316
1
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase = logging.get_logger(__name__) UpperCAmelCase = { '''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 __snake_case( a__ ): '''simple docstring''' UpperCAmelCase : Tuple = """gpt_neox""" def __init__( self , A_=5_0432 , A_=6144 , A_=44 , A_=64 , A_=2_4576 , A_="gelu" , A_=0.2_5 , A_=1_0000 , A_=0.0 , A_=0.0 , A_=0.1 , A_=2048 , A_=0.0_2 , A_=1e-5 , A_=True , A_=0 , A_=2 , A_=False , A_=True , A_=None , **A_ , ) -> Tuple: super().__init__(bos_token_id=lowerCAmelCase__ , eos_token_id=lowerCAmelCase__ , **lowerCAmelCase__ ) lowerCAmelCase = vocab_size lowerCAmelCase = max_position_embeddings lowerCAmelCase = hidden_size lowerCAmelCase = num_hidden_layers lowerCAmelCase = num_attention_heads lowerCAmelCase = intermediate_size lowerCAmelCase = hidden_act lowerCAmelCase = rotary_pct lowerCAmelCase = rotary_emb_base lowerCAmelCase = attention_dropout lowerCAmelCase = hidden_dropout lowerCAmelCase = classifier_dropout lowerCAmelCase = initializer_range lowerCAmelCase = layer_norm_eps lowerCAmelCase = use_cache lowerCAmelCase = tie_word_embeddings lowerCAmelCase = use_parallel_residual lowerCAmelCase = 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 __snake_case ( self ) -> Union[str, Any]: if self.rope_scaling is None: return if not isinstance(self.rope_scaling , lowerCAmelCase__ ) 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}' ) lowerCAmelCase = self.rope_scaling.get("""type""" , lowerCAmelCase__ ) lowerCAmelCase = self.rope_scaling.get("""factor""" , lowerCAmelCase__ ) 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(lowerCAmelCase__ , lowerCAmelCase__ ) or rope_scaling_factor <= 1.0: raise ValueError(f'`rope_scaling`\'s factor field must be an float > 1, got {rope_scaling_factor}' )
363
'''simple docstring''' import time import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch, torch_device from ..test_modeling_common import ids_tensor if is_torch_available(): import torch from transformers.generation import ( MaxLengthCriteria, MaxNewTokensCriteria, MaxTimeCriteria, StoppingCriteriaList, validate_stopping_criteria, ) @require_torch class __snake_case( unittest.TestCase ): '''simple docstring''' def __snake_case ( self , A_ ) -> str: lowerCAmelCase = 3 lowerCAmelCase = 250 lowerCAmelCase = ids_tensor((batch_size, length) , A_ ) lowerCAmelCase = torch.ones((batch_size, length) , device=A_ , dtype=torch.float ) / length return input_ids, scores def __snake_case ( self ) -> Any: lowerCAmelCase, lowerCAmelCase = self._get_tensors(5 ) lowerCAmelCase = StoppingCriteriaList( [ MaxLengthCriteria(max_length=10 ), MaxTimeCriteria(max_time=0.1 ), ] ) self.assertFalse(criteria(A_ , A_ ) ) lowerCAmelCase, lowerCAmelCase = self._get_tensors(9 ) self.assertFalse(criteria(A_ , A_ ) ) lowerCAmelCase, lowerCAmelCase = self._get_tensors(10 ) self.assertTrue(criteria(A_ , A_ ) ) def __snake_case ( self ) -> Optional[int]: lowerCAmelCase = MaxLengthCriteria(max_length=10 ) lowerCAmelCase, lowerCAmelCase = self._get_tensors(5 ) self.assertFalse(criteria(A_ , A_ ) ) lowerCAmelCase, lowerCAmelCase = self._get_tensors(9 ) self.assertFalse(criteria(A_ , A_ ) ) lowerCAmelCase, lowerCAmelCase = self._get_tensors(10 ) self.assertTrue(criteria(A_ , A_ ) ) def __snake_case ( self ) -> List[Any]: lowerCAmelCase = MaxNewTokensCriteria(start_length=5 , max_new_tokens=5 ) lowerCAmelCase, lowerCAmelCase = self._get_tensors(5 ) self.assertFalse(criteria(A_ , A_ ) ) lowerCAmelCase, lowerCAmelCase = self._get_tensors(9 ) self.assertFalse(criteria(A_ , A_ ) ) lowerCAmelCase, lowerCAmelCase = self._get_tensors(10 ) self.assertTrue(criteria(A_ , A_ ) ) lowerCAmelCase = StoppingCriteriaList([criteria] ) self.assertEqual(criteria_list.max_length , 10 ) def __snake_case ( self ) -> List[str]: lowerCAmelCase, lowerCAmelCase = self._get_tensors(5 ) lowerCAmelCase = MaxTimeCriteria(max_time=0.1 ) self.assertFalse(criteria(A_ , A_ ) ) lowerCAmelCase = MaxTimeCriteria(max_time=0.1 , initial_timestamp=time.time() - 0.2 ) self.assertTrue(criteria(A_ , A_ ) ) def __snake_case ( self ) -> Optional[int]: validate_stopping_criteria(StoppingCriteriaList([MaxLengthCriteria(10 )] ) , 10 ) with self.assertWarns(A_ ): validate_stopping_criteria(StoppingCriteriaList([MaxLengthCriteria(10 )] ) , 11 ) lowerCAmelCase = validate_stopping_criteria(StoppingCriteriaList() , 11 ) self.assertEqual(len(A_ ) , 1 )
187
0
"""simple docstring""" import flax.linen as nn import jax import jax.numpy as jnp class __A ( nn.Module ): _UpperCamelCase : int _UpperCamelCase : jnp.dtype = jnp.floataa def __A ( self ): _lowerCAmelCase : str = nn.Conv( self.out_channels , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) def __call__( self , a__ ): _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase : Tuple = hidden_states.shape _lowerCAmelCase : List[Any] = jax.image.resize( a__ , shape=(batch, height * 2, width * 2, channels) , method="""nearest""" , ) _lowerCAmelCase : str = self.conv(a__ ) return hidden_states class __A ( nn.Module ): _UpperCamelCase : int _UpperCamelCase : jnp.dtype = jnp.floataa def __A ( self ): _lowerCAmelCase : List[Any] = nn.Conv( self.out_channels , kernel_size=(3, 3) , strides=(2, 2) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) def __call__( self , a__ ): # pad = ((0, 0), (0, 1), (0, 1), (0, 0)) # pad height and width dim # hidden_states = jnp.pad(hidden_states, pad_width=pad) _lowerCAmelCase : Optional[int] = self.conv(a__ ) return hidden_states class __A ( nn.Module ): _UpperCamelCase : int _UpperCamelCase : int = None _UpperCamelCase : float = 0.0 _UpperCamelCase : bool = None _UpperCamelCase : jnp.dtype = jnp.floataa def __A ( self ): _lowerCAmelCase : Tuple = self.in_channels if self.out_channels is None else self.out_channels _lowerCAmelCase : List[str] = nn.GroupNorm(num_groups=32 , epsilon=1e-5 ) _lowerCAmelCase : Tuple = nn.Conv( a__ , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) _lowerCAmelCase : Optional[Any] = nn.Dense(a__ , dtype=self.dtype ) _lowerCAmelCase : Any = nn.GroupNorm(num_groups=32 , epsilon=1e-5 ) _lowerCAmelCase : Any = nn.Dropout(self.dropout_prob ) _lowerCAmelCase : Optional[Any] = nn.Conv( a__ , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) _lowerCAmelCase : Any = self.in_channels != out_channels if self.use_nin_shortcut is None else self.use_nin_shortcut _lowerCAmelCase : str = None if use_nin_shortcut: _lowerCAmelCase : Dict = nn.Conv( a__ , kernel_size=(1, 1) , strides=(1, 1) , padding="""VALID""" , dtype=self.dtype , ) def __call__( self , a__ , a__ , a__=True ): _lowerCAmelCase : Union[str, Any] = hidden_states _lowerCAmelCase : Union[str, Any] = self.norma(a__ ) _lowerCAmelCase : Union[str, Any] = nn.swish(a__ ) _lowerCAmelCase : Dict = self.conva(a__ ) _lowerCAmelCase : Any = self.time_emb_proj(nn.swish(a__ ) ) _lowerCAmelCase : int = jnp.expand_dims(jnp.expand_dims(a__ , 1 ) , 1 ) _lowerCAmelCase : Optional[Any] = hidden_states + temb _lowerCAmelCase : Optional[Any] = self.norma(a__ ) _lowerCAmelCase : int = nn.swish(a__ ) _lowerCAmelCase : Optional[int] = self.dropout(a__ , a__ ) _lowerCAmelCase : List[Any] = self.conva(a__ ) if self.conv_shortcut is not None: _lowerCAmelCase : Tuple = self.conv_shortcut(a__ ) return hidden_states + residual
44
"""simple docstring""" import json import logging import os import socket import git import numpy as np import torch logging.basicConfig( format="""%(asctime)s - %(levelname)s - %(name)s - PID: %(process)d - %(message)s""", datefmt="""%m/%d/%Y %H:%M:%S""", level=logging.INFO, ) SCREAMING_SNAKE_CASE__:Any = logging.getLogger(__name__) def _lowerCamelCase( a ): __a = git.Repo(search_parent_directories=a ) __a = { "repo_id": str(a ), "repo_sha": str(repo.head.object.hexsha ), "repo_branch": str(repo.active_branch ), } with open(os.path.join(a , "git_log.json" ) , "w" ) as f: json.dump(a , a , indent=4 ) def _lowerCamelCase( a ): if params.n_gpu <= 0: __a = 0 __a = -1 __a = True __a = False return assert torch.cuda.is_available() logger.info("Initializing GPUs" ) if params.n_gpu > 1: assert params.local_rank != -1 __a = int(os.environ["WORLD_SIZE"] ) __a = int(os.environ["N_GPU_NODE"] ) __a = int(os.environ["RANK"] ) # number of nodes / node ID __a = params.world_size // params.n_gpu_per_node __a = params.global_rank // params.n_gpu_per_node __a = True assert params.n_nodes == int(os.environ["N_NODES"] ) assert params.node_id == int(os.environ["NODE_RANK"] ) # local job (single GPU) else: assert params.local_rank == -1 __a = 1 __a = 0 __a = 0 __a = 0 __a = 1 __a = 1 __a = False # sanity checks assert params.n_nodes >= 1 assert 0 <= params.node_id < params.n_nodes assert 0 <= params.local_rank <= params.global_rank < params.world_size assert params.world_size == params.n_nodes * params.n_gpu_per_node # define whether this is the master process / if we are in multi-node distributed mode __a = params.node_id == 0 and params.local_rank == 0 __a = params.n_nodes > 1 # summary __a = F"--- Global rank: {params.global_rank} - " logger.info(PREFIX + "Number of nodes: %i" % params.n_nodes ) logger.info(PREFIX + "Node ID : %i" % params.node_id ) logger.info(PREFIX + "Local rank : %i" % params.local_rank ) logger.info(PREFIX + "World size : %i" % params.world_size ) logger.info(PREFIX + "GPUs per node : %i" % params.n_gpu_per_node ) logger.info(PREFIX + "Master : %s" % str(params.is_master ) ) logger.info(PREFIX + "Multi-node : %s" % str(params.multi_node ) ) logger.info(PREFIX + "Multi-GPU : %s" % str(params.multi_gpu ) ) logger.info(PREFIX + "Hostname : %s" % socket.gethostname() ) # set GPU device torch.cuda.set_device(params.local_rank ) # initialize multi-GPU if params.multi_gpu: logger.info("Initializing PyTorch distributed" ) torch.distributed.init_process_group( init_method="env://" , backend="nccl" , ) def _lowerCamelCase( a ): np.random.seed(args.seed ) torch.manual_seed(args.seed ) if args.n_gpu > 0: torch.cuda.manual_seed_all(args.seed )
261
0
import unittest import numpy as np import torch from .utils_summarization import build_mask, compute_token_type_ids, process_story, truncate_or_pad class a ( unittest.TestCase ): def __lowerCamelCase ( self :List[str] ): snake_case__ : Any = 1_0 def __lowerCamelCase ( self :int ): snake_case__ : List[Any] = [1, 2, 3, 4] snake_case__ : List[str] = [1, 2, 3, 4, 0, 0, 0, 0, 0, 0] self.assertEqual(truncate_or_pad(__lowercase ,self.block_size ,0 ) ,__lowercase ) def __lowerCamelCase ( self :List[str] ): snake_case__ : str = [1, 2, 3, 4, 5, 6, 7, 8, 9, 1_0] snake_case__ : Optional[int] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 1_0] self.assertEqual(truncate_or_pad(__lowercase ,self.block_size ,0 ) ,__lowercase ) def __lowerCamelCase ( self :Union[str, Any] ): snake_case__ : Any = [1, 2, 3, 4, 5, 6, 7, 8, 9, 1_0, 1_1, 1_2, 1_3] snake_case__ : List[Any] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 1_0] self.assertEqual(truncate_or_pad(__lowercase ,self.block_size ,0 ) ,__lowercase ) def __lowerCamelCase ( self :List[Any] ): snake_case__ : str = '''It was the year of Our Lord one thousand seven hundred and seventy-five.\n\nSpiritual revelations were conceded to England at that favoured period, as at this.''' snake_case__ , snake_case__ : str = process_story(__lowercase ) self.assertEqual(__lowercase ,[] ) def __lowerCamelCase ( self :int ): snake_case__ : int = '''''' snake_case__ , snake_case__ : Dict = process_story(__lowercase ) self.assertEqual(__lowercase ,[] ) self.assertEqual(__lowercase ,[] ) def __lowerCamelCase ( self :int ): snake_case__ : Dict = ( '''It was the year of Our Lord one thousand seven hundred and ''' '''seventy-five\n\nSpiritual revelations were conceded to England ''' '''at that favoured period, as at this.\n@highlight\n\nIt was the best of times''' ) snake_case__ , snake_case__ : Tuple = process_story(__lowercase ) snake_case__ : Dict = [ '''It was the year of Our Lord one thousand seven hundred and seventy-five.''', '''Spiritual revelations were conceded to England at that favoured period, as at this.''', ] self.assertEqual(__lowercase ,__lowercase ) snake_case__ : str = ['''It was the best of times.'''] self.assertEqual(__lowercase ,__lowercase ) def __lowerCamelCase ( self :List[Any] ): snake_case__ : Dict = torch.tensor([1, 2, 3, 4] ) snake_case__ : str = torch.tensor([1, 1, 1, 1] ) np.testing.assert_array_equal(build_mask(__lowercase ,0 ).numpy() ,expected.numpy() ) def __lowerCamelCase ( self :Optional[Any] ): snake_case__ : Tuple = torch.tensor([1, 2, 3, 4, 2_3, 2_3, 2_3] ) snake_case__ : int = torch.tensor([1, 1, 1, 1, 0, 0, 0] ) np.testing.assert_array_equal(build_mask(__lowercase ,2_3 ).numpy() ,expected.numpy() ) def __lowerCamelCase ( self :Tuple ): snake_case__ : List[Any] = torch.tensor([8, 2, 3, 4, 1, 1, 1] ) snake_case__ : Optional[int] = torch.tensor([1, 1, 1, 1, 0, 0, 0] ) np.testing.assert_array_equal(build_mask(__lowercase ,1 ).numpy() ,expected.numpy() ) def __lowerCamelCase ( self :Dict ): snake_case__ : Tuple = 1_0_1 snake_case__ : str = torch.tensor([[1, 2, 3, 4, 5, 6], [1, 2, 3, 1_0_1, 5, 6], [1, 1_0_1, 3, 4, 1_0_1, 6]] ) snake_case__ : Tuple = torch.tensor([[1, 1, 1, 1, 1, 1], [1, 1, 1, 0, 0, 0], [1, 0, 0, 0, 1, 1]] ) snake_case__ : str = compute_token_type_ids(__lowercase ,__lowercase ) np.testing.assert_array_equal(__lowercase ,__lowercase )
44
A__ = 256 # Modulus to hash a string A__ = 100_0003 def _lowerCAmelCase ( __lowerCAmelCase , __lowerCAmelCase ) -> bool: """simple docstring""" snake_case__ : str = len(__lowerCAmelCase ) snake_case__ : Optional[int] = len(__lowerCAmelCase ) if p_len > t_len: return False snake_case__ : str = 0 snake_case__ : Union[str, Any] = 0 snake_case__ : Dict = 1 # Calculating the hash of pattern and substring of text for i in range(__lowerCAmelCase ): snake_case__ : int = (ord(pattern[i] ) + p_hash * alphabet_size) % modulus snake_case__ : str = (ord(text[i] ) + text_hash * alphabet_size) % modulus if i == p_len - 1: continue snake_case__ : str = (modulus_power * alphabet_size) % modulus for i in range(0 , t_len - p_len + 1 ): if text_hash == p_hash and text[i : i + p_len] == pattern: return True if i == t_len - p_len: continue # Calculate the https://en.wikipedia.org/wiki/Rolling_hash snake_case__ : Any = ( (text_hash - ord(text[i] ) * modulus_power) * alphabet_size + ord(text[i + p_len] ) ) % modulus return False def _lowerCAmelCase ( ) -> None: """simple docstring""" snake_case__ : Optional[int] = '''abc1abc12''' snake_case__ : Dict = '''alskfjaldsabc1abc1abc12k23adsfabcabc''' snake_case__ : int = '''alskfjaldsk23adsfabcabc''' assert rabin_karp(__lowerCAmelCase , __lowerCAmelCase ) and not rabin_karp(__lowerCAmelCase , __lowerCAmelCase ) # Test 2) snake_case__ : int = '''ABABX''' snake_case__ : Any = '''ABABZABABYABABX''' assert rabin_karp(__lowerCAmelCase , __lowerCAmelCase ) # Test 3) snake_case__ : Dict = '''AAAB''' snake_case__ : Union[str, Any] = '''ABAAAAAB''' assert rabin_karp(__lowerCAmelCase , __lowerCAmelCase ) # Test 4) snake_case__ : Union[str, Any] = '''abcdabcy''' snake_case__ : Optional[Any] = '''abcxabcdabxabcdabcdabcy''' assert rabin_karp(__lowerCAmelCase , __lowerCAmelCase ) # Test 5) snake_case__ : Dict = '''Lü''' snake_case__ : Optional[Any] = '''Lüsai''' assert rabin_karp(__lowerCAmelCase , __lowerCAmelCase ) snake_case__ : str = '''Lue''' assert not rabin_karp(__lowerCAmelCase , __lowerCAmelCase ) print('''Success.''' ) if __name__ == "__main__": test_rabin_karp()
44
1
import argparse from torch import nn # transformers_old should correspond to branch `save_old_prophetnet_model_structure` here # original prophetnet_checkpoints are saved under `patrickvonplaten/..._old` respectively from transformers_old.modeling_prophetnet import ( ProphetNetForConditionalGeneration as ProphetNetForConditionalGenerationOld, ) from transformers_old.modeling_xlm_prophetnet import ( XLMProphetNetForConditionalGeneration as XLMProphetNetForConditionalGenerationOld, ) from transformers import ProphetNetForConditionalGeneration, XLMProphetNetForConditionalGeneration, logging lowercase_ = logging.get_logger(__name__) logging.set_verbosity_info() def a ( A__ : str , A__ : str ) -> Any: """simple docstring""" if "xprophetnet" in prophetnet_checkpoint_path: _lowercase =XLMProphetNetForConditionalGenerationOld.from_pretrained(A__ ) _lowercase , _lowercase =XLMProphetNetForConditionalGeneration.from_pretrained( A__ , output_loading_info=A__ ) else: _lowercase =ProphetNetForConditionalGenerationOld.from_pretrained(A__ ) _lowercase , _lowercase =ProphetNetForConditionalGeneration.from_pretrained( A__ , output_loading_info=A__ ) _lowercase =['key_proj', 'value_proj', 'query_proj'] _lowercase ={ 'self_attn': 'ngram_self_attn', 'cross_attn': 'encoder_attn', 'cross_attn_layer_norm': 'encoder_attn_layer_norm', 'feed_forward_layer_norm': 'final_layer_norm', 'feed_forward': '', 'intermediate': 'fc1', 'output': 'fc2', 'key_proj': 'k_proj', 'query_proj': 'q_proj', 'value_proj': 'v_proj', 'word_embeddings': 'embed_tokens', 'embeddings_layer_norm': 'emb_layer_norm', 'relative_pos_embeddings': 'relative_linear', 'ngram_embeddings': 'ngram_input_embed', 'position_embeddings': 'embed_positions', } for key in loading_info["missing_keys"]: _lowercase =key.split('.' ) if attributes[0] == "lm_head": _lowercase =prophet _lowercase =prophet_old else: _lowercase =prophet.prophetnet _lowercase =prophet_old.model _lowercase =False for attribute in attributes: if attribute in mapping: _lowercase =mapping[attribute] if not hasattr(A__ , A__ ) and len(A__ ) > 0: _lowercase =attribute elif hasattr(A__ , A__ ): _lowercase =attribute if attribute == "weight": assert old_model.weight.shape == model.weight.shape, "Shapes have to match!" _lowercase =old_model.weight logger.info(F'''{attribute} is initialized.''' ) _lowercase =True break elif attribute == "bias": assert old_model.bias.shape == model.bias.shape, "Shapes have to match!" _lowercase =old_model.bias logger.info(F'''{attribute} is initialized''' ) _lowercase =True break elif attribute in special_keys and hasattr(A__ , 'in_proj_weight' ): _lowercase =old_model.in_proj_weight.shape[0] // 3 _lowercase =getattr(A__ , A__ ) param.weight.shape == old_model.in_proj_weight[:embed_dim, :].shape, "Shapes have to match" param.bias.shape == old_model.in_proj_bias[:embed_dim].shape, "Shapes have to match" if attribute == "query_proj": _lowercase =nn.Parameter(old_model.in_proj_weight[:embed_dim, :] ) _lowercase =nn.Parameter(old_model.in_proj_bias[:embed_dim] ) elif attribute == "key_proj": _lowercase =nn.Parameter(old_model.in_proj_weight[embed_dim : 2 * embed_dim, :] ) _lowercase =nn.Parameter(old_model.in_proj_bias[embed_dim : 2 * embed_dim] ) elif attribute == "value_proj": _lowercase =nn.Parameter(old_model.in_proj_weight[2 * embed_dim :, :] ) _lowercase =nn.Parameter(old_model.in_proj_bias[2 * embed_dim :] ) _lowercase =True break elif attribute == "position_embeddings": assert ( model.position_embeddings.weight.shape[-1] == old_model.embed_positions.weight.shape[-1] ), "Hidden size has to match" assert model.position_embeddings.weight.shape[0] == 512, "We want 512 position_embeddings." _lowercase =nn.Parameter(old_model.embed_positions.weight[:512, :] ) _lowercase =True break if attribute.isdigit(): _lowercase =model[int(A__ )] _lowercase =old_model[int(A__ )] else: _lowercase =getattr(A__ , A__ ) if old_attribute == "": _lowercase =old_model else: if not hasattr(A__ , A__ ): raise ValueError(F'''{old_model} does not have {old_attribute}''' ) _lowercase =getattr(A__ , A__ ) if not is_key_init: raise ValueError(F'''{key} was not correctly initialized!''' ) print(F'''Saving model to {pytorch_dump_folder_path}''' ) prophet.save_pretrained(A__ ) if __name__ == "__main__": lowercase_ = argparse.ArgumentParser() # Required parameters parser.add_argument( '--prophetnet_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.' ) lowercase_ = parser.parse_args() convert_prophetnet_checkpoint_to_pytorch(args.prophetnet_checkpoint_path, args.pytorch_dump_folder_path)
205
from typing import Dict, List, Optional, Union import numpy as np from .feature_extraction_utils import BatchFeature, FeatureExtractionMixin from .utils import PaddingStrategy, TensorType, is_tf_tensor, is_torch_tensor, logging, to_numpy lowercase_ = logging.get_logger(__name__) class __lowerCAmelCase ( SCREAMING_SNAKE_CASE ): def __init__( self , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , **lowerCAmelCase ) -> Dict: '''simple docstring''' _lowercase =feature_size _lowercase =sampling_rate _lowercase =padding_value _lowercase =kwargs.pop('padding_side' , 'right' ) _lowercase =kwargs.pop('return_attention_mask' , lowerCAmelCase ) super().__init__(**lowerCAmelCase ) def A__ ( self , lowerCAmelCase , lowerCAmelCase = True , lowerCAmelCase = None , lowerCAmelCase = False , lowerCAmelCase = None , lowerCAmelCase = None , lowerCAmelCase = None , ) -> BatchFeature: '''simple docstring''' if isinstance(lowerCAmelCase , (list, tuple) ) and isinstance(processed_features[0] , (dict, BatchFeature) ): _lowercase ={ key: [example[key] for example in processed_features] for key in processed_features[0].keys() } # The model's main input name, usually `input_values`, has be passed for padding if self.model_input_names[0] not in processed_features: raise ValueError( 'You should supply an instance of `transformers.BatchFeature` or list of `transformers.BatchFeature`' F''' to this method that includes {self.model_input_names[0]}, but you provided''' F''' {list(processed_features.keys() )}''' ) _lowercase =processed_features[self.model_input_names[0]] _lowercase =( return_attention_mask if return_attention_mask is not None else self.return_attention_mask ) if len(lowerCAmelCase ) == 0: if return_attention_mask: _lowercase =[] return processed_features # If we have PyTorch/TF tensors or lists as inputs, we cast them as Numpy arrays # and rebuild them afterwards if no return_tensors is specified # Note that we lose the specific device the tensor may be on for PyTorch _lowercase =required_input[0] if isinstance(lowerCAmelCase , (list, tuple) ): # first_element might be an empty list/tuple in some edge cases so we grab the first non empty element. _lowercase =0 while len(required_input[index] ) == 0: index += 1 if index < len(lowerCAmelCase ): _lowercase =required_input[index][0] if return_tensors is None: if is_tf_tensor(lowerCAmelCase ): _lowercase ='tf' elif is_torch_tensor(lowerCAmelCase ): _lowercase ='pt' elif isinstance(lowerCAmelCase , (int, float, list, tuple, np.ndarray) ): _lowercase ='np' else: raise ValueError( F'''type of {first_element} unknown: {type(lowerCAmelCase )}. ''' 'Should be one of a python, numpy, pytorch or tensorflow object.' ) for key, value in processed_features.items(): if isinstance(value[0] , (int, float) ): _lowercase =to_numpy(lowerCAmelCase ) else: _lowercase =[to_numpy(lowerCAmelCase ) for v in value] # Convert padding_strategy in PaddingStrategy _lowercase =self._get_padding_strategies(padding=lowerCAmelCase , max_length=lowerCAmelCase ) _lowercase =processed_features[self.model_input_names[0]] _lowercase =len(lowerCAmelCase ) if not all(len(lowerCAmelCase ) == batch_size for v in processed_features.values() ): raise ValueError('Some items in the output dictionary have a different batch size than others.' ) _lowercase =[] for i in range(lowerCAmelCase ): _lowercase ={k: v[i] for k, v in processed_features.items()} # truncation _lowercase =self._truncate( lowerCAmelCase , max_length=lowerCAmelCase , pad_to_multiple_of=lowerCAmelCase , truncation=lowerCAmelCase , ) truncated_inputs.append(lowerCAmelCase ) if padding_strategy == PaddingStrategy.LONGEST: # make sure that `max_length` cannot be longer than the longest truncated length _lowercase =max(len(input_slice[self.model_input_names[0]] ) for input_slice in truncated_inputs ) _lowercase =PaddingStrategy.MAX_LENGTH _lowercase ={} for i in range(lowerCAmelCase ): # padding _lowercase =self._pad( truncated_inputs[i] , max_length=lowerCAmelCase , padding_strategy=lowerCAmelCase , pad_to_multiple_of=lowerCAmelCase , return_attention_mask=lowerCAmelCase , ) for key, value in outputs.items(): if key not in batch_outputs: _lowercase =[] if value.dtype is np.dtype(np.floataa ): _lowercase =value.astype(np.floataa ) batch_outputs[key].append(lowerCAmelCase ) return BatchFeature(lowerCAmelCase , tensor_type=lowerCAmelCase ) def A__ ( self , lowerCAmelCase , lowerCAmelCase = None , lowerCAmelCase = PaddingStrategy.DO_NOT_PAD , lowerCAmelCase = None , lowerCAmelCase = None , ) -> dict: '''simple docstring''' _lowercase =processed_features[self.model_input_names[0]] if padding_strategy == PaddingStrategy.LONGEST: _lowercase =len(lowerCAmelCase ) if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0): _lowercase =((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of _lowercase =padding_strategy != PaddingStrategy.DO_NOT_PAD and len(lowerCAmelCase ) < max_length if return_attention_mask and "attention_mask" not in processed_features: _lowercase =np.ones(len(lowerCAmelCase ) , dtype=np.intaa ) if needs_to_be_padded: _lowercase =max_length - len(lowerCAmelCase ) if self.padding_side == "right": if return_attention_mask: _lowercase =np.pad( processed_features['attention_mask'] , (0, difference) ) _lowercase =((0, difference), (0, 0)) if self.feature_size > 1 else (0, difference) _lowercase =np.pad( lowerCAmelCase , lowerCAmelCase , 'constant' , constant_values=self.padding_value ) elif self.padding_side == "left": if return_attention_mask: _lowercase =np.pad( processed_features['attention_mask'] , (difference, 0) ) _lowercase =((difference, 0), (0, 0)) if self.feature_size > 1 else (difference, 0) _lowercase =np.pad( lowerCAmelCase , lowerCAmelCase , 'constant' , constant_values=self.padding_value ) else: raise ValueError('Invalid padding strategy:' + str(self.padding_side ) ) return processed_features def A__ ( self , lowerCAmelCase , lowerCAmelCase = None , lowerCAmelCase = None , lowerCAmelCase = None , ) -> Any: '''simple docstring''' if not truncation: return processed_features elif truncation and max_length is None: raise ValueError('When setting ``truncation=True``, make sure that ``max_length`` is defined.' ) _lowercase =processed_features[self.model_input_names[0]] # find `max_length` that fits `pad_to_multiple_of` if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0): _lowercase =((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of _lowercase =len(lowerCAmelCase ) > max_length if needs_to_be_truncated: _lowercase =processed_features[self.model_input_names[0]][:max_length] if "attention_mask" in processed_features: _lowercase =processed_features['attention_mask'][:max_length] return processed_features def A__ ( self , lowerCAmelCase=False , lowerCAmelCase=None ) -> Optional[int]: '''simple docstring''' if padding is not False: if padding is True: _lowercase =PaddingStrategy.LONGEST # Default to pad to the longest sequence in the batch elif not isinstance(lowerCAmelCase , lowerCAmelCase ): _lowercase =PaddingStrategy(lowerCAmelCase ) elif isinstance(lowerCAmelCase , lowerCAmelCase ): _lowercase =padding else: _lowercase =PaddingStrategy.DO_NOT_PAD # Set max length if needed if max_length is None: if padding_strategy == PaddingStrategy.MAX_LENGTH: raise ValueError( F'''When setting ``padding={PaddingStrategy.MAX_LENGTH}``, make sure that max_length is defined''' ) # Test if we have a padding value if padding_strategy != PaddingStrategy.DO_NOT_PAD and (self.padding_value is None): raise ValueError( 'Asking to pad but the feature_extractor does not have a padding value. Please select a value to use' ' as `padding_value`. For example: `feature_extractor.padding_value = 0.0`.' ) return padding_strategy
205
1
# Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from ..models.auto import AutoModelForSeqaSeqLM, AutoTokenizer from .base import PipelineTool lowercase_ = { "Acehnese Arabic": "ace_Arab", "Acehnese Latin": "ace_Latn", "Mesopotamian Arabic": "acm_Arab", "Ta'izzi-Adeni Arabic": "acq_Arab", "Tunisian Arabic": "aeb_Arab", "Afrikaans": "afr_Latn", "South Levantine Arabic": "ajp_Arab", "Akan": "aka_Latn", "Amharic": "amh_Ethi", "North Levantine Arabic": "apc_Arab", "Modern Standard Arabic": "arb_Arab", "Modern Standard Arabic Romanized": "arb_Latn", "Najdi Arabic": "ars_Arab", "Moroccan Arabic": "ary_Arab", "Egyptian Arabic": "arz_Arab", "Assamese": "asm_Beng", "Asturian": "ast_Latn", "Awadhi": "awa_Deva", "Central Aymara": "ayr_Latn", "South Azerbaijani": "azb_Arab", "North Azerbaijani": "azj_Latn", "Bashkir": "bak_Cyrl", "Bambara": "bam_Latn", "Balinese": "ban_Latn", "Belarusian": "bel_Cyrl", "Bemba": "bem_Latn", "Bengali": "ben_Beng", "Bhojpuri": "bho_Deva", "Banjar Arabic": "bjn_Arab", "Banjar Latin": "bjn_Latn", "Standard Tibetan": "bod_Tibt", "Bosnian": "bos_Latn", "Buginese": "bug_Latn", "Bulgarian": "bul_Cyrl", "Catalan": "cat_Latn", "Cebuano": "ceb_Latn", "Czech": "ces_Latn", "Chokwe": "cjk_Latn", "Central Kurdish": "ckb_Arab", "Crimean Tatar": "crh_Latn", "Welsh": "cym_Latn", "Danish": "dan_Latn", "German": "deu_Latn", "Southwestern Dinka": "dik_Latn", "Dyula": "dyu_Latn", "Dzongkha": "dzo_Tibt", "Greek": "ell_Grek", "English": "eng_Latn", "Esperanto": "epo_Latn", "Estonian": "est_Latn", "Basque": "eus_Latn", "Ewe": "ewe_Latn", "Faroese": "fao_Latn", "Fijian": "fij_Latn", "Finnish": "fin_Latn", "Fon": "fon_Latn", "French": "fra_Latn", "Friulian": "fur_Latn", "Nigerian Fulfulde": "fuv_Latn", "Scottish Gaelic": "gla_Latn", "Irish": "gle_Latn", "Galician": "glg_Latn", "Guarani": "grn_Latn", "Gujarati": "guj_Gujr", "Haitian Creole": "hat_Latn", "Hausa": "hau_Latn", "Hebrew": "heb_Hebr", "Hindi": "hin_Deva", "Chhattisgarhi": "hne_Deva", "Croatian": "hrv_Latn", "Hungarian": "hun_Latn", "Armenian": "hye_Armn", "Igbo": "ibo_Latn", "Ilocano": "ilo_Latn", "Indonesian": "ind_Latn", "Icelandic": "isl_Latn", "Italian": "ita_Latn", "Javanese": "jav_Latn", "Japanese": "jpn_Jpan", "Kabyle": "kab_Latn", "Jingpho": "kac_Latn", "Kamba": "kam_Latn", "Kannada": "kan_Knda", "Kashmiri Arabic": "kas_Arab", "Kashmiri Devanagari": "kas_Deva", "Georgian": "kat_Geor", "Central Kanuri Arabic": "knc_Arab", "Central Kanuri Latin": "knc_Latn", "Kazakh": "kaz_Cyrl", "Kabiyè": "kbp_Latn", "Kabuverdianu": "kea_Latn", "Khmer": "khm_Khmr", "Kikuyu": "kik_Latn", "Kinyarwanda": "kin_Latn", "Kyrgyz": "kir_Cyrl", "Kimbundu": "kmb_Latn", "Northern Kurdish": "kmr_Latn", "Kikongo": "kon_Latn", "Korean": "kor_Hang", "Lao": "lao_Laoo", "Ligurian": "lij_Latn", "Limburgish": "lim_Latn", "Lingala": "lin_Latn", "Lithuanian": "lit_Latn", "Lombard": "lmo_Latn", "Latgalian": "ltg_Latn", "Luxembourgish": "ltz_Latn", "Luba-Kasai": "lua_Latn", "Ganda": "lug_Latn", "Luo": "luo_Latn", "Mizo": "lus_Latn", "Standard Latvian": "lvs_Latn", "Magahi": "mag_Deva", "Maithili": "mai_Deva", "Malayalam": "mal_Mlym", "Marathi": "mar_Deva", "Minangkabau Arabic ": "min_Arab", "Minangkabau Latin": "min_Latn", "Macedonian": "mkd_Cyrl", "Plateau Malagasy": "plt_Latn", "Maltese": "mlt_Latn", "Meitei Bengali": "mni_Beng", "Halh Mongolian": "khk_Cyrl", "Mossi": "mos_Latn", "Maori": "mri_Latn", "Burmese": "mya_Mymr", "Dutch": "nld_Latn", "Norwegian Nynorsk": "nno_Latn", "Norwegian Bokmål": "nob_Latn", "Nepali": "npi_Deva", "Northern Sotho": "nso_Latn", "Nuer": "nus_Latn", "Nyanja": "nya_Latn", "Occitan": "oci_Latn", "West Central Oromo": "gaz_Latn", "Odia": "ory_Orya", "Pangasinan": "pag_Latn", "Eastern Panjabi": "pan_Guru", "Papiamento": "pap_Latn", "Western Persian": "pes_Arab", "Polish": "pol_Latn", "Portuguese": "por_Latn", "Dari": "prs_Arab", "Southern Pashto": "pbt_Arab", "Ayacucho Quechua": "quy_Latn", "Romanian": "ron_Latn", "Rundi": "run_Latn", "Russian": "rus_Cyrl", "Sango": "sag_Latn", "Sanskrit": "san_Deva", "Santali": "sat_Olck", "Sicilian": "scn_Latn", "Shan": "shn_Mymr", "Sinhala": "sin_Sinh", "Slovak": "slk_Latn", "Slovenian": "slv_Latn", "Samoan": "smo_Latn", "Shona": "sna_Latn", "Sindhi": "snd_Arab", "Somali": "som_Latn", "Southern Sotho": "sot_Latn", "Spanish": "spa_Latn", "Tosk Albanian": "als_Latn", "Sardinian": "srd_Latn", "Serbian": "srp_Cyrl", "Swati": "ssw_Latn", "Sundanese": "sun_Latn", "Swedish": "swe_Latn", "Swahili": "swh_Latn", "Silesian": "szl_Latn", "Tamil": "tam_Taml", "Tatar": "tat_Cyrl", "Telugu": "tel_Telu", "Tajik": "tgk_Cyrl", "Tagalog": "tgl_Latn", "Thai": "tha_Thai", "Tigrinya": "tir_Ethi", "Tamasheq Latin": "taq_Latn", "Tamasheq Tifinagh": "taq_Tfng", "Tok Pisin": "tpi_Latn", "Tswana": "tsn_Latn", "Tsonga": "tso_Latn", "Turkmen": "tuk_Latn", "Tumbuka": "tum_Latn", "Turkish": "tur_Latn", "Twi": "twi_Latn", "Central Atlas Tamazight": "tzm_Tfng", "Uyghur": "uig_Arab", "Ukrainian": "ukr_Cyrl", "Umbundu": "umb_Latn", "Urdu": "urd_Arab", "Northern Uzbek": "uzn_Latn", "Venetian": "vec_Latn", "Vietnamese": "vie_Latn", "Waray": "war_Latn", "Wolof": "wol_Latn", "Xhosa": "xho_Latn", "Eastern Yiddish": "ydd_Hebr", "Yoruba": "yor_Latn", "Yue Chinese": "yue_Hant", "Chinese Simplified": "zho_Hans", "Chinese Traditional": "zho_Hant", "Standard Malay": "zsm_Latn", "Zulu": "zul_Latn", } class A ( _UpperCAmelCase ): """simple docstring""" lowerCamelCase = 'facebook/nllb-200-distilled-600M' lowerCamelCase = ( 'This is a tool that translates text from a language to another. It takes three inputs: `text`, which should ' 'be the text to translate, `src_lang`, which should be the language of the text to translate and `tgt_lang`, ' 'which should be the language for the desired ouput language. Both `src_lang` and `tgt_lang` are written in ' 'plain English, such as \'Romanian\', or \'Albanian\'. It returns the text translated in `tgt_lang`.' ) lowerCamelCase = 'translator' lowerCamelCase = AutoTokenizer lowerCamelCase = AutoModelForSeqaSeqLM lowerCamelCase = LANGUAGE_CODES lowerCamelCase = ['text', 'text', 'text'] lowerCamelCase = ['text'] def snake_case__ ( self : Union[str, Any],lowercase_ : int,lowercase_ : Optional[int],lowercase_ : Dict )-> Any: '''simple docstring''' if src_lang not in self.lang_to_code: raise ValueError(F'{src_lang} is not a supported language.' ) if tgt_lang not in self.lang_to_code: raise ValueError(F'{tgt_lang} is not a supported language.' ) A__ = self.lang_to_code[src_lang] A__ = self.lang_to_code[tgt_lang] return self.pre_processor._build_translation_inputs( lowercase_,return_tensors='pt',src_lang=lowercase_,tgt_lang=lowercase_ ) def snake_case__ ( self : Optional[int],lowercase_ : Dict )-> List[Any]: '''simple docstring''' return self.model.generate(**lowercase_ ) def snake_case__ ( self : Optional[Any],lowercase_ : Union[str, Any] )-> Optional[int]: '''simple docstring''' return self.post_processor.decode(outputs[0].tolist(),skip_special_tokens=lowercase_ )
282
# XXX: we want transformers master here - in the absense of conftest manipulating sys.path: # hack it in for now: import sys from pathlib import Path lowercase_ = Path(__file__).resolve().parents[3] / "src" sys.path.insert(1, str(git_repo_path)) import dataclasses # noqa import io # noqa import itertools # noqa import json # noqa import os # noqa import unittest # noqa from copy import deepcopy # noqa from parameterized import parameterized # noqa from transformers import TrainingArguments, is_torch_available # noqa from transformers.deepspeed import is_deepspeed_available # noqa from transformers.file_utils import WEIGHTS_NAME # noqa from transformers.testing_utils import ( # noqa CaptureLogger, ExtendSysPath, TestCasePlus, execute_subprocess_async, get_gpu_count, mockenv_context, require_deepspeed, require_torch_gpu, require_torch_multi_gpu, slow, ) from transformers.trainer_utils import set_seed # noqa set_seed(42) lowercase_ = {"base": "patrickvonplaten/wav2vec2_tiny_random", "robust": "patrickvonplaten/wav2vec2_tiny_random_robust"} lowercase_ = "zero2" lowercase_ = "zero3" lowercase_ = [ZEROa, ZEROa] def _snake_case( SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : List[Any] ) -> Dict: '''simple docstring''' A__ = parameterized.to_safe_name('_'.join(str(SCREAMING_SNAKE_CASE__ ) for x in param.args ) ) return f'{func.__name__}_{param_based_name}' # Cartesian-product of zero stages with models to test lowercase_ = list(itertools.product(stages, models.keys())) @slow @require_deepspeed @require_torch_gpu class A ( _UpperCAmelCase ): """simple docstring""" @parameterized.expand(lowercase_,name_func=lowercase_ ) def snake_case__ ( self : int,lowercase_ : str,lowercase_ : Any )-> Optional[int]: '''simple docstring''' self.run_and_check( stage=lowercase_,model=lowercase_,distributed=lowercase_,fpaa=lowercase_,) @require_torch_multi_gpu @parameterized.expand(lowercase_,name_func=lowercase_ ) def snake_case__ ( self : Union[str, Any],lowercase_ : Optional[Any],lowercase_ : List[Any] )-> int: '''simple docstring''' self.run_and_check( stage=lowercase_,model=lowercase_,distributed=lowercase_,fpaa=lowercase_,) @parameterized.expand(lowercase_,name_func=lowercase_ ) def snake_case__ ( self : List[str],lowercase_ : List[str],lowercase_ : List[Any] )-> Any: '''simple docstring''' self.run_and_check( stage=lowercase_,model=lowercase_,distributed=lowercase_,fpaa=lowercase_,) @require_torch_multi_gpu @parameterized.expand(lowercase_,name_func=lowercase_ ) def snake_case__ ( self : Dict,lowercase_ : Optional[Any],lowercase_ : List[Any] )-> Optional[int]: '''simple docstring''' self.run_and_check( stage=lowercase_,model=lowercase_,distributed=lowercase_,fpaa=lowercase_,) def snake_case__ ( self : Tuple,lowercase_ : Any )-> Union[str, Any]: '''simple docstring''' pass def snake_case__ ( self : int,lowercase_ : str,lowercase_ : str,lowercase_ : int = 1_0,lowercase_ : bool = True,lowercase_ : bool = True,lowercase_ : bool = True,)-> Union[str, Any]: '''simple docstring''' A__ = models[model] A__ = self.run_trainer( stage=lowercase_,model_name=lowercase_,eval_steps=lowercase_,num_train_epochs=1,distributed=lowercase_,fpaa=lowercase_,) self.do_checks(lowercase_ ) return output_dir def snake_case__ ( self : Union[str, Any],lowercase_ : str,lowercase_ : str,lowercase_ : int = 1_0,lowercase_ : int = 1,lowercase_ : bool = True,lowercase_ : bool = True,)-> Any: '''simple docstring''' A__ = self.get_auto_remove_tmp_dir('./xxx',after=lowercase_ ) A__ = F'\n --model_name_or_path {model_name}\n --dataset_name hf-internal-testing/librispeech_asr_dummy\n --dataset_config_name clean\n --train_split_name validation\n --validation_split_name validation\n --output_dir {output_dir}\n --num_train_epochs {str(lowercase_ )}\n --per_device_train_batch_size 2\n --per_device_eval_batch_size 2\n --evaluation_strategy steps\n --learning_rate 5e-4\n --warmup_steps 8\n --orthography timit\n --preprocessing_num_workers 1\n --group_by_length\n --freeze_feature_extractor\n --report_to none\n --save_steps 0\n --eval_steps {eval_steps}\n --report_to none\n '.split() if fpaa: args.extend(['--fp16'] ) # currently ds_config_wav2vec2_zero.json requires "zero_optimization.find_unused_parameters": true, # hence the separate config files A__ = F'--deepspeed {self.test_file_dir_str}/ds_config_wav2vec2_{stage}.json'.split() A__ = [F'{self.examples_dir_str}/research_projects/wav2vec2/run_asr.py'] A__ = self.get_launcher(lowercase_ ) A__ = launcher + script + args + ds_args # keep for quick debug # print(" ".join([f"\nPYTHONPATH={self.src_dir_str}"] +cmd)); die execute_subprocess_async(lowercase_,env=self.get_env() ) return output_dir def snake_case__ ( self : Any,lowercase_ : int=False )-> Tuple: '''simple docstring''' A__ = min(2,get_gpu_count() ) if distributed else 1 return F'deepspeed --num_nodes 1 --num_gpus {num_gpus}'.split()
282
1
from typing import List, Optional, Tuple, Union import torch from ...utils import logging, randn_tensor from ..pipeline_utils import AudioPipelineOutput, DiffusionPipeline lowerCamelCase : Tuple = logging.get_logger(__name__) # pylint: disable=invalid-name class __lowercase (UpperCamelCase__ ): """simple docstring""" def __init__( self , A , A ) -> Optional[int]: super().__init__() self.register_modules(unet=A , scheduler=A ) @torch.no_grad() def __call__( self , A = 1 , A = 1_0_0 , A = None , A = None , A = True , ) -> Union[AudioPipelineOutput, Tuple]: if audio_length_in_s is None: snake_case : Any = self.unet.config.sample_size / self.unet.config.sample_rate snake_case : Optional[Any] = audio_length_in_s * self.unet.config.sample_rate snake_case : Tuple = 2 ** len(self.unet.up_blocks ) if sample_size < 3 * down_scale_factor: raise ValueError( f"""{audio_length_in_s} is too small. Make sure it's bigger or equal to""" f""" {3 * down_scale_factor / self.unet.config.sample_rate}.""" ) snake_case : List[Any] = int(A ) if sample_size % down_scale_factor != 0: snake_case : Union[str, Any] = ( (audio_length_in_s * self.unet.config.sample_rate) // down_scale_factor + 1 ) * down_scale_factor logger.info( f"""{audio_length_in_s} is increased to {sample_size / self.unet.config.sample_rate} so that it can be handled""" f""" by the model. It will be cut to {original_sample_size / self.unet.config.sample_rate} after the denoising""" """ process.""" ) snake_case : Tuple = int(A ) snake_case : List[Any] = next(iter(self.unet.parameters() ) ).dtype snake_case : int = (batch_size, self.unet.config.in_channels, sample_size) if isinstance(A , A ) and len(A ) != batch_size: raise ValueError( f"""You have passed a list of generators of length {len(A )}, but requested an effective batch""" f""" size of {batch_size}. Make sure the batch size matches the length of the generators.""" ) snake_case : List[Any] = randn_tensor(A , generator=A , device=self.device , dtype=A ) # set step values self.scheduler.set_timesteps(A , device=audio.device ) snake_case : Any = self.scheduler.timesteps.to(A ) for t in self.progress_bar(self.scheduler.timesteps ): # 1. predict noise model_output snake_case : Dict = self.unet(A , A ).sample # 2. compute previous image: x_t -> t_t-1 snake_case : Union[str, Any] = self.scheduler.step(A , A , A ).prev_sample snake_case : str = audio.clamp(-1 , 1 ).float().cpu().numpy() snake_case : Optional[Any] = audio[:, :, :original_sample_size] if not return_dict: return (audio,) return AudioPipelineOutput(audios=A )
124
import argparse import json import os import fairseq import torch from fairseq.data import Dictionary from transformers import ( HubertConfig, HubertForCTC, HubertModel, WavaVecaCTCTokenizer, WavaVecaFeatureExtractor, WavaVecaProcessor, logging, ) logging.set_verbosity_info() lowerCamelCase : Optional[Any] = logging.get_logger(__name__) lowerCamelCase : Optional[int] = { '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', 'w2v_encoder.proj': 'lm_head', 'mask_emb': 'masked_spec_embed', } def SCREAMING_SNAKE_CASE__ ( lowercase ,lowercase ,lowercase ,lowercase ,lowercase ) -> Union[str, Any]: for attribute in key.split(""".""" ): snake_case : Optional[Any] = getattr(lowercase ,lowercase ) if weight_type is not None: snake_case : Any = getattr(lowercase ,lowercase ).shape else: snake_case : List[str] = 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": snake_case : str = value elif weight_type == "weight_g": snake_case : Optional[int] = value elif weight_type == "weight_v": snake_case : List[str] = value elif weight_type == "bias": snake_case : int = value else: snake_case : str = value logger.info(f"""{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.""" ) def SCREAMING_SNAKE_CASE__ ( lowercase ,lowercase ,lowercase ) -> List[Any]: snake_case : Optional[Any] = [] snake_case : Optional[Any] = fairseq_model.state_dict() snake_case : Tuple = hf_model.hubert.feature_extractor if is_finetuned else hf_model.feature_extractor for name, value in fairseq_dict.items(): snake_case : Optional[Any] = False if "conv_layers" in name: load_conv_layer( lowercase ,lowercase ,lowercase ,lowercase ,hf_model.config.feat_extract_norm == """group""" ,) snake_case : Any = True else: for key, mapped_key in MAPPING.items(): snake_case : Optional[int] = """hubert.""" + mapped_key if (is_finetuned and mapped_key != """lm_head""") else mapped_key if key in name or (key.split("""w2v_model.""" )[-1] == name.split(""".""" )[0] and not is_finetuned): snake_case : Union[str, Any] = True if "*" in mapped_key: snake_case : Dict = name.split(lowercase )[0].split(""".""" )[-2] snake_case : str = mapped_key.replace("""*""" ,lowercase ) if "weight_g" in name: snake_case : int = """weight_g""" elif "weight_v" in name: snake_case : Optional[int] = """weight_v""" elif "weight" in name: snake_case : Tuple = """weight""" elif "bias" in name: snake_case : List[Any] = """bias""" else: snake_case : List[str] = None set_recursively(lowercase ,lowercase ,lowercase ,lowercase ,lowercase ) continue if not is_used: unused_weights.append(lowercase ) logger.warning(f"""Unused weights: {unused_weights}""" ) def SCREAMING_SNAKE_CASE__ ( lowercase ,lowercase ,lowercase ,lowercase ,lowercase ) -> Dict: snake_case : str = full_name.split("""conv_layers.""" )[-1] snake_case : Dict = name.split(""".""" ) snake_case : Any = int(items[0] ) snake_case : Optional[int] = int(items[1] ) if type_id == 0: if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, ( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.""" ) snake_case : int = 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.""" ) snake_case : List[Any] = 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." ) snake_case : Optional[Any] = value logger.info(f"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, ( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor[layer_id].layer_norm.weight.data.shape} was found.""" ) snake_case : Tuple = value logger.info(f"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) else: unused_weights.append(lowercase ) @torch.no_grad() def SCREAMING_SNAKE_CASE__ ( lowercase ,lowercase ,lowercase=None ,lowercase=None ,lowercase=True ) -> Union[str, Any]: if config_path is not None: snake_case : Optional[int] = HubertConfig.from_pretrained(lowercase ) else: snake_case : Tuple = HubertConfig() if is_finetuned: if dict_path: snake_case : List[str] = Dictionary.load(lowercase ) # important change bos & pad token id since CTC symbol is <pad> and # not <s> as in fairseq snake_case : Optional[int] = target_dict.pad_index snake_case : Any = target_dict.bos_index snake_case : Dict = target_dict.eos_index snake_case : List[str] = len(target_dict.symbols ) snake_case : Union[str, Any] = os.path.join(lowercase ,"""vocab.json""" ) if not os.path.isdir(lowercase ): logger.error("""--pytorch_dump_folder_path ({}) should be a directory""".format(lowercase ) ) return os.makedirs(lowercase ,exist_ok=lowercase ) with open(lowercase ,"""w""" ,encoding="""utf-8""" ) as vocab_handle: json.dump(target_dict.indices ,lowercase ) snake_case : Union[str, Any] = WavaVecaCTCTokenizer( lowercase ,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=lowercase ,) snake_case : Union[str, Any] = True if config.feat_extract_norm == """layer""" else False snake_case : Union[str, Any] = WavaVecaFeatureExtractor( feature_size=1 ,sampling_rate=16000 ,padding_value=0 ,do_normalize=lowercase ,return_attention_mask=lowercase ,) snake_case : Dict = WavaVecaProcessor(feature_extractor=lowercase ,tokenizer=lowercase ) processor.save_pretrained(lowercase ) snake_case : List[Any] = HubertForCTC(lowercase ) else: snake_case : Any = HubertModel(lowercase ) if is_finetuned: snake_case , snake_case , snake_case : int = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] ,arg_overrides={"""data""": """/""".join(dict_path.split("""/""" )[:-1] )} ) else: snake_case , snake_case , snake_case : Any = fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path] ) snake_case : Any = model[0].eval() recursively_load_weights(lowercase ,lowercase ,lowercase ) hf_wavavec.save_pretrained(lowercase ) if __name__ == "__main__": lowerCamelCase : Any = 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 : List[str] = parser.parse_args() convert_hubert_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned )
124
1
'''simple docstring''' def A_( A : int , A : int): if b == 0: return 1 if (b % 2) == 0: return actual_power(A , int(b / 2)) * actual_power(A , int(b / 2)) else: return a * actual_power(A , int(b / 2)) * actual_power(A , int(b / 2)) def A_( A : int , A : int): if b < 0: return 1 / actual_power(A , A) return actual_power(A , A) if __name__ == "__main__": print(power(-2, -3))
251
'''simple docstring''' import datasets import faiss import numpy as np import streamlit as st import torch from elasticsearch import Elasticsearch from elia_utils import ( embed_questions_for_retrieval, make_qa_sas_model, qa_sas_generate, query_es_index, query_qa_dense_index, ) import transformers from transformers import AutoModel, AutoModelForSeqaSeqLM, AutoTokenizer lowerCAmelCase : int = 'bart' lowerCAmelCase : Union[str, Any] = True @st.cache(allow_output_mutation=A) def A_( ): if LOAD_DENSE_INDEX: UpperCamelCase = AutoTokenizer.from_pretrained('yjernite/retribert-base-uncased') UpperCamelCase = AutoModel.from_pretrained('yjernite/retribert-base-uncased').to('cuda:0') UpperCamelCase = qar_model.eval() else: UpperCamelCase , UpperCamelCase = (None, None) if MODEL_TYPE == "bart": UpperCamelCase = AutoTokenizer.from_pretrained('yjernite/bart_eli5') UpperCamelCase = AutoModelForSeqaSeqLM.from_pretrained('yjernite/bart_eli5').to('cuda:0') UpperCamelCase = torch.load('seq2seq_models/eli5_bart_model_blm_2.pth') sas_model.load_state_dict(save_dict['model']) UpperCamelCase = sas_model.eval() else: UpperCamelCase , UpperCamelCase = make_qa_sas_model( model_name='t5-small' , from_file='seq2seq_models/eli5_t5_model_1024_4.pth' , device='cuda:0') return (qar_tokenizer, qar_model, sas_tokenizer, sas_model) @st.cache(allow_output_mutation=A) def A_( ): if LOAD_DENSE_INDEX: UpperCamelCase = faiss.StandardGpuResources() UpperCamelCase = datasets.load_dataset(path='wiki_snippets' , name='wiki40b_en_100_0')['train'] UpperCamelCase = np.memmap( 'wiki40b_passages_reps_32_l-8_h-768_b-512-512.dat' , dtype='float32' , mode='r' , shape=(wikiaab_passages.num_rows, 128) , ) UpperCamelCase = faiss.IndexFlatIP(128) UpperCamelCase = faiss.index_cpu_to_gpu(A , 1 , A) wikiaab_gpu_index_flat.add(A) # TODO fix for larger GPU else: UpperCamelCase , UpperCamelCase = (None, None) UpperCamelCase = Elasticsearch([{'host': 'localhost', 'port': '9200'}]) return (wikiaab_passages, wikiaab_gpu_index_flat, es_client) @st.cache(allow_output_mutation=A) def A_( ): UpperCamelCase = datasets.load_dataset('eli5' , name='LFQA_reddit') UpperCamelCase = elia['train_eli5'] UpperCamelCase = np.memmap( 'eli5_questions_reps.dat' , dtype='float32' , mode='r' , shape=(elia_train.num_rows, 128)) UpperCamelCase = faiss.IndexFlatIP(128) eli5_train_q_index.add(A) return (elia_train, eli5_train_q_index) lowerCAmelCase , lowerCAmelCase , lowerCAmelCase : Optional[Any] = load_indexes() lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase : int = load_models() lowerCAmelCase , lowerCAmelCase : Tuple = load_train_data() def A_( A : Dict , A : str=10): UpperCamelCase = embed_questions_for_retrieval([question] , A , A) UpperCamelCase , UpperCamelCase = eli5_train_q_index.search(A , A) UpperCamelCase = [elia_train[int(A)] for i in I[0]] return nn_examples def A_( A : str , A : Optional[int]="wiki40b" , A : List[Any]="dense" , A : Dict=10): if source == "none": UpperCamelCase , UpperCamelCase = (' <P> '.join(['' for _ in range(11)]).strip(), []) else: if method == "dense": UpperCamelCase , UpperCamelCase = query_qa_dense_index( A , A , A , A , A , A) else: UpperCamelCase , UpperCamelCase = query_es_index( A , A , index_name='english_wiki40b_snippets_100w' , n_results=A , ) UpperCamelCase = [ (res['article_title'], res['section_title'].strip(), res['score'], res['passage_text']) for res in hit_lst ] UpperCamelCase = 'question: {} context: {}'.format(A , A) return question_doc, support_list @st.cache( hash_funcs={ torch.Tensor: (lambda A: None), transformers.models.bart.tokenization_bart.BartTokenizer: (lambda A: None), }) def A_( A : Optional[Any] , A : List[str] , A : str , A : List[Any]=64 , A : List[Any]=256 , A : int=False , A : List[str]=2 , A : Any=0.95 , A : int=0.8): with torch.no_grad(): UpperCamelCase = qa_sas_generate( A , A , A , num_answers=1 , num_beams=A , min_len=A , max_len=A , do_sample=A , temp=A , top_p=A , top_k=A , max_input_length=1024 , device='cuda:0' , )[0] return (answer, support_list) st.title('Long Form Question Answering with ELI5') # Start sidebar lowerCAmelCase : List[str] = '<img src=\'https://huggingface.co/front/assets/huggingface_logo.svg\'>' lowerCAmelCase : Dict = '\n<html>\n <head>\n <style>\n .img-container {\n padding-left: 90px;\n padding-right: 90px;\n padding-top: 50px;\n padding-bottom: 50px;\n background-color: #f0f3f9;\n }\n </style>\n </head>\n <body>\n <span class="img-container"> <!-- Inline parent element -->\n %s\n </span>\n </body>\n</html>\n' % ( header_html, ) st.sidebar.markdown( header_full, unsafe_allow_html=True, ) # Long Form QA with ELI5 and Wikipedia lowerCAmelCase : List[Any] = '\nThis demo presents a model trained to [provide long-form answers to open-domain questions](https://yjernite.github.io/lfqa.html).\nFirst, a document retriever fetches a set of relevant Wikipedia passages given the question from the [Wiki40b](https://research.google/pubs/pub49029/) dataset,\na pre-processed fixed snapshot of Wikipedia.\n' st.sidebar.markdown(description, unsafe_allow_html=True) lowerCAmelCase : Optional[int] = [ 'Answer the question', 'View the retrieved document only', 'View the most similar ELI5 question and answer', 'Show me everything, please!', ] lowerCAmelCase : List[str] = st.sidebar.checkbox('Demo options') if demo_options: lowerCAmelCase : Dict = st.sidebar.selectbox( '', action_list, index=3, ) lowerCAmelCase : int = action_list.index(action_st) lowerCAmelCase : Optional[Any] = st.sidebar.selectbox( '', ['Show full text of passages', 'Show passage section titles'], index=0, ) lowerCAmelCase : Any = show_type == 'Show full text of passages' else: lowerCAmelCase : Optional[Any] = 3 lowerCAmelCase : Optional[Any] = True lowerCAmelCase : Optional[Any] = st.sidebar.checkbox('Retrieval options') if retrieval_options: lowerCAmelCase : Any = '\n ### Information retriever options\n\n The **sparse** retriever uses ElasticSearch, while the **dense** retriever uses max-inner-product search between a question and passage embedding\n trained using the [ELI5](https://arxiv.org/abs/1907.09190) questions-answer pairs.\n The answer is then generated by sequence to sequence model which takes the question and retrieved document as input.\n ' st.sidebar.markdown(retriever_info) lowerCAmelCase : Optional[Any] = st.sidebar.selectbox('Which Wikipedia format should the model use?', ['wiki40b', 'none']) lowerCAmelCase : List[str] = st.sidebar.selectbox('Which Wikipedia indexer should the model use?', ['dense', 'sparse', 'mixed']) else: lowerCAmelCase : str = 'wiki40b' lowerCAmelCase : Tuple = 'dense' lowerCAmelCase : Union[str, Any] = 'beam' lowerCAmelCase : Optional[int] = 2 lowerCAmelCase : Any = 64 lowerCAmelCase : int = 2_56 lowerCAmelCase : Optional[Any] = None lowerCAmelCase : List[str] = None lowerCAmelCase : List[str] = st.sidebar.checkbox('Generation options') if generate_options: lowerCAmelCase : str = '\n ### Answer generation options\n\n The sequence-to-sequence model was initialized with [BART](https://huggingface.co/facebook/bart-large)\n weights and fine-tuned on the ELI5 QA pairs and retrieved documents. You can use the model for greedy decoding with\n **beam** search, or **sample** from the decoder\'s output probabilities.\n ' st.sidebar.markdown(generate_info) lowerCAmelCase : str = st.sidebar.selectbox('Would you like to use beam search or sample an answer?', ['beam', 'sampled']) lowerCAmelCase : Any = st.sidebar.slider( 'Minimum generation length', min_value=8, max_value=2_56, value=64, step=8, format=None, key=None ) lowerCAmelCase : Any = st.sidebar.slider( 'Maximum generation length', min_value=64, max_value=5_12, value=2_56, step=16, format=None, key=None ) if sampled == "beam": lowerCAmelCase : Union[str, Any] = st.sidebar.slider('Beam size', min_value=1, max_value=8, value=2, step=None, format=None, key=None) else: lowerCAmelCase : Tuple = st.sidebar.slider( 'Nucleus sampling p', min_value=0.1, max_value=1.0, value=0.95, step=0.01, format=None, key=None ) lowerCAmelCase : List[Any] = st.sidebar.slider( 'Temperature', min_value=0.1, max_value=1.0, value=0.7, step=0.01, format=None, key=None ) lowerCAmelCase : Tuple = None # start main text lowerCAmelCase : Optional[Any] = [ '<MY QUESTION>', 'How do people make chocolate?', 'Why do we get a fever when we are sick?', 'How can different animals perceive different colors?', 'What is natural language processing?', 'What\'s the best way to treat a sunburn?', 'What exactly are vitamins ?', 'How does nuclear energy provide electricity?', 'What\'s the difference between viruses and bacteria?', 'Why are flutes classified as woodwinds when most of them are made out of metal ?', 'Why do people like drinking coffee even though it tastes so bad?', 'What happens when wine ages? How does it make the wine taste better?', 'If an animal is an herbivore, where does it get the protein that it needs to survive if it only eats grass?', 'How can we set a date to the beginning or end of an artistic period? Doesn\'t the change happen gradually?', 'How does New Zealand have so many large bird predators?', ] lowerCAmelCase : int = st.selectbox( 'What would you like to ask? ---- select <MY QUESTION> to enter a new query', questions_list, index=1, ) if question_s == "<MY QUESTION>": lowerCAmelCase : List[str] = st.text_input('Enter your question here:', '') else: lowerCAmelCase : Tuple = question_s if st.button('Show me!'): if action in [0, 1, 3]: if index_type == "mixed": lowerCAmelCase , lowerCAmelCase : Any = make_support(question, source=wiki_source, method='dense', n_results=10) lowerCAmelCase , lowerCAmelCase : Dict = make_support(question, source=wiki_source, method='sparse', n_results=10) lowerCAmelCase : List[str] = [] for res_d, res_s in zip(support_list_dense, support_list_sparse): if tuple(res_d) not in support_list: support_list += [tuple(res_d)] if tuple(res_s) not in support_list: support_list += [tuple(res_s)] lowerCAmelCase : Optional[Any] = support_list[:10] lowerCAmelCase : Dict = '<P> ' + ' <P> '.join([res[-1] for res in support_list]) else: lowerCAmelCase , lowerCAmelCase : Union[str, Any] = make_support(question, source=wiki_source, method=index_type, n_results=10) if action in [0, 3]: lowerCAmelCase , lowerCAmelCase : Union[str, Any] = answer_question( question_doc, sas_model, sas_tokenizer, min_len=min_len, max_len=int(max_len), sampling=(sampled == 'sampled'), n_beams=n_beams, top_p=top_p, temp=temp, ) st.markdown('### The model generated answer is:') st.write(answer) if action in [0, 1, 3] and wiki_source != "none": st.markdown('--- \n ### The model is drawing information from the following Wikipedia passages:') for i, res in enumerate(support_list): lowerCAmelCase : int = 'https://en.wikipedia.org/wiki/{}'.format(res[0].replace(' ', '_')) lowerCAmelCase : Optional[int] = res[1].strip() if sec_titles == "": lowerCAmelCase : Dict = '[{}]({})'.format(res[0], wiki_url) else: lowerCAmelCase : Dict = sec_titles.split(' & ') lowerCAmelCase : str = ' & '.join( ['[{}]({}#{})'.format(sec.strip(), wiki_url, sec.strip().replace(' ', '_')) for sec in sec_list] ) st.markdown( '{0:02d} - **Article**: {1:<18} <br> _Section_: {2}'.format(i + 1, res[0], sections), unsafe_allow_html=True, ) if show_passages: st.write( '> <span style="font-family:arial; font-size:10pt;">' + res[-1] + '</span>', unsafe_allow_html=True ) if action in [2, 3]: lowerCAmelCase : Optional[Any] = find_nearest_training(question) lowerCAmelCase : Optional[int] = nn_train_list[0] st.markdown( '--- \n ### The most similar question in the ELI5 training set was: \n\n {}'.format(train_exple['title']) ) lowerCAmelCase : List[str] = [ '{}. {}'.format(i + 1, ' \n'.join([line.strip() for line in ans.split('\n') if line.strip() != ''])) for i, (ans, sc) in enumerate(zip(train_exple['answers']['text'], train_exple['answers']['score'])) if i == 0 or sc > 2 ] st.markdown('##### Its answers were: \n\n {}'.format('\n'.join(answers_st))) lowerCAmelCase : int = '\n---\n\n**Disclaimer**\n\n*The intent of this app is to provide some (hopefully entertaining) insights into the behavior of a current LFQA system.\nEvaluating biases of such a model and ensuring factual generations are still very much open research problems.\nTherefore, until some significant progress is achieved, we caution against using the generated answers for practical purposes.*\n' st.sidebar.markdown(disclaimer, unsafe_allow_html=True)
251
1
'''simple docstring''' import cva import numpy as np class lowercase_ : """simple docstring""" def __init__( self : str ,lowercase__ : float ,lowercase__ : int ): if k in (0.0_4, 0.0_6): __lowercase = k __lowercase = window_size else: raise ValueError('''invalid k value''' ) def __str__( self : Dict ): return str(self.k ) def SCREAMING_SNAKE_CASE ( self : Optional[int] ,lowercase__ : str ): __lowercase = cva.imread(lowercase__ ,0 ) __lowercase , __lowercase = img.shape __lowercase = [] __lowercase = img.copy() __lowercase = cva.cvtColor(lowercase__ ,cva.COLOR_GRAY2RGB ) __lowercase , __lowercase = np.gradient(lowercase__ ) __lowercase = dx**2 __lowercase = dy**2 __lowercase = dx * dy __lowercase = 0.0_4 __lowercase = self.window_size // 2 for y in range(lowercase__ ,h - offset ): for x in range(lowercase__ ,w - offset ): __lowercase = ixx[ y - offset : y + offset + 1, x - offset : x + offset + 1 ].sum() __lowercase = iyy[ y - offset : y + offset + 1, x - offset : x + offset + 1 ].sum() __lowercase = ixy[ y - offset : y + offset + 1, x - offset : x + offset + 1 ].sum() __lowercase = (wxx * wyy) - (wxy**2) __lowercase = wxx + wyy __lowercase = det - k * (trace**2) # Can change the value if r > 0.5: corner_list.append([x, y, r] ) color_img.itemset((y, x, 0) ,0 ) color_img.itemset((y, x, 1) ,0 ) color_img.itemset((y, x, 2) ,2_5_5 ) return color_img, corner_list if __name__ == "__main__": lowerCAmelCase__ = HarrisCorner(0.04, 3) lowerCAmelCase__ , lowerCAmelCase__ = edge_detect.detect('''path_to_image''') cva.imwrite('''detect.png''', color_img)
104
from typing import List from ...configuration_utils import PretrainedConfig from ...utils import logging SCREAMING_SNAKE_CASE_ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE_ = { """snap-research/efficientformer-l1-300""": ( """https://huggingface.co/snap-research/efficientformer-l1-300/resolve/main/config.json""" ), } class UpperCamelCase__ ( lowerCAmelCase_ ): '''simple docstring''' __snake_case : int = "efficientformer" def __init__( self : Optional[int] ,lowerCamelCase__ : List[int] = [3, 2, 6, 4] ,lowerCamelCase__ : List[int] = [48, 96, 224, 448] ,lowerCamelCase__ : List[bool] = [True, True, True, True] ,lowerCamelCase__ : int = 448 ,lowerCamelCase__ : int = 32 ,lowerCamelCase__ : int = 4 ,lowerCamelCase__ : int = 7 ,lowerCamelCase__ : int = 5 ,lowerCamelCase__ : int = 8 ,lowerCamelCase__ : int = 4 ,lowerCamelCase__ : float = 0.0 ,lowerCamelCase__ : int = 16 ,lowerCamelCase__ : int = 3 ,lowerCamelCase__ : int = 3 ,lowerCamelCase__ : int = 3 ,lowerCamelCase__ : int = 2 ,lowerCamelCase__ : int = 1 ,lowerCamelCase__ : float = 0.0 ,lowerCamelCase__ : int = 1 ,lowerCamelCase__ : bool = True ,lowerCamelCase__ : bool = True ,lowerCamelCase__ : float = 1e-5 ,lowerCamelCase__ : str = "gelu" ,lowerCamelCase__ : float = 0.02 ,lowerCamelCase__ : float = 1e-1_2 ,lowerCamelCase__ : int = 224 ,lowerCamelCase__ : float = 1e-0_5 ,**lowerCamelCase__ : str ,) -> None: '''simple docstring''' super().__init__(**lowerCamelCase__ ) SCREAMING_SNAKE_CASE = hidden_act SCREAMING_SNAKE_CASE = hidden_dropout_prob SCREAMING_SNAKE_CASE = hidden_sizes SCREAMING_SNAKE_CASE = num_hidden_layers SCREAMING_SNAKE_CASE = num_attention_heads SCREAMING_SNAKE_CASE = initializer_range SCREAMING_SNAKE_CASE = layer_norm_eps SCREAMING_SNAKE_CASE = patch_size SCREAMING_SNAKE_CASE = num_channels SCREAMING_SNAKE_CASE = depths SCREAMING_SNAKE_CASE = mlp_expansion_ratio SCREAMING_SNAKE_CASE = downsamples SCREAMING_SNAKE_CASE = dim SCREAMING_SNAKE_CASE = key_dim SCREAMING_SNAKE_CASE = attention_ratio SCREAMING_SNAKE_CASE = resolution SCREAMING_SNAKE_CASE = pool_size SCREAMING_SNAKE_CASE = downsample_patch_size SCREAMING_SNAKE_CASE = downsample_stride SCREAMING_SNAKE_CASE = downsample_pad SCREAMING_SNAKE_CASE = drop_path_rate SCREAMING_SNAKE_CASE = num_metaad_blocks SCREAMING_SNAKE_CASE = distillation SCREAMING_SNAKE_CASE = use_layer_scale SCREAMING_SNAKE_CASE = layer_scale_init_value SCREAMING_SNAKE_CASE = image_size SCREAMING_SNAKE_CASE = batch_norm_eps
296
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) lowerCAmelCase__ = {'''configuration_opt''': ['''OPT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''OPTConfig''']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ = [ '''OPT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''OPTForCausalLM''', '''OPTModel''', '''OPTPreTrainedModel''', '''OPTForSequenceClassification''', '''OPTForQuestionAnswering''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ = ['''TFOPTForCausalLM''', '''TFOPTModel''', '''TFOPTPreTrainedModel'''] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ = [ '''FlaxOPTForCausalLM''', '''FlaxOPTModel''', '''FlaxOPTPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_opt import OPT_PRETRAINED_CONFIG_ARCHIVE_MAP, OPTConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_opt import ( OPT_PRETRAINED_MODEL_ARCHIVE_LIST, OPTForCausalLM, OPTForQuestionAnswering, OPTForSequenceClassification, OPTModel, OPTPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_opt import TFOPTForCausalLM, TFOPTModel, TFOPTPreTrainedModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_opt import FlaxOPTForCausalLM, FlaxOPTModel, FlaxOPTPreTrainedModel else: import sys lowerCAmelCase__ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
355
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase__ = logging.get_logger(__name__) lowerCAmelCase__ = { '''tiiuae/falcon-40b''': '''https://huggingface.co/tiiuae/falcon-40b/resolve/main/config.json''', '''tiiuae/falcon-7b''': '''https://huggingface.co/tiiuae/falcon-7b/resolve/main/config.json''', } class _lowerCamelCase ( _lowercase ): UpperCAmelCase_ = "falcon" UpperCAmelCase_ = ["past_key_values"] def __init__(self , __a=6_50_24 , __a=45_44 , __a=32 , __a=71 , __a=1e-5 , __a=0.02 , __a=True , __a=0.0 , __a=0.0 , __a=None , __a=False , __a=False , __a=True , __a=True , __a=False , __a=11 , __a=11 , **__a , ) -> Union[str, Any]: UpperCamelCase = vocab_size # Backward compatibility with n_embed kwarg UpperCamelCase = kwargs.pop("n_embed" , __a ) UpperCamelCase = hidden_size if n_embed is None else n_embed UpperCamelCase = num_hidden_layers UpperCamelCase = num_attention_heads UpperCamelCase = layer_norm_epsilon UpperCamelCase = initializer_range UpperCamelCase = use_cache UpperCamelCase = hidden_dropout UpperCamelCase = attention_dropout UpperCamelCase = bos_token_id UpperCamelCase = eos_token_id UpperCamelCase = num_attention_heads if num_kv_heads is None else num_kv_heads UpperCamelCase = alibi UpperCamelCase = new_decoder_architecture UpperCamelCase = multi_query # Ignored when new_decoder_architecture is True UpperCamelCase = parallel_attn UpperCamelCase = bias super().__init__(bos_token_id=__a , eos_token_id=__a , **__a ) @property def snake_case_ (self ) -> Optional[int]: return self.hidden_size // self.num_attention_heads @property def snake_case_ (self ) -> Dict: return not self.alibi
244
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 _snake_case = logging.get_logger(__name__) _snake_case = { "microsoft/beit-base-patch16-224-pt22k": ( "https://huggingface.co/microsoft/beit-base-patch16-224-pt22k/resolve/main/config.json" ), # See all BEiT models at https://huggingface.co/models?filter=beit } class UpperCAmelCase_ ( a): lowerCamelCase__ = 'beit' def __init__( self, __a=8192, __a=768, __a=12, __a=12, __a=3072, __a="gelu", __a=0.0, __a=0.0, __a=0.02, __a=1E-12, __a=224, __a=16, __a=3, __a=False, __a=False, __a=False, __a=False, __a=0.1, __a=0.1, __a=True, __a=[3, 5, 7, 11], __a=[1, 2, 3, 6], __a=True, __a=0.4, __a=256, __a=1, __a=False, __a=255, **__a, ): '''simple docstring''' super().__init__(**__a) _lowerCAmelCase : str = vocab_size _lowerCAmelCase : Tuple = hidden_size _lowerCAmelCase : Optional[int] = num_hidden_layers _lowerCAmelCase : Tuple = num_attention_heads _lowerCAmelCase : str = intermediate_size _lowerCAmelCase : Optional[Any] = hidden_act _lowerCAmelCase : Tuple = hidden_dropout_prob _lowerCAmelCase : Dict = attention_probs_dropout_prob _lowerCAmelCase : Any = initializer_range _lowerCAmelCase : List[str] = layer_norm_eps _lowerCAmelCase : Dict = image_size _lowerCAmelCase : int = patch_size _lowerCAmelCase : str = num_channels _lowerCAmelCase : List[Any] = use_mask_token _lowerCAmelCase : List[Any] = use_absolute_position_embeddings _lowerCAmelCase : List[str] = use_relative_position_bias _lowerCAmelCase : Tuple = use_shared_relative_position_bias _lowerCAmelCase : Any = layer_scale_init_value _lowerCAmelCase : Optional[Any] = drop_path_rate _lowerCAmelCase : Any = use_mean_pooling # decode head attributes (semantic segmentation) _lowerCAmelCase : Any = out_indices _lowerCAmelCase : List[str] = pool_scales # auxiliary head attributes (semantic segmentation) _lowerCAmelCase : Any = use_auxiliary_head _lowerCAmelCase : List[Any] = auxiliary_loss_weight _lowerCAmelCase : List[Any] = auxiliary_channels _lowerCAmelCase : Union[str, Any] = auxiliary_num_convs _lowerCAmelCase : Optional[Any] = auxiliary_concat_input _lowerCAmelCase : Union[str, Any] = semantic_loss_ignore_index class UpperCAmelCase_ ( a): lowerCamelCase__ = version.parse('1.11') @property def snake_case__ ( self): '''simple docstring''' return OrderedDict( [ ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}), ]) @property def snake_case__ ( self): '''simple docstring''' return 1E-4
36
"""simple docstring""" from __future__ import annotations def UpperCAmelCase__ ( SCREAMING_SNAKE_CASE : str ): '''simple docstring''' return [ord(SCREAMING_SNAKE_CASE ) - 96 for elem in plain] def UpperCAmelCase__ ( SCREAMING_SNAKE_CASE : list[int] ): '''simple docstring''' return "".join(chr(elem + 96 ) for elem in encoded ) def UpperCAmelCase__ ( ): '''simple docstring''' lowerCAmelCase = encode(input("""-> """ ).strip().lower() ) print("""Encoded: """ , SCREAMING_SNAKE_CASE ) print("""Decoded:""" , decode(SCREAMING_SNAKE_CASE ) ) if __name__ == "__main__": main()
46
0
"""simple docstring""" import argparse import json from typing import List from ltp import LTP from transformers import BertTokenizer def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : List[Any] ): # This defines a "chinese character" as anything in the CJK Unicode block: # https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block) # # Note that the CJK Unicode block is NOT all Japanese and Korean characters, # despite its name. The modern Korean Hangul alphabet is a different block, # as is Japanese Hiragana and Katakana. Those alphabets are used to write # space-separated words, so they are not treated specially and handled # like the all of the other languages. 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 _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : str ): # word like '180' or '身高' or '神' for char in word: __UpperCamelCase =ord(SCREAMING_SNAKE_CASE__ ) if not _is_chinese_char(SCREAMING_SNAKE_CASE__ ): return 0 return 1 def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : List[str] ): __UpperCamelCase =set() for token in tokens: __UpperCamelCase =len(SCREAMING_SNAKE_CASE__ ) > 1 and is_chinese(SCREAMING_SNAKE_CASE__ ) if chinese_word: word_set.add(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =list(SCREAMING_SNAKE_CASE__ ) return word_list def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : set() ): if not chinese_word_set: return bert_tokens __UpperCamelCase =max([len(SCREAMING_SNAKE_CASE__ ) for w in chinese_word_set] ) __UpperCamelCase =bert_tokens __UpperCamelCase , __UpperCamelCase =0, len(SCREAMING_SNAKE_CASE__ ) while start < end: __UpperCamelCase =True if is_chinese(bert_word[start] ): __UpperCamelCase =min(end - start , SCREAMING_SNAKE_CASE__ ) for i in range(SCREAMING_SNAKE_CASE__ , 1 , -1 ): __UpperCamelCase =''.join(bert_word[start : start + i] ) if whole_word in chinese_word_set: for j in range(start + 1 , start + i ): __UpperCamelCase ='##' + bert_word[j] __UpperCamelCase =start + i __UpperCamelCase =False break if single_word: start += 1 return bert_word def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : LTP , SCREAMING_SNAKE_CASE__ : BertTokenizer ): __UpperCamelCase =[] for i in range(0 , len(SCREAMING_SNAKE_CASE__ ) , 1_00 ): __UpperCamelCase =ltp_tokenizer.seg(lines[i : i + 1_00] )[0] __UpperCamelCase =[get_chinese_word(SCREAMING_SNAKE_CASE__ ) for r in res] ltp_res.extend(SCREAMING_SNAKE_CASE__ ) assert len(SCREAMING_SNAKE_CASE__ ) == len(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =[] for i in range(0 , len(SCREAMING_SNAKE_CASE__ ) , 1_00 ): __UpperCamelCase =bert_tokenizer(lines[i : i + 1_00] , add_special_tokens=SCREAMING_SNAKE_CASE__ , truncation=SCREAMING_SNAKE_CASE__ , max_length=5_12 ) bert_res.extend(res['input_ids'] ) assert len(SCREAMING_SNAKE_CASE__ ) == len(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =[] for input_ids, chinese_word in zip(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): __UpperCamelCase =[] for id in input_ids: __UpperCamelCase =bert_tokenizer._convert_id_to_token(SCREAMING_SNAKE_CASE__ ) input_tokens.append(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =add_sub_symbol(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =[] # We only save pos of chinese subwords start with ##, which mean is part of a whole word. for i, token in enumerate(SCREAMING_SNAKE_CASE__ ): if token[:2] == "##": __UpperCamelCase =token[2:] # save chinese tokens' pos if len(SCREAMING_SNAKE_CASE__ ) == 1 and _is_chinese_char(ord(SCREAMING_SNAKE_CASE__ ) ): ref_id.append(SCREAMING_SNAKE_CASE__ ) ref_ids.append(SCREAMING_SNAKE_CASE__ ) assert len(SCREAMING_SNAKE_CASE__ ) == len(SCREAMING_SNAKE_CASE__ ) return ref_ids def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : List[Any] ): # For Chinese (Ro)Bert, the best result is from : RoBERTa-wwm-ext (https://github.com/ymcui/Chinese-BERT-wwm) # If we want to fine-tune these model, we have to use same tokenizer : LTP (https://github.com/HIT-SCIR/ltp) with open(args.file_name , 'r' , encoding='utf-8' ) as f: __UpperCamelCase =f.readlines() __UpperCamelCase =[line.strip() for line in data if len(SCREAMING_SNAKE_CASE__ ) > 0 and not line.isspace()] # avoid delimiter like '\u2029' __UpperCamelCase =LTP(args.ltp ) # faster in GPU device __UpperCamelCase =BertTokenizer.from_pretrained(args.bert ) __UpperCamelCase =prepare_ref(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) with open(args.save_path , 'w' , encoding='utf-8' ) as f: __UpperCamelCase =[json.dumps(SCREAMING_SNAKE_CASE__ ) + '\n' for ref in ref_ids] f.writelines(SCREAMING_SNAKE_CASE__ ) if __name__ == "__main__": _A = 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') _A = parser.parse_args() main(args)
364
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 UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : str = "realm" def __init__( self , A_=30522 , A_=768 , A_=128 , A_=12 , A_=12 , A_=8 , A_=3072 , A_="gelu_new" , A_=0.1 , A_=0.1 , A_=512 , A_=2 , A_=0.02 , A_=1E-12 , A_=256 , A_=10 , A_=1E-3 , A_=5 , A_=320 , A_=13353718 , A_=5000 , A_=1 , A_=0 , A_=2 , **A_ , ) -> Dict: super().__init__(pad_token_id=A_ , bos_token_id=A_ , eos_token_id=A_ , **A_ ) # Common config __UpperCamelCase =vocab_size __UpperCamelCase =max_position_embeddings __UpperCamelCase =hidden_size __UpperCamelCase =retriever_proj_size __UpperCamelCase =num_hidden_layers __UpperCamelCase =num_attention_heads __UpperCamelCase =num_candidates __UpperCamelCase =intermediate_size __UpperCamelCase =hidden_act __UpperCamelCase =hidden_dropout_prob __UpperCamelCase =attention_probs_dropout_prob __UpperCamelCase =initializer_range __UpperCamelCase =type_vocab_size __UpperCamelCase =layer_norm_eps # Reader config __UpperCamelCase =span_hidden_size __UpperCamelCase =max_span_width __UpperCamelCase =reader_layer_norm_eps __UpperCamelCase =reader_beam_size __UpperCamelCase =reader_seq_len # Retrieval config __UpperCamelCase =num_block_records __UpperCamelCase =searcher_beam_size
117
0
import unittest from transformers import load_tool from transformers.utils import is_torch_available if is_torch_available(): import torch from transformers.testing_utils import require_torch from .test_tools_common import ToolTesterMixin @require_torch class UpperCamelCase__ ( unittest.TestCase , lowerCAmelCase_ ): '''simple docstring''' def SCREAMING_SNAKE_CASE__ ( self : Tuple ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE = load_tool("""text-to-speech""" ) self.tool.setup() def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ) -> Any: '''simple docstring''' torch.manual_seed(0 ) SCREAMING_SNAKE_CASE = self.tool("""hey""" ) SCREAMING_SNAKE_CASE = result.to_raw() self.assertTrue( torch.allclose( resulting_tensor[:3] ,torch.tensor([-0.0005966668832115829, -0.0003657640190795064, -0.00013439502799883485] ) ,) ) def SCREAMING_SNAKE_CASE__ ( self : Dict ) -> Tuple: '''simple docstring''' torch.manual_seed(0 ) SCREAMING_SNAKE_CASE = self.tool("""hey""" ) SCREAMING_SNAKE_CASE = result.to_raw() self.assertTrue( torch.allclose( resulting_tensor[:3] ,torch.tensor([-0.0005966668832115829, -0.0003657640190795064, -0.00013439502799883485] ) ,) )
296
import unittest import numpy as np import torch from diffusers import KarrasVePipeline, KarrasVeScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class UpperCamelCase__ ( unittest.TestCase ): '''simple docstring''' @property def SCREAMING_SNAKE_CASE__ ( self : str ) -> Optional[int]: '''simple docstring''' torch.manual_seed(0 ) SCREAMING_SNAKE_CASE = UNetaDModel( block_out_channels=(32, 64) ,layers_per_block=2 ,sample_size=32 ,in_channels=3 ,out_channels=3 ,down_block_types=("""DownBlock2D""", """AttnDownBlock2D""") ,up_block_types=("""AttnUpBlock2D""", """UpBlock2D""") ,) return model def SCREAMING_SNAKE_CASE__ ( self : Tuple ) -> Union[str, Any]: '''simple docstring''' SCREAMING_SNAKE_CASE = self.dummy_uncond_unet SCREAMING_SNAKE_CASE = KarrasVeScheduler() SCREAMING_SNAKE_CASE = KarrasVePipeline(unet=lowerCamelCase__ ,scheduler=lowerCamelCase__ ) pipe.to(lowerCamelCase__ ) pipe.set_progress_bar_config(disable=lowerCamelCase__ ) SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE = pipe(num_inference_steps=2 ,generator=lowerCamelCase__ ,output_type="""numpy""" ).images SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE = pipe(num_inference_steps=2 ,generator=lowerCamelCase__ ,output_type="""numpy""" ,return_dict=lowerCamelCase__ )[0] SCREAMING_SNAKE_CASE = image[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) SCREAMING_SNAKE_CASE = np.array([0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 @slow @require_torch class UpperCamelCase__ ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ) -> Optional[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE = """google/ncsnpp-celebahq-256""" SCREAMING_SNAKE_CASE = UNetaDModel.from_pretrained(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = KarrasVeScheduler() SCREAMING_SNAKE_CASE = KarrasVePipeline(unet=lowerCamelCase__ ,scheduler=lowerCamelCase__ ) pipe.to(lowerCamelCase__ ) pipe.set_progress_bar_config(disable=lowerCamelCase__ ) SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE = pipe(num_inference_steps=20 ,generator=lowerCamelCase__ ,output_type="""numpy""" ).images SCREAMING_SNAKE_CASE = image[0, -3:, -3:, -1] assert image.shape == (1, 256, 256, 3) SCREAMING_SNAKE_CASE = np.array([0.578, 0.5811, 0.5924, 0.5809, 0.587, 0.5886, 0.5861, 0.5802, 0.586] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
296
1
'''simple docstring''' import os from typing import List, Optional, Union from ...image_processing_utils import BatchFeature from ...image_utils import ImageInput from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType from ..auto import AutoTokenizer class lowerCAmelCase_ ( lowerCamelCase__ ): '''simple docstring''' UpperCamelCase_ : List[Any] = ["""image_processor""", """tokenizer"""] UpperCamelCase_ : Optional[Any] = """BlipImageProcessor""" UpperCamelCase_ : List[Any] = """AutoTokenizer""" def __init__( self : Dict , SCREAMING_SNAKE_CASE_ : Tuple , SCREAMING_SNAKE_CASE_ : List[str] , SCREAMING_SNAKE_CASE_ : List[Any] ) -> str: '''simple docstring''' super().__init__(__snake_case , __snake_case ) # add QFormer tokenizer A: Optional[Any] = qformer_tokenizer def __call__( self : Any , SCREAMING_SNAKE_CASE_ : ImageInput = None , SCREAMING_SNAKE_CASE_ : Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None , SCREAMING_SNAKE_CASE_ : bool = True , SCREAMING_SNAKE_CASE_ : Union[bool, str, PaddingStrategy] = False , SCREAMING_SNAKE_CASE_ : Union[bool, str, TruncationStrategy] = None , SCREAMING_SNAKE_CASE_ : Optional[int] = None , SCREAMING_SNAKE_CASE_ : int = 0 , SCREAMING_SNAKE_CASE_ : Optional[int] = None , SCREAMING_SNAKE_CASE_ : Optional[bool] = None , SCREAMING_SNAKE_CASE_ : bool = False , SCREAMING_SNAKE_CASE_ : bool = False , SCREAMING_SNAKE_CASE_ : bool = False , SCREAMING_SNAKE_CASE_ : bool = False , SCREAMING_SNAKE_CASE_ : bool = False , SCREAMING_SNAKE_CASE_ : bool = True , SCREAMING_SNAKE_CASE_ : Optional[Union[str, TensorType]] = None , **SCREAMING_SNAKE_CASE_ : Optional[int] , ) -> Dict: '''simple docstring''' if images is None and text is None: raise ValueError('''You have to specify at least images or text.''' ) A: Dict = BatchFeature() if text is not None: A: List[str] = self.tokenizer( text=__snake_case , add_special_tokens=__snake_case , padding=__snake_case , truncation=__snake_case , max_length=__snake_case , stride=__snake_case , pad_to_multiple_of=__snake_case , return_attention_mask=__snake_case , return_overflowing_tokens=__snake_case , return_special_tokens_mask=__snake_case , return_offsets_mapping=__snake_case , return_token_type_ids=__snake_case , return_length=__snake_case , verbose=__snake_case , return_tensors=__snake_case , **__snake_case , ) encoding.update(__snake_case ) A: int = self.qformer_tokenizer( text=__snake_case , add_special_tokens=__snake_case , padding=__snake_case , truncation=__snake_case , max_length=__snake_case , stride=__snake_case , pad_to_multiple_of=__snake_case , return_attention_mask=__snake_case , return_overflowing_tokens=__snake_case , return_special_tokens_mask=__snake_case , return_offsets_mapping=__snake_case , return_token_type_ids=__snake_case , return_length=__snake_case , verbose=__snake_case , return_tensors=__snake_case , **__snake_case , ) A: Union[str, Any] = qformer_text_encoding.pop('''input_ids''' ) A: List[str] = qformer_text_encoding.pop('''attention_mask''' ) if images is not None: A: List[Any] = self.image_processor(__snake_case , return_tensors=__snake_case ) encoding.update(__snake_case ) return encoding def _snake_case ( self : int , *SCREAMING_SNAKE_CASE_ : Optional[Any] , **SCREAMING_SNAKE_CASE_ : Union[str, Any] ) -> str: '''simple docstring''' return self.tokenizer.batch_decode(*__snake_case , **__snake_case ) def _snake_case ( self : Dict , *SCREAMING_SNAKE_CASE_ : Union[str, Any] , **SCREAMING_SNAKE_CASE_ : int ) -> List[str]: '''simple docstring''' return self.tokenizer.decode(*__snake_case , **__snake_case ) @property # Copied from transformers.models.blip.processing_blip.BlipProcessor.model_input_names def _snake_case ( self : List[str] ) -> Tuple: '''simple docstring''' A: List[Any] = self.tokenizer.model_input_names A: Dict = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) ) def _snake_case ( self : Optional[Any] , SCREAMING_SNAKE_CASE_ : Tuple , **SCREAMING_SNAKE_CASE_ : int ) -> Optional[Any]: '''simple docstring''' if os.path.isfile(__snake_case ): raise ValueError(f"""Provided path ({save_directory}) should be a directory, not a file""" ) os.makedirs(__snake_case , exist_ok=__snake_case ) A: Tuple = os.path.join(__snake_case , '''qformer_tokenizer''' ) self.qformer_tokenizer.save_pretrained(__snake_case ) return super().save_pretrained(__snake_case , **__snake_case ) @classmethod def _snake_case ( cls : List[Any] , SCREAMING_SNAKE_CASE_ : Union[str, Any] , **SCREAMING_SNAKE_CASE_ : int ) -> str: '''simple docstring''' A: Tuple = AutoTokenizer.from_pretrained(__snake_case , subfolder='''qformer_tokenizer''' ) A: Any = cls._get_arguments_from_pretrained(__snake_case , **__snake_case ) args.append(__snake_case ) return cls(*__snake_case )
358
'''simple docstring''' from __future__ import annotations from typing import Any class lowerCAmelCase_ ( UpperCAmelCase_ ): '''simple docstring''' pass class lowerCAmelCase_ : '''simple docstring''' def __init__( self : List[Any] , SCREAMING_SNAKE_CASE_ : Any ) -> None: '''simple docstring''' A: Any = data A: Node | None = None def __iter__( self : Optional[int] ) -> List[str]: '''simple docstring''' A: List[str] = self A: Dict = [] while node: if node in visited: raise ContainsLoopError visited.append(SCREAMING_SNAKE_CASE_ ) yield node.data A: str = node.next_node @property def _snake_case ( self : List[str] ) -> bool: '''simple docstring''' try: list(self ) return False except ContainsLoopError: return True if __name__ == "__main__": UpperCamelCase = Node(1) UpperCamelCase = Node(2) UpperCamelCase = Node(3) UpperCamelCase = Node(4) print(root_node.has_loop) # False UpperCamelCase = root_node.next_node print(root_node.has_loop) # True UpperCamelCase = Node(5) UpperCamelCase = Node(6) UpperCamelCase = Node(5) UpperCamelCase = Node(6) print(root_node.has_loop) # False UpperCamelCase = Node(1) print(root_node.has_loop) # False
334
0
import re import jax.numpy as jnp from flax.traverse_util import flatten_dict, unflatten_dict from jax.random import PRNGKey from ..utils import logging UpperCAmelCase__ = logging.get_logger(__name__) def UpperCAmelCase_ ( __snake_case ) -> int: """simple docstring""" _lowercase =R"\w+[.]\d+" _lowercase =re.findall(__a , __a ) for pat in pats: _lowercase =key.replace(__a , '''_'''.join(pat.split('''.''' ) ) ) return key def UpperCAmelCase_ ( __snake_case , __snake_case , __snake_case ) -> Any: """simple docstring""" _lowercase =pt_tuple_key[:-1] + ("scale",) if ( any('''norm''' in str_ for str_ in pt_tuple_key ) and (pt_tuple_key[-1] == "bias") and (pt_tuple_key[:-1] + ("bias",) not in random_flax_state_dict) and (pt_tuple_key[:-1] + ("scale",) in random_flax_state_dict) ): _lowercase =pt_tuple_key[:-1] + ("scale",) return renamed_pt_tuple_key, pt_tensor elif pt_tuple_key[-1] in ["weight", "gamma"] and pt_tuple_key[:-1] + ("scale",) in random_flax_state_dict: _lowercase =pt_tuple_key[:-1] + ("scale",) return renamed_pt_tuple_key, pt_tensor # embedding if pt_tuple_key[-1] == "weight" and pt_tuple_key[:-1] + ("embedding",) in random_flax_state_dict: _lowercase =pt_tuple_key[:-1] + ("embedding",) return renamed_pt_tuple_key, pt_tensor # conv layer _lowercase =pt_tuple_key[:-1] + ("kernel",) if pt_tuple_key[-1] == "weight" and pt_tensor.ndim == 4: _lowercase =pt_tensor.transpose(2 , 3 , 1 , 0 ) return renamed_pt_tuple_key, pt_tensor # linear layer _lowercase =pt_tuple_key[:-1] + ("kernel",) if pt_tuple_key[-1] == "weight": _lowercase =pt_tensor.T return renamed_pt_tuple_key, pt_tensor # old PyTorch layer norm weight _lowercase =pt_tuple_key[:-1] + ("weight",) if pt_tuple_key[-1] == "gamma": return renamed_pt_tuple_key, pt_tensor # old PyTorch layer norm bias _lowercase =pt_tuple_key[:-1] + ("bias",) if pt_tuple_key[-1] == "beta": return renamed_pt_tuple_key, pt_tensor return pt_tuple_key, pt_tensor def UpperCAmelCase_ ( __snake_case , __snake_case , __snake_case=42 ) -> Tuple: """simple docstring""" _lowercase ={k: v.numpy() for k, v in pt_state_dict.items()} # Step 2: Since the model is stateless, get random Flax params _lowercase =flax_model.init_weights(PRNGKey(__a ) ) _lowercase =flatten_dict(__a ) _lowercase ={} # Need to change some parameters name to match Flax names for pt_key, pt_tensor in pt_state_dict.items(): _lowercase =rename_key(__a ) _lowercase =tuple(renamed_pt_key.split('''.''' ) ) # Correctly rename weight parameters _lowercase =rename_key_and_reshape_tensor(__a , __a , __a ) if flax_key in random_flax_state_dict: if flax_tensor.shape != random_flax_state_dict[flax_key].shape: raise ValueError( F"PyTorch checkpoint seems to be incorrect. Weight {pt_key} was expected to be of shape " F"{random_flax_state_dict[flax_key].shape}, but is {flax_tensor.shape}." ) # also add unexpected weight so that warning is thrown _lowercase =jnp.asarray(__a ) return unflatten_dict(__a )
5
from math import ceil, sqrt def lowerCAmelCase_ ( __a = 1000000 ) -> int: """simple docstring""" lowerCamelCase__: Optional[int] =0 for outer_width in range(3 , (limit // 4) + 2 ): if outer_width**2 > limit: lowerCamelCase__: Dict =max(ceil(sqrt(outer_width**2 - limit ) ) , 1 ) else: lowerCamelCase__: str =1 if (outer_width - hole_width_lower_bound) % 2: hole_width_lower_bound += 1 answer += (outer_width - hole_width_lower_bound - 2) // 2 + 1 return answer if __name__ == "__main__": print(f'{solution() = }')
10
0
"""simple docstring""" import json import os import unittest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_ftfy, require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class __a ( lowerCAmelCase__ , unittest.TestCase ): SCREAMING_SNAKE_CASE__ : Optional[Any] = CLIPTokenizer SCREAMING_SNAKE_CASE__ : int = CLIPTokenizerFast SCREAMING_SNAKE_CASE__ : Optional[Any] = True SCREAMING_SNAKE_CASE__ : Any = {} SCREAMING_SNAKE_CASE__ : Tuple = False def snake_case_ ( self ): super().setUp() # fmt: off _lowerCamelCase = ['l', 'o', 'w', 'e', 'r', 's', 't', 'i', 'd', 'n', 'lo', 'l</w>', 'w</w>', 'r</w>', 't</w>', 'low</w>', 'er</w>', 'lowest</w>', 'newer</w>', 'wider', '<unk>', '<|startoftext|>', '<|endoftext|>'] # fmt: on _lowerCamelCase = dict(zip(a__ , range(len(a__ ) ) ) ) _lowerCamelCase = ['#version: 0.2', 'l o', 'lo w</w>', 'e r</w>'] _lowerCamelCase = {'unk_token': '<unk>'} _lowerCamelCase = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) _lowerCamelCase = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['merges_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as fp: fp.write(json.dumps(a__ ) + '\n' ) with open(self.merges_file , 'w' , encoding='utf-8' ) as fp: fp.write('\n'.join(a__ ) ) def snake_case_ ( self , **a__ ): kwargs.update(self.special_tokens_map ) return CLIPTokenizer.from_pretrained(self.tmpdirname , **a__ ) def snake_case_ ( self , **a__ ): kwargs.update(self.special_tokens_map ) return CLIPTokenizerFast.from_pretrained(self.tmpdirname , **a__ ) def snake_case_ ( self , a__ ): _lowerCamelCase = 'lower newer' _lowerCamelCase = 'lower newer' return input_text, output_text def snake_case_ ( self ): _lowerCamelCase = CLIPTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) _lowerCamelCase = 'lower newer' _lowerCamelCase = ['lo', 'w', 'er</w>', 'n', 'e', 'w', 'er</w>'] _lowerCamelCase = tokenizer.tokenize(a__ ) self.assertListEqual(a__ , a__ ) _lowerCamelCase = tokens + [tokenizer.unk_token] _lowerCamelCase = [10, 2, 16, 9, 3, 2, 16, 20] self.assertListEqual(tokenizer.convert_tokens_to_ids(a__ ) , a__ ) @require_ftfy def snake_case_ ( self ): for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'{tokenizer.__class__.__name__} ({pretrained_name})' ): _lowerCamelCase = self.tokenizer_class.from_pretrained(a__ , **a__ ) _lowerCamelCase = self.rust_tokenizer_class.from_pretrained(a__ , **a__ ) _lowerCamelCase = 'A\n\'ll 11p223RF☆ho!!to?\'d\'d\'\'d of a cat to-$\'\'d.' _lowerCamelCase = tokenizer_s.tokenize(a__ ) _lowerCamelCase = tokenizer_r.tokenize(a__ ) self.assertListEqual(a__ , a__ ) # Test that the tokenization is identical on an example containing a character (Latin Small Letter A # with Tilde) encoded in 2 different ways _lowerCamelCase = 'xa\u0303y' + ' ' + 'x\xe3y' _lowerCamelCase = tokenizer_s.tokenize(a__ ) _lowerCamelCase = tokenizer_r.tokenize(a__ ) self.assertListEqual(a__ , a__ ) # Test that the tokenization is identical on unicode of space type _lowerCamelCase = [ '\u0009', # (horizontal tab, '\t') '\u000B', # (vertical tab) '\u000C', # (form feed) '\u0020', # (space, ' ') '\u200E', # (left-to-right mark):w '\u200F', # (right-to-left mark) ] for unicode_seq in spaces_unicodes: _lowerCamelCase = tokenizer_s.tokenize(a__ ) _lowerCamelCase = tokenizer_r.tokenize(a__ ) self.assertListEqual(a__ , a__ ) # Test that the tokenization is identical on unicode of line break type _lowerCamelCase = [ '\u000A', # (line feed, '\n') '\r\n', # (carriage return and line feed, '\r\n') '\u000D', # (carriage return, '\r') '\r', # (carriage return, '\r') '\u000D', # (carriage return, '\r') '\u2028', # (line separator) '\u2029', # (paragraph separator) # "\u0085", # (next line) ] # The tokenization is not identical for the character "\u0085" (next line). The slow version using ftfy transforms # it into the Horizontal Ellipsis character "…" ("\u2026") while the fast version transforms it into a # space (and thus into an empty list). for unicode_seq in line_break_unicodes: _lowerCamelCase = tokenizer_s.tokenize(a__ ) _lowerCamelCase = tokenizer_r.tokenize(a__ ) self.assertListEqual(a__ , a__ ) def snake_case_ ( self ): # Test which aims to verify that the offsets are well adapted to the argument `add_prefix_space` for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'{tokenizer.__class__.__name__} ({pretrained_name})' ): _lowerCamelCase = 'hello' # `hello` is a token in the vocabulary of `pretrained_name` _lowerCamelCase = F'{text_of_1_token} {text_of_1_token}' _lowerCamelCase = self.rust_tokenizer_class.from_pretrained( a__ , use_fast=a__ , ) _lowerCamelCase = tokenizer_r(a__ , return_offsets_mapping=a__ , add_special_tokens=a__ ) self.assertEqual(encoding.offset_mapping[0] , (0, len(a__ )) ) self.assertEqual( encoding.offset_mapping[1] , (len(a__ ) + 1, len(a__ ) + 1 + len(a__ )) , ) _lowerCamelCase = F' {text}' _lowerCamelCase = self.rust_tokenizer_class.from_pretrained( a__ , use_fast=a__ , ) _lowerCamelCase = tokenizer_r(a__ , return_offsets_mapping=a__ , add_special_tokens=a__ ) self.assertEqual(encoding.offset_mapping[0] , (1, 1 + len(a__ )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(a__ ) + 1, 1 + len(a__ ) + 1 + len(a__ )) , ) def snake_case_ ( self ): # Test related to the breaking change introduced in transformers v4.17.0 # We need to check that an error in raised when the user try to load a previous version of the tokenizer. with self.assertRaises(a__ ) as context: self.rust_tokenizer_class.from_pretrained('robot-test/old-clip-tokenizer' ) self.assertTrue( context.exception.args[0].startswith( 'The `backend_tokenizer` provided does not match the expected format.' ) ) @require_ftfy def snake_case_ ( self ): super().test_tokenization_python_rust_equals() def snake_case_ ( self ): # CLIP always lower cases letters pass
358
"""simple docstring""" from dataclasses import dataclass from typing import Dict, Optional, Tuple, Union import torch import torch.nn as nn from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, apply_forward_hook from .attention_processor import AttentionProcessor, AttnProcessor from .modeling_utils import ModelMixin from .vae import Decoder, DecoderOutput, DiagonalGaussianDistribution, Encoder @dataclass class __a ( lowerCAmelCase__ ): SCREAMING_SNAKE_CASE__ : "DiagonalGaussianDistribution" class __a ( lowerCAmelCase__ , lowerCAmelCase__ ): SCREAMING_SNAKE_CASE__ : Any = True @register_to_config def __init__( self , a__ = 3 , a__ = 3 , a__ = ("DownEncoderBlock2D",) , a__ = ("UpDecoderBlock2D",) , a__ = (64,) , a__ = 1 , a__ = "silu" , a__ = 4 , a__ = 32 , a__ = 32 , a__ = 0.18215 , ): super().__init__() # pass init params to Encoder _lowerCamelCase = Encoder( in_channels=a__ , out_channels=a__ , down_block_types=a__ , block_out_channels=a__ , layers_per_block=a__ , act_fn=a__ , norm_num_groups=a__ , double_z=a__ , ) # pass init params to Decoder _lowerCamelCase = Decoder( in_channels=a__ , out_channels=a__ , up_block_types=a__ , block_out_channels=a__ , layers_per_block=a__ , norm_num_groups=a__ , act_fn=a__ , ) _lowerCamelCase = nn.Convad(2 * latent_channels , 2 * latent_channels , 1 ) _lowerCamelCase = nn.Convad(a__ , a__ , 1 ) _lowerCamelCase = False _lowerCamelCase = False # only relevant if vae tiling is enabled _lowerCamelCase = self.config.sample_size _lowerCamelCase = ( self.config.sample_size[0] if isinstance(self.config.sample_size , (list, tuple) ) else self.config.sample_size ) _lowerCamelCase = int(sample_size / (2 ** (len(self.config.block_out_channels ) - 1)) ) _lowerCamelCase = 0.25 def snake_case_ ( self , a__ , a__=False ): if isinstance(a__ , (Encoder, Decoder) ): _lowerCamelCase = value def snake_case_ ( self , a__ = True ): _lowerCamelCase = use_tiling def snake_case_ ( self ): self.enable_tiling(a__ ) def snake_case_ ( self ): _lowerCamelCase = True def snake_case_ ( self ): _lowerCamelCase = False @property # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.attn_processors def snake_case_ ( self ): _lowerCamelCase = {} def fn_recursive_add_processors(a__ , a__ , a__ ): if hasattr(a__ , 'set_processor' ): _lowerCamelCase = module.processor for sub_name, child in module.named_children(): fn_recursive_add_processors(F'{name}.{sub_name}' , a__ , a__ ) return processors for name, module in self.named_children(): fn_recursive_add_processors(a__ , a__ , a__ ) return processors def snake_case_ ( self , a__ ): _lowerCamelCase = len(self.attn_processors.keys() ) if isinstance(a__ , a__ ) and len(a__ ) != count: raise ValueError( F'A dict of processors was passed, but the number of processors {len(a__ )} does not match the' F' number of attention layers: {count}. Please make sure to pass {count} processor classes.' ) def fn_recursive_attn_processor(a__ , a__ , a__ ): if hasattr(a__ , 'set_processor' ): if not isinstance(a__ , a__ ): module.set_processor(a__ ) else: module.set_processor(processor.pop(F'{name}.processor' ) ) for sub_name, child in module.named_children(): fn_recursive_attn_processor(F'{name}.{sub_name}' , a__ , a__ ) for name, module in self.named_children(): fn_recursive_attn_processor(a__ , a__ , a__ ) def snake_case_ ( self ): self.set_attn_processor(AttnProcessor() ) @apply_forward_hook def snake_case_ ( self , a__ , a__ = True ): if self.use_tiling and (x.shape[-1] > self.tile_sample_min_size or x.shape[-2] > self.tile_sample_min_size): return self.tiled_encode(a__ , return_dict=a__ ) if self.use_slicing and x.shape[0] > 1: _lowerCamelCase = [self.encoder(a__ ) for x_slice in x.split(1 )] _lowerCamelCase = torch.cat(a__ ) else: _lowerCamelCase = self.encoder(a__ ) _lowerCamelCase = self.quant_conv(a__ ) _lowerCamelCase = DiagonalGaussianDistribution(a__ ) if not return_dict: return (posterior,) return AutoencoderKLOutput(latent_dist=a__ ) def snake_case_ ( self , a__ , a__ = True ): if self.use_tiling and (z.shape[-1] > self.tile_latent_min_size or z.shape[-2] > self.tile_latent_min_size): return self.tiled_decode(a__ , return_dict=a__ ) _lowerCamelCase = self.post_quant_conv(a__ ) _lowerCamelCase = self.decoder(a__ ) if not return_dict: return (dec,) return DecoderOutput(sample=a__ ) @apply_forward_hook def snake_case_ ( self , a__ , a__ = True ): if self.use_slicing and z.shape[0] > 1: _lowerCamelCase = [self._decode(a__ ).sample for z_slice in z.split(1 )] _lowerCamelCase = torch.cat(a__ ) else: _lowerCamelCase = self._decode(a__ ).sample if not return_dict: return (decoded,) return DecoderOutput(sample=a__ ) def snake_case_ ( self , a__ , a__ , a__ ): _lowerCamelCase = min(a.shape[2] , b.shape[2] , a__ ) for y in range(a__ ): _lowerCamelCase = a[:, :, -blend_extent + y, :] * (1 - y / blend_extent) + b[:, :, y, :] * (y / blend_extent) return b def snake_case_ ( self , a__ , a__ , a__ ): _lowerCamelCase = min(a.shape[3] , b.shape[3] , a__ ) for x in range(a__ ): _lowerCamelCase = a[:, :, :, -blend_extent + x] * (1 - x / blend_extent) + b[:, :, :, x] * (x / blend_extent) return b def snake_case_ ( self , a__ , a__ = True ): _lowerCamelCase = int(self.tile_sample_min_size * (1 - self.tile_overlap_factor) ) _lowerCamelCase = int(self.tile_latent_min_size * self.tile_overlap_factor ) _lowerCamelCase = self.tile_latent_min_size - blend_extent # Split the image into 512x512 tiles and encode them separately. _lowerCamelCase = [] for i in range(0 , x.shape[2] , a__ ): _lowerCamelCase = [] for j in range(0 , x.shape[3] , a__ ): _lowerCamelCase = x[:, :, i : i + self.tile_sample_min_size, j : j + self.tile_sample_min_size] _lowerCamelCase = self.encoder(a__ ) _lowerCamelCase = self.quant_conv(a__ ) row.append(a__ ) rows.append(a__ ) _lowerCamelCase = [] for i, row in enumerate(a__ ): _lowerCamelCase = [] for j, tile in enumerate(a__ ): # blend the above tile and the left tile # to the current tile and add the current tile to the result row if i > 0: _lowerCamelCase = self.blend_v(rows[i - 1][j] , a__ , a__ ) if j > 0: _lowerCamelCase = self.blend_h(row[j - 1] , a__ , a__ ) result_row.append(tile[:, :, :row_limit, :row_limit] ) result_rows.append(torch.cat(a__ , dim=3 ) ) _lowerCamelCase = torch.cat(a__ , dim=2 ) _lowerCamelCase = DiagonalGaussianDistribution(a__ ) if not return_dict: return (posterior,) return AutoencoderKLOutput(latent_dist=a__ ) def snake_case_ ( self , a__ , a__ = True ): _lowerCamelCase = int(self.tile_latent_min_size * (1 - self.tile_overlap_factor) ) _lowerCamelCase = int(self.tile_sample_min_size * self.tile_overlap_factor ) _lowerCamelCase = self.tile_sample_min_size - blend_extent # Split z into overlapping 64x64 tiles and decode them separately. # The tiles have an overlap to avoid seams between tiles. _lowerCamelCase = [] for i in range(0 , z.shape[2] , a__ ): _lowerCamelCase = [] for j in range(0 , z.shape[3] , a__ ): _lowerCamelCase = z[:, :, i : i + self.tile_latent_min_size, j : j + self.tile_latent_min_size] _lowerCamelCase = self.post_quant_conv(a__ ) _lowerCamelCase = self.decoder(a__ ) row.append(a__ ) rows.append(a__ ) _lowerCamelCase = [] for i, row in enumerate(a__ ): _lowerCamelCase = [] for j, tile in enumerate(a__ ): # blend the above tile and the left tile # to the current tile and add the current tile to the result row if i > 0: _lowerCamelCase = self.blend_v(rows[i - 1][j] , a__ , a__ ) if j > 0: _lowerCamelCase = self.blend_h(row[j - 1] , a__ , a__ ) result_row.append(tile[:, :, :row_limit, :row_limit] ) result_rows.append(torch.cat(a__ , dim=3 ) ) _lowerCamelCase = torch.cat(a__ , dim=2 ) if not return_dict: return (dec,) return DecoderOutput(sample=a__ ) def snake_case_ ( self , a__ , a__ = False , a__ = True , a__ = None , ): _lowerCamelCase = sample _lowerCamelCase = self.encode(a__ ).latent_dist if sample_posterior: _lowerCamelCase = posterior.sample(generator=a__ ) else: _lowerCamelCase = posterior.mode() _lowerCamelCase = self.decode(a__ ).sample if not return_dict: return (dec,) return DecoderOutput(sample=a__ )
80
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_speech_available, is_torch_available, ) a_ : Union[str, Any] = { """configuration_trocr""": ["""TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP""", """TrOCRConfig"""], """processing_trocr""": ["""TrOCRProcessor"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : Union[str, Any] = [ """TROCR_PRETRAINED_MODEL_ARCHIVE_LIST""", """TrOCRForCausalLM""", """TrOCRPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_trocr import TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP, TrOCRConfig from .processing_trocr import TrOCRProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_trocr import TROCR_PRETRAINED_MODEL_ARCHIVE_LIST, TrOCRForCausalLM, TrOCRPreTrainedModel else: import sys a_ : Tuple = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
75
import itertools import json import linecache import os import pickle import re import socket import string from collections import Counter from logging import getLogger from pathlib import Path from typing import Callable, Dict, Iterable, List import git import torch from torch.utils.data import Dataset from transformers import BartTokenizer, RagTokenizer, TaTokenizer def lowerCamelCase__ ( _A , _A , _A , _A , _A=True , _A="pt" ): '''simple docstring''' snake_case_ = {"add_prefix_space": True} if isinstance(_A , _A ) and not line.startswith(" " ) else {} snake_case_ = padding_side return tokenizer( [line] , max_length=_A , padding="max_length" if pad_to_max_length else None , truncation=_A , return_tensors=_A , add_special_tokens=_A , **_A , ) def lowerCamelCase__ ( _A , _A , _A=None , ): '''simple docstring''' snake_case_ = input_ids.ne(_A ).any(dim=0 ) if attention_mask is None: return input_ids[:, keep_column_mask] else: return (input_ids[:, keep_column_mask], attention_mask[:, keep_column_mask]) class UpperCAmelCase ( UpperCAmelCase__ ): '''simple docstring''' def __init__( self : int , __lowercase : List[Any] , __lowercase : Tuple , __lowercase : List[Any] , __lowercase : str , __lowercase : Tuple="train" , __lowercase : List[str]=None , __lowercase : List[Any]=None , __lowercase : Optional[Any]=None , __lowercase : Union[str, Any]="" , ): """simple docstring""" super().__init__() snake_case_ = Path(__lowercase ).joinpath(type_path + ".source" ) snake_case_ = Path(__lowercase ).joinpath(type_path + ".target" ) snake_case_ = self.get_char_lens(self.src_file ) snake_case_ = max_source_length snake_case_ = max_target_length assert min(self.src_lens ) > 0, f"found empty line in {self.src_file}" snake_case_ = tokenizer snake_case_ = prefix if n_obs is not None: snake_case_ = self.src_lens[:n_obs] snake_case_ = src_lang snake_case_ = tgt_lang def __len__( self : List[Any] ): """simple docstring""" return len(self.src_lens ) def __getitem__( self : List[Any] , __lowercase : Dict ): """simple docstring""" snake_case_ = index + 1 # linecache starts at 1 snake_case_ = self.prefix + linecache.getline(str(self.src_file ) , __lowercase ).rstrip("\n" ) snake_case_ = linecache.getline(str(self.tgt_file ) , __lowercase ).rstrip("\n" ) assert source_line, f"empty source line for index {index}" assert tgt_line, f"empty tgt line for index {index}" # Need to add eos token manually for T5 if isinstance(self.tokenizer , __lowercase ): source_line += self.tokenizer.eos_token tgt_line += self.tokenizer.eos_token # Pad source and target to the right snake_case_ = ( self.tokenizer.question_encoder if isinstance(self.tokenizer , __lowercase ) else self.tokenizer ) snake_case_ = self.tokenizer.generator if isinstance(self.tokenizer , __lowercase ) else self.tokenizer snake_case_ = encode_line(__lowercase , __lowercase , self.max_source_length , "right" ) snake_case_ = encode_line(__lowercase , __lowercase , self.max_target_length , "right" ) snake_case_ = source_inputs["input_ids"].squeeze() snake_case_ = target_inputs["input_ids"].squeeze() snake_case_ = source_inputs["attention_mask"].squeeze() return { "input_ids": source_ids, "attention_mask": src_mask, "decoder_input_ids": target_ids, } @staticmethod def snake_case__ ( __lowercase : Optional[int] ): """simple docstring""" return [len(__lowercase ) for x in Path(__lowercase ).open().readlines()] def snake_case__ ( self : Dict , __lowercase : Union[str, Any] ): """simple docstring""" snake_case_ = torch.stack([x["input_ids"] for x in batch] ) snake_case_ = torch.stack([x["attention_mask"] for x in batch] ) snake_case_ = torch.stack([x["decoder_input_ids"] for x in batch] ) snake_case_ = ( self.tokenizer.generator.pad_token_id if isinstance(self.tokenizer , __lowercase ) else self.tokenizer.pad_token_id ) snake_case_ = ( self.tokenizer.question_encoder.pad_token_id if isinstance(self.tokenizer , __lowercase ) else self.tokenizer.pad_token_id ) snake_case_ = trim_batch(__lowercase , __lowercase ) snake_case_ , snake_case_ = trim_batch(__lowercase , __lowercase , attention_mask=__lowercase ) snake_case_ = { "input_ids": source_ids, "attention_mask": source_mask, "decoder_input_ids": y, } return batch lowercase__ : str = getLogger(__name__) def lowerCamelCase__ ( _A ): '''simple docstring''' return list(itertools.chain.from_iterable(_A ) ) def lowerCamelCase__ ( _A ): '''simple docstring''' snake_case_ = get_git_info() save_json(_A , os.path.join(_A , "git_log.json" ) ) def lowerCamelCase__ ( _A , _A , _A=4 , **_A ): '''simple docstring''' with open(_A , "w" ) as f: json.dump(_A , _A , indent=_A , **_A ) def lowerCamelCase__ ( _A ): '''simple docstring''' with open(_A ) as f: return json.load(_A ) def lowerCamelCase__ ( ): '''simple docstring''' snake_case_ = git.Repo(search_parent_directories=_A ) snake_case_ = { "repo_id": str(_A ), "repo_sha": str(repo.head.object.hexsha ), "repo_branch": str(repo.active_branch ), "hostname": str(socket.gethostname() ), } return repo_infos def lowerCamelCase__ ( _A , _A ): '''simple docstring''' return list(map(_A , _A ) ) def lowerCamelCase__ ( _A , _A ): '''simple docstring''' with open(_A , "wb" ) as f: return pickle.dump(_A , _A ) def lowerCamelCase__ ( _A ): '''simple docstring''' def remove_articles(_A ): return re.sub(R"\b(a|an|the)\b" , " " , _A ) def white_space_fix(_A ): return " ".join(text.split() ) def remove_punc(_A ): snake_case_ = set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(_A ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(_A ) ) ) ) def lowerCamelCase__ ( _A , _A ): '''simple docstring''' snake_case_ = normalize_answer(_A ).split() snake_case_ = normalize_answer(_A ).split() snake_case_ = Counter(_A ) & Counter(_A ) snake_case_ = sum(common.values() ) if num_same == 0: return 0 snake_case_ = 1.0 * num_same / len(_A ) snake_case_ = 1.0 * num_same / len(_A ) snake_case_ = (2 * precision * recall) / (precision + recall) return fa def lowerCamelCase__ ( _A , _A ): '''simple docstring''' return normalize_answer(_A ) == normalize_answer(_A ) def lowerCamelCase__ ( _A , _A ): '''simple docstring''' assert len(_A ) == len(_A ) snake_case_ = 0 for hypo, pred in zip(_A , _A ): em += exact_match_score(_A , _A ) if len(_A ) > 0: em /= len(_A ) return {"em": em} def lowerCamelCase__ ( _A ): '''simple docstring''' return model_prefix.startswith("rag" ) def lowerCamelCase__ ( _A , _A , _A ): '''simple docstring''' snake_case_ = {p: p for p in extra_params} # T5 models don't have `dropout` param, they have `dropout_rate` instead snake_case_ = "dropout_rate" for p in extra_params: if getattr(_A , _A , _A ): if not hasattr(_A , _A ) and not hasattr(_A , equivalent_param[p] ): logger.info("config doesn't have a `{}` attribute".format(_A ) ) delattr(_A , _A ) continue snake_case_ = p if hasattr(_A , _A ) else equivalent_param[p] setattr(_A , _A , getattr(_A , _A ) ) delattr(_A , _A ) return hparams, config
187
0
'''simple docstring''' import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import Audio, Features, Value from .base import TaskTemplate @dataclass(frozen=SCREAMING_SNAKE_CASE_ ) class lowerCAmelCase_( SCREAMING_SNAKE_CASE_ ): '''simple docstring''' __lowercase : str = field(default='''automatic-speech-recognition''' , metadata={'''include_in_asdict_even_if_is_default''': True} ) __lowercase : ClassVar[Features] = Features({'''audio''': Audio()} ) __lowercase : ClassVar[Features] = Features({'''transcription''': Value('''string''' )} ) __lowercase : str = "audio" __lowercase : str = "transcription" def UpperCAmelCase_ ( self ,__UpperCAmelCase ) -> Optional[int]: if self.audio_column not in features: raise ValueError(F"""Column {self.audio_column} is not present in features.""" ) if not isinstance(features[self.audio_column] ,__UpperCAmelCase ): raise ValueError(F"""Column {self.audio_column} is not an Audio type.""" ) lowerCAmelCase__ : Optional[int] = copy.deepcopy(self ) lowerCAmelCase__ : Optional[Any] = self.input_schema.copy() lowerCAmelCase__ : List[Any] = features[self.audio_column] lowerCAmelCase__ : Any = input_schema return task_template @property def UpperCAmelCase_ ( self ) -> Dict[str, str]: return {self.audio_column: "audio", self.transcription_column: "transcription"}
184
'''simple docstring''' import random import unittest import torch from diffusers import IFInpaintingSuperResolutionPipeline from diffusers.utils import floats_tensor from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import skip_mps, torch_device from ..pipeline_params import ( TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS, ) from ..test_pipelines_common import PipelineTesterMixin from . import IFPipelineTesterMixin @skip_mps class lowerCAmelCase_( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , unittest.TestCase ): '''simple docstring''' __lowercase : List[str] = IFInpaintingSuperResolutionPipeline __lowercase : int = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS - {'''width''', '''height'''} __lowercase : List[str] = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS.union({'''original_image'''} ) __lowercase : Optional[Any] = PipelineTesterMixin.required_optional_params - {'''latents'''} def UpperCAmelCase_ ( self ) -> Any: return self._get_superresolution_dummy_components() def UpperCAmelCase_ ( self ,__UpperCAmelCase ,__UpperCAmelCase=0 ) -> List[Any]: if str(__UpperCAmelCase ).startswith("""mps""" ): lowerCAmelCase__ : Any = torch.manual_seed(__UpperCAmelCase ) else: lowerCAmelCase__ : Dict = torch.Generator(device=__UpperCAmelCase ).manual_seed(__UpperCAmelCase ) lowerCAmelCase__ : Tuple = floats_tensor((1, 3, 16, 16) ,rng=random.Random(__UpperCAmelCase ) ).to(__UpperCAmelCase ) lowerCAmelCase__ : Union[str, Any] = floats_tensor((1, 3, 32, 32) ,rng=random.Random(__UpperCAmelCase ) ).to(__UpperCAmelCase ) lowerCAmelCase__ : Any = floats_tensor((1, 3, 32, 32) ,rng=random.Random(__UpperCAmelCase ) ).to(__UpperCAmelCase ) lowerCAmelCase__ : Dict = { """prompt""": """A painting of a squirrel eating a burger""", """image""": image, """original_image""": original_image, """mask_image""": mask_image, """generator""": generator, """num_inference_steps""": 2, """output_type""": """numpy""", } return inputs @unittest.skipIf( torch_device != """cuda""" or not is_xformers_available() ,reason="""XFormers attention is only available with CUDA and `xformers` installed""" ,) def UpperCAmelCase_ ( self ) -> Union[str, Any]: self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1E-3 ) def UpperCAmelCase_ ( self ) -> Optional[int]: self._test_save_load_optional_components() @unittest.skipIf(torch_device != """cuda""" ,reason="""float16 requires CUDA""" ) def UpperCAmelCase_ ( self ) -> List[Any]: # Due to non-determinism in save load of the hf-internal-testing/tiny-random-t5 text encoder super().test_save_load_floataa(expected_max_diff=1E-1 ) def UpperCAmelCase_ ( self ) -> str: self._test_attention_slicing_forward_pass(expected_max_diff=1E-2 ) def UpperCAmelCase_ ( self ) -> List[Any]: self._test_save_load_local() def UpperCAmelCase_ ( self ) -> int: self._test_inference_batch_single_identical( expected_max_diff=1E-2 ,)
184
1
"""simple docstring""" from scipy.stats import pearsonr import datasets _a : str = '\nPearson correlation coefficient and p-value for testing non-correlation.\nThe Pearson correlation coefficient measures the linear relationship between two datasets. The calculation of the p-value relies on the assumption that each dataset is normally distributed. Like other correlation coefficients, this one varies between -1 and +1 with 0 implying no correlation. Correlations of -1 or +1 imply an exact linear relationship. Positive correlations imply that as x increases, so does y. Negative correlations imply that as x increases, y decreases.\nThe p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets.\n' _a : List[str] = '\nArgs:\n predictions (`list` of `int`): Predicted class labels, as returned by a model.\n references (`list` of `int`): Ground truth labels.\n return_pvalue (`boolean`): If `True`, returns the p-value, along with the correlation coefficient. If `False`, returns only the correlation coefficient. Defaults to `False`.\n\nReturns:\n pearsonr (`float`): Pearson correlation coefficient. Minimum possible value is -1. Maximum possible value is 1. Values of 1 and -1 indicate exact linear positive and negative relationships, respectively. A value of 0 implies no correlation.\n p-value (`float`): P-value, which roughly indicates the probability of an The p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets. Minimum possible value is 0. Maximum possible value is 1. Higher values indicate higher probabilities.\n\nExamples:\n\n Example 1-A simple example using only predictions and references.\n >>> pearsonr_metric = datasets.load_metric("pearsonr")\n >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5])\n >>> print(round(results[\'pearsonr\'], 2))\n -0.74\n\n Example 2-The same as Example 1, but that also returns the `p-value`.\n >>> pearsonr_metric = datasets.load_metric("pearsonr")\n >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5], return_pvalue=True)\n >>> print(sorted(list(results.keys())))\n [\'p-value\', \'pearsonr\']\n >>> print(round(results[\'pearsonr\'], 2))\n -0.74\n >>> print(round(results[\'p-value\'], 2))\n 0.15\n' _a : List[Any] = '\n@article{2020SciPy-NMeth,\nauthor = {Virtanen, Pauli and Gommers, Ralf and Oliphant, Travis E. and\n Haberland, Matt and Reddy, Tyler and Cournapeau, David and\n Burovski, Evgeni and Peterson, Pearu and Weckesser, Warren and\n Bright, Jonathan and {van der Walt}, St{\'e}fan J. and\n Brett, Matthew and Wilson, Joshua and Millman, K. Jarrod and\n Mayorov, Nikolay and Nelson, Andrew R. J. and Jones, Eric and\n Kern, Robert and Larson, Eric and Carey, C J and\n Polat, Ilhan and Feng, Yu and Moore, Eric W. and\n {VanderPlas}, Jake and Laxalde, Denis and Perktold, Josef and\n Cimrman, Robert and Henriksen, Ian and Quintero, E. A. and\n Harris, Charles R. and Archibald, Anne M. and\n Ribeiro, Antonio H. and Pedregosa, Fabian and\n {van Mulbregt}, Paul and {SciPy 1.0 Contributors}},\ntitle = {{{SciPy} 1.0: Fundamental Algorithms for Scientific\n Computing in Python}},\njournal = {Nature Methods},\nyear = {2020},\nvolume = {17},\npages = {261--272},\nadsurl = {https://rdcu.be/b08Wh},\ndoi = {10.1038/s41592-019-0686-2},\n}\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class __A ( datasets.Metric ): def __A ( self ): 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.pearsonr.html"""] , ) def __A ( self , a__ , a__ , a__=False ): if return_pvalue: _lowerCAmelCase : List[Any] = pearsonr(a__ , a__ ) return {"pearsonr": results[0], "p-value": results[1]} else: return {"pearsonr": float(pearsonr(a__ , a__ )[0] )}
44
"""simple docstring""" from typing import List, Union from ..utils import ( add_end_docstrings, is_tf_available, is_torch_available, is_vision_available, logging, requires_backends, ) from .base import PIPELINE_INIT_ARGS, Pipeline if is_vision_available(): from PIL import Image from ..image_utils import load_image if is_tf_available(): from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_VISION_2_SEQ_MAPPING if is_torch_available(): import torch from ..models.auto.modeling_auto import MODEL_FOR_VISION_2_SEQ_MAPPING _a : Dict = logging.get_logger(__name__) @add_end_docstrings(SCREAMING_SNAKE_CASE_ ) class __A ( SCREAMING_SNAKE_CASE_ ): def __init__( self , *a__ , **a__ ): super().__init__(*a__ , **a__ ) requires_backends(self , """vision""" ) self.check_model_type( TF_MODEL_FOR_VISION_2_SEQ_MAPPING if self.framework == """tf""" else MODEL_FOR_VISION_2_SEQ_MAPPING ) def __A ( self , a__=None , a__=None , a__=None ): _lowerCAmelCase : List[str] = {} _lowerCAmelCase : Union[str, Any] = {} if prompt is not None: _lowerCAmelCase : List[Any] = prompt if generate_kwargs is not None: _lowerCAmelCase : List[str] = generate_kwargs if max_new_tokens is not None: if "generate_kwargs" not in forward_kwargs: _lowerCAmelCase : str = {} if "max_new_tokens" in forward_kwargs["generate_kwargs"]: raise ValueError( """'max_new_tokens' is defined twice, once in 'generate_kwargs' and once as a direct parameter,""" """ please use only one""" ) _lowerCAmelCase : Optional[Any] = max_new_tokens return preprocess_params, forward_kwargs, {} def __call__( self , a__ , **a__ ): return super().__call__(a__ , **a__ ) def __A ( self , a__ , a__=None ): _lowerCAmelCase : Tuple = load_image(a__ ) if prompt is not None: if not isinstance(a__ , a__ ): raise ValueError( F"Received an invalid text input, got - {type(a__ )} - but expected a single string. " """Note also that one single text can be provided for conditional image to text generation.""" ) _lowerCAmelCase : Optional[int] = self.model.config.model_type if model_type == "git": _lowerCAmelCase : Optional[Any] = self.image_processor(images=a__ , return_tensors=self.framework ) _lowerCAmelCase : List[str] = self.tokenizer(text=a__ , add_special_tokens=a__ ).input_ids _lowerCAmelCase : Union[str, Any] = [self.tokenizer.cls_token_id] + input_ids _lowerCAmelCase : Dict = torch.tensor(a__ ).unsqueeze(0 ) model_inputs.update({"""input_ids""": input_ids} ) elif model_type == "pix2struct": _lowerCAmelCase : Tuple = self.image_processor(images=a__ , header_text=a__ , return_tensors=self.framework ) elif model_type != "vision-encoder-decoder": # vision-encoder-decoder does not support conditional generation _lowerCAmelCase : Optional[int] = self.image_processor(images=a__ , return_tensors=self.framework ) _lowerCAmelCase : Optional[int] = self.tokenizer(a__ , return_tensors=self.framework ) model_inputs.update(a__ ) else: raise ValueError(F"Model type {model_type} does not support conditional text generation" ) else: _lowerCAmelCase : Any = self.image_processor(images=a__ , return_tensors=self.framework ) if self.model.config.model_type == "git" and prompt is None: _lowerCAmelCase : Union[str, Any] = None return model_inputs def __A ( self , a__ , a__=None ): # Git model sets `model_inputs["input_ids"] = None` in `preprocess` (when `prompt=None`). In batch model, the # pipeline will group them into a list of `None`, which fail `_forward`. Avoid this by checking it first. if ( "input_ids" in model_inputs and isinstance(model_inputs["""input_ids"""] , a__ ) and all(x is None for x in model_inputs["""input_ids"""] ) ): _lowerCAmelCase : Optional[int] = None if generate_kwargs is None: _lowerCAmelCase : List[str] = {} # FIXME: We need to pop here due to a difference in how `generation.py` and `generation.tf_utils.py` # parse inputs. In the Tensorflow version, `generate` raises an error if we don't use `input_ids` whereas # the PyTorch version matches it with `self.model.main_input_name` or `self.model.encoder.main_input_name` # in the `_prepare_model_inputs` method. _lowerCAmelCase : Tuple = model_inputs.pop(self.model.main_input_name ) _lowerCAmelCase : Union[str, Any] = self.model.generate(a__ , **a__ , **a__ ) return model_outputs def __A ( self , a__ ): _lowerCAmelCase : Optional[int] = [] for output_ids in model_outputs: _lowerCAmelCase : Any = { """generated_text""": self.tokenizer.decode( a__ , skip_special_tokens=a__ , ) } records.append(a__ ) return records
44
1
"""simple docstring""" def SCREAMING_SNAKE_CASE__ ( snake_case : List[str] )-> str: '''simple docstring''' if a < 0: raise ValueError("Input value must be a positive integer" ) elif isinstance(__lowerCamelCase , __lowerCamelCase ): raise TypeError("Input value must be a 'int' type" ) return bin(__lowerCamelCase ).count("1" ) if __name__ == "__main__": import doctest doctest.testmod()
351
"""simple docstring""" import inspect import unittest from datasets import load_dataset from packaging import version from transformers import BeitConfig from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ( MODEL_MAPPING, BeitForImageClassification, BeitForMaskedImageModeling, BeitForSemanticSegmentation, BeitModel, ) from transformers.models.beit.modeling_beit import BEIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): import PIL from PIL import Image from transformers import BeitImageProcessor class lowerCAmelCase__ : def __init__( self : Any , snake_case__ : Union[str, Any] , snake_case__ : str=1_0_0 , snake_case__ : str=1_3 , snake_case__ : Optional[int]=3_0 , snake_case__ : List[Any]=2 , snake_case__ : Any=3 , snake_case__ : Union[str, Any]=True , snake_case__ : List[Any]=True , snake_case__ : Any=3_2 , snake_case__ : List[str]=4 , snake_case__ : Any=4 , snake_case__ : Dict=3_7 , snake_case__ : str="gelu" , snake_case__ : Union[str, Any]=0.1 , snake_case__ : int=0.1 , snake_case__ : List[Any]=1_0 , snake_case__ : Any=0.02 , snake_case__ : List[str]=3 , snake_case__ : Tuple=None , snake_case__ : Tuple=[0, 1, 2, 3] , ): '''simple docstring''' UpperCAmelCase__ : int = parent UpperCAmelCase__ : List[str] = 1_0_0 UpperCAmelCase__ : List[Any] = batch_size UpperCAmelCase__ : int = image_size UpperCAmelCase__ : List[Any] = patch_size UpperCAmelCase__ : List[Any] = num_channels UpperCAmelCase__ : Any = is_training UpperCAmelCase__ : str = use_labels UpperCAmelCase__ : Any = hidden_size UpperCAmelCase__ : Dict = num_hidden_layers UpperCAmelCase__ : int = num_attention_heads UpperCAmelCase__ : Tuple = intermediate_size UpperCAmelCase__ : Any = hidden_act UpperCAmelCase__ : Optional[int] = hidden_dropout_prob UpperCAmelCase__ : str = attention_probs_dropout_prob UpperCAmelCase__ : Optional[int] = type_sequence_label_size UpperCAmelCase__ : Any = initializer_range UpperCAmelCase__ : Any = scope UpperCAmelCase__ : Optional[Any] = out_indices UpperCAmelCase__ : int = num_labels # in BeiT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) UpperCAmelCase__ : List[Any] = (image_size // patch_size) ** 2 UpperCAmelCase__ : Optional[int] = num_patches + 1 def __a ( self : Dict ): '''simple docstring''' UpperCAmelCase__ : Any = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) UpperCAmelCase__ : str = None UpperCAmelCase__ : Optional[int] = None if self.use_labels: UpperCAmelCase__ : Tuple = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCAmelCase__ : Any = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels ) UpperCAmelCase__ : Tuple = self.get_config() return config, pixel_values, labels, pixel_labels def __a ( self : int ): '''simple docstring''' return BeitConfig( vocab_size=self.vocab_size , image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=snake_case__ , initializer_range=self.initializer_range , out_indices=self.out_indices , ) def __a ( self : int , snake_case__ : str , snake_case__ : str , snake_case__ : Dict , snake_case__ : List[str] ): '''simple docstring''' UpperCAmelCase__ : Dict = BeitModel(config=snake_case__ ) model.to(snake_case__ ) model.eval() UpperCAmelCase__ : Dict = model(snake_case__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __a ( self : Any , snake_case__ : List[str] , snake_case__ : Union[str, Any] , snake_case__ : Dict , snake_case__ : Any ): '''simple docstring''' UpperCAmelCase__ : int = BeitForMaskedImageModeling(config=snake_case__ ) model.to(snake_case__ ) model.eval() UpperCAmelCase__ : List[Any] = model(snake_case__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length - 1, self.vocab_size) ) def __a ( self : Optional[Any] , snake_case__ : Tuple , snake_case__ : Tuple , snake_case__ : str , snake_case__ : Optional[Any] ): '''simple docstring''' UpperCAmelCase__ : List[Any] = self.type_sequence_label_size UpperCAmelCase__ : Union[str, Any] = BeitForImageClassification(snake_case__ ) model.to(snake_case__ ) model.eval() UpperCAmelCase__ : Union[str, Any] = model(snake_case__ , labels=snake_case__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images UpperCAmelCase__ : Any = 1 UpperCAmelCase__ : List[Any] = BeitForImageClassification(snake_case__ ) model.to(snake_case__ ) model.eval() UpperCAmelCase__ : Optional[int] = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) UpperCAmelCase__ : Optional[Any] = model(snake_case__ , labels=snake_case__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def __a ( self : Union[str, Any] , snake_case__ : int , snake_case__ : str , snake_case__ : Any , snake_case__ : Dict ): '''simple docstring''' UpperCAmelCase__ : Optional[Any] = self.num_labels UpperCAmelCase__ : int = BeitForSemanticSegmentation(snake_case__ ) model.to(snake_case__ ) model.eval() UpperCAmelCase__ : int = model(snake_case__ ) self.parent.assertEqual( result.logits.shape , (self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2) ) UpperCAmelCase__ : Dict = model(snake_case__ , labels=snake_case__ ) self.parent.assertEqual( result.logits.shape , (self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2) ) def __a ( self : int ): '''simple docstring''' UpperCAmelCase__ : Optional[Any] = self.prepare_config_and_inputs() UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ : List[str] = config_and_inputs UpperCAmelCase__ : Any = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class lowerCAmelCase__ ( __magic_name__ , __magic_name__ , unittest.TestCase ): SCREAMING_SNAKE_CASE_ =( (BeitModel, BeitForImageClassification, BeitForMaskedImageModeling, BeitForSemanticSegmentation) if is_torch_available() else () ) SCREAMING_SNAKE_CASE_ =( { '''feature-extraction''': BeitModel, '''image-classification''': BeitForImageClassification, '''image-segmentation''': BeitForSemanticSegmentation, } if is_torch_available() else {} ) SCREAMING_SNAKE_CASE_ =False SCREAMING_SNAKE_CASE_ =False SCREAMING_SNAKE_CASE_ =False def __a ( self : Dict ): '''simple docstring''' UpperCAmelCase__ : Dict = BeitModelTester(self ) UpperCAmelCase__ : List[str] = ConfigTester(self , config_class=snake_case__ , has_text_modality=snake_case__ , hidden_size=3_7 ) def __a ( self : List[str] ): '''simple docstring''' self.config_tester.run_common_tests() @unittest.skip(reason="BEiT does not use inputs_embeds" ) def __a ( self : List[Any] ): '''simple docstring''' pass @require_torch_multi_gpu @unittest.skip(reason="BEiT has some layers using `add_module` which doesn't work well with `nn.DataParallel`" ) def __a ( self : List[str] ): '''simple docstring''' pass def __a ( self : Tuple ): '''simple docstring''' UpperCAmelCase__ , UpperCAmelCase__ : Dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCAmelCase__ : Dict = model_class(snake_case__ ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) UpperCAmelCase__ : Tuple = model.get_output_embeddings() self.assertTrue(x is None or isinstance(snake_case__ , nn.Linear ) ) def __a ( self : str ): '''simple docstring''' UpperCAmelCase__ , UpperCAmelCase__ : Tuple = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCAmelCase__ : int = model_class(snake_case__ ) UpperCAmelCase__ : int = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic UpperCAmelCase__ : str = [*signature.parameters.keys()] UpperCAmelCase__ : int = ["pixel_values"] self.assertListEqual(arg_names[:1] , snake_case__ ) def __a ( self : str ): '''simple docstring''' UpperCAmelCase__ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*snake_case__ ) def __a ( self : Dict ): '''simple docstring''' UpperCAmelCase__ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*snake_case__ ) def __a ( self : str ): '''simple docstring''' UpperCAmelCase__ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*snake_case__ ) def __a ( self : Dict ): '''simple docstring''' UpperCAmelCase__ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*snake_case__ ) def __a ( self : List[Any] ): '''simple docstring''' if not self.model_tester.is_training: return UpperCAmelCase__ , UpperCAmelCase__ : Tuple = self.model_tester.prepare_config_and_inputs_for_common() UpperCAmelCase__ : Optional[int] = True for model_class in self.all_model_classes: # we don't test BeitForMaskedImageModeling if model_class in [*get_values(snake_case__ ), BeitForMaskedImageModeling]: continue UpperCAmelCase__ : Optional[Any] = model_class(snake_case__ ) model.to(snake_case__ ) model.train() UpperCAmelCase__ : Optional[int] = self._prepare_for_class(snake_case__ , snake_case__ , return_labels=snake_case__ ) UpperCAmelCase__ : Tuple = model(**snake_case__ ).loss loss.backward() def __a ( self : Optional[int] ): '''simple docstring''' UpperCAmelCase__ , UpperCAmelCase__ : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() if not self.model_tester.is_training: return UpperCAmelCase__ : Optional[int] = False UpperCAmelCase__ : List[str] = True for model_class in self.all_model_classes: # we don't test BeitForMaskedImageModeling if ( model_class in [*get_values(snake_case__ ), BeitForMaskedImageModeling] or not model_class.supports_gradient_checkpointing ): continue UpperCAmelCase__ : List[Any] = model_class(snake_case__ ) model.gradient_checkpointing_enable() model.to(snake_case__ ) model.train() UpperCAmelCase__ : Dict = self._prepare_for_class(snake_case__ , snake_case__ , return_labels=snake_case__ ) UpperCAmelCase__ : Optional[Any] = model(**snake_case__ ).loss loss.backward() def __a ( self : str ): '''simple docstring''' UpperCAmelCase__ , UpperCAmelCase__ : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() UpperCAmelCase__ : Union[str, Any] = _config_zero_init(snake_case__ ) for model_class in self.all_model_classes: UpperCAmelCase__ : int = model_class(config=snake_case__ ) for name, param in model.named_parameters(): # we skip lambda parameters as these require special initial values # determined by config.layer_scale_init_value if "lambda" in name: continue if param.requires_grad: self.assertIn( ((param.data.mean() * 1e9).round() / 1e9).item() , [0.0, 1.0] , msg=f'Parameter {name} of model {model_class} seems not properly initialized' , ) @slow def __a ( self : Any ): '''simple docstring''' for model_name in BEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCAmelCase__ : Optional[Any] = BeitModel.from_pretrained(snake_case__ ) self.assertIsNotNone(snake_case__ ) def SCREAMING_SNAKE_CASE__ ( )-> Optional[Any]: '''simple docstring''' UpperCAmelCase__ : List[Any] = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_torch @require_vision class lowerCAmelCase__ ( unittest.TestCase ): @cached_property def __a ( self : Union[str, Any] ): '''simple docstring''' return BeitImageProcessor.from_pretrained("microsoft/beit-base-patch16-224" ) if is_vision_available() else None @slow def __a ( self : Optional[int] ): '''simple docstring''' UpperCAmelCase__ : Optional[Any] = BeitForMaskedImageModeling.from_pretrained("microsoft/beit-base-patch16-224-pt22k" ).to(snake_case__ ) UpperCAmelCase__ : int = self.default_image_processor UpperCAmelCase__ : List[Any] = prepare_img() UpperCAmelCase__ : Dict = image_processor(images=snake_case__ , return_tensors="pt" ).pixel_values.to(snake_case__ ) # prepare bool_masked_pos UpperCAmelCase__ : Union[str, Any] = torch.ones((1, 1_9_6) , dtype=torch.bool ).to(snake_case__ ) # forward pass with torch.no_grad(): UpperCAmelCase__ : Optional[int] = model(pixel_values=snake_case__ , bool_masked_pos=snake_case__ ) UpperCAmelCase__ : str = outputs.logits # verify the logits UpperCAmelCase__ : int = torch.Size((1, 1_9_6, 8_1_9_2) ) self.assertEqual(logits.shape , snake_case__ ) UpperCAmelCase__ : Any = torch.tensor( [[-3.2437, 0.5072, -13.9174], [-3.2456, 0.4948, -13.9401], [-3.2033, 0.5121, -13.8550]] ).to(snake_case__ ) self.assertTrue(torch.allclose(logits[bool_masked_pos][:3, :3] , snake_case__ , atol=1e-2 ) ) @slow def __a ( self : Optional[Any] ): '''simple docstring''' UpperCAmelCase__ : Tuple = BeitForImageClassification.from_pretrained("microsoft/beit-base-patch16-224" ).to(snake_case__ ) UpperCAmelCase__ : Tuple = self.default_image_processor UpperCAmelCase__ : Dict = prepare_img() UpperCAmelCase__ : Tuple = image_processor(images=snake_case__ , return_tensors="pt" ).to(snake_case__ ) # forward pass with torch.no_grad(): UpperCAmelCase__ : Union[str, Any] = model(**snake_case__ ) UpperCAmelCase__ : Any = outputs.logits # verify the logits UpperCAmelCase__ : Optional[Any] = torch.Size((1, 1_0_0_0) ) self.assertEqual(logits.shape , snake_case__ ) UpperCAmelCase__ : Optional[Any] = torch.tensor([-1.2385, -1.0987, -1.0108] ).to(snake_case__ ) self.assertTrue(torch.allclose(logits[0, :3] , snake_case__ , atol=1e-4 ) ) UpperCAmelCase__ : List[str] = 2_8_1 self.assertEqual(logits.argmax(-1 ).item() , snake_case__ ) @slow def __a ( self : Optional[int] ): '''simple docstring''' UpperCAmelCase__ : int = BeitForImageClassification.from_pretrained("microsoft/beit-large-patch16-224-pt22k-ft22k" ).to( snake_case__ ) UpperCAmelCase__ : Tuple = self.default_image_processor UpperCAmelCase__ : Any = prepare_img() UpperCAmelCase__ : Union[str, Any] = image_processor(images=snake_case__ , return_tensors="pt" ).to(snake_case__ ) # forward pass with torch.no_grad(): UpperCAmelCase__ : List[Any] = model(**snake_case__ ) UpperCAmelCase__ : int = outputs.logits # verify the logits UpperCAmelCase__ : int = torch.Size((1, 2_1_8_4_1) ) self.assertEqual(logits.shape , snake_case__ ) UpperCAmelCase__ : int = torch.tensor([1.6881, -0.2787, 0.5901] ).to(snake_case__ ) self.assertTrue(torch.allclose(logits[0, :3] , snake_case__ , atol=1e-4 ) ) UpperCAmelCase__ : Any = 2_3_9_6 self.assertEqual(logits.argmax(-1 ).item() , snake_case__ ) @slow def __a ( self : Union[str, Any] ): '''simple docstring''' UpperCAmelCase__ : Dict = BeitForSemanticSegmentation.from_pretrained("microsoft/beit-base-finetuned-ade-640-640" ) UpperCAmelCase__ : List[Any] = model.to(snake_case__ ) UpperCAmelCase__ : int = BeitImageProcessor(do_resize=snake_case__ , size=6_4_0 , do_center_crop=snake_case__ ) UpperCAmelCase__ : Any = load_dataset("hf-internal-testing/fixtures_ade20k" , split="test" ) UpperCAmelCase__ : List[Any] = Image.open(ds[0]["file"] ) UpperCAmelCase__ : str = image_processor(images=snake_case__ , return_tensors="pt" ).to(snake_case__ ) # forward pass with torch.no_grad(): UpperCAmelCase__ : List[str] = model(**snake_case__ ) UpperCAmelCase__ : Dict = outputs.logits # verify the logits UpperCAmelCase__ : Any = torch.Size((1, 1_5_0, 1_6_0, 1_6_0) ) self.assertEqual(logits.shape , snake_case__ ) UpperCAmelCase__ : List[str] = version.parse(PIL.__version__ ) < version.parse("9.0.0" ) if is_pillow_less_than_a: UpperCAmelCase__ : Optional[Any] = torch.tensor( [ [[-4.9225, -2.3954, -3.0522], [-2.8822, -1.0046, -1.7561], [-2.9549, -1.3228, -2.1347]], [[-5.8168, -3.4129, -4.0778], [-3.8651, -2.2214, -3.0277], [-3.8356, -2.4643, -3.3535]], [[-0.0078, 3.9952, 4.0754], [2.9856, 4.6944, 5.0035], [3.2413, 4.7813, 4.9969]], ] , device=snake_case__ , ) else: UpperCAmelCase__ : int = torch.tensor( [ [[-4.8960, -2.3688, -3.0355], [-2.8478, -0.9836, -1.7418], [-2.9449, -1.3332, -2.1456]], [[-5.8081, -3.4124, -4.1006], [-3.8561, -2.2081, -3.0323], [-3.8365, -2.4601, -3.3669]], [[-0.0309, 3.9868, 4.0540], [2.9640, 4.6877, 4.9976], [3.2081, 4.7690, 4.9942]], ] , device=snake_case__ , ) self.assertTrue(torch.allclose(logits[0, :3, :3, :3] , snake_case__ , atol=1e-4 ) ) @slow def __a ( self : Any ): '''simple docstring''' UpperCAmelCase__ : str = BeitForSemanticSegmentation.from_pretrained("microsoft/beit-base-finetuned-ade-640-640" ) UpperCAmelCase__ : Any = model.to(snake_case__ ) UpperCAmelCase__ : Dict = BeitImageProcessor(do_resize=snake_case__ , size=6_4_0 , do_center_crop=snake_case__ ) UpperCAmelCase__ : Tuple = load_dataset("hf-internal-testing/fixtures_ade20k" , split="test" ) UpperCAmelCase__ : Optional[int] = Image.open(ds[0]["file"] ) UpperCAmelCase__ : Optional[int] = image_processor(images=snake_case__ , return_tensors="pt" ).to(snake_case__ ) # forward pass with torch.no_grad(): UpperCAmelCase__ : Optional[int] = model(**snake_case__ ) UpperCAmelCase__ : int = outputs.logits.detach().cpu() UpperCAmelCase__ : str = image_processor.post_process_semantic_segmentation(outputs=snake_case__ , target_sizes=[(5_0_0, 3_0_0)] ) UpperCAmelCase__ : List[Any] = torch.Size((5_0_0, 3_0_0) ) self.assertEqual(segmentation[0].shape , snake_case__ ) UpperCAmelCase__ : Any = image_processor.post_process_semantic_segmentation(outputs=snake_case__ ) UpperCAmelCase__ : int = torch.Size((1_6_0, 1_6_0) ) self.assertEqual(segmentation[0].shape , snake_case__ )
298
0