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""" def lowerCAmelCase__ ( UpperCamelCase__ = 1_0 ): '''simple docstring''' if not isinstance(UpperCamelCase__ , UpperCamelCase__ ) or n < 0: raise ValueError("""Invalid input""" ) _a : str = 1_0**n _a : Union[str, Any] = 2_8_4_3_3 * (pow(2 , 7_8_3_0_4_5_7 , UpperCamelCase__ )) + 1 return str(number % modulus ) if __name__ == "__main__": from doctest import testmod testmod() print(F'''{solution(10) = }''')
324
"""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 how to properly calculate the metrics on the # validation dataset when in a distributed system, 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 # ######################################################################## _snake_case = 16 _snake_case = 32 def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ = 1_6 ): '''simple docstring''' _a : str = AutoTokenizer.from_pretrained("""bert-base-cased""" ) _a : Dict = load_dataset("""glue""" , """mrpc""" ) def tokenize_function(UpperCamelCase__ ): # max_length=None => use the model max length (it's actually the default) _a : Optional[int] = 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(): _a : Tuple = 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 _a : List[Any] = tokenized_datasets.rename_column("""label""" , """labels""" ) def collate_fn(UpperCamelCase__ ): # On TPU it's best to pad everything to the same length or training will be very slow. _a : Union[str, Any] = 1_2_8 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": _a : int = 1_6 elif accelerator.mixed_precision != "no": _a : int = 8 else: _a : str = None return tokenizer.pad( UpperCamelCase__ , padding="""longest""" , max_length=UpperCamelCase__ , pad_to_multiple_of=UpperCamelCase__ , return_tensors="""pt""" , ) # Instantiate dataloaders. _a : int = DataLoader( tokenized_datasets["""train"""] , shuffle=UpperCamelCase__ , collate_fn=UpperCamelCase__ , batch_size=UpperCamelCase__ ) _a : List[str] = 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 _snake_case = mocked_dataloaders # noqa: F811 def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' # For testing only if os.environ.get("""TESTING_MOCKED_DATALOADERS""" , UpperCamelCase__ ) == "1": _a : str = 2 # Initialize accelerator _a : int = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs _a : Any = config["""lr"""] _a : Union[str, Any] = int(config["""num_epochs"""] ) _a : str = int(config["""seed"""] ) _a : List[Any] = int(config["""batch_size"""] ) _a : Tuple = evaluate.load("""glue""" , """mrpc""" ) # If the batch size is too big we use gradient accumulation _a : Optional[Any] = 1 if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU: _a : Optional[Any] = batch_size // MAX_GPU_BATCH_SIZE _a : str = MAX_GPU_BATCH_SIZE set_seed(UpperCamelCase__ ) _a , _a : Optional[int] = get_dataloaders(UpperCamelCase__ , UpperCamelCase__ ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) _a : int = 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). _a : List[str] = model.to(accelerator.device ) # Instantiate optimizer _a : List[str] = AdamW(params=model.parameters() , lr=UpperCamelCase__ ) # Instantiate scheduler _a : List[str] = get_linear_schedule_with_warmup( optimizer=UpperCamelCase__ , num_warmup_steps=1_0_0 , 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. _a , _a , _a , _a , _a : Optional[Any] = accelerator.prepare( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) # Now we train the model for epoch in range(UpperCamelCase__ ): model.train() for step, batch in enumerate(UpperCamelCase__ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) _a : Optional[Any] = model(**UpperCamelCase__ ) _a : str = outputs.loss _a : Optional[int] = loss / gradient_accumulation_steps accelerator.backward(UpperCamelCase__ ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() _a : Union[str, Any] = 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 ) with torch.no_grad(): _a : Dict = model(**UpperCamelCase__ ) _a : Optional[Any] = outputs.logits.argmax(dim=-1 ) _a , _a : int = accelerator.gather((predictions, batch["""labels"""]) ) # New Code # # First we check if it's a distributed system if accelerator.use_distributed: # Then see if we're on the last batch of our eval dataloader if step == len(UpperCamelCase__ ) - 1: # Last batch needs to be truncated on distributed systems as it contains additional samples _a : str = predictions[: len(eval_dataloader.dataset ) - samples_seen] _a : int = references[: len(eval_dataloader.dataset ) - samples_seen] else: # Otherwise we add the number of samples seen samples_seen += references.shape[0] # All of this can be avoided if you use `Accelerator.gather_for_metrics` instead of `Accelerator.gather`: # accelerator.gather_for_metrics((predictions, batch["labels"])) metric.add_batch( predictions=UpperCamelCase__ , references=UpperCamelCase__ , ) _a : int = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F"""epoch {epoch}:""" , UpperCamelCase__ ) def lowerCAmelCase__ ( ): '''simple docstring''' _a : Tuple = 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.""" ) _a : Optional[Any] = parser.parse_args() _a : Tuple = {"""lr""": 2e-5, """num_epochs""": 3, """seed""": 4_2, """batch_size""": 1_6} training_function(UpperCamelCase__ , UpperCamelCase__ ) if __name__ == "__main__": main()
324
1
"""simple docstring""" from __future__ import annotations def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , ): '''simple docstring''' if (stress, tangential_force, area).count(0 ) != 1: raise ValueError("""You cannot supply more or less than 2 values""" ) elif stress < 0: raise ValueError("""Stress cannot be negative""" ) elif tangential_force < 0: raise ValueError("""Tangential Force cannot be negative""" ) elif area < 0: raise ValueError("""Area cannot be negative""" ) elif stress == 0: return ( "stress", tangential_force / area, ) elif tangential_force == 0: return ( "tangential_force", stress * area, ) else: return ( "area", tangential_force / stress, ) if __name__ == "__main__": import doctest doctest.testmod()
324
"""simple docstring""" import numpy as np def lowerCAmelCase__ ( UpperCamelCase__ ): '''simple docstring''' return 1 / (1 + np.exp(-vector )) def lowerCAmelCase__ ( UpperCamelCase__ ): '''simple docstring''' return vector * sigmoid(1.702 * vector ) if __name__ == "__main__": import doctest doctest.testmod()
324
1
"""simple docstring""" import json import os import tempfile import datasets from utils import generate_example_dataset, get_duration _snake_case = 5_0000 _snake_case = 5000 _snake_case , _snake_case = os.path.split(__file__) _snake_case = os.path.join(RESULTS_BASEPATH, 'results', RESULTS_FILENAME.replace('.py', '.json')) @get_duration def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' for i in range(UpperCamelCase__ ): _a : Any = dataset[i] @get_duration def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' for i in range(0 , len(UpperCamelCase__ ) , UpperCamelCase__ ): _a : Any = dataset[i : i + batch_size] @get_duration def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' with dataset.formatted_as(type=UpperCamelCase__ ): for i in range(UpperCamelCase__ ): _a : List[Any] = dataset[i] @get_duration def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' with dataset.formatted_as(type=UpperCamelCase__ ): for i in range(0 , UpperCamelCase__ , UpperCamelCase__ ): _a : List[str] = dataset[i : i + batch_size] def lowerCAmelCase__ ( ): '''simple docstring''' _a : Optional[Any] = {"""num examples""": SPEED_TEST_N_EXAMPLES} _a : List[str] = [ (read, {"""length""": SMALL_TEST}), (read, {"""length""": SPEED_TEST_N_EXAMPLES}), (read_batch, {"""length""": SPEED_TEST_N_EXAMPLES, """batch_size""": 1_0}), (read_batch, {"""length""": SPEED_TEST_N_EXAMPLES, """batch_size""": 1_0_0}), (read_batch, {"""length""": SPEED_TEST_N_EXAMPLES, """batch_size""": 1_0_0_0}), (read_formatted, {"""type""": """numpy""", """length""": SMALL_TEST}), (read_formatted, {"""type""": """pandas""", """length""": SMALL_TEST}), (read_formatted, {"""type""": """torch""", """length""": SMALL_TEST}), (read_formatted, {"""type""": """tensorflow""", """length""": SMALL_TEST}), (read_formatted_batch, {"""type""": """numpy""", """length""": SMALL_TEST, """batch_size""": 1_0}), (read_formatted_batch, {"""type""": """numpy""", """length""": SMALL_TEST, """batch_size""": 1_0_0_0}), ] _a : Optional[Any] = [ (read, {"""length""": SMALL_TEST}), (read, {"""length""": SPEED_TEST_N_EXAMPLES}), (read_batch, {"""length""": SPEED_TEST_N_EXAMPLES, """batch_size""": 1_0}), (read_batch, {"""length""": SPEED_TEST_N_EXAMPLES, """batch_size""": 1_0_0}), (read_batch, {"""length""": SPEED_TEST_N_EXAMPLES, """batch_size""": 1_0_0_0}), (read_formatted, {"""type""": """numpy""", """length""": SMALL_TEST}), (read_formatted_batch, {"""type""": """numpy""", """length""": SMALL_TEST, """batch_size""": 1_0}), (read_formatted_batch, {"""type""": """numpy""", """length""": SMALL_TEST, """batch_size""": 1_0_0_0}), ] with tempfile.TemporaryDirectory() as tmp_dir: print("""generating dataset""" ) _a : str = datasets.Features( {"""list""": datasets.Sequence(datasets.Value("""float32""" ) ), """numbers""": datasets.Value("""float32""" )} ) _a : int = generate_example_dataset( os.path.join(UpperCamelCase__ , """dataset.arrow""" ) , UpperCamelCase__ , num_examples=UpperCamelCase__ , seq_shapes={"""list""": (1_0_0,)} , ) print("""first set of iterations""" ) for func, kwargs in functions: print(func.__name__ , str(UpperCamelCase__ ) ) _a : Tuple = func(UpperCamelCase__ , **UpperCamelCase__ ) print("""shuffling dataset""" ) _a : str = dataset.shuffle() print("""Second set of iterations (after shuffling""" ) for func, kwargs in functions_shuffled: print("""shuffled """ , func.__name__ , str(UpperCamelCase__ ) ) _a : str = func( UpperCamelCase__ , **UpperCamelCase__ ) with open(UpperCamelCase__ , """wb""" ) as f: f.write(json.dumps(UpperCamelCase__ ).encode("""utf-8""" ) ) if __name__ == "__main__": # useful to run the profiler benchmark_iterating()
324
"""simple docstring""" import unittest from transformers import CamembertTokenizer, CamembertTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.utils import is_torch_available from ...test_tokenization_common import TokenizerTesterMixin _snake_case = get_tests_dir('fixtures/test_sentencepiece.model') _snake_case = get_tests_dir('fixtures/test_sentencepiece_bpe.model') _snake_case = 'pt' if is_torch_available() else 'tf' @require_sentencepiece @require_tokenizers class UpperCamelCase ( snake_case_ , unittest.TestCase ): UpperCamelCase : str = CamembertTokenizer UpperCamelCase : List[Any] = CamembertTokenizerFast UpperCamelCase : Optional[int] = True UpperCamelCase : Union[str, Any] = True def _lowercase ( self : List[Any] ) -> Union[str, Any]: super().setUp() # We have a SentencePiece fixture for testing _a : List[Any] = CamembertTokenizer(UpperCAmelCase__ ) tokenizer.save_pretrained(self.tmpdirname ) def _lowercase ( self : List[str] ) -> Tuple: _a : Optional[Any] = """<pad>""" _a : Tuple = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(UpperCAmelCase__ ) , UpperCAmelCase__ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(UpperCAmelCase__ ) , UpperCAmelCase__ ) def _lowercase ( self : Union[str, Any] ) -> str: _a : List[str] = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , """<s>NOTUSED""" ) self.assertEqual(vocab_keys[1] , """<pad>""" ) self.assertEqual(vocab_keys[-1] , """<mask>""" ) self.assertEqual(len(UpperCAmelCase__ ) , 1004 ) def _lowercase ( self : List[str] ) -> List[Any]: self.assertEqual(self.get_tokenizer().vocab_size , 1005 ) def _lowercase ( self : Union[str, Any] ) -> str: _a : Tuple = CamembertTokenizer(UpperCAmelCase__ ) tokenizer.save_pretrained(self.tmpdirname ) _a : List[Any] = CamembertTokenizerFast.from_pretrained(self.tmpdirname ) _a : Any = """I was born in 92000, and this is falsé.""" _a : Union[str, Any] = tokenizer.encode(UpperCAmelCase__ ) _a : Dict = rust_tokenizer.encode(UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) _a : Tuple = tokenizer.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) _a : List[Any] = rust_tokenizer.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) # <unk> tokens are not the same for `rust` than for `slow`. # Because spm gives back raw token instead of `unk` in EncodeAsPieces # tokens = tokenizer.tokenize(sequence) _a : List[str] = tokenizer.convert_ids_to_tokens(UpperCAmelCase__ ) _a : int = rust_tokenizer.tokenize(UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) def _lowercase ( self : Dict ) -> List[str]: if not self.test_rust_tokenizer: return _a : Optional[int] = self.get_tokenizer() _a : Tuple = self.get_rust_tokenizer() _a : List[Any] = """I was born in 92000, and this is falsé.""" _a : List[str] = tokenizer.tokenize(UpperCAmelCase__ ) _a : Union[str, Any] = rust_tokenizer.tokenize(UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) _a : int = tokenizer.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) _a : Optional[int] = rust_tokenizer.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) _a : int = self.get_rust_tokenizer() _a : Optional[Any] = tokenizer.encode(UpperCAmelCase__ ) _a : Dict = rust_tokenizer.encode(UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) @slow def _lowercase ( self : Tuple ) -> List[Any]: # fmt: off _a : Dict = {"""input_ids""": [[5, 54, 7196, 297, 30, 23, 776, 18, 11, 3215, 3705, 8252, 22, 3164, 1181, 2116, 29, 16, 813, 25, 791, 3314, 20, 3446, 38, 27575, 120, 6, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [5, 468, 17, 11, 9088, 20, 1517, 8, 22804, 18818, 10, 38, 629, 607, 607, 142, 19, 7196, 867, 56, 10326, 24, 2267, 20, 416, 5072, 15612, 233, 734, 7, 2399, 27, 16, 3015, 1649, 7, 24, 20, 4338, 2399, 27, 13, 3400, 14, 13, 6189, 8, 930, 9, 6]], """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, 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, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]} # noqa: E501 # fmt: on # camembert is a french model. So we also use french texts. _a : Union[str, Any] = [ """Le transformeur est un modèle d'apprentissage profond introduit en 2017, """ """utilisé principalement dans le domaine du traitement automatique des langues (TAL).""", """À l'instar des réseaux de neurones récurrents (RNN), les transformeurs sont conçus """ """pour gérer des données séquentielles, telles que le langage naturel, pour des tâches """ """telles que la traduction et la synthèse de texte.""", ] self.tokenizer_integration_test_util( expected_encoding=UpperCAmelCase__ , model_name="""camembert-base""" , revision="""3a0641d9a1aeb7e848a74299e7e4c4bca216b4cf""" , sequences=UpperCAmelCase__ , )
324
1
"""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 model through reduction of a normal pre-trained model, but keeping the # full vocab, merges file, and thus also resulting in a larger model due to a large vocab size. # This gives ~3MB in total for all files. # # If you want a 50 times smaller than this see `fsmt-make-super-tiny-model.py`, which is slightly more complicated # # # It will be used then as "stas/tiny-wmt19-en-de" # Build from transformers import FSMTTokenizer, FSMTConfig, FSMTForConditionalGeneration _snake_case = 'facebook/wmt19-en-de' _snake_case = FSMTTokenizer.from_pretrained(mname) # get the correct vocab sizes, etc. from the master model _snake_case = FSMTConfig.from_pretrained(mname) config.update( dict( 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, ) ) _snake_case = FSMTForConditionalGeneration(config) print(F'''num of params {tiny_model.num_parameters()}''') # Test _snake_case = tokenizer(['Making tiny model'], return_tensors='pt') _snake_case = tiny_model(**batch) print('test output:', len(outputs.logits[0])) # Save _snake_case = 'tiny-wmt19-en-de' 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-de
324
"""simple docstring""" import argparse import collections import os import re import tempfile import pandas as pd from datasets import Dataset from huggingface_hub import hf_hub_download, upload_folder from transformers.utils import direct_transformers_import # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/update_metadata.py _snake_case = 'src/transformers' # This is to make sure the transformers module imported is the one in the repo. _snake_case = direct_transformers_import(TRANSFORMERS_PATH) # Regexes that match TF/Flax/PT model names. _snake_case = re.compile(r'TF(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)') _snake_case = re.compile(r'Flax(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)') # Will match any TF or Flax model too so need to be in an else branch afterthe two previous regexes. _snake_case = re.compile(r'(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)') # Fill this with tuples (pipeline_tag, model_mapping, auto_model) _snake_case = [ ('pretraining', 'MODEL_FOR_PRETRAINING_MAPPING_NAMES', 'AutoModelForPreTraining'), ('feature-extraction', 'MODEL_MAPPING_NAMES', 'AutoModel'), ('audio-classification', 'MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES', 'AutoModelForAudioClassification'), ('text-generation', 'MODEL_FOR_CAUSAL_LM_MAPPING_NAMES', 'AutoModelForCausalLM'), ('automatic-speech-recognition', 'MODEL_FOR_CTC_MAPPING_NAMES', 'AutoModelForCTC'), ('image-classification', 'MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES', 'AutoModelForImageClassification'), ('image-segmentation', 'MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES', 'AutoModelForImageSegmentation'), ('fill-mask', 'MODEL_FOR_MASKED_LM_MAPPING_NAMES', 'AutoModelForMaskedLM'), ('object-detection', 'MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES', 'AutoModelForObjectDetection'), ( 'zero-shot-object-detection', 'MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES', 'AutoModelForZeroShotObjectDetection', ), ('question-answering', 'MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES', 'AutoModelForQuestionAnswering'), ('text2text-generation', 'MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES', 'AutoModelForSeq2SeqLM'), ('text-classification', 'MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES', 'AutoModelForSequenceClassification'), ('automatic-speech-recognition', 'MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES', 'AutoModelForSpeechSeq2Seq'), ( 'table-question-answering', 'MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING_NAMES', 'AutoModelForTableQuestionAnswering', ), ('token-classification', 'MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES', 'AutoModelForTokenClassification'), ('multiple-choice', 'MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES', 'AutoModelForMultipleChoice'), ( 'next-sentence-prediction', 'MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING_NAMES', 'AutoModelForNextSentencePrediction', ), ( 'audio-frame-classification', 'MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES', 'AutoModelForAudioFrameClassification', ), ('audio-xvector', 'MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES', 'AutoModelForAudioXVector'), ( 'document-question-answering', 'MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES', 'AutoModelForDocumentQuestionAnswering', ), ( 'visual-question-answering', 'MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING_NAMES', 'AutoModelForVisualQuestionAnswering', ), ('image-to-text', 'MODEL_FOR_FOR_VISION_2_SEQ_MAPPING_NAMES', 'AutoModelForVision2Seq'), ( 'zero-shot-image-classification', 'MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING_NAMES', 'AutoModelForZeroShotImageClassification', ), ('depth-estimation', 'MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES', 'AutoModelForDepthEstimation'), ('video-classification', 'MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING_NAMES', 'AutoModelForVideoClassification'), ('mask-generation', 'MODEL_FOR_MASK_GENERATION_MAPPING_NAMES', 'AutoModelForMaskGeneration'), ] def lowerCAmelCase__ ( UpperCamelCase__ ): '''simple docstring''' _a : Dict = re.finditer(""".+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)""" , UpperCamelCase__ ) return [m.group(0 ) for m in matches] def lowerCAmelCase__ ( ): '''simple docstring''' _a : Tuple = transformers_module.models.auto.configuration_auto.CONFIG_MAPPING_NAMES _a : Optional[int] = { config.replace("""Config""" , """""" ): model_type for model_type, config in config_maping_names.items() } # Dictionaries flagging if each model prefix has a backend in PT/TF/Flax. _a : List[Any] = collections.defaultdict(UpperCamelCase__ ) _a : List[str] = collections.defaultdict(UpperCamelCase__ ) _a : Tuple = collections.defaultdict(UpperCamelCase__ ) # Let's lookup through all transformers object (once) and find if models are supported by a given backend. for attr_name in dir(UpperCamelCase__ ): _a : str = None if _re_tf_models.match(UpperCamelCase__ ) is not None: _a : List[Any] = tf_models _a : int = _re_tf_models.match(UpperCamelCase__ ).groups()[0] elif _re_flax_models.match(UpperCamelCase__ ) is not None: _a : Any = flax_models _a : Any = _re_flax_models.match(UpperCamelCase__ ).groups()[0] elif _re_pt_models.match(UpperCamelCase__ ) is not None: _a : int = pt_models _a : int = _re_pt_models.match(UpperCamelCase__ ).groups()[0] if lookup_dict is not None: while len(UpperCamelCase__ ) > 0: if attr_name in model_prefix_to_model_type: _a : Optional[int] = True break # Try again after removing the last word in the name _a : List[Any] = """""".join(camel_case_split(UpperCamelCase__ )[:-1] ) _a : Optional[int] = set(list(pt_models.keys() ) + list(tf_models.keys() ) + list(flax_models.keys() ) ) _a : Dict = list(UpperCamelCase__ ) all_models.sort() _a : str = {"""model_type""": all_models} _a : List[Any] = [pt_models[t] for t in all_models] _a : str = [tf_models[t] for t in all_models] _a : Optional[int] = [flax_models[t] for t in all_models] # Now let's use the auto-mapping names to make sure _a : str = {} for t in all_models: if t in transformers_module.models.auto.processing_auto.PROCESSOR_MAPPING_NAMES: _a : List[str] = """AutoProcessor""" elif t in transformers_module.models.auto.tokenization_auto.TOKENIZER_MAPPING_NAMES: _a : str = """AutoTokenizer""" elif t in transformers_module.models.auto.feature_extraction_auto.FEATURE_EXTRACTOR_MAPPING_NAMES: _a : int = """AutoFeatureExtractor""" else: # Default to AutoTokenizer if a model has nothing, for backward compatibility. _a : int = """AutoTokenizer""" _a : Any = [processors[t] for t in all_models] return pd.DataFrame(UpperCamelCase__ ) def lowerCAmelCase__ ( UpperCamelCase__ ): '''simple docstring''' _a : List[Any] = [ transformers_module.models.auto.modeling_auto, transformers_module.models.auto.modeling_tf_auto, transformers_module.models.auto.modeling_flax_auto, ] for pipeline_tag, model_mapping, auto_class in PIPELINE_TAGS_AND_AUTO_MODELS: _a : List[Any] = [model_mapping, F"""TF_{model_mapping}""", F"""FLAX_{model_mapping}"""] _a : Union[str, Any] = [auto_class, F"""TF_{auto_class}""", F"""Flax_{auto_class}"""] # Loop through all three frameworks for module, cls, mapping in zip(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): # The type of pipeline may not exist in this framework if not hasattr(UpperCamelCase__ , UpperCamelCase__ ): continue # First extract all model_names _a : str = [] for name in getattr(UpperCamelCase__ , UpperCamelCase__ ).values(): if isinstance(UpperCamelCase__ , UpperCamelCase__ ): model_names.append(UpperCamelCase__ ) else: model_names.extend(list(UpperCamelCase__ ) ) # Add pipeline tag and auto model class for those models table.update({model_name: (pipeline_tag, cls) for model_name in model_names} ) return table def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' _a : Dict = get_frameworks_table() _a : Optional[Any] = Dataset.from_pandas(UpperCamelCase__ ) _a : Any = hf_hub_download( """huggingface/transformers-metadata""" , """pipeline_tags.json""" , repo_type="""dataset""" , token=UpperCamelCase__ ) _a : List[Any] = Dataset.from_json(UpperCamelCase__ ) _a : List[str] = { tags_dataset[i]["""model_class"""]: (tags_dataset[i]["""pipeline_tag"""], tags_dataset[i]["""auto_class"""]) for i in range(len(UpperCamelCase__ ) ) } _a : str = update_pipeline_and_auto_class_table(UpperCamelCase__ ) # Sort the model classes to avoid some nondeterministic updates to create false update commits. _a : int = sorted(table.keys() ) _a : Union[str, Any] = pd.DataFrame( { """model_class""": model_classes, """pipeline_tag""": [table[m][0] for m in model_classes], """auto_class""": [table[m][1] for m in model_classes], } ) _a : Dict = Dataset.from_pandas(UpperCamelCase__ ) with tempfile.TemporaryDirectory() as tmp_dir: frameworks_dataset.to_json(os.path.join(UpperCamelCase__ , """frameworks.json""" ) ) tags_dataset.to_json(os.path.join(UpperCamelCase__ , """pipeline_tags.json""" ) ) if commit_sha is not None: _a : List[str] = ( F"""Update with commit {commit_sha}\n\nSee: """ F"""https://github.com/huggingface/transformers/commit/{commit_sha}""" ) else: _a : Optional[Any] = """Update""" upload_folder( repo_id="""huggingface/transformers-metadata""" , folder_path=UpperCamelCase__ , repo_type="""dataset""" , token=UpperCamelCase__ , commit_message=UpperCamelCase__ , ) def lowerCAmelCase__ ( ): '''simple docstring''' _a : List[str] = {tag: cls for tag, _, cls in PIPELINE_TAGS_AND_AUTO_MODELS} _a : Any = transformers_module.pipelines.SUPPORTED_TASKS _a : List[str] = [] for key in pipeline_tasks: if key not in in_table: _a : Tuple = pipeline_tasks[key]["""pt"""] if isinstance(UpperCamelCase__ , (list, tuple) ): _a : Dict = model[0] _a : List[str] = model.__name__ if model not in in_table.values(): missing.append(UpperCamelCase__ ) if len(UpperCamelCase__ ) > 0: _a : Union[str, Any] = """, """.join(UpperCamelCase__ ) raise ValueError( """The following pipeline tags are not present in the `PIPELINE_TAGS_AND_AUTO_MODELS` constant inside """ F"""`utils/update_metadata.py`: {msg}. Please add them!""" ) if __name__ == "__main__": _snake_case = argparse.ArgumentParser() parser.add_argument('--token', type=str, help='The token to use to push to the transformers-metadata dataset.') parser.add_argument('--commit_sha', type=str, help='The sha of the commit going with this update.') parser.add_argument('--check-only', action='store_true', help='Activate to just check all pipelines are present.') _snake_case = parser.parse_args() if args.check_only: check_pipeline_tags() else: update_metadata(args.token, args.commit_sha)
324
1
"""simple docstring""" from sympy import diff, lambdify, symbols from sympy.functions import * # noqa: F403 def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = "x" , UpperCamelCase__ = 1_0**-1_0 , UpperCamelCase__ = 1 , ): '''simple docstring''' _a : Tuple = symbols(UpperCamelCase__ ) _a : Union[str, Any] = lambdify(UpperCamelCase__ , UpperCamelCase__ ) _a : List[Any] = lambdify(UpperCamelCase__ , diff(UpperCamelCase__ , UpperCamelCase__ ) ) _a : Union[str, Any] = starting_point while True: if diff_function(UpperCamelCase__ ) != 0: _a : Dict = prev_guess - multiplicity * func(UpperCamelCase__ ) / diff_function( UpperCamelCase__ ) else: raise ZeroDivisionError("""Could not find root""" ) from None # Precision is checked by comparing the difference of consecutive guesses if abs(next_guess - prev_guess ) < precision: return next_guess _a : Optional[int] = next_guess # Let's Execute if __name__ == "__main__": # Find root of trigonometric function # Find value of pi print(F'''The root of sin(x) = 0 is {newton_raphson('sin(x)', 2)}''') # Find root of polynomial # Find fourth Root of 5 print(F'''The root of x**4 - 5 = 0 is {newton_raphson('x**4 -5', 0.4 +5J)}''') # Find value of e print( 'The root of log(y) - 1 = 0 is ', F'''{newton_raphson('log(y) - 1', 2, variable='y')}''', ) # Exponential Roots print( 'The root of exp(x) - 1 = 0 is', F'''{newton_raphson('exp(x) - 1', 10, precision=0.0_05)}''', ) # Find root of cos(x) print(F'''The root of cos(x) = 0 is {newton_raphson('cos(x)', 0)}''')
324
"""simple docstring""" import os import pytest import yaml from datasets.features.features import Features, Value from datasets.info import DatasetInfo, DatasetInfosDict @pytest.mark.parametrize( """files""" , [ ["""full:README.md""", """dataset_infos.json"""], ["""empty:README.md""", """dataset_infos.json"""], ["""dataset_infos.json"""], ["""full:README.md"""], ] , ) def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' _a : Dict = tmp_path_factory.mktemp("""dset_infos_dir""" ) if "full:README.md" in files: with open(dataset_infos_dir / """README.md""" , """w""" ) as f: f.write("""---\ndataset_info:\n dataset_size: 42\n---""" ) if "empty:README.md" in files: with open(dataset_infos_dir / """README.md""" , """w""" ) as f: f.write("""""" ) # we want to support dataset_infos.json for backward compatibility if "dataset_infos.json" in files: with open(dataset_infos_dir / """dataset_infos.json""" , """w""" ) as f: f.write("""{\"default\": {\"dataset_size\": 42}}""" ) _a : Dict = DatasetInfosDict.from_directory(UpperCamelCase__ ) assert dataset_infos assert dataset_infos["default"].dataset_size == 4_2 @pytest.mark.parametrize( """dataset_info""" , [ DatasetInfo(), DatasetInfo( description="""foo""" , features=Features({"""a""": Value("""int32""" )} ) , builder_name="""builder""" , config_name="""config""" , version="""1.0.0""" , splits=[{"""name""": """train"""}] , download_size=4_2 , ), ] , ) def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' _a : Optional[int] = str(UpperCamelCase__ ) dataset_info.write_to_directory(UpperCamelCase__ ) _a : Any = DatasetInfo.from_directory(UpperCamelCase__ ) assert dataset_info == reloaded assert os.path.exists(os.path.join(UpperCamelCase__ , """dataset_info.json""" ) ) def lowerCAmelCase__ ( ): '''simple docstring''' _a : Dict = DatasetInfo( description="""foo""" , citation="""bar""" , homepage="""https://foo.bar""" , license="""CC0""" , features=Features({"""a""": Value("""int32""" )} ) , post_processed={} , supervised_keys=() , task_templates=[] , builder_name="""builder""" , config_name="""config""" , version="""1.0.0""" , splits=[{"""name""": """train""", """num_examples""": 4_2}] , download_checksums={} , download_size=1_3_3_7 , post_processing_size=4_4_2 , dataset_size=1_2_3_4 , size_in_bytes=1_3_3_7 + 4_4_2 + 1_2_3_4 , ) _a : int = dataset_info._to_yaml_dict() assert sorted(UpperCamelCase__ ) == sorted(DatasetInfo._INCLUDED_INFO_IN_YAML ) for key in DatasetInfo._INCLUDED_INFO_IN_YAML: assert key in dataset_info_yaml_dict assert isinstance(dataset_info_yaml_dict[key] , (list, dict, int, str) ) _a : List[str] = yaml.safe_dump(UpperCamelCase__ ) _a : Optional[int] = yaml.safe_load(UpperCamelCase__ ) assert dataset_info_yaml_dict == reloaded def lowerCAmelCase__ ( ): '''simple docstring''' _a : List[Any] = DatasetInfo() _a : Any = dataset_info._to_yaml_dict() assert dataset_info_yaml_dict == {} @pytest.mark.parametrize( """dataset_infos_dict""" , [ DatasetInfosDict(), DatasetInfosDict({"""default""": DatasetInfo()} ), DatasetInfosDict({"""my_config_name""": DatasetInfo()} ), DatasetInfosDict( { """default""": DatasetInfo( description="""foo""" , features=Features({"""a""": Value("""int32""" )} ) , builder_name="""builder""" , config_name="""config""" , version="""1.0.0""" , splits=[{"""name""": """train"""}] , download_size=4_2 , ) } ), DatasetInfosDict( { """v1""": DatasetInfo(dataset_size=4_2 ), """v2""": DatasetInfo(dataset_size=1_3_3_7 ), } ), ] , ) def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' _a : List[Any] = str(UpperCamelCase__ ) dataset_infos_dict.write_to_directory(UpperCamelCase__ ) _a : List[Any] = DatasetInfosDict.from_directory(UpperCamelCase__ ) # the config_name of the dataset_infos_dict take over the attribute for config_name, dataset_info in dataset_infos_dict.items(): _a : str = config_name # the yaml representation doesn't include fields like description or citation # so we just test that we can recover what we can from the yaml _a : Dict = DatasetInfo._from_yaml_dict(dataset_info._to_yaml_dict() ) assert dataset_infos_dict == reloaded if dataset_infos_dict: assert os.path.exists(os.path.join(UpperCamelCase__ , """README.md""" ) )
324
1
"""simple docstring""" # This code is adapted from OpenAI's release # https://github.com/openai/human-eval/blob/master/human_eval/execution.py import contextlib import faulthandler import io import multiprocessing import os import platform import signal import tempfile def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' _a : Dict = multiprocessing.Manager() _a : List[Any] = manager.list() _a : Union[str, Any] = multiprocessing.Process(target=UpperCamelCase__ , args=(check_program, result, timeout) ) p.start() p.join(timeout=timeout + 1 ) if p.is_alive(): p.kill() if not result: result.append("""timed out""" ) return { "task_id": task_id, "passed": result[0] == "passed", "result": result[0], "completion_id": completion_id, } def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' with create_tempdir(): # These system calls are needed when cleaning up tempdir. import os import shutil _a : Optional[Any] = shutil.rmtree _a : Any = os.rmdir _a : List[Any] = os.chdir # Disable functionalities that can make destructive changes to the test. reliability_guard() # Run program. try: _a : str = {} with swallow_io(): with time_limit(UpperCamelCase__ ): exec(UpperCamelCase__ , UpperCamelCase__ ) result.append("""passed""" ) except TimeoutException: result.append("""timed out""" ) except BaseException as e: result.append(F"""failed: {e}""" ) # Needed for cleaning up. _a : Union[str, Any] = rmtree _a : Optional[Any] = rmdir _a : List[str] = chdir @contextlib.contextmanager def lowerCAmelCase__ ( UpperCamelCase__ ): '''simple docstring''' def signal_handler(UpperCamelCase__ , UpperCamelCase__ ): raise TimeoutException("""Timed out!""" ) signal.setitimer(signal.ITIMER_REAL , UpperCamelCase__ ) signal.signal(signal.SIGALRM , UpperCamelCase__ ) try: yield finally: signal.setitimer(signal.ITIMER_REAL , 0 ) @contextlib.contextmanager def lowerCAmelCase__ ( ): '''simple docstring''' _a : Tuple = WriteOnlyStringIO() with contextlib.redirect_stdout(UpperCamelCase__ ): with contextlib.redirect_stderr(UpperCamelCase__ ): with redirect_stdin(UpperCamelCase__ ): yield @contextlib.contextmanager def lowerCAmelCase__ ( ): '''simple docstring''' with tempfile.TemporaryDirectory() as dirname: with chdir(UpperCamelCase__ ): yield dirname class UpperCamelCase ( snake_case_ ): pass class UpperCamelCase ( io.StringIO ): def _lowercase ( self : str , *UpperCAmelCase__ : Union[str, Any] , **UpperCAmelCase__ : List[str] ) -> List[str]: raise OSError def _lowercase ( self : Union[str, Any] , *UpperCAmelCase__ : Optional[Any] , **UpperCAmelCase__ : Optional[Any] ) -> Optional[int]: raise OSError def _lowercase ( self : str , *UpperCAmelCase__ : str , **UpperCAmelCase__ : List[Any] ) -> List[Any]: raise OSError def _lowercase ( self : str , *UpperCAmelCase__ : Union[str, Any] , **UpperCAmelCase__ : Any ) -> str: return False class UpperCamelCase ( contextlib._RedirectStream ): # type: ignore UpperCamelCase : Dict = '''stdin''' @contextlib.contextmanager def lowerCAmelCase__ ( UpperCamelCase__ ): '''simple docstring''' if root == ".": yield return _a : Tuple = os.getcwd() os.chdir(UpperCamelCase__ ) try: yield except BaseException as exc: raise exc finally: os.chdir(UpperCamelCase__ ) def lowerCAmelCase__ ( UpperCamelCase__=None ): '''simple docstring''' if maximum_memory_bytes is not None: import resource resource.setrlimit(resource.RLIMIT_AS , (maximum_memory_bytes, maximum_memory_bytes) ) resource.setrlimit(resource.RLIMIT_DATA , (maximum_memory_bytes, maximum_memory_bytes) ) if not platform.uname().system == "Darwin": resource.setrlimit(resource.RLIMIT_STACK , (maximum_memory_bytes, maximum_memory_bytes) ) faulthandler.disable() import builtins _a : Optional[Any] = None _a : List[str] = None import os _a : Any = """1""" _a : Any = None _a : Optional[Any] = None _a : List[str] = None _a : Optional[int] = None _a : Dict = None _a : Union[str, Any] = None _a : int = None _a : Optional[Any] = None _a : Any = None _a : int = None _a : Any = None _a : str = None _a : int = None _a : Optional[int] = None _a : str = None _a : List[Any] = None _a : Optional[Any] = None _a : Any = None _a : str = None _a : Optional[Any] = None _a : List[str] = None _a : Tuple = None _a : Any = None _a : Tuple = None _a : List[Any] = None _a : int = None _a : Union[str, Any] = None import shutil _a : str = None _a : str = None _a : Union[str, Any] = None import subprocess _a : List[Any] = None # type: ignore _a : Optional[Any] = None import sys _a : Optional[Any] = None _a : List[str] = None _a : List[str] = None _a : List[Any] = None _a : Dict = None
324
"""simple docstring""" 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 , snake_case_ ): def _lowercase ( self : int ) -> int: _a : Optional[Any] = load_tool("""text-to-speech""" ) self.tool.setup() def _lowercase ( self : List[str] ) -> Union[str, Any]: # SpeechT5 isn't deterministic torch.manual_seed(0 ) _a : str = self.tool("""hey""" ) _a : List[str] = result.to_raw() self.assertTrue( torch.allclose( resulting_tensor[:3] , torch.tensor([-0.0_0_0_5_9_6_6_6_6_8_8_3_2_1_1_5_8_2_9, -0.0_0_0_3_6_5_7_6_4_0_1_9_0_7_9_5_0_6_4, -0.0_0_0_1_3_4_3_9_5_0_2_7_9_9_8_8_3_4_8_5] ) , ) ) def _lowercase ( self : Optional[int] ) -> Optional[Any]: # SpeechT5 isn't deterministic torch.manual_seed(0 ) _a : int = self.tool("""hey""" ) _a : str = result.to_raw() self.assertTrue( torch.allclose( resulting_tensor[:3] , torch.tensor([-0.0_0_0_5_9_6_6_6_6_8_8_3_2_1_1_5_8_2_9, -0.0_0_0_3_6_5_7_6_4_0_1_9_0_7_9_5_0_6_4, -0.0_0_0_1_3_4_3_9_5_0_2_7_9_9_8_8_3_4_8_5] ) , ) )
324
1
"""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, BatchEncoding, PreTrainedTokenizer from ...utils import logging _snake_case = logging.get_logger(__name__) _snake_case = '▁' _snake_case = {'vocab_file': 'sentencepiece.bpe.model'} _snake_case = { 'vocab_file': { 'facebook/mbart-large-50-one-to-many-mmt': ( 'https://huggingface.co/facebook/mbart-large-50-one-to-many-mmt/resolve/main/sentencepiece.bpe.model' ), } } _snake_case = { 'facebook/mbart-large-50-one-to-many-mmt': 1024, } # fmt: off _snake_case = ['ar_AR', 'cs_CZ', 'de_DE', 'en_XX', 'es_XX', 'et_EE', 'fi_FI', 'fr_XX', 'gu_IN', 'hi_IN', 'it_IT', 'ja_XX', 'kk_KZ', 'ko_KR', 'lt_LT', 'lv_LV', 'my_MM', 'ne_NP', 'nl_XX', 'ro_RO', 'ru_RU', 'si_LK', 'tr_TR', 'vi_VN', 'zh_CN', 'af_ZA', 'az_AZ', 'bn_IN', 'fa_IR', 'he_IL', 'hr_HR', 'id_ID', 'ka_GE', 'km_KH', 'mk_MK', 'ml_IN', 'mn_MN', 'mr_IN', 'pl_PL', 'ps_AF', 'pt_XX', 'sv_SE', 'sw_KE', 'ta_IN', 'te_IN', 'th_TH', 'tl_XX', 'uk_UA', 'ur_PK', 'xh_ZA', 'gl_ES', 'sl_SI'] class UpperCamelCase ( snake_case_ ): UpperCamelCase : Optional[Any] = VOCAB_FILES_NAMES UpperCamelCase : Any = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCamelCase : str = PRETRAINED_VOCAB_FILES_MAP UpperCamelCase : Any = ['''input_ids''', '''attention_mask'''] UpperCamelCase : List[int] = [] UpperCamelCase : List[int] = [] def __init__( self : List[Any] , UpperCAmelCase__ : str , UpperCAmelCase__ : Union[str, Any]=None , UpperCAmelCase__ : List[str]=None , UpperCAmelCase__ : Tuple="</s>" , UpperCAmelCase__ : Any="</s>" , UpperCAmelCase__ : Dict="<s>" , UpperCAmelCase__ : str="<unk>" , UpperCAmelCase__ : Tuple="<pad>" , UpperCAmelCase__ : Tuple="<mask>" , UpperCAmelCase__ : Optional[Dict[str, Any]] = None , **UpperCAmelCase__ : Optional[Any] , ) -> None: # Mask token behave like a normal word, i.e. include the space before it _a : Tuple = AddedToken(UpperCAmelCase__ , lstrip=UpperCAmelCase__ , rstrip=UpperCAmelCase__ ) if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ) else mask_token _a : List[str] = {} if sp_model_kwargs is None else sp_model_kwargs _a : List[Any] = kwargs.get("""additional_special_tokens""" , [] ) kwargs["additional_special_tokens"] += [ code for code in FAIRSEQ_LANGUAGE_CODES if code not in kwargs["additional_special_tokens"] ] super().__init__( src_lang=UpperCAmelCase__ , tgt_lang=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__ , ) _a : str = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(UpperCAmelCase__ ) ) _a : Tuple = 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 _a : Any = {"""<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 _a : Dict = 1 _a : Tuple = len(self.sp_model ) _a : Tuple = { code: self.sp_model_size + i + self.fairseq_offset for i, code in enumerate(UpperCAmelCase__ ) } _a : Optional[int] = {v: k for k, v in self.lang_code_to_id.items()} _a : int = len(self.sp_model ) + len(self.lang_code_to_id ) + self.fairseq_offset self.fairseq_tokens_to_ids.update(self.lang_code_to_id ) _a : Optional[Any] = {v: k for k, v in self.fairseq_tokens_to_ids.items()} _a : Union[str, Any] = src_lang if src_lang is not None else """en_XX""" _a : Optional[Any] = self.lang_code_to_id[self._src_lang] _a : Optional[Any] = tgt_lang self.set_src_lang_special_tokens(self._src_lang ) @property def _lowercase ( self : List[Any] ) -> int: return len(self.sp_model ) + len(self.lang_code_to_id ) + self.fairseq_offset + 1 # Plus 1 for the mask token @property def _lowercase ( self : int ) -> str: return self._src_lang @src_lang.setter def _lowercase ( self : List[Any] , UpperCAmelCase__ : str ) -> None: _a : List[str] = new_src_lang self.set_src_lang_special_tokens(self._src_lang ) def __getstate__( self : str ) -> Dict: _a : List[Any] = self.__dict__.copy() _a : Any = None return state def __setstate__( self : Tuple , UpperCAmelCase__ : Dict ) -> None: _a : Union[str, Any] = d # for backward compatibility if not hasattr(self , """sp_model_kwargs""" ): _a : Optional[int] = {} _a : Optional[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def _lowercase ( self : List[Any] ) -> Dict: _a : Optional[int] = {self.convert_ids_to_tokens(UpperCAmelCase__ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def _lowercase ( self : Union[str, Any] , UpperCAmelCase__ : str ) -> List[str]: return self.sp_model.encode(UpperCAmelCase__ , out_type=UpperCAmelCase__ ) def _lowercase ( self : Dict , UpperCAmelCase__ : str ) -> int: if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] _a : Union[str, Any] = 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 _lowercase ( self : List[str] , UpperCAmelCase__ : int ) -> str: 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 _lowercase ( self : Optional[int] , UpperCAmelCase__ : str ) -> str: _a : str = [] _a : Any = """""" _a : List[str] = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(UpperCAmelCase__ ) + token _a : str = True _a : Any = [] else: current_sub_tokens.append(UpperCAmelCase__ ) _a : str = False out_string += self.sp_model.decode(UpperCAmelCase__ ) return out_string.strip() def _lowercase ( self : Tuple , 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 _a : int = 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: _a : Dict = self.sp_model.serialized_model_proto() fi.write(UpperCAmelCase__ ) return (out_vocab_file,) def _lowercase ( self : Optional[int] , 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__ ) _a : Tuple = [1] * len(self.prefix_tokens ) _a : Optional[Any] = [1] * len(self.suffix_tokens ) if token_ids_a is None: return prefix_ones + ([0] * len(UpperCAmelCase__ )) + suffix_ones return prefix_ones + ([0] * len(UpperCAmelCase__ )) + ([0] * len(UpperCAmelCase__ )) + suffix_ones def _lowercase ( self : int , UpperCAmelCase__ : List[int] , UpperCAmelCase__ : Optional[List[int]] = None ) -> List[int]: 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 _lowercase ( self : List[str] , UpperCAmelCase__ : str , UpperCAmelCase__ : str , UpperCAmelCase__ : Optional[str] , UpperCAmelCase__ : Optional[str] , **UpperCAmelCase__ : Optional[int] ) -> Dict: if src_lang is None or tgt_lang is None: raise ValueError("""Translation requires a `src_lang` and a `tgt_lang` for this model""" ) _a : int = src_lang _a : int = self(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ , return_tensors=UpperCAmelCase__ , **UpperCAmelCase__ ) _a : List[Any] = self.convert_tokens_to_ids(UpperCAmelCase__ ) _a : Optional[Any] = tgt_lang_id return inputs def _lowercase ( self : Dict , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : str = "en_XX" , UpperCAmelCase__ : Optional[List[str]] = None , UpperCAmelCase__ : str = "ro_RO" , **UpperCAmelCase__ : int , ) -> BatchEncoding: _a : int = src_lang _a : Optional[Any] = tgt_lang return super().prepare_seqaseq_batch(UpperCAmelCase__ , UpperCAmelCase__ , **UpperCAmelCase__ ) def _lowercase ( self : Dict ) -> List[str]: return self.set_src_lang_special_tokens(self.src_lang ) def _lowercase ( self : List[str] ) -> List[Any]: return self.set_tgt_lang_special_tokens(self.tgt_lang ) def _lowercase ( self : Tuple , UpperCAmelCase__ : str ) -> None: _a : Optional[Any] = self.lang_code_to_id[src_lang] _a : List[Any] = [self.cur_lang_code_id] _a : int = [self.eos_token_id] def _lowercase ( self : Optional[Any] , UpperCAmelCase__ : str ) -> None: _a : Optional[Any] = self.lang_code_to_id[tgt_lang] _a : Optional[Any] = [self.cur_lang_code_id] _a : Optional[int] = [self.eos_token_id]
324
"""simple docstring""" import copy import json import os import tempfile from transformers import is_torch_available from .test_configuration_utils import config_common_kwargs class UpperCamelCase ( snake_case_ ): def __init__( self : Union[str, Any] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : int=None , UpperCAmelCase__ : Optional[Any]=True , UpperCAmelCase__ : List[str]=None , **UpperCAmelCase__ : str ) -> int: _a : str = parent _a : Union[str, Any] = config_class _a : List[Any] = has_text_modality _a : List[Any] = kwargs _a : List[Any] = common_properties def _lowercase ( self : int ) -> Tuple: _a : List[str] = self.config_class(**self.inputs_dict ) _a : Dict = ( ["""hidden_size""", """num_attention_heads""", """num_hidden_layers"""] if self.common_properties is None else self.common_properties ) # Add common fields for text models if self.has_text_modality: common_properties.extend(["""vocab_size"""] ) # Test that config has the common properties as getters for prop in common_properties: self.parent.assertTrue(hasattr(UpperCAmelCase__ , UpperCAmelCase__ ) , msg=f"""`{prop}` does not exist""" ) # Test that config has the common properties as setter for idx, name in enumerate(UpperCAmelCase__ ): try: setattr(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) self.parent.assertEqual( getattr(UpperCAmelCase__ , UpperCAmelCase__ ) , UpperCAmelCase__ , msg=f"""`{name} value {idx} expected, but was {getattr(UpperCAmelCase__ , UpperCAmelCase__ )}""" ) except NotImplementedError: # Some models might not be able to implement setters for common_properties # In that case, a NotImplementedError is raised pass # Test if config class can be called with Config(prop_name=..) for idx, name in enumerate(UpperCAmelCase__ ): try: _a : Optional[int] = self.config_class(**{name: idx} ) self.parent.assertEqual( getattr(UpperCAmelCase__ , UpperCAmelCase__ ) , UpperCAmelCase__ , msg=f"""`{name} value {idx} expected, but was {getattr(UpperCAmelCase__ , UpperCAmelCase__ )}""" ) except NotImplementedError: # Some models might not be able to implement setters for common_properties # In that case, a NotImplementedError is raised pass def _lowercase ( self : Optional[int] ) -> Optional[Any]: _a : Optional[Any] = self.config_class(**self.inputs_dict ) _a : List[str] = json.loads(config.to_json_string() ) for key, value in self.inputs_dict.items(): self.parent.assertEqual(obj[key] , UpperCAmelCase__ ) def _lowercase ( self : int ) -> List[str]: _a : Optional[Any] = self.config_class(**self.inputs_dict ) with tempfile.TemporaryDirectory() as tmpdirname: _a : Tuple = os.path.join(UpperCAmelCase__ , """config.json""" ) config_first.to_json_file(UpperCAmelCase__ ) _a : List[str] = self.config_class.from_json_file(UpperCAmelCase__ ) self.parent.assertEqual(config_second.to_dict() , config_first.to_dict() ) def _lowercase ( self : Union[str, Any] ) -> Dict: _a : Dict = self.config_class(**self.inputs_dict ) with tempfile.TemporaryDirectory() as tmpdirname: config_first.save_pretrained(UpperCAmelCase__ ) _a : Dict = self.config_class.from_pretrained(UpperCAmelCase__ ) self.parent.assertEqual(config_second.to_dict() , config_first.to_dict() ) def _lowercase ( self : Dict ) -> Tuple: _a : List[Any] = self.config_class(**self.inputs_dict ) _a : Any = """test""" with tempfile.TemporaryDirectory() as tmpdirname: _a : List[Any] = os.path.join(UpperCAmelCase__ , UpperCAmelCase__ ) config_first.save_pretrained(UpperCAmelCase__ ) _a : List[Any] = self.config_class.from_pretrained(UpperCAmelCase__ , subfolder=UpperCAmelCase__ ) self.parent.assertEqual(config_second.to_dict() , config_first.to_dict() ) def _lowercase ( self : List[str] ) -> Union[str, Any]: _a : Tuple = self.config_class(**self.inputs_dict , num_labels=5 ) self.parent.assertEqual(len(config.idalabel ) , 5 ) self.parent.assertEqual(len(config.labelaid ) , 5 ) _a : Union[str, Any] = 3 self.parent.assertEqual(len(config.idalabel ) , 3 ) self.parent.assertEqual(len(config.labelaid ) , 3 ) def _lowercase ( self : Tuple ) -> List[str]: if self.config_class.is_composition: return _a : str = self.config_class() self.parent.assertIsNotNone(UpperCAmelCase__ ) def _lowercase ( self : List[Any] ) -> Optional[Any]: _a : Dict = copy.deepcopy(UpperCAmelCase__ ) _a : Any = self.config_class(**UpperCAmelCase__ ) _a : str = [] for key, value in config_common_kwargs.items(): if key == "torch_dtype": if not is_torch_available(): continue else: import torch if config.torch_dtype != torch.floataa: wrong_values.append(("""torch_dtype""", config.torch_dtype, torch.floataa) ) elif getattr(UpperCAmelCase__ , UpperCAmelCase__ ) != value: wrong_values.append((key, getattr(UpperCAmelCase__ , UpperCAmelCase__ ), value) ) if len(UpperCAmelCase__ ) > 0: _a : List[Any] = """\n""".join([f"""- {v[0]}: got {v[1]} instead of {v[2]}""" for v in wrong_values] ) raise ValueError(f"""The following keys were not properly set in the config:\n{errors}""" ) def _lowercase ( self : int ) -> Union[str, Any]: self.create_and_test_config_common_properties() self.create_and_test_config_to_json_string() self.create_and_test_config_to_json_file() self.create_and_test_config_from_and_save_pretrained() self.create_and_test_config_from_and_save_pretrained_subfolder() self.create_and_test_config_with_num_labels() self.check_config_can_be_init_without_params() self.check_config_arguments_init()
324
1
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging _snake_case = logging.get_logger(__name__) _snake_case = { 'bert-base-uncased': 'https://huggingface.co/bert-base-uncased/resolve/main/config.json', 'bert-large-uncased': 'https://huggingface.co/bert-large-uncased/resolve/main/config.json', 'bert-base-cased': 'https://huggingface.co/bert-base-cased/resolve/main/config.json', 'bert-large-cased': 'https://huggingface.co/bert-large-cased/resolve/main/config.json', 'bert-base-multilingual-uncased': 'https://huggingface.co/bert-base-multilingual-uncased/resolve/main/config.json', 'bert-base-multilingual-cased': 'https://huggingface.co/bert-base-multilingual-cased/resolve/main/config.json', 'bert-base-chinese': 'https://huggingface.co/bert-base-chinese/resolve/main/config.json', 'bert-base-german-cased': 'https://huggingface.co/bert-base-german-cased/resolve/main/config.json', 'bert-large-uncased-whole-word-masking': ( 'https://huggingface.co/bert-large-uncased-whole-word-masking/resolve/main/config.json' ), 'bert-large-cased-whole-word-masking': ( 'https://huggingface.co/bert-large-cased-whole-word-masking/resolve/main/config.json' ), 'bert-large-uncased-whole-word-masking-finetuned-squad': ( 'https://huggingface.co/bert-large-uncased-whole-word-masking-finetuned-squad/resolve/main/config.json' ), 'bert-large-cased-whole-word-masking-finetuned-squad': ( 'https://huggingface.co/bert-large-cased-whole-word-masking-finetuned-squad/resolve/main/config.json' ), 'bert-base-cased-finetuned-mrpc': 'https://huggingface.co/bert-base-cased-finetuned-mrpc/resolve/main/config.json', 'bert-base-german-dbmdz-cased': 'https://huggingface.co/bert-base-german-dbmdz-cased/resolve/main/config.json', 'bert-base-german-dbmdz-uncased': 'https://huggingface.co/bert-base-german-dbmdz-uncased/resolve/main/config.json', 'cl-tohoku/bert-base-japanese': 'https://huggingface.co/cl-tohoku/bert-base-japanese/resolve/main/config.json', 'cl-tohoku/bert-base-japanese-whole-word-masking': ( 'https://huggingface.co/cl-tohoku/bert-base-japanese-whole-word-masking/resolve/main/config.json' ), 'cl-tohoku/bert-base-japanese-char': ( 'https://huggingface.co/cl-tohoku/bert-base-japanese-char/resolve/main/config.json' ), 'cl-tohoku/bert-base-japanese-char-whole-word-masking': ( 'https://huggingface.co/cl-tohoku/bert-base-japanese-char-whole-word-masking/resolve/main/config.json' ), 'TurkuNLP/bert-base-finnish-cased-v1': ( 'https://huggingface.co/TurkuNLP/bert-base-finnish-cased-v1/resolve/main/config.json' ), 'TurkuNLP/bert-base-finnish-uncased-v1': ( 'https://huggingface.co/TurkuNLP/bert-base-finnish-uncased-v1/resolve/main/config.json' ), 'wietsedv/bert-base-dutch-cased': 'https://huggingface.co/wietsedv/bert-base-dutch-cased/resolve/main/config.json', # See all BERT models at https://huggingface.co/models?filter=bert } class UpperCamelCase ( snake_case_ ): UpperCamelCase : int = '''bert''' def __init__( self : Dict , UpperCAmelCase__ : Optional[Any]=30522 , UpperCAmelCase__ : Optional[int]=768 , UpperCAmelCase__ : Optional[Any]=12 , UpperCAmelCase__ : int=12 , UpperCAmelCase__ : Dict=3072 , UpperCAmelCase__ : Dict="gelu" , UpperCAmelCase__ : str=0.1 , UpperCAmelCase__ : List[str]=0.1 , UpperCAmelCase__ : List[str]=512 , UpperCAmelCase__ : Any=2 , UpperCAmelCase__ : Optional[int]=0.0_2 , UpperCAmelCase__ : Dict=1E-12 , UpperCAmelCase__ : Dict=0 , UpperCAmelCase__ : Optional[int]="absolute" , UpperCAmelCase__ : Tuple=True , UpperCAmelCase__ : Optional[int]=None , **UpperCAmelCase__ : List[str] , ) -> int: super().__init__(pad_token_id=UpperCAmelCase__ , **UpperCAmelCase__ ) _a : Optional[Any] = vocab_size _a : str = hidden_size _a : Optional[int] = num_hidden_layers _a : str = num_attention_heads _a : Optional[int] = hidden_act _a : Union[str, Any] = intermediate_size _a : List[Any] = hidden_dropout_prob _a : int = attention_probs_dropout_prob _a : Tuple = max_position_embeddings _a : Dict = type_vocab_size _a : Dict = initializer_range _a : List[Any] = layer_norm_eps _a : Optional[Any] = position_embedding_type _a : List[str] = use_cache _a : Optional[Any] = classifier_dropout class UpperCamelCase ( snake_case_ ): @property def _lowercase ( self : Optional[int] ) -> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": _a : List[Any] = {0: """batch""", 1: """choice""", 2: """sequence"""} else: _a : Any = {0: """batch""", 1: """sequence"""} return OrderedDict( [ ("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ("""token_type_ids""", dynamic_axis), ] )
324
"""simple docstring""" import os from huggingface_hub.constants import HUGGINGFACE_HUB_CACHE, hf_cache_home _snake_case = HUGGINGFACE_HUB_CACHE _snake_case = 'config.json' _snake_case = 'diffusion_pytorch_model.bin' _snake_case = 'diffusion_flax_model.msgpack' _snake_case = 'model.onnx' _snake_case = 'diffusion_pytorch_model.safetensors' _snake_case = 'weights.pb' _snake_case = 'https://huggingface.co' _snake_case = default_cache_path _snake_case = 'diffusers_modules' _snake_case = os.getenv('HF_MODULES_CACHE', os.path.join(hf_cache_home, 'modules')) _snake_case = ['fp16', 'non-ema'] _snake_case = '.self_attn'
324
1
"""simple docstring""" import argparse import json from pathlib import Path import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import DeiTImageProcessor, ViTConfig, ViTForImageClassification, ViTImageProcessor, ViTModel from transformers.utils import logging logging.set_verbosity_info() _snake_case = logging.get_logger(__name__) def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__=False ): '''simple docstring''' _a : Any = [] for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((F"""blocks.{i}.norm1.weight""", F"""vit.encoder.layer.{i}.layernorm_before.weight""") ) rename_keys.append((F"""blocks.{i}.norm1.bias""", F"""vit.encoder.layer.{i}.layernorm_before.bias""") ) rename_keys.append((F"""blocks.{i}.attn.proj.weight""", F"""vit.encoder.layer.{i}.attention.output.dense.weight""") ) rename_keys.append((F"""blocks.{i}.attn.proj.bias""", F"""vit.encoder.layer.{i}.attention.output.dense.bias""") ) rename_keys.append((F"""blocks.{i}.norm2.weight""", F"""vit.encoder.layer.{i}.layernorm_after.weight""") ) rename_keys.append((F"""blocks.{i}.norm2.bias""", F"""vit.encoder.layer.{i}.layernorm_after.bias""") ) rename_keys.append((F"""blocks.{i}.mlp.fc1.weight""", F"""vit.encoder.layer.{i}.intermediate.dense.weight""") ) rename_keys.append((F"""blocks.{i}.mlp.fc1.bias""", F"""vit.encoder.layer.{i}.intermediate.dense.bias""") ) rename_keys.append((F"""blocks.{i}.mlp.fc2.weight""", F"""vit.encoder.layer.{i}.output.dense.weight""") ) rename_keys.append((F"""blocks.{i}.mlp.fc2.bias""", F"""vit.encoder.layer.{i}.output.dense.bias""") ) # projection layer + position embeddings rename_keys.extend( [ ("""cls_token""", """vit.embeddings.cls_token"""), ("""patch_embed.proj.weight""", """vit.embeddings.patch_embeddings.projection.weight"""), ("""patch_embed.proj.bias""", """vit.embeddings.patch_embeddings.projection.bias"""), ("""pos_embed""", """vit.embeddings.position_embeddings"""), ] ) if base_model: # layernorm + pooler rename_keys.extend( [ ("""norm.weight""", """layernorm.weight"""), ("""norm.bias""", """layernorm.bias"""), ("""pre_logits.fc.weight""", """pooler.dense.weight"""), ("""pre_logits.fc.bias""", """pooler.dense.bias"""), ] ) # if just the base model, we should remove "vit" from all keys that start with "vit" _a : Tuple = [(pair[0], pair[1][4:]) if pair[1].startswith("""vit""" ) else pair for pair in rename_keys] else: # layernorm + classification head rename_keys.extend( [ ("""norm.weight""", """vit.layernorm.weight"""), ("""norm.bias""", """vit.layernorm.bias"""), ("""head.weight""", """classifier.weight"""), ("""head.bias""", """classifier.bias"""), ] ) return rename_keys def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__=False ): '''simple docstring''' for i in range(config.num_hidden_layers ): if base_model: _a : Tuple = """""" else: _a : int = """vit.""" # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) _a : int = state_dict.pop(F"""blocks.{i}.attn.qkv.weight""" ) _a : Dict = state_dict.pop(F"""blocks.{i}.attn.qkv.bias""" ) # next, add query, keys and values (in that order) to the state dict _a : List[str] = in_proj_weight[ : config.hidden_size, : ] _a : List[Any] = in_proj_bias[: config.hidden_size] _a : str = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] _a : List[Any] = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] _a : Optional[Any] = in_proj_weight[ -config.hidden_size :, : ] _a : List[str] = in_proj_bias[-config.hidden_size :] def lowerCAmelCase__ ( UpperCamelCase__ ): '''simple docstring''' _a : List[str] = ["""head.weight""", """head.bias"""] for k in ignore_keys: state_dict.pop(UpperCamelCase__ , UpperCamelCase__ ) def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' _a : Tuple = dct.pop(UpperCamelCase__ ) _a : Union[str, Any] = val def lowerCAmelCase__ ( ): '''simple docstring''' _a : Dict = """http://images.cocodataset.org/val2017/000000039769.jpg""" _a : List[Any] = Image.open(requests.get(UpperCamelCase__ , stream=UpperCamelCase__ ).raw ) return im @torch.no_grad() def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' _a : Union[str, Any] = ViTConfig() _a : Any = False # dataset (ImageNet-21k only or also fine-tuned on ImageNet 2012), patch_size and image_size if vit_name[-5:] == "in21k": _a : Tuple = True _a : List[str] = int(vit_name[-1_2:-1_0] ) _a : Dict = int(vit_name[-9:-6] ) else: _a : Optional[Any] = 1_0_0_0 _a : Any = """huggingface/label-files""" _a : List[str] = """imagenet-1k-id2label.json""" _a : Optional[Any] = json.load(open(hf_hub_download(UpperCamelCase__ , UpperCamelCase__ , repo_type="""dataset""" ) , """r""" ) ) _a : Tuple = {int(UpperCamelCase__ ): v for k, v in idalabel.items()} _a : List[Any] = idalabel _a : Union[str, Any] = {v: k for k, v in idalabel.items()} _a : int = int(vit_name[-6:-4] ) _a : Optional[Any] = int(vit_name[-3:] ) # size of the architecture if "deit" in vit_name: if vit_name[9:].startswith("""tiny""" ): _a : Any = 1_9_2 _a : str = 7_6_8 _a : List[str] = 1_2 _a : Tuple = 3 elif vit_name[9:].startswith("""small""" ): _a : int = 3_8_4 _a : Union[str, Any] = 1_5_3_6 _a : Optional[Any] = 1_2 _a : List[str] = 6 else: pass else: if vit_name[4:].startswith("""small""" ): _a : Tuple = 7_6_8 _a : str = 2_3_0_4 _a : Tuple = 8 _a : Optional[int] = 8 elif vit_name[4:].startswith("""base""" ): pass elif vit_name[4:].startswith("""large""" ): _a : int = 1_0_2_4 _a : List[str] = 4_0_9_6 _a : int = 2_4 _a : Dict = 1_6 elif vit_name[4:].startswith("""huge""" ): _a : int = 1_2_8_0 _a : Any = 5_1_2_0 _a : Any = 3_2 _a : Optional[int] = 1_6 # load original model from timm _a : Tuple = timm.create_model(UpperCamelCase__ , pretrained=UpperCamelCase__ ) timm_model.eval() # load state_dict of original model, remove and rename some keys _a : Dict = timm_model.state_dict() if base_model: remove_classification_head_(UpperCamelCase__ ) _a : Optional[int] = create_rename_keys(UpperCamelCase__ , UpperCamelCase__ ) for src, dest in rename_keys: rename_key(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) read_in_q_k_v(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) # load HuggingFace model if vit_name[-5:] == "in21k": _a : List[str] = ViTModel(UpperCamelCase__ ).eval() else: _a : Union[str, Any] = ViTForImageClassification(UpperCamelCase__ ).eval() model.load_state_dict(UpperCamelCase__ ) # Check outputs on an image, prepared by ViTImageProcessor/DeiTImageProcessor if "deit" in vit_name: _a : List[str] = DeiTImageProcessor(size=config.image_size ) else: _a : Optional[Any] = ViTImageProcessor(size=config.image_size ) _a : List[Any] = image_processor(images=prepare_img() , return_tensors="""pt""" ) _a : Any = encoding["""pixel_values"""] _a : Tuple = model(UpperCamelCase__ ) if base_model: _a : Optional[int] = timm_model.forward_features(UpperCamelCase__ ) assert timm_pooled_output.shape == outputs.pooler_output.shape assert torch.allclose(UpperCamelCase__ , outputs.pooler_output , atol=1e-3 ) else: _a : int = timm_model(UpperCamelCase__ ) assert timm_logits.shape == outputs.logits.shape assert torch.allclose(UpperCamelCase__ , outputs.logits , atol=1e-3 ) Path(UpperCamelCase__ ).mkdir(exist_ok=UpperCamelCase__ ) print(F"""Saving model {vit_name} to {pytorch_dump_folder_path}""" ) model.save_pretrained(UpperCamelCase__ ) print(F"""Saving image processor to {pytorch_dump_folder_path}""" ) image_processor.save_pretrained(UpperCamelCase__ ) if __name__ == "__main__": _snake_case = argparse.ArgumentParser() # Required parameters parser.add_argument( '--vit_name', default='vit_base_patch16_224', type=str, help='Name of the ViT timm model you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model directory.' ) _snake_case = parser.parse_args() convert_vit_checkpoint(args.vit_name, args.pytorch_dump_folder_path)
324
"""simple docstring""" from math import factorial def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' if successes > trials: raise ValueError("""successes must be lower or equal to trials""" ) if trials < 0 or successes < 0: raise ValueError("""the function is defined for non-negative integers""" ) if not isinstance(UpperCamelCase__ , UpperCamelCase__ ) or not isinstance(UpperCamelCase__ , UpperCamelCase__ ): raise ValueError("""the function is defined for non-negative integers""" ) if not 0 < prob < 1: raise ValueError("""prob has to be in range of 1 - 0""" ) _a : Optional[int] = (prob**successes) * ((1 - prob) ** (trials - successes)) # Calculate the binomial coefficient: n! / k!(n-k)! _a : Optional[int] = float(factorial(UpperCamelCase__ ) ) coefficient /= factorial(UpperCamelCase__ ) * factorial(trials - successes ) return probability * coefficient if __name__ == "__main__": from doctest import testmod testmod() print('Probability of 2 successes out of 4 trails') print('with probability of 0.75 is:', end=' ') print(binomial_distribution(2, 4, 0.75))
324
1
"""simple docstring""" import webbrowser from sys import argv from urllib.parse import parse_qs, quote import requests from bsa import BeautifulSoup from fake_useragent import UserAgent if __name__ == "__main__": _snake_case = '%20'.join(argv[1:]) if len(argv) > 1 else quote(str(input('Search: '))) print('Googling.....') _snake_case = F'''https://www.google.com/search?q={query}&num=100''' _snake_case = requests.get( url, headers={'User-Agent': str(UserAgent().random)}, ) try: _snake_case = ( BeautifulSoup(res.text, 'html.parser') .find('div', attrs={'class': 'yuRUbf'}) .find('a') .get('href') ) except AttributeError: _snake_case = parse_qs( BeautifulSoup(res.text, 'html.parser') .find('div', attrs={'class': 'kCrYT'}) .find('a') .get('href') )['url'][0] webbrowser.open(link)
324
"""simple docstring""" def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' _a , _a : Dict = len(UpperCamelCase__ ), len(grid[0] ) if ( min(UpperCamelCase__ , UpperCamelCase__ ) < 0 or row == row_length or col == col_length or (row, col) in visit or grid[row][col] == 1 ): return 0 if row == row_length - 1 and col == col_length - 1: return 1 visit.add((row, col) ) _a : Any = 0 count += depth_first_search(UpperCamelCase__ , row + 1 , UpperCamelCase__ , UpperCamelCase__ ) count += depth_first_search(UpperCamelCase__ , row - 1 , UpperCamelCase__ , UpperCamelCase__ ) count += depth_first_search(UpperCamelCase__ , UpperCamelCase__ , col + 1 , UpperCamelCase__ ) count += depth_first_search(UpperCamelCase__ , UpperCamelCase__ , col - 1 , UpperCamelCase__ ) visit.remove((row, col) ) return count if __name__ == "__main__": import doctest doctest.testmod()
324
1
"""simple docstring""" from functools import reduce _snake_case = ( '73167176531330624919225119674426574742355349194934' '96983520312774506326239578318016984801869478851843' '85861560789112949495459501737958331952853208805511' '12540698747158523863050715693290963295227443043557' '66896648950445244523161731856403098711121722383113' '62229893423380308135336276614282806444486645238749' '30358907296290491560440772390713810515859307960866' '70172427121883998797908792274921901699720888093776' '65727333001053367881220235421809751254540594752243' '52584907711670556013604839586446706324415722155397' '53697817977846174064955149290862569321978468622482' '83972241375657056057490261407972968652414535100474' '82166370484403199890008895243450658541227588666881' '16427171479924442928230863465674813919123162824586' '17866458359124566529476545682848912883142607690042' '24219022671055626321111109370544217506941658960408' '07198403850962455444362981230987879927244284909188' '84580156166097919133875499200524063689912560717606' '05886116467109405077541002256983155200055935729725' '71636269561882670428252483600823257530420752963450' ) def lowerCAmelCase__ ( UpperCamelCase__ = N ): '''simple docstring''' return max( # mypy cannot properly interpret reduce int(reduce(lambda UpperCamelCase__ , UpperCamelCase__ : str(int(UpperCamelCase__ ) * int(UpperCamelCase__ ) ) , n[i : i + 1_3] ) ) for i in range(len(UpperCamelCase__ ) - 1_2 ) ) if __name__ == "__main__": print(F'''{solution() = }''')
324
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) _snake_case = { 'configuration_vision_encoder_decoder': ['VisionEncoderDecoderConfig', 'VisionEncoderDecoderOnnxConfig'] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _snake_case = ['VisionEncoderDecoderModel'] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _snake_case = ['TFVisionEncoderDecoderModel'] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _snake_case = ['FlaxVisionEncoderDecoderModel'] if TYPE_CHECKING: from .configuration_vision_encoder_decoder import VisionEncoderDecoderConfig, VisionEncoderDecoderOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_vision_encoder_decoder import VisionEncoderDecoderModel try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_vision_encoder_decoder import TFVisionEncoderDecoderModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_vision_encoder_decoder import FlaxVisionEncoderDecoderModel else: import sys _snake_case = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
324
1
"""simple docstring""" # Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available _snake_case = {'configuration_mra': ['MRA_PRETRAINED_CONFIG_ARCHIVE_MAP', 'MraConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _snake_case = [ 'MRA_PRETRAINED_MODEL_ARCHIVE_LIST', 'MraForMaskedLM', 'MraForMultipleChoice', 'MraForQuestionAnswering', 'MraForSequenceClassification', 'MraForTokenClassification', 'MraLayer', 'MraModel', 'MraPreTrainedModel', ] if TYPE_CHECKING: from .configuration_mra import MRA_PRETRAINED_CONFIG_ARCHIVE_MAP, MraConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mra import ( MRA_PRETRAINED_MODEL_ARCHIVE_LIST, MraForMaskedLM, MraForMultipleChoice, MraForQuestionAnswering, MraForSequenceClassification, MraForTokenClassification, MraLayer, MraModel, MraPreTrainedModel, ) else: import sys _snake_case = _LazyModule(__name__, globals()['__file__'], _import_structure)
324
"""simple docstring""" from __future__ import annotations import time _snake_case = list[tuple[int, int]] _snake_case = [ [0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles [0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0], [1, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0], ] _snake_case = [[-1, 0], [0, -1], [1, 0], [0, 1]] # up, left, down, right class UpperCamelCase : def __init__( self : Optional[int] , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : Node | None ) -> List[str]: _a : int = pos_x _a : Union[str, Any] = pos_y _a : Tuple = (pos_y, pos_x) _a : Tuple = goal_x _a : int = goal_y _a : str = parent class UpperCamelCase : def __init__( self : List[Any] , UpperCAmelCase__ : tuple[int, int] , UpperCAmelCase__ : tuple[int, int] ) -> List[str]: _a : List[Any] = Node(start[1] , start[0] , goal[1] , goal[0] , UpperCAmelCase__ ) _a : List[str] = Node(goal[1] , goal[0] , goal[1] , goal[0] , UpperCAmelCase__ ) _a : Optional[int] = [self.start] _a : Tuple = False def _lowercase ( self : str ) -> Path | None: while self.node_queue: _a : Tuple = self.node_queue.pop(0 ) if current_node.pos == self.target.pos: _a : Dict = True return self.retrace_path(UpperCAmelCase__ ) _a : Tuple = self.get_successors(UpperCAmelCase__ ) for node in successors: self.node_queue.append(UpperCAmelCase__ ) if not self.reached: return [self.start.pos] return None def _lowercase ( self : Optional[int] , UpperCAmelCase__ : Node ) -> list[Node]: _a : Optional[Any] = [] for action in delta: _a : str = parent.pos_x + action[1] _a : List[Any] = parent.pos_y + action[0] if not (0 <= pos_x <= len(grid[0] ) - 1 and 0 <= pos_y <= len(UpperCAmelCase__ ) - 1): continue if grid[pos_y][pos_x] != 0: continue successors.append( Node(UpperCAmelCase__ , UpperCAmelCase__ , self.target.pos_y , self.target.pos_x , UpperCAmelCase__ ) ) return successors def _lowercase ( self : List[Any] , UpperCAmelCase__ : Node | None ) -> Path: _a : Dict = node _a : List[str] = [] while current_node is not None: path.append((current_node.pos_y, current_node.pos_x) ) _a : Any = current_node.parent path.reverse() return path class UpperCamelCase : def __init__( self : List[str] , UpperCAmelCase__ : int , UpperCAmelCase__ : List[Any] ) -> Any: _a : Dict = BreadthFirstSearch(UpperCAmelCase__ , UpperCAmelCase__ ) _a : Optional[int] = BreadthFirstSearch(UpperCAmelCase__ , UpperCAmelCase__ ) _a : Dict = False def _lowercase ( self : Any ) -> Path | None: while self.fwd_bfs.node_queue or self.bwd_bfs.node_queue: _a : List[Any] = self.fwd_bfs.node_queue.pop(0 ) _a : Union[str, Any] = self.bwd_bfs.node_queue.pop(0 ) if current_bwd_node.pos == current_fwd_node.pos: _a : Optional[int] = True return self.retrace_bidirectional_path( UpperCAmelCase__ , UpperCAmelCase__ ) _a : List[str] = current_bwd_node _a : int = current_fwd_node _a : Optional[Any] = { self.fwd_bfs: self.fwd_bfs.get_successors(UpperCAmelCase__ ), self.bwd_bfs: self.bwd_bfs.get_successors(UpperCAmelCase__ ), } for bfs in [self.fwd_bfs, self.bwd_bfs]: for node in successors[bfs]: bfs.node_queue.append(UpperCAmelCase__ ) if not self.reached: return [self.fwd_bfs.start.pos] return None def _lowercase ( self : Optional[int] , UpperCAmelCase__ : Node , UpperCAmelCase__ : Node ) -> Path: _a : str = self.fwd_bfs.retrace_path(UpperCAmelCase__ ) _a : List[Any] = self.bwd_bfs.retrace_path(UpperCAmelCase__ ) bwd_path.pop() bwd_path.reverse() _a : Tuple = fwd_path + bwd_path return path if __name__ == "__main__": # all coordinates are given in format [y,x] import doctest doctest.testmod() _snake_case = (0, 0) _snake_case = (len(grid) - 1, len(grid[0]) - 1) for elem in grid: print(elem) _snake_case = time.time() _snake_case = BreadthFirstSearch(init, goal) _snake_case = bfs.search() _snake_case = time.time() - start_bfs_time print('Unidirectional BFS computation time : ', bfs_time) _snake_case = time.time() _snake_case = BidirectionalBreadthFirstSearch(init, goal) _snake_case = bd_bfs.search() _snake_case = time.time() - start_bd_bfs_time print('Bidirectional BFS computation time : ', bd_bfs_time)
324
1
"""simple docstring""" from __future__ import annotations from math import pi, sqrt def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' if inductance <= 0: raise ValueError("""Inductance cannot be 0 or negative""" ) elif capacitance <= 0: raise ValueError("""Capacitance cannot be 0 or negative""" ) else: return ( "Resonant frequency", float(1 / (2 * pi * (sqrt(inductance * capacitance ))) ), ) if __name__ == "__main__": import doctest doctest.testmod()
324
"""simple docstring""" import logging import math import os from dataclasses import dataclass, field from glob import glob from typing import Optional from torch.utils.data import ConcatDataset import transformers from transformers import ( CONFIG_MAPPING, MODEL_WITH_LM_HEAD_MAPPING, AutoConfig, AutoModelWithLMHead, AutoTokenizer, DataCollatorForLanguageModeling, DataCollatorForPermutationLanguageModeling, DataCollatorForWholeWordMask, HfArgumentParser, LineByLineTextDataset, LineByLineWithRefDataset, PreTrainedTokenizer, TextDataset, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import is_main_process _snake_case = logging.getLogger(__name__) _snake_case = list(MODEL_WITH_LM_HEAD_MAPPING.keys()) _snake_case = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES) @dataclass class UpperCamelCase : UpperCamelCase : Optional[str] = field( default=snake_case_ , metadata={ '''help''': ( '''The model checkpoint for weights initialization. Leave None if you want to train a model from''' ''' scratch.''' ) } , ) UpperCamelCase : Optional[str] = field( default=snake_case_ , metadata={'''help''': '''If training from scratch, pass a model type from the list: ''' + ''', '''.join(snake_case_ )} , ) UpperCamelCase : Optional[str] = field( default=snake_case_ , metadata={'''help''': '''Pretrained config name or path if not the same as model_name'''} ) UpperCamelCase : Optional[str] = field( default=snake_case_ , metadata={'''help''': '''Pretrained tokenizer name or path if not the same as model_name'''} ) UpperCamelCase : Optional[str] = field( default=snake_case_ , metadata={'''help''': '''Where do you want to store the pretrained models downloaded from huggingface.co'''} , ) @dataclass class UpperCamelCase : UpperCamelCase : Optional[str] = field( default=snake_case_ , metadata={'''help''': '''The input training data file (a text file).'''} ) UpperCamelCase : Optional[str] = field( default=snake_case_ , metadata={ '''help''': ( '''The input training data files (multiple files in glob format). ''' '''Very often splitting large files to smaller files can prevent tokenizer going out of memory''' ) } , ) UpperCamelCase : Optional[str] = field( default=snake_case_ , metadata={'''help''': '''An optional input evaluation data file to evaluate the perplexity on (a text file).'''} , ) UpperCamelCase : Optional[str] = field( default=snake_case_ , metadata={'''help''': '''An optional input train ref data file for whole word mask in Chinese.'''} , ) UpperCamelCase : Optional[str] = field( default=snake_case_ , metadata={'''help''': '''An optional input eval ref data file for whole word mask in Chinese.'''} , ) UpperCamelCase : bool = field( default=snake_case_ , metadata={'''help''': '''Whether distinct lines of text in the dataset are to be handled as distinct sequences.'''} , ) UpperCamelCase : bool = field( default=snake_case_ , metadata={'''help''': '''Train with masked-language modeling loss instead of language modeling.'''} ) UpperCamelCase : bool = field(default=snake_case_ , metadata={'''help''': '''Whether ot not to use whole word mask.'''} ) UpperCamelCase : float = field( default=0.1_5 , metadata={'''help''': '''Ratio of tokens to mask for masked language modeling loss'''} ) UpperCamelCase : float = field( default=1 / 6 , metadata={ '''help''': ( '''Ratio of length of a span of masked tokens to surrounding context length for permutation language''' ''' modeling.''' ) } , ) UpperCamelCase : int = field( default=5 , metadata={'''help''': '''Maximum length of a span of masked tokens for permutation language modeling.'''} ) UpperCamelCase : int = field( default=-1 , metadata={ '''help''': ( '''Optional input sequence length after tokenization.''' '''The training dataset will be truncated in block of this size for training.''' '''Default to the model max input length for single sentence inputs (take into account special tokens).''' ) } , ) UpperCamelCase : bool = field( default=snake_case_ , metadata={'''help''': '''Overwrite the cached training and evaluation sets'''} ) def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = False , UpperCamelCase__ = None , ): '''simple docstring''' def _dataset(UpperCamelCase__ , UpperCamelCase__=None ): if args.line_by_line: if ref_path is not None: if not args.whole_word_mask or not args.mlm: raise ValueError("""You need to set world whole masking and mlm to True for Chinese Whole Word Mask""" ) return LineByLineWithRefDataset( tokenizer=UpperCamelCase__ , file_path=UpperCamelCase__ , block_size=args.block_size , ref_path=UpperCamelCase__ , ) return LineByLineTextDataset(tokenizer=UpperCamelCase__ , file_path=UpperCamelCase__ , block_size=args.block_size ) else: return TextDataset( tokenizer=UpperCamelCase__ , file_path=UpperCamelCase__ , block_size=args.block_size , overwrite_cache=args.overwrite_cache , cache_dir=UpperCamelCase__ , ) if evaluate: return _dataset(args.eval_data_file , args.eval_ref_file ) elif args.train_data_files: return ConcatDataset([_dataset(UpperCamelCase__ ) for f in glob(args.train_data_files )] ) else: return _dataset(args.train_data_file , args.train_ref_file ) def lowerCAmelCase__ ( ): '''simple docstring''' # See all possible arguments in src/transformers/training_args.py # or by passing the --help flag to this script. # We now keep distinct sets of args, for a cleaner separation of concerns. _a : Any = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) _a , _a , _a : List[str] = parser.parse_args_into_dataclasses() if data_args.eval_data_file is None and training_args.do_eval: raise ValueError( """Cannot do evaluation without an evaluation data file. Either supply a file to --eval_data_file """ """or remove the --do_eval argument.""" ) if ( os.path.exists(training_args.output_dir ) and os.listdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir ): raise ValueError( F"""Output directory ({training_args.output_dir}) already exists and is not empty. Use""" """ --overwrite_output_dir to overcome.""" ) # Setup logging logging.basicConfig( format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""" , datefmt="""%m/%d/%Y %H:%M:%S""" , level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN , ) logger.warning( """Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s""" , training_args.local_rank , training_args.device , training_args.n_gpu , bool(training_args.local_rank != -1 ) , training_args.fpaa , ) # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank ): transformers.utils.logging.set_verbosity_info() transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() logger.info("""Training/evaluation parameters %s""" , UpperCamelCase__ ) # Set seed set_seed(training_args.seed ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. if model_args.config_name: _a : str = AutoConfig.from_pretrained(model_args.config_name , cache_dir=model_args.cache_dir ) elif model_args.model_name_or_path: _a : Union[str, Any] = AutoConfig.from_pretrained(model_args.model_name_or_path , cache_dir=model_args.cache_dir ) else: _a : str = CONFIG_MAPPING[model_args.model_type]() logger.warning("""You are instantiating a new config instance from scratch.""" ) if model_args.tokenizer_name: _a : List[str] = AutoTokenizer.from_pretrained(model_args.tokenizer_name , cache_dir=model_args.cache_dir ) elif model_args.model_name_or_path: _a : Union[str, Any] = AutoTokenizer.from_pretrained(model_args.model_name_or_path , cache_dir=model_args.cache_dir ) else: raise ValueError( """You are instantiating a new tokenizer from scratch. This is not supported, but you can do it from another""" """ script, save it,and load it from here, using --tokenizer_name""" ) if model_args.model_name_or_path: _a : Optional[Any] = AutoModelWithLMHead.from_pretrained( model_args.model_name_or_path , from_tf=bool(""".ckpt""" in model_args.model_name_or_path ) , config=UpperCamelCase__ , cache_dir=model_args.cache_dir , ) else: logger.info("""Training new model from scratch""" ) _a : List[Any] = AutoModelWithLMHead.from_config(UpperCamelCase__ ) model.resize_token_embeddings(len(UpperCamelCase__ ) ) if config.model_type in ["bert", "roberta", "distilbert", "camembert"] and not data_args.mlm: raise ValueError( """BERT and RoBERTa-like models do not have LM heads but masked LM heads. They must be run using the""" """--mlm flag (masked language modeling).""" ) if data_args.block_size <= 0: _a : int = tokenizer.max_len # Our input block size will be the max possible for the model else: _a : Optional[Any] = min(data_args.block_size , tokenizer.max_len ) # Get datasets _a : Optional[Any] = ( get_dataset(UpperCamelCase__ , tokenizer=UpperCamelCase__ , cache_dir=model_args.cache_dir ) if training_args.do_train else None ) _a : Optional[int] = ( get_dataset(UpperCamelCase__ , tokenizer=UpperCamelCase__ , evaluate=UpperCamelCase__ , cache_dir=model_args.cache_dir ) if training_args.do_eval else None ) if config.model_type == "xlnet": _a : Any = DataCollatorForPermutationLanguageModeling( tokenizer=UpperCamelCase__ , plm_probability=data_args.plm_probability , max_span_length=data_args.max_span_length , ) else: if data_args.mlm and data_args.whole_word_mask: _a : Union[str, Any] = DataCollatorForWholeWordMask( tokenizer=UpperCamelCase__ , mlm_probability=data_args.mlm_probability ) else: _a : str = DataCollatorForLanguageModeling( tokenizer=UpperCamelCase__ , mlm=data_args.mlm , mlm_probability=data_args.mlm_probability ) # Initialize our Trainer _a : Union[str, Any] = Trainer( model=UpperCamelCase__ , args=UpperCamelCase__ , data_collator=UpperCamelCase__ , train_dataset=UpperCamelCase__ , eval_dataset=UpperCamelCase__ , prediction_loss_only=UpperCamelCase__ , ) # Training if training_args.do_train: _a : Optional[Any] = ( model_args.model_name_or_path if model_args.model_name_or_path is not None and os.path.isdir(model_args.model_name_or_path ) else None ) trainer.train(model_path=UpperCamelCase__ ) trainer.save_model() # For convenience, we also re-save the tokenizer to the same directory, # so that you can share your model easily on huggingface.co/models =) if trainer.is_world_master(): tokenizer.save_pretrained(training_args.output_dir ) # Evaluation _a : Union[str, Any] = {} if training_args.do_eval: logger.info("""*** Evaluate ***""" ) _a : int = trainer.evaluate() _a : Dict = math.exp(eval_output["""eval_loss"""] ) _a : Union[str, Any] = {"""perplexity""": perplexity} _a : Optional[Any] = os.path.join(training_args.output_dir , """eval_results_lm.txt""" ) if trainer.is_world_master(): with open(UpperCamelCase__ , """w""" ) as writer: logger.info("""***** Eval results *****""" ) for key in sorted(result.keys() ): logger.info(""" %s = %s""" , UpperCamelCase__ , str(result[key] ) ) writer.write("""%s = %s\n""" % (key, str(result[key] )) ) results.update(UpperCamelCase__ ) return results def lowerCAmelCase__ ( UpperCamelCase__ ): '''simple docstring''' # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
324
1
"""simple docstring""" import argparse import collections import os import re import tempfile import pandas as pd from datasets import Dataset from huggingface_hub import hf_hub_download, upload_folder from transformers.utils import direct_transformers_import # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/update_metadata.py _snake_case = 'src/transformers' # This is to make sure the transformers module imported is the one in the repo. _snake_case = direct_transformers_import(TRANSFORMERS_PATH) # Regexes that match TF/Flax/PT model names. _snake_case = re.compile(r'TF(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)') _snake_case = re.compile(r'Flax(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)') # Will match any TF or Flax model too so need to be in an else branch afterthe two previous regexes. _snake_case = re.compile(r'(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)') # Fill this with tuples (pipeline_tag, model_mapping, auto_model) _snake_case = [ ('pretraining', 'MODEL_FOR_PRETRAINING_MAPPING_NAMES', 'AutoModelForPreTraining'), ('feature-extraction', 'MODEL_MAPPING_NAMES', 'AutoModel'), ('audio-classification', 'MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES', 'AutoModelForAudioClassification'), ('text-generation', 'MODEL_FOR_CAUSAL_LM_MAPPING_NAMES', 'AutoModelForCausalLM'), ('automatic-speech-recognition', 'MODEL_FOR_CTC_MAPPING_NAMES', 'AutoModelForCTC'), ('image-classification', 'MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES', 'AutoModelForImageClassification'), ('image-segmentation', 'MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES', 'AutoModelForImageSegmentation'), ('fill-mask', 'MODEL_FOR_MASKED_LM_MAPPING_NAMES', 'AutoModelForMaskedLM'), ('object-detection', 'MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES', 'AutoModelForObjectDetection'), ( 'zero-shot-object-detection', 'MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES', 'AutoModelForZeroShotObjectDetection', ), ('question-answering', 'MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES', 'AutoModelForQuestionAnswering'), ('text2text-generation', 'MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES', 'AutoModelForSeq2SeqLM'), ('text-classification', 'MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES', 'AutoModelForSequenceClassification'), ('automatic-speech-recognition', 'MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES', 'AutoModelForSpeechSeq2Seq'), ( 'table-question-answering', 'MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING_NAMES', 'AutoModelForTableQuestionAnswering', ), ('token-classification', 'MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES', 'AutoModelForTokenClassification'), ('multiple-choice', 'MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES', 'AutoModelForMultipleChoice'), ( 'next-sentence-prediction', 'MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING_NAMES', 'AutoModelForNextSentencePrediction', ), ( 'audio-frame-classification', 'MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES', 'AutoModelForAudioFrameClassification', ), ('audio-xvector', 'MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES', 'AutoModelForAudioXVector'), ( 'document-question-answering', 'MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES', 'AutoModelForDocumentQuestionAnswering', ), ( 'visual-question-answering', 'MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING_NAMES', 'AutoModelForVisualQuestionAnswering', ), ('image-to-text', 'MODEL_FOR_FOR_VISION_2_SEQ_MAPPING_NAMES', 'AutoModelForVision2Seq'), ( 'zero-shot-image-classification', 'MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING_NAMES', 'AutoModelForZeroShotImageClassification', ), ('depth-estimation', 'MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES', 'AutoModelForDepthEstimation'), ('video-classification', 'MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING_NAMES', 'AutoModelForVideoClassification'), ('mask-generation', 'MODEL_FOR_MASK_GENERATION_MAPPING_NAMES', 'AutoModelForMaskGeneration'), ] def lowerCAmelCase__ ( UpperCamelCase__ ): '''simple docstring''' _a : Dict = re.finditer(""".+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)""" , UpperCamelCase__ ) return [m.group(0 ) for m in matches] def lowerCAmelCase__ ( ): '''simple docstring''' _a : Tuple = transformers_module.models.auto.configuration_auto.CONFIG_MAPPING_NAMES _a : Optional[int] = { config.replace("""Config""" , """""" ): model_type for model_type, config in config_maping_names.items() } # Dictionaries flagging if each model prefix has a backend in PT/TF/Flax. _a : List[Any] = collections.defaultdict(UpperCamelCase__ ) _a : List[str] = collections.defaultdict(UpperCamelCase__ ) _a : Tuple = collections.defaultdict(UpperCamelCase__ ) # Let's lookup through all transformers object (once) and find if models are supported by a given backend. for attr_name in dir(UpperCamelCase__ ): _a : str = None if _re_tf_models.match(UpperCamelCase__ ) is not None: _a : List[Any] = tf_models _a : int = _re_tf_models.match(UpperCamelCase__ ).groups()[0] elif _re_flax_models.match(UpperCamelCase__ ) is not None: _a : Any = flax_models _a : Any = _re_flax_models.match(UpperCamelCase__ ).groups()[0] elif _re_pt_models.match(UpperCamelCase__ ) is not None: _a : int = pt_models _a : int = _re_pt_models.match(UpperCamelCase__ ).groups()[0] if lookup_dict is not None: while len(UpperCamelCase__ ) > 0: if attr_name in model_prefix_to_model_type: _a : Optional[int] = True break # Try again after removing the last word in the name _a : List[Any] = """""".join(camel_case_split(UpperCamelCase__ )[:-1] ) _a : Optional[int] = set(list(pt_models.keys() ) + list(tf_models.keys() ) + list(flax_models.keys() ) ) _a : Dict = list(UpperCamelCase__ ) all_models.sort() _a : str = {"""model_type""": all_models} _a : List[Any] = [pt_models[t] for t in all_models] _a : str = [tf_models[t] for t in all_models] _a : Optional[int] = [flax_models[t] for t in all_models] # Now let's use the auto-mapping names to make sure _a : str = {} for t in all_models: if t in transformers_module.models.auto.processing_auto.PROCESSOR_MAPPING_NAMES: _a : List[str] = """AutoProcessor""" elif t in transformers_module.models.auto.tokenization_auto.TOKENIZER_MAPPING_NAMES: _a : str = """AutoTokenizer""" elif t in transformers_module.models.auto.feature_extraction_auto.FEATURE_EXTRACTOR_MAPPING_NAMES: _a : int = """AutoFeatureExtractor""" else: # Default to AutoTokenizer if a model has nothing, for backward compatibility. _a : int = """AutoTokenizer""" _a : Any = [processors[t] for t in all_models] return pd.DataFrame(UpperCamelCase__ ) def lowerCAmelCase__ ( UpperCamelCase__ ): '''simple docstring''' _a : List[Any] = [ transformers_module.models.auto.modeling_auto, transformers_module.models.auto.modeling_tf_auto, transformers_module.models.auto.modeling_flax_auto, ] for pipeline_tag, model_mapping, auto_class in PIPELINE_TAGS_AND_AUTO_MODELS: _a : List[Any] = [model_mapping, F"""TF_{model_mapping}""", F"""FLAX_{model_mapping}"""] _a : Union[str, Any] = [auto_class, F"""TF_{auto_class}""", F"""Flax_{auto_class}"""] # Loop through all three frameworks for module, cls, mapping in zip(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): # The type of pipeline may not exist in this framework if not hasattr(UpperCamelCase__ , UpperCamelCase__ ): continue # First extract all model_names _a : str = [] for name in getattr(UpperCamelCase__ , UpperCamelCase__ ).values(): if isinstance(UpperCamelCase__ , UpperCamelCase__ ): model_names.append(UpperCamelCase__ ) else: model_names.extend(list(UpperCamelCase__ ) ) # Add pipeline tag and auto model class for those models table.update({model_name: (pipeline_tag, cls) for model_name in model_names} ) return table def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' _a : Dict = get_frameworks_table() _a : Optional[Any] = Dataset.from_pandas(UpperCamelCase__ ) _a : Any = hf_hub_download( """huggingface/transformers-metadata""" , """pipeline_tags.json""" , repo_type="""dataset""" , token=UpperCamelCase__ ) _a : List[Any] = Dataset.from_json(UpperCamelCase__ ) _a : List[str] = { tags_dataset[i]["""model_class"""]: (tags_dataset[i]["""pipeline_tag"""], tags_dataset[i]["""auto_class"""]) for i in range(len(UpperCamelCase__ ) ) } _a : str = update_pipeline_and_auto_class_table(UpperCamelCase__ ) # Sort the model classes to avoid some nondeterministic updates to create false update commits. _a : int = sorted(table.keys() ) _a : Union[str, Any] = pd.DataFrame( { """model_class""": model_classes, """pipeline_tag""": [table[m][0] for m in model_classes], """auto_class""": [table[m][1] for m in model_classes], } ) _a : Dict = Dataset.from_pandas(UpperCamelCase__ ) with tempfile.TemporaryDirectory() as tmp_dir: frameworks_dataset.to_json(os.path.join(UpperCamelCase__ , """frameworks.json""" ) ) tags_dataset.to_json(os.path.join(UpperCamelCase__ , """pipeline_tags.json""" ) ) if commit_sha is not None: _a : List[str] = ( F"""Update with commit {commit_sha}\n\nSee: """ F"""https://github.com/huggingface/transformers/commit/{commit_sha}""" ) else: _a : Optional[Any] = """Update""" upload_folder( repo_id="""huggingface/transformers-metadata""" , folder_path=UpperCamelCase__ , repo_type="""dataset""" , token=UpperCamelCase__ , commit_message=UpperCamelCase__ , ) def lowerCAmelCase__ ( ): '''simple docstring''' _a : List[str] = {tag: cls for tag, _, cls in PIPELINE_TAGS_AND_AUTO_MODELS} _a : Any = transformers_module.pipelines.SUPPORTED_TASKS _a : List[str] = [] for key in pipeline_tasks: if key not in in_table: _a : Tuple = pipeline_tasks[key]["""pt"""] if isinstance(UpperCamelCase__ , (list, tuple) ): _a : Dict = model[0] _a : List[str] = model.__name__ if model not in in_table.values(): missing.append(UpperCamelCase__ ) if len(UpperCamelCase__ ) > 0: _a : Union[str, Any] = """, """.join(UpperCamelCase__ ) raise ValueError( """The following pipeline tags are not present in the `PIPELINE_TAGS_AND_AUTO_MODELS` constant inside """ F"""`utils/update_metadata.py`: {msg}. Please add them!""" ) if __name__ == "__main__": _snake_case = argparse.ArgumentParser() parser.add_argument('--token', type=str, help='The token to use to push to the transformers-metadata dataset.') parser.add_argument('--commit_sha', type=str, help='The sha of the commit going with this update.') parser.add_argument('--check-only', action='store_true', help='Activate to just check all pipelines are present.') _snake_case = parser.parse_args() if args.check_only: check_pipeline_tags() else: update_metadata(args.token, args.commit_sha)
324
"""simple docstring""" import argparse import os from pathlib import Path from typing import Dict import tensorflow as tf import torch from tqdm import tqdm from transformers import PegasusConfig, PegasusForConditionalGeneration, PegasusTokenizer from transformers.models.pegasus.configuration_pegasus import DEFAULTS, task_specific_params _snake_case = [ # replace left string with right string to get the relevant state_dict key (identical state dict to bart) ['memory_attention', 'encoder_attn'], ['attention', 'attn'], ['/', '.'], ['.LayerNorm.gamma', '_layer_norm.weight'], ['.LayerNorm.beta', '_layer_norm.bias'], ['r.layer_', 'r.layers.'], ['output_proj', 'out_proj'], ['ffn.dense_1.', 'fc2.'], ['ffn.dense.', 'fc1.'], ['ffn_layer_norm', 'final_layer_norm'], ['kernel', 'weight'], ['encoder_layer_norm.', 'encoder.layer_norm.'], ['decoder_layer_norm.', 'decoder.layer_norm.'], ['embeddings.weights', 'shared.weight'], ] def lowerCAmelCase__ ( UpperCamelCase__ ): '''simple docstring''' for pegasus_name, hf_name in PATTERNS: _a : Optional[Any] = k.replace(UpperCamelCase__ , UpperCamelCase__ ) return k def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' _a : Union[str, Any] = DEFAULTS.copy() cfg_kwargs.update(UpperCamelCase__ ) _a : Optional[Any] = PegasusConfig(**UpperCamelCase__ ) _a : Tuple = PegasusForConditionalGeneration(UpperCamelCase__ ) _a : str = torch_model.model.state_dict() _a : Union[str, Any] = {} for k, v in tf_weights.items(): _a : Any = rename_state_dict_key(UpperCamelCase__ ) if new_k not in sd: raise ValueError(F"""could not find new key {new_k} in state dict. (converted from {k})""" ) if "dense" in k or "proj" in new_k: _a : str = v.T _a : int = torch.tensor(UpperCamelCase__ , dtype=sd[new_k].dtype ) assert v.shape == sd[new_k].shape, F"""{new_k}, {k}, {v.shape}, {sd[new_k].shape}""" # make sure embedding.padding_idx is respected _a : Union[str, Any] = torch.zeros_like(mapping["""shared.weight"""][cfg.pad_token_id + 1] ) _a : str = mapping["""shared.weight"""] _a : Union[str, Any] = mapping["""shared.weight"""] _a : Optional[Any] = {k: torch.zeros_like(UpperCamelCase__ ) for k, v in sd.items() if k.endswith("""bias""" ) and k not in mapping} mapping.update(**UpperCamelCase__ ) _a , _a : int = torch_model.model.load_state_dict(UpperCamelCase__ , strict=UpperCamelCase__ ) _a : Optional[Any] = [ k for k in missing if k not in ["""encoder.embed_positions.weight""", """decoder.embed_positions.weight"""] ] assert unexpected_missing == [], F"""no matches found for the following torch keys {unexpected_missing}""" assert extra == [], F"""no matches found for the following tf keys {extra}""" return torch_model def lowerCAmelCase__ ( UpperCamelCase__="./ckpt/aeslc/model.ckpt-32000" ): '''simple docstring''' _a : List[Any] = tf.train.list_variables(UpperCamelCase__ ) _a : Optional[int] = {} _a : Dict = ["""Adafactor""", """global_step"""] for name, shape in tqdm(UpperCamelCase__ , desc="""converting tf checkpoint to dict""" ): _a : Optional[Any] = any(pat in name for pat in ignore_name ) if skip_key: continue _a : str = tf.train.load_variable(UpperCamelCase__ , UpperCamelCase__ ) _a : int = array return tf_weights def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' # save tokenizer first _a : Dict = Path(UpperCamelCase__ ).parent.name _a : Optional[Any] = task_specific_params[F"""summarization_{dataset}"""]["""max_position_embeddings"""] _a : Tuple = PegasusTokenizer.from_pretrained("""sshleifer/pegasus""" , model_max_length=UpperCamelCase__ ) assert tok.model_max_length == desired_max_model_length tok.save_pretrained(UpperCamelCase__ ) # convert model _a : List[Any] = get_tf_weights_as_numpy(UpperCamelCase__ ) _a : Dict = task_specific_params[F"""summarization_{dataset}"""] if dataset == "large": _a : Tuple = task_specific_params _a : Optional[int] = convert_pegasus(UpperCamelCase__ , UpperCamelCase__ ) torch_model.save_pretrained(UpperCamelCase__ ) _a : Dict = torch_model.state_dict() sd.pop("""model.decoder.embed_positions.weight""" ) sd.pop("""model.encoder.embed_positions.weight""" ) torch.save(UpperCamelCase__ , Path(UpperCamelCase__ ) / """pytorch_model.bin""" ) if __name__ == "__main__": _snake_case = argparse.ArgumentParser() # Required parameters parser.add_argument('tf_ckpt_path', type=str, help='passed to tf.train.list_variables') parser.add_argument('save_dir', default=None, type=str, help='Path to the output PyTorch model.') _snake_case = parser.parse_args() if args.save_dir is None: _snake_case = Path(args.tf_ckpt_path).parent.name _snake_case = os.path.join('pegasus', dataset) convert_pegasus_ckpt_to_pytorch(args.tf_ckpt_path, args.save_dir)
324
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) _snake_case = { 'configuration_convbert': ['CONVBERT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'ConvBertConfig', 'ConvBertOnnxConfig'], 'tokenization_convbert': ['ConvBertTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _snake_case = ['ConvBertTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _snake_case = [ 'CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'ConvBertForMaskedLM', 'ConvBertForMultipleChoice', 'ConvBertForQuestionAnswering', 'ConvBertForSequenceClassification', 'ConvBertForTokenClassification', 'ConvBertLayer', 'ConvBertModel', 'ConvBertPreTrainedModel', 'load_tf_weights_in_convbert', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _snake_case = [ 'TF_CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFConvBertForMaskedLM', 'TFConvBertForMultipleChoice', 'TFConvBertForQuestionAnswering', 'TFConvBertForSequenceClassification', 'TFConvBertForTokenClassification', 'TFConvBertLayer', 'TFConvBertModel', 'TFConvBertPreTrainedModel', ] if TYPE_CHECKING: from .configuration_convbert import CONVBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ConvBertConfig, ConvBertOnnxConfig from .tokenization_convbert import ConvBertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_convbert_fast import ConvBertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_convbert import ( CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST, ConvBertForMaskedLM, ConvBertForMultipleChoice, ConvBertForQuestionAnswering, ConvBertForSequenceClassification, ConvBertForTokenClassification, ConvBertLayer, ConvBertModel, ConvBertPreTrainedModel, load_tf_weights_in_convbert, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_convbert import ( TF_CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFConvBertForMaskedLM, TFConvBertForMultipleChoice, TFConvBertForQuestionAnswering, TFConvBertForSequenceClassification, TFConvBertForTokenClassification, TFConvBertLayer, TFConvBertModel, TFConvBertPreTrainedModel, ) else: import sys _snake_case = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
324
"""simple docstring""" import gc import random import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTextModelWithProjection, CLIPTokenizer from diffusers import ( AutoencoderKL, DiffusionPipeline, EulerDiscreteScheduler, StableDiffusionXLImgaImgPipeline, UNetaDConditionModel, ) from diffusers.utils import floats_tensor, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import ( IMAGE_TO_IMAGE_IMAGE_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class UpperCamelCase ( snake_case_ , snake_case_ , unittest.TestCase ): UpperCamelCase : Union[str, Any] = StableDiffusionXLImgaImgPipeline UpperCamelCase : Any = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'''height''', '''width'''} UpperCamelCase : Tuple = PipelineTesterMixin.required_optional_params - {'''latents'''} UpperCamelCase : int = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS UpperCamelCase : Optional[Any] = IMAGE_TO_IMAGE_IMAGE_PARAMS UpperCamelCase : Optional[Any] = IMAGE_TO_IMAGE_IMAGE_PARAMS def _lowercase ( self : Any ) -> List[Any]: torch.manual_seed(0 ) _a : str = 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""") , attention_head_dim=(2, 4) , use_linear_projection=UpperCAmelCase__ , addition_embed_type="""text_time""" , addition_time_embed_dim=8 , transformer_layers_per_block=(1, 2) , projection_class_embeddings_input_dim=80 , cross_attention_dim=64 , ) _a : Union[str, Any] = EulerDiscreteScheduler( beta_start=0.0_0_0_8_5 , beta_end=0.0_1_2 , steps_offset=1 , beta_schedule="""scaled_linear""" , timestep_spacing="""leading""" , ) torch.manual_seed(0 ) _a : List[str] = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , sample_size=128 , ) torch.manual_seed(0 ) _a : int = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , hidden_act="""gelu""" , projection_dim=32 , ) _a : Tuple = CLIPTextModel(UpperCAmelCase__ ) _a : str = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" , local_files_only=UpperCAmelCase__ ) _a : Dict = CLIPTextModelWithProjection(UpperCAmelCase__ ) _a : Dict = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" , local_files_only=UpperCAmelCase__ ) _a : Any = { """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """text_encoder_2""": text_encoder_a, """tokenizer_2""": tokenizer_a, # "safety_checker": None, # "feature_extractor": None, } return components def _lowercase ( self : List[Any] , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : int=0 ) -> int: _a : Dict = floats_tensor((1, 3, 32, 32) , rng=random.Random(UpperCAmelCase__ ) ).to(UpperCAmelCase__ ) _a : Any = image / 2 + 0.5 if str(UpperCAmelCase__ ).startswith("""mps""" ): _a : Any = torch.manual_seed(UpperCAmelCase__ ) else: _a : Tuple = torch.Generator(device=UpperCAmelCase__ ).manual_seed(UpperCAmelCase__ ) _a : Optional[Any] = { """prompt""": """A painting of a squirrel eating a burger""", """image""": image, """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 5.0, """output_type""": """numpy""", """strength""": 0.7_5, } return inputs def _lowercase ( self : Any ) -> List[Any]: _a : Union[str, Any] = """cpu""" # ensure determinism for the device-dependent torch.Generator _a : Dict = self.get_dummy_components() _a : List[Any] = StableDiffusionXLImgaImgPipeline(**UpperCAmelCase__ ) _a : Union[str, Any] = sd_pipe.to(UpperCAmelCase__ ) sd_pipe.set_progress_bar_config(disable=UpperCAmelCase__ ) _a : List[str] = self.get_dummy_inputs(UpperCAmelCase__ ) _a : List[str] = sd_pipe(**UpperCAmelCase__ ).images _a : Union[str, Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) _a : List[str] = np.array([0.4_6_5_6, 0.4_8_4_0, 0.4_4_3_9, 0.6_6_9_8, 0.5_5_7_4, 0.4_5_2_4, 0.5_7_9_9, 0.5_9_4_3, 0.5_1_6_5] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def _lowercase ( self : Any ) -> Any: super().test_attention_slicing_forward_pass(expected_max_diff=3E-3 ) def _lowercase ( self : List[Any] ) -> Optional[Any]: super().test_inference_batch_single_identical(expected_max_diff=3E-3 ) def _lowercase ( self : Any ) -> Any: pass def _lowercase ( self : Tuple ) -> Union[str, Any]: _a : int = self.get_dummy_components() _a : Any = StableDiffusionXLImgaImgPipeline(**UpperCAmelCase__ ) _a : Dict = sd_pipe.to(UpperCAmelCase__ ) _a : List[str] = sd_pipe.to(UpperCAmelCase__ ) sd_pipe.set_progress_bar_config(disable=UpperCAmelCase__ ) # forward without prompt embeds _a : int = self.get_dummy_inputs(UpperCAmelCase__ ) _a : List[str] = 3 * ["""this is a negative prompt"""] _a : Dict = negative_prompt _a : Dict = 3 * [inputs["""prompt"""]] _a : Optional[Any] = sd_pipe(**UpperCAmelCase__ ) _a : Tuple = output.images[0, -3:, -3:, -1] # forward with prompt embeds _a : int = self.get_dummy_inputs(UpperCAmelCase__ ) _a : Union[str, Any] = 3 * ["""this is a negative prompt"""] _a : int = 3 * [inputs.pop("""prompt""" )] ( ( _a ) , ( _a ) , ( _a ) , ( _a ) , ) : List[str] = sd_pipe.encode_prompt(UpperCAmelCase__ , negative_prompt=UpperCAmelCase__ ) _a : Tuple = sd_pipe( **UpperCAmelCase__ , prompt_embeds=UpperCAmelCase__ , negative_prompt_embeds=UpperCAmelCase__ , pooled_prompt_embeds=UpperCAmelCase__ , negative_pooled_prompt_embeds=UpperCAmelCase__ , ) _a : Dict = output.images[0, -3:, -3:, -1] # make sure that it's equal assert np.abs(image_slice_a.flatten() - image_slice_a.flatten() ).max() < 1E-4 @slow @require_torch_gpu class UpperCamelCase ( unittest.TestCase ): def _lowercase ( self : List[str] ) -> Union[str, Any]: super().tearDown() gc.collect() torch.cuda.empty_cache() def _lowercase ( self : List[str] , UpperCAmelCase__ : str , UpperCAmelCase__ : str="cpu" , UpperCAmelCase__ : str=torch.floataa , UpperCAmelCase__ : List[Any]=0 ) -> List[str]: _a : List[str] = torch.Generator(device=UpperCAmelCase__ ).manual_seed(UpperCAmelCase__ ) _a : Union[str, Any] = np.random.RandomState(UpperCAmelCase__ ).standard_normal((1, 4, 64, 64) ) _a : List[Any] = torch.from_numpy(UpperCAmelCase__ ).to(device=UpperCAmelCase__ , dtype=UpperCAmelCase__ ) _a : Any = { """prompt""": """a photograph of an astronaut riding a horse""", """latents""": latents, """generator""": generator, """num_inference_steps""": 3, """guidance_scale""": 7.5, """output_type""": """numpy""", } return inputs def _lowercase ( self : int ) -> Union[str, Any]: _a : Union[str, Any] = DiffusionPipeline.from_pretrained("""stabilityai/stable-diffusion-2-base""" ) pipe.to(UpperCAmelCase__ ) pipe.set_progress_bar_config(disable=UpperCAmelCase__ ) _a : List[str] = self.get_inputs(UpperCAmelCase__ ) _a : Tuple = pipe(**UpperCAmelCase__ ).images _a : List[str] = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 512, 512, 3) _a : int = np.array([0.4_9_4_9_3, 0.4_7_8_9_6, 0.4_0_7_9_8, 0.5_4_2_1_4, 0.5_3_2_1_2, 0.4_8_2_0_2, 0.4_7_6_5_6, 0.4_6_3_2_9, 0.4_8_5_0_6] ) assert np.abs(image_slice - expected_slice ).max() < 7E-3
324
1
"""simple docstring""" import fire from utils import calculate_rouge, save_json def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__=None , **UpperCamelCase__ ): '''simple docstring''' _a : Union[str, Any] = [x.strip() for x in open(UpperCamelCase__ ).readlines()] _a : int = [x.strip() for x in open(UpperCamelCase__ ).readlines()][: len(UpperCamelCase__ )] _a : int = calculate_rouge(UpperCamelCase__ , UpperCamelCase__ , **UpperCamelCase__ ) if save_path is not None: save_json(UpperCamelCase__ , UpperCamelCase__ , indent=UpperCamelCase__ ) return metrics # these print nicely if __name__ == "__main__": fire.Fire(calculate_rouge_path)
324
"""simple docstring""" import argparse import json from dataclasses import dataclass, field from functools import partial from pathlib import Path from typing import List import timm import torch import torch.nn as nn from huggingface_hub import hf_hub_download from torch import Tensor from transformers import AutoImageProcessor, ResNetConfig, ResNetForImageClassification from transformers.utils import logging logging.set_verbosity_info() _snake_case = logging.get_logger() @dataclass class UpperCamelCase : UpperCamelCase : nn.Module UpperCamelCase : List[nn.Module] = field(default_factory=snake_case_ ) UpperCamelCase : list = field(default_factory=snake_case_ ) def _lowercase ( self : List[Any] , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : Tensor , UpperCAmelCase__ : Tensor ) -> Any: _a : int = len(list(m.modules() ) ) == 1 or isinstance(UpperCAmelCase__ , nn.Convad ) or isinstance(UpperCAmelCase__ , nn.BatchNormad ) if has_not_submodules: self.traced.append(UpperCAmelCase__ ) def __call__( self : Tuple , UpperCAmelCase__ : Tensor ) -> Tuple: for m in self.module.modules(): self.handles.append(m.register_forward_hook(self._forward_hook ) ) self.module(UpperCAmelCase__ ) [x.remove() for x in self.handles] return self @property def _lowercase ( self : Optional[int] ) -> int: # check the len of the state_dict keys to see if we have learnable params return list(filter(lambda UpperCAmelCase__ : len(list(x.state_dict().keys() ) ) > 0 , self.traced ) ) @dataclass class UpperCamelCase : UpperCamelCase : nn.Module UpperCamelCase : nn.Module UpperCamelCase : int = 0 UpperCamelCase : List = field(default_factory=snake_case_ ) UpperCamelCase : List = field(default_factory=snake_case_ ) def __call__( self : Optional[Any] , UpperCAmelCase__ : Tensor ) -> Tuple: _a : Union[str, Any] = Tracker(self.dest )(UpperCAmelCase__ ).parametrized _a : List[Any] = Tracker(self.src )(UpperCAmelCase__ ).parametrized _a : Tuple = list(filter(lambda UpperCAmelCase__ : type(UpperCAmelCase__ ) not in self.src_skip , UpperCAmelCase__ ) ) _a : Union[str, Any] = list(filter(lambda UpperCAmelCase__ : type(UpperCAmelCase__ ) not in self.dest_skip , UpperCAmelCase__ ) ) if len(UpperCAmelCase__ ) != len(UpperCAmelCase__ ): raise Exception( f"""Numbers of operations are different. Source module has {len(UpperCAmelCase__ )} operations while""" f""" destination module has {len(UpperCAmelCase__ )}.""" ) for dest_m, src_m in zip(UpperCAmelCase__ , UpperCAmelCase__ ): dest_m.load_state_dict(src_m.state_dict() ) if self.verbose == 1: print(f"""Transfered from={src_m} to={dest_m}""" ) def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = True ): '''simple docstring''' print(F"""Converting {name}...""" ) with torch.no_grad(): _a : List[str] = timm.create_model(UpperCamelCase__ , pretrained=UpperCamelCase__ ).eval() _a : str = ResNetForImageClassification(UpperCamelCase__ ).eval() _a : List[str] = ModuleTransfer(src=UpperCamelCase__ , dest=UpperCamelCase__ ) _a : List[str] = torch.randn((1, 3, 2_2_4, 2_2_4) ) module_transfer(UpperCamelCase__ ) assert torch.allclose(from_model(UpperCamelCase__ ) , our_model(UpperCamelCase__ ).logits ), "The model logits don't match the original one." _a : Dict = F"""resnet{'-'.join(name.split('resnet' ) )}""" print(UpperCamelCase__ ) if push_to_hub: our_model.push_to_hub( repo_path_or_name=save_directory / checkpoint_name , commit_message="""Add model""" , use_temp_dir=UpperCamelCase__ , ) # we can use the convnext one _a : Optional[Any] = AutoImageProcessor.from_pretrained("""facebook/convnext-base-224-22k-1k""" ) image_processor.push_to_hub( repo_path_or_name=save_directory / checkpoint_name , commit_message="""Add image processor""" , use_temp_dir=UpperCamelCase__ , ) print(F"""Pushed {checkpoint_name}""" ) def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ = None , UpperCamelCase__ = True ): '''simple docstring''' _a : Any = """imagenet-1k-id2label.json""" _a : Optional[int] = 1_0_0_0 _a : Any = (1, num_labels) _a : Union[str, Any] = """huggingface/label-files""" _a : Tuple = num_labels _a : Optional[int] = json.load(open(hf_hub_download(UpperCamelCase__ , UpperCamelCase__ , repo_type="""dataset""" ) , """r""" ) ) _a : Optional[Any] = {int(UpperCamelCase__ ): v for k, v in idalabel.items()} _a : Any = idalabel _a : Tuple = {v: k for k, v in idalabel.items()} _a : List[str] = partial(UpperCamelCase__ , num_labels=UpperCamelCase__ , idalabel=UpperCamelCase__ , labelaid=UpperCamelCase__ ) _a : Union[str, Any] = { """resnet18""": ImageNetPreTrainedConfig( depths=[2, 2, 2, 2] , hidden_sizes=[6_4, 1_2_8, 2_5_6, 5_1_2] , layer_type="""basic""" ), """resnet26""": ImageNetPreTrainedConfig( depths=[2, 2, 2, 2] , hidden_sizes=[2_5_6, 5_1_2, 1_0_2_4, 2_0_4_8] , layer_type="""bottleneck""" ), """resnet34""": ImageNetPreTrainedConfig( depths=[3, 4, 6, 3] , hidden_sizes=[6_4, 1_2_8, 2_5_6, 5_1_2] , layer_type="""basic""" ), """resnet50""": ImageNetPreTrainedConfig( depths=[3, 4, 6, 3] , hidden_sizes=[2_5_6, 5_1_2, 1_0_2_4, 2_0_4_8] , layer_type="""bottleneck""" ), """resnet101""": ImageNetPreTrainedConfig( depths=[3, 4, 2_3, 3] , hidden_sizes=[2_5_6, 5_1_2, 1_0_2_4, 2_0_4_8] , layer_type="""bottleneck""" ), """resnet152""": ImageNetPreTrainedConfig( depths=[3, 8, 3_6, 3] , hidden_sizes=[2_5_6, 5_1_2, 1_0_2_4, 2_0_4_8] , layer_type="""bottleneck""" ), } if model_name: convert_weight_and_push(UpperCamelCase__ , names_to_config[model_name] , UpperCamelCase__ , UpperCamelCase__ ) else: for model_name, config in names_to_config.items(): convert_weight_and_push(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) return config, expected_shape if __name__ == "__main__": _snake_case = argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default=None, type=str, help=( 'The name of the model you wish to convert, it must be one of the supported resnet* architecture,' ' currently: resnet18,26,34,50,101,152. If `None`, all of them will the converted.' ), ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=Path, required=True, help='Path to the output PyTorch model directory.', ) parser.add_argument( '--push_to_hub', default=True, type=bool, required=False, help='If True, push model and image processor to the hub.', ) _snake_case = parser.parse_args() _snake_case = args.pytorch_dump_folder_path pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True) convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)
324
1
"""simple docstring""" from typing import Callable, List, Optional, Tuple, Union import torch from transformers import CLIPTextModel, CLIPTokenizer from ...configuration_utils import ConfigMixin, register_to_config from ...models import ModelMixin, TransformeraDModel, VQModel from ...schedulers import VQDiffusionScheduler from ...utils import logging from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput _snake_case = logging.get_logger(__name__) # pylint: disable=invalid-name class UpperCamelCase ( snake_case_ , snake_case_ ): @register_to_config def __init__( self : Tuple , UpperCAmelCase__ : bool , UpperCAmelCase__ : Optional[int] = None , UpperCAmelCase__ : Optional[int] = None ) -> List[str]: super().__init__() _a : List[Any] = learnable if self.learnable: assert hidden_size is not None, "learnable=True requires `hidden_size` to be set" assert length is not None, "learnable=True requires `length` to be set" _a : Tuple = torch.zeros(UpperCAmelCase__ , UpperCAmelCase__ ) else: _a : Optional[int] = None _a : List[Any] = torch.nn.Parameter(UpperCAmelCase__ ) class UpperCamelCase ( snake_case_ ): UpperCamelCase : VQModel UpperCamelCase : CLIPTextModel UpperCamelCase : CLIPTokenizer UpperCamelCase : TransformeraDModel UpperCamelCase : LearnedClassifierFreeSamplingEmbeddings UpperCamelCase : VQDiffusionScheduler def __init__( self : List[Any] , UpperCAmelCase__ : VQModel , UpperCAmelCase__ : CLIPTextModel , UpperCAmelCase__ : CLIPTokenizer , UpperCAmelCase__ : TransformeraDModel , UpperCAmelCase__ : VQDiffusionScheduler , UpperCAmelCase__ : LearnedClassifierFreeSamplingEmbeddings , ) -> List[Any]: super().__init__() self.register_modules( vqvae=UpperCAmelCase__ , transformer=UpperCAmelCase__ , text_encoder=UpperCAmelCase__ , tokenizer=UpperCAmelCase__ , scheduler=UpperCAmelCase__ , learned_classifier_free_sampling_embeddings=UpperCAmelCase__ , ) def _lowercase ( self : int , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : int ) -> List[str]: _a : Tuple = len(UpperCAmelCase__ ) if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ) else 1 # get prompt text embeddings _a : List[str] = self.tokenizer( UpperCAmelCase__ , padding="""max_length""" , max_length=self.tokenizer.model_max_length , return_tensors="""pt""" , ) _a : List[str] = text_inputs.input_ids if text_input_ids.shape[-1] > self.tokenizer.model_max_length: _a : int = self.tokenizer.batch_decode(text_input_ids[:, self.tokenizer.model_max_length :] ) logger.warning( """The following part of your input was truncated because CLIP can only handle sequences up to""" f""" {self.tokenizer.model_max_length} tokens: {removed_text}""" ) _a : str = text_input_ids[:, : self.tokenizer.model_max_length] _a : Dict = self.text_encoder(text_input_ids.to(self.device ) )[0] # NOTE: This additional step of normalizing the text embeddings is from VQ-Diffusion. # While CLIP does normalize the pooled output of the text transformer when combining # the image and text embeddings, CLIP does not directly normalize the last hidden state. # # CLIP normalizing the pooled output. # https://github.com/huggingface/transformers/blob/d92e22d1f28324f513f3080e5c47c071a3916721/src/transformers/models/clip/modeling_clip.py#L1052-L1053 _a : Optional[Any] = prompt_embeds / prompt_embeds.norm(dim=-1 , keepdim=UpperCAmelCase__ ) # duplicate text embeddings for each generation per prompt _a : Optional[Any] = prompt_embeds.repeat_interleave(UpperCAmelCase__ , dim=0 ) if do_classifier_free_guidance: if self.learned_classifier_free_sampling_embeddings.learnable: _a : Union[str, Any] = self.learned_classifier_free_sampling_embeddings.embeddings _a : Any = negative_prompt_embeds.unsqueeze(0 ).repeat(UpperCAmelCase__ , 1 , 1 ) else: _a : Dict = [""""""] * batch_size _a : Optional[int] = text_input_ids.shape[-1] _a : Optional[Any] = self.tokenizer( UpperCAmelCase__ , padding="""max_length""" , max_length=UpperCAmelCase__ , truncation=UpperCAmelCase__ , return_tensors="""pt""" , ) _a : Any = self.text_encoder(uncond_input.input_ids.to(self.device ) )[0] # See comment for normalizing text embeddings _a : Any = negative_prompt_embeds / negative_prompt_embeds.norm(dim=-1 , keepdim=UpperCAmelCase__ ) # duplicate unconditional embeddings for each generation per prompt, using mps friendly method _a : Any = negative_prompt_embeds.shape[1] _a : Union[str, Any] = negative_prompt_embeds.repeat(1 , UpperCAmelCase__ , 1 ) _a : Optional[Any] = negative_prompt_embeds.view(batch_size * num_images_per_prompt , UpperCAmelCase__ , -1 ) # For classifier free guidance, we need to do two forward passes. # Here we concatenate the unconditional and text embeddings into a single batch # to avoid doing two forward passes _a : Optional[Any] = torch.cat([negative_prompt_embeds, prompt_embeds] ) return prompt_embeds @torch.no_grad() def __call__( self : Tuple , UpperCAmelCase__ : Union[str, List[str]] , UpperCAmelCase__ : int = 100 , UpperCAmelCase__ : float = 5.0 , UpperCAmelCase__ : float = 1.0 , UpperCAmelCase__ : int = 1 , UpperCAmelCase__ : Optional[Union[torch.Generator, List[torch.Generator]]] = None , UpperCAmelCase__ : Optional[torch.FloatTensor] = None , UpperCAmelCase__ : Optional[str] = "pil" , UpperCAmelCase__ : bool = True , UpperCAmelCase__ : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , UpperCAmelCase__ : int = 1 , ) -> Union[ImagePipelineOutput, Tuple]: if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): _a : str = 1 elif isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): _a : Any = len(UpperCAmelCase__ ) else: raise ValueError(f"""`prompt` has to be of type `str` or `list` but is {type(UpperCAmelCase__ )}""" ) _a : List[str] = batch_size * num_images_per_prompt _a : Optional[Any] = guidance_scale > 1.0 _a : int = self._encode_prompt(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) if (callback_steps is None) or ( callback_steps is not None and (not isinstance(UpperCAmelCase__ , UpperCAmelCase__ ) or callback_steps <= 0) ): raise ValueError( f"""`callback_steps` has to be a positive integer but is {callback_steps} of type""" f""" {type(UpperCAmelCase__ )}.""" ) # get the initial completely masked latents unless the user supplied it _a : Dict = (batch_size, self.transformer.num_latent_pixels) if latents is None: _a : List[Any] = self.transformer.num_vector_embeds - 1 _a : str = torch.full(UpperCAmelCase__ , UpperCAmelCase__ ).to(self.device ) else: if latents.shape != latents_shape: raise ValueError(f"""Unexpected latents shape, got {latents.shape}, expected {latents_shape}""" ) if (latents < 0).any() or (latents >= self.transformer.num_vector_embeds).any(): raise ValueError( """Unexpected latents value(s). All latents be valid embedding indices i.e. in the range 0,""" f""" {self.transformer.num_vector_embeds - 1} (inclusive).""" ) _a : int = latents.to(self.device ) # set timesteps self.scheduler.set_timesteps(UpperCAmelCase__ , device=self.device ) _a : Any = self.scheduler.timesteps.to(self.device ) _a : str = latents for i, t in enumerate(self.progress_bar(UpperCAmelCase__ ) ): # expand the sample if we are doing classifier free guidance _a : Any = torch.cat([sample] * 2 ) if do_classifier_free_guidance else sample # predict the un-noised image # model_output == `log_p_x_0` _a : Optional[int] = self.transformer(UpperCAmelCase__ , encoder_hidden_states=UpperCAmelCase__ , timestep=UpperCAmelCase__ ).sample if do_classifier_free_guidance: _a , _a : Optional[Any] = model_output.chunk(2 ) _a : Optional[int] = model_output_uncond + guidance_scale * (model_output_text - model_output_uncond) model_output -= torch.logsumexp(UpperCAmelCase__ , dim=1 , keepdim=UpperCAmelCase__ ) _a : Optional[int] = self.truncate(UpperCAmelCase__ , UpperCAmelCase__ ) # remove `log(0)`'s (`-inf`s) _a : Dict = model_output.clamp(-70 ) # compute the previous noisy sample x_t -> x_t-1 _a : Optional[int] = self.scheduler.step(UpperCAmelCase__ , timestep=UpperCAmelCase__ , sample=UpperCAmelCase__ , generator=UpperCAmelCase__ ).prev_sample # call the callback, if provided if callback is not None and i % callback_steps == 0: callback(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) _a : str = self.vqvae.config.vq_embed_dim _a : Tuple = (batch_size, self.transformer.height, self.transformer.width, embedding_channels) _a : str = self.vqvae.quantize.get_codebook_entry(UpperCAmelCase__ , shape=UpperCAmelCase__ ) _a : Optional[int] = self.vqvae.decode(UpperCAmelCase__ , force_not_quantize=UpperCAmelCase__ ).sample _a : int = (image / 2 + 0.5).clamp(0 , 1 ) _a : Union[str, Any] = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": _a : Any = self.numpy_to_pil(UpperCAmelCase__ ) if not return_dict: return (image,) return ImagePipelineOutput(images=UpperCAmelCase__ ) def _lowercase ( self : List[str] , UpperCAmelCase__ : torch.FloatTensor , UpperCAmelCase__ : float ) -> torch.FloatTensor: _a , _a : Optional[Any] = torch.sort(UpperCAmelCase__ , 1 , descending=UpperCAmelCase__ ) _a : Tuple = torch.exp(UpperCAmelCase__ ) _a : str = sorted_p_x_0.cumsum(dim=1 ) < truncation_rate # Ensure that at least the largest probability is not zeroed out _a : Any = torch.full_like(keep_mask[:, 0:1, :] , UpperCAmelCase__ ) _a : Tuple = torch.cat((all_true, keep_mask) , dim=1 ) _a : List[str] = keep_mask[:, :-1, :] _a : str = keep_mask.gather(1 , indices.argsort(1 ) ) _a : Optional[int] = log_p_x_0.clone() _a : int = -torch.inf # -inf = log(0) return rv
324
"""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, )
324
1
"""simple docstring""" from __future__ import annotations from collections import namedtuple from dataclasses import dataclass @dataclass class UpperCamelCase : UpperCamelCase : int UpperCamelCase : TreeNode | None = None UpperCamelCase : TreeNode | None = None _snake_case = namedtuple('CoinsDistribResult', 'moves excess') def lowerCAmelCase__ ( UpperCamelCase__ ): '''simple docstring''' if root is None: return 0 # Validation def count_nodes(UpperCamelCase__ ) -> int: if node is None: return 0 return count_nodes(node.left ) + count_nodes(node.right ) + 1 def count_coins(UpperCamelCase__ ) -> int: if node is None: return 0 return count_coins(node.left ) + count_coins(node.right ) + node.data if count_nodes(UpperCamelCase__ ) != count_coins(UpperCamelCase__ ): raise ValueError("""The nodes number should be same as the number of coins""" ) # Main calculation def get_distrib(UpperCamelCase__ ) -> CoinsDistribResult: if node is None: return CoinsDistribResult(0 , 1 ) _a , _a : Any = get_distrib(node.left ) _a , _a : List[Any] = get_distrib(node.right ) _a : str = 1 - left_distrib_excess _a : Union[str, Any] = 1 - right_distrib_excess _a : Optional[int] = ( left_distrib_moves + right_distrib_moves + abs(UpperCamelCase__ ) + abs(UpperCamelCase__ ) ) _a : List[Any] = node.data - coins_to_left - coins_to_right return CoinsDistribResult(UpperCamelCase__ , UpperCamelCase__ ) return get_distrib(UpperCamelCase__ )[0] if __name__ == "__main__": import doctest doctest.testmod()
324
"""simple docstring""" _snake_case = 8.31_44_62 # Unit - J mol-1 K-1 def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' if moles < 0 or kelvin < 0 or volume < 0: raise ValueError("""Invalid inputs. Enter positive value.""" ) return moles * kelvin * UNIVERSAL_GAS_CONSTANT / volume def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' if moles < 0 or kelvin < 0 or pressure < 0: raise ValueError("""Invalid inputs. Enter positive value.""" ) return moles * kelvin * UNIVERSAL_GAS_CONSTANT / pressure if __name__ == "__main__": from doctest import testmod testmod()
324
1
"""simple docstring""" import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING _snake_case = logging.get_logger(__name__) _snake_case = { 'SenseTime/deformable-detr': 'https://huggingface.co/sensetime/deformable-detr/resolve/main/config.json', # See all Deformable DETR models at https://huggingface.co/models?filter=deformable-detr } class UpperCamelCase ( snake_case_ ): UpperCamelCase : Tuple = '''deformable_detr''' UpperCamelCase : Tuple = { '''hidden_size''': '''d_model''', '''num_attention_heads''': '''encoder_attention_heads''', } def __init__( self : int , UpperCAmelCase__ : Union[str, Any]=True , UpperCAmelCase__ : int=None , UpperCAmelCase__ : List[Any]=3 , UpperCAmelCase__ : int=300 , UpperCAmelCase__ : Dict=1024 , UpperCAmelCase__ : List[Any]=6 , UpperCAmelCase__ : str=1024 , UpperCAmelCase__ : Any=8 , UpperCAmelCase__ : Dict=6 , UpperCAmelCase__ : Union[str, Any]=1024 , UpperCAmelCase__ : int=8 , UpperCAmelCase__ : int=0.0 , UpperCAmelCase__ : Optional[int]=True , UpperCAmelCase__ : Dict="relu" , UpperCAmelCase__ : Any=256 , UpperCAmelCase__ : str=0.1 , UpperCAmelCase__ : Any=0.0 , UpperCAmelCase__ : str=0.0 , UpperCAmelCase__ : Optional[int]=0.0_2 , UpperCAmelCase__ : Tuple=1.0 , UpperCAmelCase__ : Optional[Any]=True , UpperCAmelCase__ : str=False , UpperCAmelCase__ : str="sine" , UpperCAmelCase__ : Union[str, Any]="resnet50" , UpperCAmelCase__ : List[str]=True , UpperCAmelCase__ : List[Any]=False , UpperCAmelCase__ : str=4 , UpperCAmelCase__ : Dict=4 , UpperCAmelCase__ : List[Any]=4 , UpperCAmelCase__ : Optional[Any]=False , UpperCAmelCase__ : Optional[Any]=300 , UpperCAmelCase__ : int=False , UpperCAmelCase__ : Optional[int]=1 , UpperCAmelCase__ : Dict=5 , UpperCAmelCase__ : int=2 , UpperCAmelCase__ : List[str]=1 , UpperCAmelCase__ : Any=1 , UpperCAmelCase__ : List[str]=5 , UpperCAmelCase__ : Optional[int]=2 , UpperCAmelCase__ : Any=0.1 , UpperCAmelCase__ : Any=0.2_5 , UpperCAmelCase__ : Any=False , **UpperCAmelCase__ : Optional[Any] , ) -> Union[str, Any]: 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 : Tuple = CONFIG_MAPPING["""resnet"""](out_features=["""stage4"""] ) elif isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): _a : Any = backbone_config.get("""model_type""" ) _a : str = CONFIG_MAPPING[backbone_model_type] _a : List[str] = config_class.from_dict(UpperCAmelCase__ ) _a : Union[str, Any] = use_timm_backbone _a : List[Any] = backbone_config _a : Optional[Any] = num_channels _a : str = num_queries _a : List[str] = max_position_embeddings _a : str = d_model _a : Union[str, Any] = encoder_ffn_dim _a : Union[str, Any] = encoder_layers _a : List[Any] = encoder_attention_heads _a : Optional[Any] = decoder_ffn_dim _a : List[Any] = decoder_layers _a : Dict = decoder_attention_heads _a : Optional[int] = dropout _a : List[str] = attention_dropout _a : List[Any] = activation_dropout _a : Optional[int] = activation_function _a : int = init_std _a : Tuple = init_xavier_std _a : List[Any] = encoder_layerdrop _a : List[str] = auxiliary_loss _a : Any = position_embedding_type _a : Dict = backbone _a : Dict = use_pretrained_backbone _a : Union[str, Any] = dilation # deformable attributes _a : int = num_feature_levels _a : Dict = encoder_n_points _a : Any = decoder_n_points _a : str = two_stage _a : List[Any] = two_stage_num_proposals _a : int = with_box_refine if two_stage is True and with_box_refine is False: raise ValueError("""If two_stage is True, with_box_refine must be True.""" ) # Hungarian matcher _a : List[str] = class_cost _a : str = bbox_cost _a : Dict = giou_cost # Loss coefficients _a : Union[str, Any] = mask_loss_coefficient _a : str = dice_loss_coefficient _a : Any = bbox_loss_coefficient _a : Union[str, Any] = giou_loss_coefficient _a : List[Any] = eos_coefficient _a : List[Any] = focal_alpha _a : Dict = disable_custom_kernels super().__init__(is_encoder_decoder=UpperCAmelCase__ , **UpperCAmelCase__ ) @property def _lowercase ( self : Any ) -> int: return self.encoder_attention_heads @property def _lowercase ( self : List[Any] ) -> int: return self.d_model def _lowercase ( self : List[Any] ) -> List[str]: _a : int = copy.deepcopy(self.__dict__ ) if self.backbone_config is not None: _a : Optional[int] = self.backbone_config.to_dict() _a : Union[str, Any] = self.__class__.model_type return output
324
"""simple docstring""" import argparse import dataclasses import json import logging import os import shutil from typing import List, Optional import datasets from accelerate import Accelerator from datasets import load_dataset from finetuning import finetune from tqdm.auto import tqdm import transformers from transformers import AutoConfig, set_seed from transformers.trainer_utils import IntervalStrategy _snake_case = logging.getLogger(__name__) _snake_case = 'pytorch_model.bin' @dataclasses.dataclass class UpperCamelCase : UpperCamelCase : str = dataclasses.field( metadata={'''help''': '''Path to pretrained model or model identifier from huggingface.co/models.'''} ) UpperCamelCase : Optional[str] = dataclasses.field( default=snake_case_ , metadata={'''help''': '''Where do you want to store the pretrained models downloaded from huggingface.co.'''} , ) @dataclasses.dataclass class UpperCamelCase : UpperCamelCase : str = dataclasses.field(metadata={'''help''': '''A csv or a json file containing the training data.'''} ) UpperCamelCase : str = dataclasses.field(metadata={'''help''': '''A csv or a json file containing the data to predict on.'''} ) UpperCamelCase : Optional[str] = dataclasses.field( default=snake_case_ , metadata={'''help''': '''A csv or a json file containing the validation data.'''} ) UpperCamelCase : Optional[str] = dataclasses.field( default=snake_case_ , metadata={'''help''': '''The name of the task to train on.'''} , ) UpperCamelCase : Optional[List[str]] = dataclasses.field( default=snake_case_ , metadata={'''help''': '''The list of labels for the task.'''} ) @dataclasses.dataclass class UpperCamelCase : UpperCamelCase : str = dataclasses.field( metadata={'''help''': '''The output directory where the model predictions and checkpoints will be written.'''} ) UpperCamelCase : Optional[str] = dataclasses.field( default='''accuracy''' , metadata={'''help''': '''The evaluation metric used for the task.'''} ) UpperCamelCase : Optional[str] = dataclasses.field( default='''no''' , metadata={ '''help''': '''The evaluation strategy to adopt during training. Possible values are: ["no", "step", "epoch]''' } , ) UpperCamelCase : Optional[int] = dataclasses.field( default=10 , metadata={'''help''': '''Number of evaluation calls with no improvement after which training will be stopped.'''} , ) UpperCamelCase : Optional[float] = dataclasses.field( default=0.0 , metadata={ '''help''': '''How much the specified evaluation metric must improve to satisfy early stopping conditions.''' } , ) UpperCamelCase : Optional[bool] = dataclasses.field( default=snake_case_ , metadata={'''help''': '''Whether to filter the pseudo-labeled data based on the confidence score.'''} , ) UpperCamelCase : Optional[bool] = dataclasses.field( default=snake_case_ , metadata={'''help''': '''Whether to filter the pseudo-labeled data based on the validation performance.'''} , ) UpperCamelCase : Optional[bool] = dataclasses.field( default=snake_case_ , metadata={'''help''': '''Whether to fine-tune on labeled data after pseudo training.'''} , ) UpperCamelCase : Optional[float] = dataclasses.field( default=0.0 , metadata={'''help''': '''Confidence threshold for pseudo-labeled data filtering.'''} , ) UpperCamelCase : Optional[int] = dataclasses.field( default=100 , metadata={'''help''': '''Number of evaluation calls with no improvement after which training will be stopped.'''} , ) UpperCamelCase : Optional[int] = dataclasses.field( default=snake_case_ , metadata={'''help''': '''Random seed for initialization.'''} , ) def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' _a : Optional[int] = datasets.concatenate_datasets([infer_input, infer_output] , axis=1 ) if args.do_filter_by_confidence: _a : Union[str, Any] = dataset.filter(lambda UpperCamelCase__ : example["probability"] > args.confidence_threshold ) if args.do_filter_by_val_performance: assert eval_result >= 0.0 and eval_result <= 1.0 _a : Any = int(eval_result * len(UpperCamelCase__ ) ) print(UpperCamelCase__ ) _a : str = dataset.sort("""probability""" , reverse=UpperCamelCase__ ) _a : Any = dataset.select(range(UpperCamelCase__ ) ) _a : Tuple = dataset.remove_columns(["""label""", """probability"""] ) _a : Optional[Any] = dataset.rename_column("""prediction""" , """label""" ) _a : Dict = dataset.map(lambda UpperCamelCase__ : {"label": idalabel[example["label"]]} ) _a : Union[str, Any] = dataset.shuffle(seed=args.seed ) _a : Optional[int] = os.path.join(UpperCamelCase__ , F"""train_pseudo.{args.data_file_extension}""" ) if args.data_file_extension == "csv": dataset.to_csv(UpperCamelCase__ , index=UpperCamelCase__ ) else: dataset.to_json(UpperCamelCase__ ) def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , **UpperCamelCase__ ): '''simple docstring''' _a : Optional[int] = Accelerator() # Make one log on every process with the configuration for debugging. logging.basicConfig( format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""" , datefmt="""%m/%d/%Y %H:%M:%S""" , level=logging.INFO , ) logger.info(accelerator.state ) # Setup logging, we only want one process per machine to log things on the # screen. accelerator.is_local_main_process is only True for one process per # machine. logger.setLevel(logging.INFO if accelerator.is_local_main_process else logging.ERROR ) if accelerator.is_local_main_process: datasets.utils.logging.set_verbosity_warning() transformers.utils.logging.set_verbosity_info() else: datasets.utils.logging.set_verbosity_error() transformers.utils.logging.set_verbosity_error() _a : Dict = STModelArguments(model_name_or_path=UpperCamelCase__ ) _a : Union[str, Any] = STDataArguments(train_file=UpperCamelCase__ , infer_file=UpperCamelCase__ ) _a : Any = STTrainingArguments(output_dir=UpperCamelCase__ ) _a : Any = argparse.Namespace() for arg_class in (model_args, data_args, training_args): for key, value in vars(UpperCamelCase__ ).items(): setattr(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) for key, value in kwargs.items(): if hasattr(UpperCamelCase__ , UpperCamelCase__ ): setattr(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) # Sanity checks _a : Union[str, Any] = {} _a : Tuple = None # You need to provide the training data and the data to predict on assert args.train_file is not None assert args.infer_file is not None _a : int = args.train_file _a : List[Any] = args.infer_file if args.evaluation_strategy != IntervalStrategy.NO.value: assert args.eval_file is not None _a : Union[str, Any] = args.eval_file for key in data_files: _a : Optional[Any] = data_files[key].split(""".""" )[-1] assert extension in ["csv", "json"], F"""`{key}_file` should be a csv or a json file.""" if args.data_file_extension is None: _a : str = extension else: assert extension == args.data_file_extension, F"""`{key}_file` should be a {args.data_file_extension} file`.""" assert ( args.eval_metric in datasets.list_metrics() ), F"""{args.eval_metric} not in the list of supported metrics {datasets.list_metrics()}.""" # If passed along, set the training seed now. if args.seed is not None: set_seed(args.seed ) logger.info("""Creating the initial data directory for self-training...""" ) _a : Tuple = F"""{args.output_dir}/self-train_iter-{{}}""".format _a : Dict = data_dir_format(0 ) if accelerator.is_main_process: if args.output_dir is not None: os.makedirs(args.output_dir , exist_ok=UpperCamelCase__ ) os.makedirs(UpperCamelCase__ , exist_ok=UpperCamelCase__ ) accelerator.wait_for_everyone() _a : str = None _a : int = None _a : str = 0 _a : List[Any] = False # Show the progress bar _a : List[Any] = tqdm(range(args.max_selftrain_iterations ) , disable=not accelerator.is_local_main_process ) # Self-train for iteration in range(0 , int(args.max_selftrain_iterations ) ): _a : Union[str, Any] = data_dir_format(UpperCamelCase__ ) assert os.path.exists(UpperCamelCase__ ) # Stage 1: initial fine-tuning for iteration = 0 or pseudo-training for # iteration > 0 _a : str = os.path.join(UpperCamelCase__ , """stage-1""" ) _a : Tuple = { """accelerator""": accelerator, """model_name_or_path""": args.model_name_or_path, """cache_dir""": args.cache_dir, """do_train""": True, """train_file""": data_files["""train"""] if iteration == 0 else data_files["""train_pseudo"""], """do_eval""": True if args.eval_file is not None else False, """eval_file""": data_files["""eval"""], """do_predict""": True, """infer_file""": data_files["""infer"""], """task_name""": args.task_name, """label_list""": args.label_list, """output_dir""": current_output_dir, """eval_metric""": args.eval_metric, """evaluation_strategy""": args.evaluation_strategy, """early_stopping_patience""": args.early_stopping_patience, """early_stopping_threshold""": args.early_stopping_threshold, """seed""": args.seed, } # Add additional training arguments for key, value in kwargs.items(): if key not in arguments_dict and not hasattr(UpperCamelCase__ , UpperCamelCase__ ): arguments_dict.update({key: value} ) _a : int = os.path.join(UpperCamelCase__ , """best-checkpoint""" , UpperCamelCase__ ) if os.path.exists(UpperCamelCase__ ): logger.info( """Found existing model checkpoint at %s. Skipping self-training: iteration: %d, stage: 1.""" , UpperCamelCase__ , UpperCamelCase__ , ) else: logger.info("""***** Running self-training: iteration: %d, stage: 1 *****""" , UpperCamelCase__ ) finetune(**UpperCamelCase__ ) accelerator.wait_for_everyone() assert os.path.exists(UpperCamelCase__ ) logger.info("""Self-training job completed: iteration: %d, stage: 1.""" , UpperCamelCase__ ) if iteration > 0 and args.finetune_on_labeled_data: # Stage 2 (optional): fine-tuning on the original labeled data _a : Dict = os.path.join(UpperCamelCase__ , """best-checkpoint""" ) _a : List[str] = os.path.join(UpperCamelCase__ , """stage-2""" ) # Update arguments_dict _a : int = model_path _a : Dict = data_files["""train"""] _a : int = current_output_dir _a : Any = os.path.join(UpperCamelCase__ , """best-checkpoint""" , UpperCamelCase__ ) if os.path.exists(UpperCamelCase__ ): logger.info( """Found existing model checkpoint at %s. Skipping self-training: iteration: %d, stage: 2.""" , UpperCamelCase__ , UpperCamelCase__ , ) else: logger.info("""***** Running self-training: iteration: %d, stage: 2 *****""" , UpperCamelCase__ ) finetune(**UpperCamelCase__ ) accelerator.wait_for_everyone() assert os.path.exists(UpperCamelCase__ ) logger.info("""Self-training job completed: iteration: %d, stage: 2.""" , UpperCamelCase__ ) _a : List[Any] = iteration _a : int = data_dir_format(iteration + 1 ) _a : Dict = AutoConfig.from_pretrained(os.path.join(UpperCamelCase__ , """best-checkpoint""" ) ) _a : Union[str, Any] = config.idalabel _a : Any = os.path.join(UpperCamelCase__ , """eval_results_best-checkpoint.json""" ) _a : Any = os.path.join(UpperCamelCase__ , """test_results_best-checkpoint.json""" ) assert os.path.exists(UpperCamelCase__ ) with open(UpperCamelCase__ , """r""" ) as f: _a : Tuple = float(json.load(UpperCamelCase__ )[args.eval_metric] ) _a : Dict = os.path.join(UpperCamelCase__ , """infer_output_best-checkpoint.csv""" ) assert os.path.exists(UpperCamelCase__ ) # Loading the dataset from local csv or json files. _a : List[Any] = load_dataset(args.data_file_extension , data_files={"""data""": data_files["""infer"""]} )["""data"""] _a : Any = load_dataset("""csv""" , data_files={"""data""": infer_output_file} )["""data"""] if accelerator.is_main_process: os.makedirs(UpperCamelCase__ , exist_ok=UpperCamelCase__ ) shutil.copy(UpperCamelCase__ , os.path.join(UpperCamelCase__ , F"""eval_results_iter-{iteration}.json""" ) ) if os.path.exists(UpperCamelCase__ ): shutil.copy(UpperCamelCase__ , os.path.join(UpperCamelCase__ , F"""test_results_iter-{iteration}.json""" ) ) create_pseudo_labeled_data(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) accelerator.wait_for_everyone() _a : List[str] = os.path.join(UpperCamelCase__ , F"""train_pseudo.{args.data_file_extension}""" ) if args.evaluation_strategy != IntervalStrategy.NO.value: _a : Any = eval_result if best_iteration is None: _a : Union[str, Any] = new_iteration _a : str = new_eval_result else: if new_eval_result - best_eval_result > args.early_stopping_threshold: _a : Union[str, Any] = new_iteration _a : List[str] = new_eval_result _a : Optional[Any] = 0 else: if new_eval_result == best_eval_result: _a : Tuple = new_iteration _a : List[Any] = new_eval_result early_stopping_patience_counter += 1 if early_stopping_patience_counter >= args.early_stopping_patience: _a : Union[str, Any] = True progress_bar.update(1 ) if should_training_stop: break if best_iteration is not None: # Save the best iteration logger.info("""Best iteration: %d""" , UpperCamelCase__ ) logger.info("""Best evaluation result: %s = %f""" , args.eval_metric , UpperCamelCase__ ) accelerator.wait_for_everyone() if accelerator.is_main_process: shutil.copy( os.path.join(UpperCamelCase__ , F"""eval_results_iter-{iteration}.json""" ) , os.path.join(UpperCamelCase__ , """eval_results_best-iteration.json""" ) , ) else: # Assume that the last iteration is the best logger.info("""Best iteration: %d""" , args.max_selftrain_iterations - 1 ) logger.info("""Best evaluation result: %s = %f""" , args.eval_metric , UpperCamelCase__ ) accelerator.wait_for_everyone() if accelerator.is_main_process: shutil.copy( os.path.join(UpperCamelCase__ , F"""eval_results_iter-{args.max_selftrain_iterations - 1}.json""" ) , os.path.join(UpperCamelCase__ , """eval_results_best-iteration.json""" ) , )
324
1
"""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 from accelerate.local_sgd import LocalSGD ######################################################################## # This is a fully working simple example to use Accelerate # with LocalSGD, which is a method to synchronize model # parameters every K batches. It is different, but complementary # to gradient accumulation. # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## _snake_case = 16 _snake_case = 32 def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ = 1_6 ): '''simple docstring''' _a : Tuple = AutoTokenizer.from_pretrained("""bert-base-cased""" ) _a : Optional[Any] = load_dataset("""glue""" , """mrpc""" ) def tokenize_function(UpperCamelCase__ ): # max_length=None => use the model max length (it's actually the default) _a : List[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(): _a : Union[str, 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 _a : Union[str, Any] = tokenized_datasets.rename_column("""label""" , """labels""" ) def collate_fn(UpperCamelCase__ ): # On TPU it's best to pad everything to the same length or training will be very slow. _a : Optional[Any] = 1_2_8 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": _a : Optional[Any] = 1_6 elif accelerator.mixed_precision != "no": _a : List[Any] = 8 else: _a : str = None return tokenizer.pad( UpperCamelCase__ , padding="""longest""" , max_length=UpperCamelCase__ , pad_to_multiple_of=UpperCamelCase__ , return_tensors="""pt""" , ) # Instantiate dataloaders. _a : int = DataLoader( tokenized_datasets["""train"""] , shuffle=UpperCamelCase__ , collate_fn=UpperCamelCase__ , batch_size=UpperCamelCase__ ) _a : Dict = 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 _snake_case = mocked_dataloaders # noqa: F811 def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' # For testing only if os.environ.get("""TESTING_MOCKED_DATALOADERS""" , UpperCamelCase__ ) == "1": _a : Optional[Any] = 2 # New Code # _a : Union[str, Any] = int(args.gradient_accumulation_steps ) _a : str = int(args.local_sgd_steps ) # Initialize accelerator _a : Dict = Accelerator( cpu=args.cpu , mixed_precision=args.mixed_precision , gradient_accumulation_steps=UpperCamelCase__ ) if accelerator.distributed_type not in [DistributedType.NO, DistributedType.MULTI_CPU, DistributedType.MULTI_GPU]: raise NotImplementedError("""LocalSGD is supported only for CPUs and GPUs (no DeepSpeed or MegatronLM)""" ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs _a : List[Any] = config["""lr"""] _a : List[Any] = int(config["""num_epochs"""] ) _a : int = int(config["""seed"""] ) _a : int = int(config["""batch_size"""] ) _a : int = evaluate.load("""glue""" , """mrpc""" ) set_seed(UpperCamelCase__ ) _a , _a : str = get_dataloaders(UpperCamelCase__ , UpperCamelCase__ ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) _a : Any = 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). _a : Tuple = model.to(accelerator.device ) # Instantiate optimizer _a : int = AdamW(params=model.parameters() , lr=UpperCamelCase__ ) # Instantiate scheduler _a : List[Any] = get_linear_schedule_with_warmup( optimizer=UpperCamelCase__ , num_warmup_steps=1_0_0 , num_training_steps=(len(UpperCamelCase__ ) * num_epochs) , ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. _a , _a , _a , _a , _a : Any = accelerator.prepare( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) # Now we train the model for epoch in range(UpperCamelCase__ ): model.train() with LocalSGD( accelerator=UpperCamelCase__ , model=UpperCamelCase__ , local_sgd_steps=UpperCamelCase__ , enabled=local_sgd_steps is not None ) as local_sgd: for step, batch in enumerate(UpperCamelCase__ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) # New code # # We use the new `accumulate` context manager to perform gradient accumulation # We also currently do not support TPUs nor advise it as bugs were found on the XLA side when running our tests. with accelerator.accumulate(UpperCamelCase__ ): _a : str = model(**UpperCamelCase__ ) _a : Dict = output.loss accelerator.backward(UpperCamelCase__ ) optimizer.step() lr_scheduler.step() optimizer.zero_grad() # LocalSGD-specific line local_sgd.step() model.eval() for step, batch in enumerate(UpperCamelCase__ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): _a : List[Any] = model(**UpperCamelCase__ ) _a : List[str] = outputs.logits.argmax(dim=-1 ) _a , _a : Optional[int] = accelerator.gather_for_metrics((predictions, batch["""labels"""]) ) metric.add_batch( predictions=UpperCamelCase__ , references=UpperCamelCase__ , ) _a : List[str] = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F"""epoch {epoch}:""" , UpperCamelCase__ ) def lowerCAmelCase__ ( ): '''simple docstring''' _a : 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.""" , ) # New Code # parser.add_argument( """--gradient_accumulation_steps""" , type=UpperCamelCase__ , default=1 , help="""The number of minibatches to be ran before gradients are accumulated.""" , ) parser.add_argument( """--local_sgd_steps""" , type=UpperCamelCase__ , default=8 , help="""Number of local SGD steps or None to disable local SGD""" ) parser.add_argument("""--cpu""" , action="""store_true""" , help="""If passed, will train on the CPU.""" ) _a : Union[str, Any] = parser.parse_args() _a : Union[str, Any] = {"""lr""": 2e-5, """num_epochs""": 3, """seed""": 4_2, """batch_size""": 1_6} training_function(UpperCamelCase__ , UpperCamelCase__ ) if __name__ == "__main__": main()
324
"""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_camembert import CamembertTokenizer else: _snake_case = None _snake_case = logging.get_logger(__name__) _snake_case = {'vocab_file': 'sentencepiece.bpe.model', 'tokenizer_file': 'tokenizer.json'} _snake_case = { 'vocab_file': { 'camembert-base': 'https://huggingface.co/camembert-base/resolve/main/sentencepiece.bpe.model', }, 'tokenizer_file': { 'camembert-base': 'https://huggingface.co/camembert-base/resolve/main/tokenizer.json', }, } _snake_case = { 'camembert-base': 512, } _snake_case = '▁' class UpperCamelCase ( snake_case_ ): UpperCamelCase : Any = VOCAB_FILES_NAMES UpperCamelCase : Union[str, Any] = PRETRAINED_VOCAB_FILES_MAP UpperCamelCase : Union[str, Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCamelCase : Dict = ['''input_ids''', '''attention_mask'''] UpperCamelCase : Optional[Any] = CamembertTokenizer def __init__( self : int , UpperCAmelCase__ : List[Any]=None , UpperCAmelCase__ : Optional[int]=None , UpperCAmelCase__ : Optional[Any]="<s>" , UpperCAmelCase__ : Optional[int]="</s>" , UpperCAmelCase__ : Tuple="</s>" , UpperCAmelCase__ : Tuple="<s>" , UpperCAmelCase__ : Tuple="<unk>" , UpperCAmelCase__ : Tuple="<pad>" , UpperCAmelCase__ : int="<mask>" , UpperCAmelCase__ : Optional[int]=["<s>NOTUSED", "</s>NOTUSED"] , **UpperCAmelCase__ : Optional[Any] , ) -> Union[str, Any]: # Mask token behave like a normal word, i.e. include the space before it _a : List[Any] = AddedToken(UpperCAmelCase__ , lstrip=UpperCAmelCase__ , rstrip=UpperCAmelCase__ ) if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ) else mask_token super().__init__( UpperCAmelCase__ , tokenizer_file=UpperCAmelCase__ , bos_token=UpperCAmelCase__ , eos_token=UpperCAmelCase__ , sep_token=UpperCAmelCase__ , cls_token=UpperCAmelCase__ , unk_token=UpperCAmelCase__ , pad_token=UpperCAmelCase__ , mask_token=UpperCAmelCase__ , additional_special_tokens=UpperCAmelCase__ , **UpperCAmelCase__ , ) _a : int = vocab_file _a : int = False if not self.vocab_file else True def _lowercase ( self : Union[str, Any] , 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] _a : List[Any] = [self.cls_token_id] _a : Dict = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def _lowercase ( self : Optional[int] , UpperCAmelCase__ : List[int] , UpperCAmelCase__ : Optional[List[int]] = None ) -> List[int]: _a : Union[str, Any] = [self.sep_token_id] _a : 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 _lowercase ( self : Optional[int] , UpperCAmelCase__ : str , UpperCAmelCase__ : Optional[str] = None ) -> Tuple[str]: 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(UpperCAmelCase__ ): logger.error(f"""Vocabulary path ({save_directory}) should be a directory""" ) return _a : List[str] = 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,)
324
1
"""simple docstring""" from __future__ import annotations from collections.abc import Iterator class UpperCamelCase : def __init__( self : Optional[int] , UpperCAmelCase__ : int ) -> None: _a : Optional[Any] = value _a : Node | None = None _a : Node | None = None class UpperCamelCase : def __init__( self : Union[str, Any] , UpperCAmelCase__ : Node ) -> None: _a : Union[str, Any] = tree def _lowercase ( self : Optional[int] , UpperCAmelCase__ : Node | None ) -> int: if node is None: return 0 return node.value + ( self.depth_first_search(node.left ) + self.depth_first_search(node.right ) ) def __iter__( self : Dict ) -> Iterator[int]: yield self.depth_first_search(self.tree ) if __name__ == "__main__": import doctest doctest.testmod()
324
"""simple docstring""" from typing import List, Optional, Union import numpy as np import PIL.Image from ...image_processing_utils import BaseImageProcessor, BatchFeature from ...image_transforms import rescale, resize, to_channel_dimension_format from ...image_utils import ( ChannelDimension, PILImageResampling, get_image_size, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, logging _snake_case = logging.get_logger(__name__) class UpperCamelCase ( snake_case_ ): UpperCamelCase : Dict = ['''pixel_values'''] def __init__( self : Any , UpperCAmelCase__ : bool = True , UpperCAmelCase__ : int = 32 , UpperCAmelCase__ : Optional[Any]=PILImageResampling.BILINEAR , UpperCAmelCase__ : bool = True , **UpperCAmelCase__ : List[str] , ) -> None: _a : int = do_resize _a : Union[str, Any] = do_rescale _a : Any = size_divisor _a : Any = resample super().__init__(**UpperCAmelCase__ ) def _lowercase ( self : Tuple , UpperCAmelCase__ : np.ndarray , UpperCAmelCase__ : int , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Optional[ChannelDimension] = None , **UpperCAmelCase__ : Optional[Any] ) -> np.ndarray: _a , _a : Tuple = get_image_size(UpperCAmelCase__ ) # Rounds the height and width down to the closest multiple of size_divisor _a : Optional[Any] = height // size_divisor * size_divisor _a : Union[str, Any] = width // size_divisor * size_divisor _a : Any = resize(UpperCAmelCase__ , (new_h, new_w) , resample=UpperCAmelCase__ , data_format=UpperCAmelCase__ , **UpperCAmelCase__ ) return image def _lowercase ( self : Union[str, Any] , UpperCAmelCase__ : np.ndarray , UpperCAmelCase__ : float , UpperCAmelCase__ : Optional[ChannelDimension] = None , **UpperCAmelCase__ : Optional[int] ) -> np.ndarray: return rescale(image=UpperCAmelCase__ , scale=UpperCAmelCase__ , data_format=UpperCAmelCase__ , **UpperCAmelCase__ ) def _lowercase ( self : Optional[int] , UpperCAmelCase__ : Union["PIL.Image.Image", TensorType, List["PIL.Image.Image"], List[TensorType]] , UpperCAmelCase__ : Optional[bool] = None , UpperCAmelCase__ : Optional[int] = None , UpperCAmelCase__ : int=None , UpperCAmelCase__ : Optional[bool] = None , UpperCAmelCase__ : Optional[Union[TensorType, str]] = None , UpperCAmelCase__ : ChannelDimension = ChannelDimension.FIRST , **UpperCAmelCase__ : int , ) -> BatchFeature: _a : Dict = do_resize if do_resize is not None else self.do_resize _a : Optional[int] = do_rescale if do_rescale is not None else self.do_rescale _a : str = size_divisor if size_divisor is not None else self.size_divisor _a : Any = resample if resample is not None else self.resample if do_resize and size_divisor is None: raise ValueError("""size_divisor is required for resizing""" ) _a : List[str] = make_list_of_images(UpperCAmelCase__ ) if not valid_images(UpperCAmelCase__ ): raise ValueError("""Invalid image(s)""" ) # All transformations expect numpy arrays. _a : Tuple = [to_numpy_array(UpperCAmelCase__ ) for img in images] if do_resize: _a : Optional[int] = [self.resize(UpperCAmelCase__ , size_divisor=UpperCAmelCase__ , resample=UpperCAmelCase__ ) for image in images] if do_rescale: _a : str = [self.rescale(UpperCAmelCase__ , scale=1 / 255 ) for image in images] _a : Any = [to_channel_dimension_format(UpperCAmelCase__ , UpperCAmelCase__ ) for image in images] _a : Optional[int] = {"""pixel_values""": images} return BatchFeature(data=UpperCAmelCase__ , tensor_type=UpperCAmelCase__ )
324
1
"""simple docstring""" import itertools import random import unittest import numpy as np from transformers import WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST, WavaVecaConfig, WavaVecaFeatureExtractor from transformers.testing_utils import require_torch, slow from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin _snake_case = random.Random() def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__=1.0 , UpperCamelCase__=None , UpperCamelCase__=None ): '''simple docstring''' if rng is None: _a : Union[str, Any] = global_rng _a : Optional[int] = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values class UpperCamelCase ( unittest.TestCase ): def __init__( self : int , UpperCAmelCase__ : Dict , UpperCAmelCase__ : str=7 , UpperCAmelCase__ : Tuple=400 , UpperCAmelCase__ : List[str]=2000 , UpperCAmelCase__ : str=1 , UpperCAmelCase__ : Optional[Any]=0.0 , UpperCAmelCase__ : int=16000 , UpperCAmelCase__ : Union[str, Any]=True , UpperCAmelCase__ : str=True , ) -> Optional[int]: _a : Optional[int] = parent _a : Optional[int] = batch_size _a : str = min_seq_length _a : Union[str, Any] = max_seq_length _a : List[Any] = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) _a : Dict = feature_size _a : int = padding_value _a : Any = sampling_rate _a : str = return_attention_mask _a : Any = do_normalize def _lowercase ( self : Tuple ) -> Optional[Any]: return { "feature_size": self.feature_size, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "return_attention_mask": self.return_attention_mask, "do_normalize": self.do_normalize, } def _lowercase ( self : List[str] , UpperCAmelCase__ : Dict=False , UpperCAmelCase__ : Union[str, Any]=False ) -> str: def _flatten(UpperCAmelCase__ : str ): return list(itertools.chain(*UpperCAmelCase__ ) ) if equal_length: _a : str = floats_list((self.batch_size, self.max_seq_length) ) else: # make sure that inputs increase in size _a : List[str] = [ _flatten(floats_list((x, self.feature_size) ) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: _a : Tuple = [np.asarray(UpperCAmelCase__ ) for x in speech_inputs] return speech_inputs class UpperCamelCase ( snake_case_ , unittest.TestCase ): UpperCamelCase : Tuple = WavaVecaFeatureExtractor def _lowercase ( self : Dict ) -> List[str]: _a : Tuple = WavaVecaFeatureExtractionTester(self ) def _lowercase ( self : Optional[int] , UpperCAmelCase__ : Optional[int] ) -> Optional[int]: self.assertTrue(np.all(np.mean(UpperCAmelCase__ , axis=0 ) < 1E-3 ) ) self.assertTrue(np.all(np.abs(np.var(UpperCAmelCase__ , axis=0 ) - 1 ) < 1E-3 ) ) def _lowercase ( self : Union[str, Any] ) -> List[Any]: # Tests that all call wrap to encode_plus and batch_encode_plus _a : Optional[Any] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 _a : str = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] _a : List[Any] = [np.asarray(UpperCAmelCase__ ) for speech_input in speech_inputs] # Test not batched input _a : Tuple = feat_extract(speech_inputs[0] , return_tensors="""np""" ).input_values _a : str = feat_extract(np_speech_inputs[0] , return_tensors="""np""" ).input_values self.assertTrue(np.allclose(UpperCAmelCase__ , UpperCAmelCase__ , atol=1E-3 ) ) # Test batched _a : int = feat_extract(UpperCAmelCase__ , return_tensors="""np""" ).input_values _a : Optional[int] = feat_extract(UpperCAmelCase__ , return_tensors="""np""" ).input_values for enc_seq_a, enc_seq_a in zip(UpperCAmelCase__ , UpperCAmelCase__ ): self.assertTrue(np.allclose(UpperCAmelCase__ , UpperCAmelCase__ , atol=1E-3 ) ) # Test 2-D numpy arrays are batched. _a : Optional[Any] = [floats_list((1, x) )[0] for x in (800, 800, 800)] _a : int = np.asarray(UpperCAmelCase__ ) _a : Tuple = feat_extract(UpperCAmelCase__ , return_tensors="""np""" ).input_values _a : List[Any] = feat_extract(UpperCAmelCase__ , return_tensors="""np""" ).input_values for enc_seq_a, enc_seq_a in zip(UpperCAmelCase__ , UpperCAmelCase__ ): self.assertTrue(np.allclose(UpperCAmelCase__ , UpperCAmelCase__ , atol=1E-3 ) ) def _lowercase ( self : Tuple ) -> Tuple: _a : List[str] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) _a : int = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] _a : Optional[Any] = ["""longest""", """max_length""", """do_not_pad"""] _a : Dict = [None, 1600, None] for max_length, padding in zip(UpperCAmelCase__ , UpperCAmelCase__ ): _a : Any = feat_extract(UpperCAmelCase__ , padding=UpperCAmelCase__ , max_length=UpperCAmelCase__ , return_tensors="""np""" ) _a : Tuple = processed.input_values self._check_zero_mean_unit_variance(input_values[0][:800] ) self.assertTrue(input_values[0][800:].sum() < 1E-6 ) self._check_zero_mean_unit_variance(input_values[1][:1000] ) self.assertTrue(input_values[0][1000:].sum() < 1E-6 ) self._check_zero_mean_unit_variance(input_values[2][:1200] ) def _lowercase ( self : List[str] ) -> str: _a : Optional[Any] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) _a : List[str] = range(800 , 1400 , 200 ) _a : int = [floats_list((1, x) )[0] for x in lengths] _a : str = ["""longest""", """max_length""", """do_not_pad"""] _a : Optional[int] = [None, 1600, None] for max_length, padding in zip(UpperCAmelCase__ , UpperCAmelCase__ ): _a : List[Any] = feat_extract(UpperCAmelCase__ , max_length=UpperCAmelCase__ , padding=UpperCAmelCase__ ) _a : Tuple = processed.input_values self._check_zero_mean_unit_variance(input_values[0][:800] ) self._check_zero_mean_unit_variance(input_values[1][:1000] ) self._check_zero_mean_unit_variance(input_values[2][:1200] ) def _lowercase ( self : int ) -> Dict: _a : List[Any] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) _a : Optional[int] = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] _a : Optional[Any] = feat_extract( UpperCAmelCase__ , truncation=UpperCAmelCase__ , max_length=1000 , padding="""max_length""" , return_tensors="""np""" ) _a : str = processed.input_values self._check_zero_mean_unit_variance(input_values[0, :800] ) self._check_zero_mean_unit_variance(input_values[1] ) self._check_zero_mean_unit_variance(input_values[2] ) def _lowercase ( self : Optional[int] ) -> Optional[Any]: _a : Optional[Any] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) _a : Tuple = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] _a : Tuple = feat_extract( UpperCAmelCase__ , truncation=UpperCAmelCase__ , max_length=1000 , padding="""longest""" , return_tensors="""np""" ) _a : Dict = processed.input_values self._check_zero_mean_unit_variance(input_values[0, :800] ) self._check_zero_mean_unit_variance(input_values[1, :1000] ) self._check_zero_mean_unit_variance(input_values[2] ) # make sure that if max_length < longest -> then pad to max_length self.assertTrue(input_values.shape == (3, 1000) ) _a : Optional[int] = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] _a : Optional[int] = feat_extract( UpperCAmelCase__ , truncation=UpperCAmelCase__ , max_length=2000 , padding="""longest""" , return_tensors="""np""" ) _a : str = processed.input_values self._check_zero_mean_unit_variance(input_values[0, :800] ) self._check_zero_mean_unit_variance(input_values[1, :1000] ) self._check_zero_mean_unit_variance(input_values[2] ) # make sure that if max_length > longest -> then pad to longest self.assertTrue(input_values.shape == (3, 1200) ) @require_torch def _lowercase ( self : str ) -> Optional[int]: import torch _a : Any = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) _a : str = np.random.rand(100 ).astype(np.floataa ) _a : Optional[Any] = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: _a : Tuple = feature_extractor.pad([{"""input_values""": inputs}] , return_tensors="""np""" ) self.assertTrue(np_processed.input_values.dtype == np.floataa ) _a : Tuple = feature_extractor.pad([{"""input_values""": inputs}] , return_tensors="""pt""" ) self.assertTrue(pt_processed.input_values.dtype == torch.floataa ) @slow @require_torch def _lowercase ( self : Union[str, Any] ) -> Optional[int]: # this test makes sure that models that are using # group norm don't have their feature extractor return the # attention_mask for model_id in WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST: _a : Optional[Any] = WavaVecaConfig.from_pretrained(UpperCAmelCase__ ) _a : List[str] = WavaVecaFeatureExtractor.from_pretrained(UpperCAmelCase__ ) # only "layer" feature extraction norm should make use of # attention_mask self.assertEqual(feat_extract.return_attention_mask , config.feat_extract_norm == """layer""" )
324
"""simple docstring""" 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 ): @property def _lowercase ( self : Optional[int] ) -> Union[str, Any]: torch.manual_seed(0 ) _a : List[str] = 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 _lowercase ( self : Dict ) -> Dict: _a : str = self.dummy_uncond_unet _a : Optional[int] = KarrasVeScheduler() _a : List[str] = KarrasVePipeline(unet=UpperCAmelCase__ , scheduler=UpperCAmelCase__ ) pipe.to(UpperCAmelCase__ ) pipe.set_progress_bar_config(disable=UpperCAmelCase__ ) _a : int = torch.manual_seed(0 ) _a : List[Any] = pipe(num_inference_steps=2 , generator=UpperCAmelCase__ , output_type="""numpy""" ).images _a : Tuple = torch.manual_seed(0 ) _a : int = pipe(num_inference_steps=2 , generator=UpperCAmelCase__ , output_type="""numpy""" , return_dict=UpperCAmelCase__ )[0] _a : int = image[0, -3:, -3:, -1] _a : Optional[int] = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) _a : str = 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 ): def _lowercase ( self : Tuple ) -> List[str]: _a : Optional[Any] = """google/ncsnpp-celebahq-256""" _a : Any = UNetaDModel.from_pretrained(UpperCAmelCase__ ) _a : Dict = KarrasVeScheduler() _a : int = KarrasVePipeline(unet=UpperCAmelCase__ , scheduler=UpperCAmelCase__ ) pipe.to(UpperCAmelCase__ ) pipe.set_progress_bar_config(disable=UpperCAmelCase__ ) _a : Optional[int] = torch.manual_seed(0 ) _a : Tuple = pipe(num_inference_steps=20 , generator=UpperCAmelCase__ , output_type="""numpy""" ).images _a : List[str] = image[0, -3:, -3:, -1] assert image.shape == (1, 256, 256, 3) _a : Optional[int] = np.array([0.5_7_8, 0.5_8_1_1, 0.5_9_2_4, 0.5_8_0_9, 0.5_8_7, 0.5_8_8_6, 0.5_8_6_1, 0.5_8_0_2, 0.5_8_6] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
324
1
"""simple docstring""" from typing import Any def lowerCAmelCase__ ( UpperCamelCase__ ): '''simple docstring''' if not input_list: return [] _a : Optional[int] = [input_list.count(UpperCamelCase__ ) for value in input_list] _a : Tuple = max(UpperCamelCase__ ) # Gets the maximum count in the input list. # Gets values of modes return sorted({input_list[i] for i, value in enumerate(UpperCamelCase__ ) if value == y} ) if __name__ == "__main__": import doctest doctest.testmod()
324
"""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 how to properly calculate the metrics on the # validation dataset when in a distributed system, 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 # ######################################################################## _snake_case = 16 _snake_case = 32 def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ = 1_6 ): '''simple docstring''' _a : str = AutoTokenizer.from_pretrained("""bert-base-cased""" ) _a : Dict = load_dataset("""glue""" , """mrpc""" ) def tokenize_function(UpperCamelCase__ ): # max_length=None => use the model max length (it's actually the default) _a : Optional[int] = 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(): _a : Tuple = 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 _a : List[Any] = tokenized_datasets.rename_column("""label""" , """labels""" ) def collate_fn(UpperCamelCase__ ): # On TPU it's best to pad everything to the same length or training will be very slow. _a : Union[str, Any] = 1_2_8 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": _a : int = 1_6 elif accelerator.mixed_precision != "no": _a : int = 8 else: _a : str = None return tokenizer.pad( UpperCamelCase__ , padding="""longest""" , max_length=UpperCamelCase__ , pad_to_multiple_of=UpperCamelCase__ , return_tensors="""pt""" , ) # Instantiate dataloaders. _a : int = DataLoader( tokenized_datasets["""train"""] , shuffle=UpperCamelCase__ , collate_fn=UpperCamelCase__ , batch_size=UpperCamelCase__ ) _a : List[str] = 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 _snake_case = mocked_dataloaders # noqa: F811 def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' # For testing only if os.environ.get("""TESTING_MOCKED_DATALOADERS""" , UpperCamelCase__ ) == "1": _a : str = 2 # Initialize accelerator _a : int = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs _a : Any = config["""lr"""] _a : Union[str, Any] = int(config["""num_epochs"""] ) _a : str = int(config["""seed"""] ) _a : List[Any] = int(config["""batch_size"""] ) _a : Tuple = evaluate.load("""glue""" , """mrpc""" ) # If the batch size is too big we use gradient accumulation _a : Optional[Any] = 1 if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU: _a : Optional[Any] = batch_size // MAX_GPU_BATCH_SIZE _a : str = MAX_GPU_BATCH_SIZE set_seed(UpperCamelCase__ ) _a , _a : Optional[int] = get_dataloaders(UpperCamelCase__ , UpperCamelCase__ ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) _a : int = 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). _a : List[str] = model.to(accelerator.device ) # Instantiate optimizer _a : List[str] = AdamW(params=model.parameters() , lr=UpperCamelCase__ ) # Instantiate scheduler _a : List[str] = get_linear_schedule_with_warmup( optimizer=UpperCamelCase__ , num_warmup_steps=1_0_0 , 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. _a , _a , _a , _a , _a : Optional[Any] = accelerator.prepare( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) # Now we train the model for epoch in range(UpperCamelCase__ ): model.train() for step, batch in enumerate(UpperCamelCase__ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) _a : Optional[Any] = model(**UpperCamelCase__ ) _a : str = outputs.loss _a : Optional[int] = loss / gradient_accumulation_steps accelerator.backward(UpperCamelCase__ ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() _a : Union[str, Any] = 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 ) with torch.no_grad(): _a : Dict = model(**UpperCamelCase__ ) _a : Optional[Any] = outputs.logits.argmax(dim=-1 ) _a , _a : int = accelerator.gather((predictions, batch["""labels"""]) ) # New Code # # First we check if it's a distributed system if accelerator.use_distributed: # Then see if we're on the last batch of our eval dataloader if step == len(UpperCamelCase__ ) - 1: # Last batch needs to be truncated on distributed systems as it contains additional samples _a : str = predictions[: len(eval_dataloader.dataset ) - samples_seen] _a : int = references[: len(eval_dataloader.dataset ) - samples_seen] else: # Otherwise we add the number of samples seen samples_seen += references.shape[0] # All of this can be avoided if you use `Accelerator.gather_for_metrics` instead of `Accelerator.gather`: # accelerator.gather_for_metrics((predictions, batch["labels"])) metric.add_batch( predictions=UpperCamelCase__ , references=UpperCamelCase__ , ) _a : int = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F"""epoch {epoch}:""" , UpperCamelCase__ ) def lowerCAmelCase__ ( ): '''simple docstring''' _a : Tuple = 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.""" ) _a : Optional[Any] = parser.parse_args() _a : Tuple = {"""lr""": 2e-5, """num_epochs""": 3, """seed""": 4_2, """batch_size""": 1_6} training_function(UpperCamelCase__ , UpperCamelCase__ ) if __name__ == "__main__": main()
324
1
"""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, FlaxCrossAttnUpBlockaD, FlaxDownBlockaD, FlaxUNetMidBlockaDCrossAttn, FlaxUpBlockaD, ) @flax.struct.dataclass class UpperCamelCase ( snake_case_ ): UpperCamelCase : jnp.ndarray @flax_register_to_config class UpperCamelCase ( nn.Module , snake_case_ , snake_case_ ): UpperCamelCase : int = 32 UpperCamelCase : int = 4 UpperCamelCase : int = 4 UpperCamelCase : Tuple[str] = ( "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "DownBlock2D", ) UpperCamelCase : Tuple[str] = ("UpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D") UpperCamelCase : Union[bool, Tuple[bool]] = False UpperCamelCase : Tuple[int] = (320, 640, 1_280, 1_280) UpperCamelCase : int = 2 UpperCamelCase : Union[int, Tuple[int]] = 8 UpperCamelCase : Optional[Union[int, Tuple[int]]] = None UpperCamelCase : int = 1_280 UpperCamelCase : float = 0.0 UpperCamelCase : bool = False UpperCamelCase : jnp.dtype = jnp.floataa UpperCamelCase : bool = True UpperCamelCase : int = 0 UpperCamelCase : bool = False def _lowercase ( self : Any , UpperCAmelCase__ : jax.random.KeyArray ) -> FrozenDict: # init input tensors _a : str = (1, self.in_channels, self.sample_size, self.sample_size) _a : Optional[int] = jnp.zeros(UpperCAmelCase__ , dtype=jnp.floataa ) _a : str = jnp.ones((1,) , dtype=jnp.intaa ) _a : List[str] = jnp.zeros((1, 1, self.cross_attention_dim) , dtype=jnp.floataa ) _a , _a : List[Any] = jax.random.split(UpperCAmelCase__ ) _a : str = {"""params""": params_rng, """dropout""": dropout_rng} return self.init(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ )["params"] def _lowercase ( self : int ) -> List[str]: _a : Union[str, Any] = self.block_out_channels _a : Any = 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 : Optional[int] = self.num_attention_heads or self.attention_head_dim # input _a : Union[str, Any] = nn.Conv( block_out_channels[0] , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) # time _a : Tuple = FlaxTimesteps( block_out_channels[0] , flip_sin_to_cos=self.flip_sin_to_cos , freq_shift=self.config.freq_shift ) _a : Optional[Any] = FlaxTimestepEmbedding(UpperCAmelCase__ , dtype=self.dtype ) _a : Any = self.only_cross_attention if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): _a : Dict = (only_cross_attention,) * len(self.down_block_types ) if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): _a : List[str] = (num_attention_heads,) * len(self.down_block_types ) # down _a : List[str] = [] _a : Optional[Any] = block_out_channels[0] for i, down_block_type in enumerate(self.down_block_types ): _a : List[str] = output_channel _a : List[Any] = block_out_channels[i] _a : List[str] = i == len(UpperCAmelCase__ ) - 1 if down_block_type == "CrossAttnDownBlock2D": _a : Dict = FlaxCrossAttnDownBlockaD( in_channels=UpperCAmelCase__ , out_channels=UpperCAmelCase__ , 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 : Optional[Any] = FlaxDownBlockaD( in_channels=UpperCAmelCase__ , out_channels=UpperCAmelCase__ , dropout=self.dropout , num_layers=self.layers_per_block , add_downsample=not is_final_block , dtype=self.dtype , ) down_blocks.append(UpperCAmelCase__ ) _a : Optional[int] = down_blocks # mid _a : Optional[Any] = 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 : int = [] _a : str = list(reversed(UpperCAmelCase__ ) ) _a : Union[str, Any] = list(reversed(UpperCAmelCase__ ) ) _a : str = list(reversed(UpperCAmelCase__ ) ) _a : Optional[int] = reversed_block_out_channels[0] for i, up_block_type in enumerate(self.up_block_types ): _a : int = output_channel _a : List[str] = reversed_block_out_channels[i] _a : Optional[Any] = reversed_block_out_channels[min(i + 1 , len(UpperCAmelCase__ ) - 1 )] _a : Optional[int] = i == len(UpperCAmelCase__ ) - 1 if up_block_type == "CrossAttnUpBlock2D": _a : Optional[int] = FlaxCrossAttnUpBlockaD( in_channels=UpperCAmelCase__ , out_channels=UpperCAmelCase__ , prev_output_channel=UpperCAmelCase__ , 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 : Tuple = FlaxUpBlockaD( in_channels=UpperCAmelCase__ , out_channels=UpperCAmelCase__ , prev_output_channel=UpperCAmelCase__ , num_layers=self.layers_per_block + 1 , add_upsample=not is_final_block , dropout=self.dropout , dtype=self.dtype , ) up_blocks.append(UpperCAmelCase__ ) _a : Optional[Any] = output_channel _a : Tuple = up_blocks # out _a : Tuple = nn.GroupNorm(num_groups=32 , epsilon=1E-5 ) _a : List[str] = nn.Conv( self.out_channels , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) def __call__( self : Tuple , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Tuple=None , UpperCAmelCase__ : List[Any]=None , UpperCAmelCase__ : bool = True , UpperCAmelCase__ : bool = False , ) -> Union[FlaxUNetaDConditionOutput, Tuple]: # 1. time if not isinstance(UpperCAmelCase__ , jnp.ndarray ): _a : int = jnp.array([timesteps] , dtype=jnp.intaa ) elif isinstance(UpperCAmelCase__ , jnp.ndarray ) and len(timesteps.shape ) == 0: _a : Tuple = timesteps.astype(dtype=jnp.floataa ) _a : Any = jnp.expand_dims(UpperCAmelCase__ , 0 ) _a : Optional[int] = self.time_proj(UpperCAmelCase__ ) _a : Optional[int] = self.time_embedding(UpperCAmelCase__ ) # 2. pre-process _a : Tuple = jnp.transpose(UpperCAmelCase__ , (0, 2, 3, 1) ) _a : Tuple = self.conv_in(UpperCAmelCase__ ) # 3. down _a : int = (sample,) for down_block in self.down_blocks: if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): _a , _a : Optional[Any] = down_block(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , deterministic=not train ) else: _a , _a : int = down_block(UpperCAmelCase__ , UpperCAmelCase__ , deterministic=not train ) down_block_res_samples += res_samples if down_block_additional_residuals is not None: _a : str = () for down_block_res_sample, down_block_additional_residual in zip( UpperCAmelCase__ , UpperCAmelCase__ ): down_block_res_sample += down_block_additional_residual new_down_block_res_samples += (down_block_res_sample,) _a : int = new_down_block_res_samples # 4. mid _a : Union[str, Any] = self.mid_block(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , 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 : str = down_block_res_samples[-(self.layers_per_block + 1) :] _a : Optional[Any] = down_block_res_samples[: -(self.layers_per_block + 1)] if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): _a : Union[str, Any] = up_block( UpperCAmelCase__ , temb=UpperCAmelCase__ , encoder_hidden_states=UpperCAmelCase__ , res_hidden_states_tuple=UpperCAmelCase__ , deterministic=not train , ) else: _a : Tuple = up_block(UpperCAmelCase__ , temb=UpperCAmelCase__ , res_hidden_states_tuple=UpperCAmelCase__ , deterministic=not train ) # 6. post-process _a : Dict = self.conv_norm_out(UpperCAmelCase__ ) _a : int = nn.silu(UpperCAmelCase__ ) _a : List[str] = self.conv_out(UpperCAmelCase__ ) _a : Any = jnp.transpose(UpperCAmelCase__ , (0, 3, 1, 2) ) if not return_dict: return (sample,) return FlaxUNetaDConditionOutput(sample=UpperCAmelCase__ )
324
"""simple docstring""" import numpy as np def lowerCAmelCase__ ( UpperCamelCase__ ): '''simple docstring''' return 1 / (1 + np.exp(-vector )) def lowerCAmelCase__ ( UpperCamelCase__ ): '''simple docstring''' return vector * sigmoid(1.702 * vector ) if __name__ == "__main__": import doctest doctest.testmod()
324
1
"""simple docstring""" import argparse import math import traceback import dateutil.parser as date_parser import requests def lowerCAmelCase__ ( UpperCamelCase__ ): '''simple docstring''' _a : List[str] = {} _a : List[str] = job["""started_at"""] _a : List[str] = job["""completed_at"""] _a : List[Any] = date_parser.parse(UpperCamelCase__ ) _a : Union[str, Any] = date_parser.parse(UpperCamelCase__ ) _a : Tuple = round((end_datetime - start_datetime).total_seconds() / 60.0 ) _a : List[Any] = start _a : Dict = end _a : Any = duration_in_min return job_info def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__=None ): '''simple docstring''' _a : Optional[int] = None if token is not None: _a : Dict = {"""Accept""": """application/vnd.github+json""", """Authorization""": F"""Bearer {token}"""} _a : List[Any] = F"""https://api.github.com/repos/huggingface/transformers/actions/runs/{workflow_run_id}/jobs?per_page=100""" _a : List[str] = requests.get(UpperCamelCase__ , headers=UpperCamelCase__ ).json() _a : int = {} try: job_time.update({job["""name"""]: extract_time_from_single_job(UpperCamelCase__ ) for job in result["""jobs"""]} ) _a : str = math.ceil((result["""total_count"""] - 1_0_0) / 1_0_0 ) for i in range(UpperCamelCase__ ): _a : Optional[int] = requests.get(url + F"""&page={i + 2}""" , headers=UpperCamelCase__ ).json() job_time.update({job["""name"""]: extract_time_from_single_job(UpperCamelCase__ ) for job in result["""jobs"""]} ) return job_time except Exception: print(F"""Unknown error, could not fetch links:\n{traceback.format_exc()}""" ) return {} if __name__ == "__main__": _snake_case = argparse.ArgumentParser() # Required parameters parser.add_argument('--workflow_run_id', type=str, required=True, help='A GitHub Actions workflow run id.') _snake_case = parser.parse_args() _snake_case = get_job_time(args.workflow_run_id) _snake_case = dict(sorted(job_time.items(), key=lambda item: item[1]["duration"], reverse=True)) for k, v in job_time.items(): print(F'''{k}: {v['duration']}''')
324
"""simple docstring""" import unittest from transformers import CamembertTokenizer, CamembertTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.utils import is_torch_available from ...test_tokenization_common import TokenizerTesterMixin _snake_case = get_tests_dir('fixtures/test_sentencepiece.model') _snake_case = get_tests_dir('fixtures/test_sentencepiece_bpe.model') _snake_case = 'pt' if is_torch_available() else 'tf' @require_sentencepiece @require_tokenizers class UpperCamelCase ( snake_case_ , unittest.TestCase ): UpperCamelCase : str = CamembertTokenizer UpperCamelCase : List[Any] = CamembertTokenizerFast UpperCamelCase : Optional[int] = True UpperCamelCase : Union[str, Any] = True def _lowercase ( self : List[Any] ) -> Union[str, Any]: super().setUp() # We have a SentencePiece fixture for testing _a : List[Any] = CamembertTokenizer(UpperCAmelCase__ ) tokenizer.save_pretrained(self.tmpdirname ) def _lowercase ( self : List[str] ) -> Tuple: _a : Optional[Any] = """<pad>""" _a : Tuple = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(UpperCAmelCase__ ) , UpperCAmelCase__ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(UpperCAmelCase__ ) , UpperCAmelCase__ ) def _lowercase ( self : Union[str, Any] ) -> str: _a : List[str] = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , """<s>NOTUSED""" ) self.assertEqual(vocab_keys[1] , """<pad>""" ) self.assertEqual(vocab_keys[-1] , """<mask>""" ) self.assertEqual(len(UpperCAmelCase__ ) , 1004 ) def _lowercase ( self : List[str] ) -> List[Any]: self.assertEqual(self.get_tokenizer().vocab_size , 1005 ) def _lowercase ( self : Union[str, Any] ) -> str: _a : Tuple = CamembertTokenizer(UpperCAmelCase__ ) tokenizer.save_pretrained(self.tmpdirname ) _a : List[Any] = CamembertTokenizerFast.from_pretrained(self.tmpdirname ) _a : Any = """I was born in 92000, and this is falsé.""" _a : Union[str, Any] = tokenizer.encode(UpperCAmelCase__ ) _a : Dict = rust_tokenizer.encode(UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) _a : Tuple = tokenizer.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) _a : List[Any] = rust_tokenizer.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) # <unk> tokens are not the same for `rust` than for `slow`. # Because spm gives back raw token instead of `unk` in EncodeAsPieces # tokens = tokenizer.tokenize(sequence) _a : List[str] = tokenizer.convert_ids_to_tokens(UpperCAmelCase__ ) _a : int = rust_tokenizer.tokenize(UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) def _lowercase ( self : Dict ) -> List[str]: if not self.test_rust_tokenizer: return _a : Optional[int] = self.get_tokenizer() _a : Tuple = self.get_rust_tokenizer() _a : List[Any] = """I was born in 92000, and this is falsé.""" _a : List[str] = tokenizer.tokenize(UpperCAmelCase__ ) _a : Union[str, Any] = rust_tokenizer.tokenize(UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) _a : int = tokenizer.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) _a : Optional[int] = rust_tokenizer.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) _a : int = self.get_rust_tokenizer() _a : Optional[Any] = tokenizer.encode(UpperCAmelCase__ ) _a : Dict = rust_tokenizer.encode(UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) @slow def _lowercase ( self : Tuple ) -> List[Any]: # fmt: off _a : Dict = {"""input_ids""": [[5, 54, 7196, 297, 30, 23, 776, 18, 11, 3215, 3705, 8252, 22, 3164, 1181, 2116, 29, 16, 813, 25, 791, 3314, 20, 3446, 38, 27575, 120, 6, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [5, 468, 17, 11, 9088, 20, 1517, 8, 22804, 18818, 10, 38, 629, 607, 607, 142, 19, 7196, 867, 56, 10326, 24, 2267, 20, 416, 5072, 15612, 233, 734, 7, 2399, 27, 16, 3015, 1649, 7, 24, 20, 4338, 2399, 27, 13, 3400, 14, 13, 6189, 8, 930, 9, 6]], """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, 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, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]} # noqa: E501 # fmt: on # camembert is a french model. So we also use french texts. _a : Union[str, Any] = [ """Le transformeur est un modèle d'apprentissage profond introduit en 2017, """ """utilisé principalement dans le domaine du traitement automatique des langues (TAL).""", """À l'instar des réseaux de neurones récurrents (RNN), les transformeurs sont conçus """ """pour gérer des données séquentielles, telles que le langage naturel, pour des tâches """ """telles que la traduction et la synthèse de texte.""", ] self.tokenizer_integration_test_util( expected_encoding=UpperCAmelCase__ , model_name="""camembert-base""" , revision="""3a0641d9a1aeb7e848a74299e7e4c4bca216b4cf""" , sequences=UpperCAmelCase__ , )
324
1
"""simple docstring""" from math import atan, cos, radians, sin, tan from .haversine_distance import haversine_distance _snake_case = 6_37_81_37.0 _snake_case = 6_35_67_52.31_42_45 _snake_case = 637_8137 def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' _a : Any = (AXIS_A - AXIS_B) / AXIS_A # Parametric latitudes # https://en.wikipedia.org/wiki/Latitude#Parametric_(or_reduced)_latitude _a : Optional[int] = atan((1 - flattening) * tan(radians(UpperCamelCase__ ) ) ) _a : Optional[int] = atan((1 - flattening) * tan(radians(UpperCamelCase__ ) ) ) # Compute central angle between two points # using haversine theta. sigma = haversine_distance / equatorial radius _a : Tuple = haversine_distance(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) / EQUATORIAL_RADIUS # Intermediate P and Q values _a : Tuple = (b_lata + b_lata) / 2 _a : List[Any] = (b_lata - b_lata) / 2 # Intermediate X value # X = (sigma - sin(sigma)) * sin^2Pcos^2Q / cos^2(sigma/2) _a : Optional[int] = (sin(UpperCamelCase__ ) ** 2) * (cos(UpperCamelCase__ ) ** 2) _a : Dict = cos(sigma / 2 ) ** 2 _a : List[Any] = (sigma - sin(UpperCamelCase__ )) * (x_numerator / x_demonimator) # Intermediate Y value # Y = (sigma + sin(sigma)) * cos^2Psin^2Q / sin^2(sigma/2) _a : List[str] = (cos(UpperCamelCase__ ) ** 2) * (sin(UpperCamelCase__ ) ** 2) _a : Optional[Any] = sin(sigma / 2 ) ** 2 _a : str = (sigma + sin(UpperCamelCase__ )) * (y_numerator / y_denominator) return EQUATORIAL_RADIUS * (sigma - ((flattening / 2) * (x_value + y_value))) if __name__ == "__main__": import doctest doctest.testmod()
324
"""simple docstring""" import argparse import collections import os import re import tempfile import pandas as pd from datasets import Dataset from huggingface_hub import hf_hub_download, upload_folder from transformers.utils import direct_transformers_import # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/update_metadata.py _snake_case = 'src/transformers' # This is to make sure the transformers module imported is the one in the repo. _snake_case = direct_transformers_import(TRANSFORMERS_PATH) # Regexes that match TF/Flax/PT model names. _snake_case = re.compile(r'TF(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)') _snake_case = re.compile(r'Flax(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)') # Will match any TF or Flax model too so need to be in an else branch afterthe two previous regexes. _snake_case = re.compile(r'(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)') # Fill this with tuples (pipeline_tag, model_mapping, auto_model) _snake_case = [ ('pretraining', 'MODEL_FOR_PRETRAINING_MAPPING_NAMES', 'AutoModelForPreTraining'), ('feature-extraction', 'MODEL_MAPPING_NAMES', 'AutoModel'), ('audio-classification', 'MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES', 'AutoModelForAudioClassification'), ('text-generation', 'MODEL_FOR_CAUSAL_LM_MAPPING_NAMES', 'AutoModelForCausalLM'), ('automatic-speech-recognition', 'MODEL_FOR_CTC_MAPPING_NAMES', 'AutoModelForCTC'), ('image-classification', 'MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES', 'AutoModelForImageClassification'), ('image-segmentation', 'MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES', 'AutoModelForImageSegmentation'), ('fill-mask', 'MODEL_FOR_MASKED_LM_MAPPING_NAMES', 'AutoModelForMaskedLM'), ('object-detection', 'MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES', 'AutoModelForObjectDetection'), ( 'zero-shot-object-detection', 'MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES', 'AutoModelForZeroShotObjectDetection', ), ('question-answering', 'MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES', 'AutoModelForQuestionAnswering'), ('text2text-generation', 'MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES', 'AutoModelForSeq2SeqLM'), ('text-classification', 'MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES', 'AutoModelForSequenceClassification'), ('automatic-speech-recognition', 'MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES', 'AutoModelForSpeechSeq2Seq'), ( 'table-question-answering', 'MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING_NAMES', 'AutoModelForTableQuestionAnswering', ), ('token-classification', 'MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES', 'AutoModelForTokenClassification'), ('multiple-choice', 'MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES', 'AutoModelForMultipleChoice'), ( 'next-sentence-prediction', 'MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING_NAMES', 'AutoModelForNextSentencePrediction', ), ( 'audio-frame-classification', 'MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES', 'AutoModelForAudioFrameClassification', ), ('audio-xvector', 'MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES', 'AutoModelForAudioXVector'), ( 'document-question-answering', 'MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES', 'AutoModelForDocumentQuestionAnswering', ), ( 'visual-question-answering', 'MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING_NAMES', 'AutoModelForVisualQuestionAnswering', ), ('image-to-text', 'MODEL_FOR_FOR_VISION_2_SEQ_MAPPING_NAMES', 'AutoModelForVision2Seq'), ( 'zero-shot-image-classification', 'MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING_NAMES', 'AutoModelForZeroShotImageClassification', ), ('depth-estimation', 'MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES', 'AutoModelForDepthEstimation'), ('video-classification', 'MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING_NAMES', 'AutoModelForVideoClassification'), ('mask-generation', 'MODEL_FOR_MASK_GENERATION_MAPPING_NAMES', 'AutoModelForMaskGeneration'), ] def lowerCAmelCase__ ( UpperCamelCase__ ): '''simple docstring''' _a : Dict = re.finditer(""".+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)""" , UpperCamelCase__ ) return [m.group(0 ) for m in matches] def lowerCAmelCase__ ( ): '''simple docstring''' _a : Tuple = transformers_module.models.auto.configuration_auto.CONFIG_MAPPING_NAMES _a : Optional[int] = { config.replace("""Config""" , """""" ): model_type for model_type, config in config_maping_names.items() } # Dictionaries flagging if each model prefix has a backend in PT/TF/Flax. _a : List[Any] = collections.defaultdict(UpperCamelCase__ ) _a : List[str] = collections.defaultdict(UpperCamelCase__ ) _a : Tuple = collections.defaultdict(UpperCamelCase__ ) # Let's lookup through all transformers object (once) and find if models are supported by a given backend. for attr_name in dir(UpperCamelCase__ ): _a : str = None if _re_tf_models.match(UpperCamelCase__ ) is not None: _a : List[Any] = tf_models _a : int = _re_tf_models.match(UpperCamelCase__ ).groups()[0] elif _re_flax_models.match(UpperCamelCase__ ) is not None: _a : Any = flax_models _a : Any = _re_flax_models.match(UpperCamelCase__ ).groups()[0] elif _re_pt_models.match(UpperCamelCase__ ) is not None: _a : int = pt_models _a : int = _re_pt_models.match(UpperCamelCase__ ).groups()[0] if lookup_dict is not None: while len(UpperCamelCase__ ) > 0: if attr_name in model_prefix_to_model_type: _a : Optional[int] = True break # Try again after removing the last word in the name _a : List[Any] = """""".join(camel_case_split(UpperCamelCase__ )[:-1] ) _a : Optional[int] = set(list(pt_models.keys() ) + list(tf_models.keys() ) + list(flax_models.keys() ) ) _a : Dict = list(UpperCamelCase__ ) all_models.sort() _a : str = {"""model_type""": all_models} _a : List[Any] = [pt_models[t] for t in all_models] _a : str = [tf_models[t] for t in all_models] _a : Optional[int] = [flax_models[t] for t in all_models] # Now let's use the auto-mapping names to make sure _a : str = {} for t in all_models: if t in transformers_module.models.auto.processing_auto.PROCESSOR_MAPPING_NAMES: _a : List[str] = """AutoProcessor""" elif t in transformers_module.models.auto.tokenization_auto.TOKENIZER_MAPPING_NAMES: _a : str = """AutoTokenizer""" elif t in transformers_module.models.auto.feature_extraction_auto.FEATURE_EXTRACTOR_MAPPING_NAMES: _a : int = """AutoFeatureExtractor""" else: # Default to AutoTokenizer if a model has nothing, for backward compatibility. _a : int = """AutoTokenizer""" _a : Any = [processors[t] for t in all_models] return pd.DataFrame(UpperCamelCase__ ) def lowerCAmelCase__ ( UpperCamelCase__ ): '''simple docstring''' _a : List[Any] = [ transformers_module.models.auto.modeling_auto, transformers_module.models.auto.modeling_tf_auto, transformers_module.models.auto.modeling_flax_auto, ] for pipeline_tag, model_mapping, auto_class in PIPELINE_TAGS_AND_AUTO_MODELS: _a : List[Any] = [model_mapping, F"""TF_{model_mapping}""", F"""FLAX_{model_mapping}"""] _a : Union[str, Any] = [auto_class, F"""TF_{auto_class}""", F"""Flax_{auto_class}"""] # Loop through all three frameworks for module, cls, mapping in zip(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): # The type of pipeline may not exist in this framework if not hasattr(UpperCamelCase__ , UpperCamelCase__ ): continue # First extract all model_names _a : str = [] for name in getattr(UpperCamelCase__ , UpperCamelCase__ ).values(): if isinstance(UpperCamelCase__ , UpperCamelCase__ ): model_names.append(UpperCamelCase__ ) else: model_names.extend(list(UpperCamelCase__ ) ) # Add pipeline tag and auto model class for those models table.update({model_name: (pipeline_tag, cls) for model_name in model_names} ) return table def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' _a : Dict = get_frameworks_table() _a : Optional[Any] = Dataset.from_pandas(UpperCamelCase__ ) _a : Any = hf_hub_download( """huggingface/transformers-metadata""" , """pipeline_tags.json""" , repo_type="""dataset""" , token=UpperCamelCase__ ) _a : List[Any] = Dataset.from_json(UpperCamelCase__ ) _a : List[str] = { tags_dataset[i]["""model_class"""]: (tags_dataset[i]["""pipeline_tag"""], tags_dataset[i]["""auto_class"""]) for i in range(len(UpperCamelCase__ ) ) } _a : str = update_pipeline_and_auto_class_table(UpperCamelCase__ ) # Sort the model classes to avoid some nondeterministic updates to create false update commits. _a : int = sorted(table.keys() ) _a : Union[str, Any] = pd.DataFrame( { """model_class""": model_classes, """pipeline_tag""": [table[m][0] for m in model_classes], """auto_class""": [table[m][1] for m in model_classes], } ) _a : Dict = Dataset.from_pandas(UpperCamelCase__ ) with tempfile.TemporaryDirectory() as tmp_dir: frameworks_dataset.to_json(os.path.join(UpperCamelCase__ , """frameworks.json""" ) ) tags_dataset.to_json(os.path.join(UpperCamelCase__ , """pipeline_tags.json""" ) ) if commit_sha is not None: _a : List[str] = ( F"""Update with commit {commit_sha}\n\nSee: """ F"""https://github.com/huggingface/transformers/commit/{commit_sha}""" ) else: _a : Optional[Any] = """Update""" upload_folder( repo_id="""huggingface/transformers-metadata""" , folder_path=UpperCamelCase__ , repo_type="""dataset""" , token=UpperCamelCase__ , commit_message=UpperCamelCase__ , ) def lowerCAmelCase__ ( ): '''simple docstring''' _a : List[str] = {tag: cls for tag, _, cls in PIPELINE_TAGS_AND_AUTO_MODELS} _a : Any = transformers_module.pipelines.SUPPORTED_TASKS _a : List[str] = [] for key in pipeline_tasks: if key not in in_table: _a : Tuple = pipeline_tasks[key]["""pt"""] if isinstance(UpperCamelCase__ , (list, tuple) ): _a : Dict = model[0] _a : List[str] = model.__name__ if model not in in_table.values(): missing.append(UpperCamelCase__ ) if len(UpperCamelCase__ ) > 0: _a : Union[str, Any] = """, """.join(UpperCamelCase__ ) raise ValueError( """The following pipeline tags are not present in the `PIPELINE_TAGS_AND_AUTO_MODELS` constant inside """ F"""`utils/update_metadata.py`: {msg}. Please add them!""" ) if __name__ == "__main__": _snake_case = argparse.ArgumentParser() parser.add_argument('--token', type=str, help='The token to use to push to the transformers-metadata dataset.') parser.add_argument('--commit_sha', type=str, help='The sha of the commit going with this update.') parser.add_argument('--check-only', action='store_true', help='Activate to just check all pipelines are present.') _snake_case = parser.parse_args() if args.check_only: check_pipeline_tags() else: update_metadata(args.token, args.commit_sha)
324
1
"""simple docstring""" import random class UpperCamelCase : @staticmethod def _lowercase ( UpperCAmelCase__ : str ) -> tuple[list[int], list[int]]: _a : Union[str, Any] = [ord(UpperCAmelCase__ ) for i in text] _a : Any = [] _a : Union[str, Any] = [] for i in plain: _a : Optional[Any] = random.randint(1 , 300 ) _a : Dict = (i + k) * k cipher.append(UpperCAmelCase__ ) key.append(UpperCAmelCase__ ) return cipher, key @staticmethod def _lowercase ( UpperCAmelCase__ : list[int] , UpperCAmelCase__ : list[int] ) -> str: _a : Optional[int] = [] for i in range(len(UpperCAmelCase__ ) ): _a : str = int((cipher[i] - (key[i]) ** 2) / key[i] ) plain.append(chr(UpperCAmelCase__ ) ) return "".join(UpperCAmelCase__ ) if __name__ == "__main__": _snake_case , _snake_case = Onepad().encrypt('Hello') print(c, k) print(Onepad().decrypt(c, k))
324
"""simple docstring""" import os import pytest import yaml from datasets.features.features import Features, Value from datasets.info import DatasetInfo, DatasetInfosDict @pytest.mark.parametrize( """files""" , [ ["""full:README.md""", """dataset_infos.json"""], ["""empty:README.md""", """dataset_infos.json"""], ["""dataset_infos.json"""], ["""full:README.md"""], ] , ) def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' _a : Dict = tmp_path_factory.mktemp("""dset_infos_dir""" ) if "full:README.md" in files: with open(dataset_infos_dir / """README.md""" , """w""" ) as f: f.write("""---\ndataset_info:\n dataset_size: 42\n---""" ) if "empty:README.md" in files: with open(dataset_infos_dir / """README.md""" , """w""" ) as f: f.write("""""" ) # we want to support dataset_infos.json for backward compatibility if "dataset_infos.json" in files: with open(dataset_infos_dir / """dataset_infos.json""" , """w""" ) as f: f.write("""{\"default\": {\"dataset_size\": 42}}""" ) _a : Dict = DatasetInfosDict.from_directory(UpperCamelCase__ ) assert dataset_infos assert dataset_infos["default"].dataset_size == 4_2 @pytest.mark.parametrize( """dataset_info""" , [ DatasetInfo(), DatasetInfo( description="""foo""" , features=Features({"""a""": Value("""int32""" )} ) , builder_name="""builder""" , config_name="""config""" , version="""1.0.0""" , splits=[{"""name""": """train"""}] , download_size=4_2 , ), ] , ) def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' _a : Optional[int] = str(UpperCamelCase__ ) dataset_info.write_to_directory(UpperCamelCase__ ) _a : Any = DatasetInfo.from_directory(UpperCamelCase__ ) assert dataset_info == reloaded assert os.path.exists(os.path.join(UpperCamelCase__ , """dataset_info.json""" ) ) def lowerCAmelCase__ ( ): '''simple docstring''' _a : Dict = DatasetInfo( description="""foo""" , citation="""bar""" , homepage="""https://foo.bar""" , license="""CC0""" , features=Features({"""a""": Value("""int32""" )} ) , post_processed={} , supervised_keys=() , task_templates=[] , builder_name="""builder""" , config_name="""config""" , version="""1.0.0""" , splits=[{"""name""": """train""", """num_examples""": 4_2}] , download_checksums={} , download_size=1_3_3_7 , post_processing_size=4_4_2 , dataset_size=1_2_3_4 , size_in_bytes=1_3_3_7 + 4_4_2 + 1_2_3_4 , ) _a : int = dataset_info._to_yaml_dict() assert sorted(UpperCamelCase__ ) == sorted(DatasetInfo._INCLUDED_INFO_IN_YAML ) for key in DatasetInfo._INCLUDED_INFO_IN_YAML: assert key in dataset_info_yaml_dict assert isinstance(dataset_info_yaml_dict[key] , (list, dict, int, str) ) _a : List[str] = yaml.safe_dump(UpperCamelCase__ ) _a : Optional[int] = yaml.safe_load(UpperCamelCase__ ) assert dataset_info_yaml_dict == reloaded def lowerCAmelCase__ ( ): '''simple docstring''' _a : List[Any] = DatasetInfo() _a : Any = dataset_info._to_yaml_dict() assert dataset_info_yaml_dict == {} @pytest.mark.parametrize( """dataset_infos_dict""" , [ DatasetInfosDict(), DatasetInfosDict({"""default""": DatasetInfo()} ), DatasetInfosDict({"""my_config_name""": DatasetInfo()} ), DatasetInfosDict( { """default""": DatasetInfo( description="""foo""" , features=Features({"""a""": Value("""int32""" )} ) , builder_name="""builder""" , config_name="""config""" , version="""1.0.0""" , splits=[{"""name""": """train"""}] , download_size=4_2 , ) } ), DatasetInfosDict( { """v1""": DatasetInfo(dataset_size=4_2 ), """v2""": DatasetInfo(dataset_size=1_3_3_7 ), } ), ] , ) def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' _a : List[Any] = str(UpperCamelCase__ ) dataset_infos_dict.write_to_directory(UpperCamelCase__ ) _a : List[Any] = DatasetInfosDict.from_directory(UpperCamelCase__ ) # the config_name of the dataset_infos_dict take over the attribute for config_name, dataset_info in dataset_infos_dict.items(): _a : str = config_name # the yaml representation doesn't include fields like description or citation # so we just test that we can recover what we can from the yaml _a : Dict = DatasetInfo._from_yaml_dict(dataset_info._to_yaml_dict() ) assert dataset_infos_dict == reloaded if dataset_infos_dict: assert os.path.exists(os.path.join(UpperCamelCase__ , """README.md""" ) )
324
1
"""simple docstring""" def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' _a : str = len(UpperCamelCase__ ) print("""The following activities are selected:""" ) # The first activity is always selected _a : List[Any] = 0 print(UpperCamelCase__ , end=""",""" ) # Consider rest of the activities for j in range(UpperCamelCase__ ): # If this activity has start time greater than # or equal to the finish time of previously # selected activity, then select it if start[j] >= finish[i]: print(UpperCamelCase__ , end=""",""" ) _a : Union[str, Any] = j if __name__ == "__main__": import doctest doctest.testmod() _snake_case = [1, 3, 0, 5, 8, 5] _snake_case = [2, 4, 6, 7, 9, 9] print_max_activities(start, finish)
324
"""simple docstring""" 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 , snake_case_ ): def _lowercase ( self : int ) -> int: _a : Optional[Any] = load_tool("""text-to-speech""" ) self.tool.setup() def _lowercase ( self : List[str] ) -> Union[str, Any]: # SpeechT5 isn't deterministic torch.manual_seed(0 ) _a : str = self.tool("""hey""" ) _a : List[str] = result.to_raw() self.assertTrue( torch.allclose( resulting_tensor[:3] , torch.tensor([-0.0_0_0_5_9_6_6_6_6_8_8_3_2_1_1_5_8_2_9, -0.0_0_0_3_6_5_7_6_4_0_1_9_0_7_9_5_0_6_4, -0.0_0_0_1_3_4_3_9_5_0_2_7_9_9_8_8_3_4_8_5] ) , ) ) def _lowercase ( self : Optional[int] ) -> Optional[Any]: # SpeechT5 isn't deterministic torch.manual_seed(0 ) _a : int = self.tool("""hey""" ) _a : str = result.to_raw() self.assertTrue( torch.allclose( resulting_tensor[:3] , torch.tensor([-0.0_0_0_5_9_6_6_6_6_8_8_3_2_1_1_5_8_2_9, -0.0_0_0_3_6_5_7_6_4_0_1_9_0_7_9_5_0_6_4, -0.0_0_0_1_3_4_3_9_5_0_2_7_9_9_8_8_3_4_8_5] ) , ) )
324
1
"""simple docstring""" from datetime import datetime import matplotlib.pyplot as plt import torch def lowerCAmelCase__ ( UpperCamelCase__ ): '''simple docstring''' for param in module.parameters(): _a : Optional[Any] = False def lowerCAmelCase__ ( ): '''simple docstring''' _a : int = """cuda""" if torch.cuda.is_available() else """cpu""" if torch.backends.mps.is_available() and torch.backends.mps.is_built(): _a : List[str] = """mps""" if device == "mps": print( """WARNING: MPS currently doesn't seem to work, and messes up backpropagation without any visible torch""" """ errors. I recommend using CUDA on a colab notebook or CPU instead if you're facing inexplicable issues""" """ with generations.""" ) return device def lowerCAmelCase__ ( UpperCamelCase__ ): '''simple docstring''' _a : int = plt.imshow(UpperCamelCase__ ) fig.axes.get_xaxis().set_visible(UpperCamelCase__ ) fig.axes.get_yaxis().set_visible(UpperCamelCase__ ) plt.show() def lowerCAmelCase__ ( ): '''simple docstring''' _a : List[Any] = datetime.now() _a : Tuple = current_time.strftime("""%H:%M:%S""" ) return timestamp
324
"""simple docstring""" import copy import json import os import tempfile from transformers import is_torch_available from .test_configuration_utils import config_common_kwargs class UpperCamelCase ( snake_case_ ): def __init__( self : Union[str, Any] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : int=None , UpperCAmelCase__ : Optional[Any]=True , UpperCAmelCase__ : List[str]=None , **UpperCAmelCase__ : str ) -> int: _a : str = parent _a : Union[str, Any] = config_class _a : List[Any] = has_text_modality _a : List[Any] = kwargs _a : List[Any] = common_properties def _lowercase ( self : int ) -> Tuple: _a : List[str] = self.config_class(**self.inputs_dict ) _a : Dict = ( ["""hidden_size""", """num_attention_heads""", """num_hidden_layers"""] if self.common_properties is None else self.common_properties ) # Add common fields for text models if self.has_text_modality: common_properties.extend(["""vocab_size"""] ) # Test that config has the common properties as getters for prop in common_properties: self.parent.assertTrue(hasattr(UpperCAmelCase__ , UpperCAmelCase__ ) , msg=f"""`{prop}` does not exist""" ) # Test that config has the common properties as setter for idx, name in enumerate(UpperCAmelCase__ ): try: setattr(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) self.parent.assertEqual( getattr(UpperCAmelCase__ , UpperCAmelCase__ ) , UpperCAmelCase__ , msg=f"""`{name} value {idx} expected, but was {getattr(UpperCAmelCase__ , UpperCAmelCase__ )}""" ) except NotImplementedError: # Some models might not be able to implement setters for common_properties # In that case, a NotImplementedError is raised pass # Test if config class can be called with Config(prop_name=..) for idx, name in enumerate(UpperCAmelCase__ ): try: _a : Optional[int] = self.config_class(**{name: idx} ) self.parent.assertEqual( getattr(UpperCAmelCase__ , UpperCAmelCase__ ) , UpperCAmelCase__ , msg=f"""`{name} value {idx} expected, but was {getattr(UpperCAmelCase__ , UpperCAmelCase__ )}""" ) except NotImplementedError: # Some models might not be able to implement setters for common_properties # In that case, a NotImplementedError is raised pass def _lowercase ( self : Optional[int] ) -> Optional[Any]: _a : Optional[Any] = self.config_class(**self.inputs_dict ) _a : List[str] = json.loads(config.to_json_string() ) for key, value in self.inputs_dict.items(): self.parent.assertEqual(obj[key] , UpperCAmelCase__ ) def _lowercase ( self : int ) -> List[str]: _a : Optional[Any] = self.config_class(**self.inputs_dict ) with tempfile.TemporaryDirectory() as tmpdirname: _a : Tuple = os.path.join(UpperCAmelCase__ , """config.json""" ) config_first.to_json_file(UpperCAmelCase__ ) _a : List[str] = self.config_class.from_json_file(UpperCAmelCase__ ) self.parent.assertEqual(config_second.to_dict() , config_first.to_dict() ) def _lowercase ( self : Union[str, Any] ) -> Dict: _a : Dict = self.config_class(**self.inputs_dict ) with tempfile.TemporaryDirectory() as tmpdirname: config_first.save_pretrained(UpperCAmelCase__ ) _a : Dict = self.config_class.from_pretrained(UpperCAmelCase__ ) self.parent.assertEqual(config_second.to_dict() , config_first.to_dict() ) def _lowercase ( self : Dict ) -> Tuple: _a : List[Any] = self.config_class(**self.inputs_dict ) _a : Any = """test""" with tempfile.TemporaryDirectory() as tmpdirname: _a : List[Any] = os.path.join(UpperCAmelCase__ , UpperCAmelCase__ ) config_first.save_pretrained(UpperCAmelCase__ ) _a : List[Any] = self.config_class.from_pretrained(UpperCAmelCase__ , subfolder=UpperCAmelCase__ ) self.parent.assertEqual(config_second.to_dict() , config_first.to_dict() ) def _lowercase ( self : List[str] ) -> Union[str, Any]: _a : Tuple = self.config_class(**self.inputs_dict , num_labels=5 ) self.parent.assertEqual(len(config.idalabel ) , 5 ) self.parent.assertEqual(len(config.labelaid ) , 5 ) _a : Union[str, Any] = 3 self.parent.assertEqual(len(config.idalabel ) , 3 ) self.parent.assertEqual(len(config.labelaid ) , 3 ) def _lowercase ( self : Tuple ) -> List[str]: if self.config_class.is_composition: return _a : str = self.config_class() self.parent.assertIsNotNone(UpperCAmelCase__ ) def _lowercase ( self : List[Any] ) -> Optional[Any]: _a : Dict = copy.deepcopy(UpperCAmelCase__ ) _a : Any = self.config_class(**UpperCAmelCase__ ) _a : str = [] for key, value in config_common_kwargs.items(): if key == "torch_dtype": if not is_torch_available(): continue else: import torch if config.torch_dtype != torch.floataa: wrong_values.append(("""torch_dtype""", config.torch_dtype, torch.floataa) ) elif getattr(UpperCAmelCase__ , UpperCAmelCase__ ) != value: wrong_values.append((key, getattr(UpperCAmelCase__ , UpperCAmelCase__ ), value) ) if len(UpperCAmelCase__ ) > 0: _a : List[Any] = """\n""".join([f"""- {v[0]}: got {v[1]} instead of {v[2]}""" for v in wrong_values] ) raise ValueError(f"""The following keys were not properly set in the config:\n{errors}""" ) def _lowercase ( self : int ) -> Union[str, Any]: self.create_and_test_config_common_properties() self.create_and_test_config_to_json_string() self.create_and_test_config_to_json_file() self.create_and_test_config_from_and_save_pretrained() self.create_and_test_config_from_and_save_pretrained_subfolder() self.create_and_test_config_with_num_labels() self.check_config_can_be_init_without_params() self.check_config_arguments_init()
324
1
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging _snake_case = logging.get_logger(__name__) _snake_case = { 'unc-nlp/lxmert-base-uncased': 'https://huggingface.co/unc-nlp/lxmert-base-uncased/resolve/main/config.json', } class UpperCamelCase ( snake_case_ ): UpperCamelCase : int = '''lxmert''' UpperCamelCase : Tuple = {} def __init__( self : Dict , UpperCAmelCase__ : Union[str, Any]=30522 , UpperCAmelCase__ : str=768 , UpperCAmelCase__ : Any=12 , UpperCAmelCase__ : Dict=9500 , UpperCAmelCase__ : Tuple=1600 , UpperCAmelCase__ : int=400 , UpperCAmelCase__ : List[str]=3072 , UpperCAmelCase__ : Optional[Any]="gelu" , UpperCAmelCase__ : Any=0.1 , UpperCAmelCase__ : List[Any]=0.1 , UpperCAmelCase__ : int=512 , UpperCAmelCase__ : str=2 , UpperCAmelCase__ : Union[str, Any]=0.0_2 , UpperCAmelCase__ : Optional[int]=1E-12 , UpperCAmelCase__ : int=9 , UpperCAmelCase__ : Union[str, Any]=5 , UpperCAmelCase__ : Optional[Any]=5 , UpperCAmelCase__ : Tuple=2048 , UpperCAmelCase__ : List[Any]=4 , UpperCAmelCase__ : Union[str, Any]=6.6_7 , UpperCAmelCase__ : Any=True , UpperCAmelCase__ : str=True , UpperCAmelCase__ : str=True , UpperCAmelCase__ : Tuple=True , UpperCAmelCase__ : List[Any]=True , UpperCAmelCase__ : str=True , UpperCAmelCase__ : str=True , **UpperCAmelCase__ : List[Any] , ) -> Optional[int]: _a : Optional[int] = vocab_size _a : List[str] = hidden_size _a : Any = num_attention_heads _a : str = hidden_act _a : Union[str, Any] = intermediate_size _a : int = hidden_dropout_prob _a : List[str] = attention_probs_dropout_prob _a : List[str] = max_position_embeddings _a : Dict = type_vocab_size _a : int = initializer_range _a : Union[str, Any] = layer_norm_eps _a : Optional[int] = num_qa_labels _a : int = num_object_labels _a : List[Any] = num_attr_labels _a : List[Any] = l_layers _a : Tuple = x_layers _a : Union[str, Any] = r_layers _a : Dict = visual_feat_dim _a : Optional[int] = visual_pos_dim _a : Dict = visual_loss_normalizer _a : Any = task_matched _a : int = task_mask_lm _a : Any = task_obj_predict _a : int = task_qa _a : Union[str, Any] = visual_obj_loss _a : str = visual_attr_loss _a : List[Any] = visual_feat_loss _a : Optional[int] = {"""vision""": r_layers, """cross_encoder""": x_layers, """language""": l_layers} super().__init__(**UpperCAmelCase__ )
324
"""simple docstring""" import os from huggingface_hub.constants import HUGGINGFACE_HUB_CACHE, hf_cache_home _snake_case = HUGGINGFACE_HUB_CACHE _snake_case = 'config.json' _snake_case = 'diffusion_pytorch_model.bin' _snake_case = 'diffusion_flax_model.msgpack' _snake_case = 'model.onnx' _snake_case = 'diffusion_pytorch_model.safetensors' _snake_case = 'weights.pb' _snake_case = 'https://huggingface.co' _snake_case = default_cache_path _snake_case = 'diffusers_modules' _snake_case = os.getenv('HF_MODULES_CACHE', os.path.join(hf_cache_home, 'modules')) _snake_case = ['fp16', 'non-ema'] _snake_case = '.self_attn'
324
1
"""simple docstring""" import os import shutil from pathlib import Path from typing import Optional, Union import numpy as np from huggingface_hub import hf_hub_download from ..utils import ONNX_EXTERNAL_WEIGHTS_NAME, ONNX_WEIGHTS_NAME, is_onnx_available, logging if is_onnx_available(): import onnxruntime as ort _snake_case = logging.get_logger(__name__) _snake_case = { 'tensor(bool)': np.bool_, 'tensor(int8)': np.inta, 'tensor(uint8)': np.uinta, 'tensor(int16)': np.intaa, 'tensor(uint16)': np.uintaa, 'tensor(int32)': np.intaa, 'tensor(uint32)': np.uintaa, 'tensor(int64)': np.intaa, 'tensor(uint64)': np.uintaa, 'tensor(float16)': np.floataa, 'tensor(float)': np.floataa, 'tensor(double)': np.floataa, } class UpperCamelCase : def __init__( self : Dict , UpperCAmelCase__ : List[Any]=None , **UpperCAmelCase__ : int ) -> str: logger.info("""`diffusers.OnnxRuntimeModel` is experimental and might change in the future.""" ) _a : Optional[Any] = model _a : List[Any] = kwargs.get("""model_save_dir""" , UpperCAmelCase__ ) _a : List[str] = kwargs.get("""latest_model_name""" , UpperCAmelCase__ ) def __call__( self : Optional[int] , **UpperCAmelCase__ : List[Any] ) -> Optional[Any]: _a : str = {k: np.array(UpperCAmelCase__ ) for k, v in kwargs.items()} return self.model.run(UpperCAmelCase__ , UpperCAmelCase__ ) @staticmethod def _lowercase ( UpperCAmelCase__ : Union[str, Path] , UpperCAmelCase__ : int=None , UpperCAmelCase__ : List[Any]=None ) -> Tuple: if provider is None: logger.info("""No onnxruntime provider specified, using CPUExecutionProvider""" ) _a : Any = """CPUExecutionProvider""" return ort.InferenceSession(UpperCAmelCase__ , providers=[provider] , sess_options=UpperCAmelCase__ ) def _lowercase ( self : Tuple , UpperCAmelCase__ : Union[str, Path] , UpperCAmelCase__ : Optional[str] = None , **UpperCAmelCase__ : Optional[Any] ) -> int: _a : Union[str, Any] = file_name if file_name is not None else ONNX_WEIGHTS_NAME _a : List[Any] = self.model_save_dir.joinpath(self.latest_model_name ) _a : Any = Path(UpperCAmelCase__ ).joinpath(UpperCAmelCase__ ) try: shutil.copyfile(UpperCAmelCase__ , UpperCAmelCase__ ) except shutil.SameFileError: pass # copy external weights (for models >2GB) _a : List[Any] = self.model_save_dir.joinpath(UpperCAmelCase__ ) if src_path.exists(): _a : str = Path(UpperCAmelCase__ ).joinpath(UpperCAmelCase__ ) try: shutil.copyfile(UpperCAmelCase__ , UpperCAmelCase__ ) except shutil.SameFileError: pass def _lowercase ( self : Tuple , UpperCAmelCase__ : Union[str, os.PathLike] , **UpperCAmelCase__ : str , ) -> Tuple: if os.path.isfile(UpperCAmelCase__ ): logger.error(f"""Provided path ({save_directory}) should be a directory, not a file""" ) return os.makedirs(UpperCAmelCase__ , exist_ok=UpperCAmelCase__ ) # saving model weights/files self._save_pretrained(UpperCAmelCase__ , **UpperCAmelCase__ ) @classmethod def _lowercase ( cls : Any , UpperCAmelCase__ : Union[str, Path] , UpperCAmelCase__ : Optional[Union[bool, str, None]] = None , UpperCAmelCase__ : Optional[Union[str, None]] = None , UpperCAmelCase__ : bool = False , UpperCAmelCase__ : Optional[str] = None , UpperCAmelCase__ : Optional[str] = None , UpperCAmelCase__ : Optional[str] = None , UpperCAmelCase__ : Optional["ort.SessionOptions"] = None , **UpperCAmelCase__ : Optional[Any] , ) -> Tuple: _a : Dict = file_name if file_name is not None else ONNX_WEIGHTS_NAME # load model from local directory if os.path.isdir(UpperCAmelCase__ ): _a : Union[str, Any] = OnnxRuntimeModel.load_model( os.path.join(UpperCAmelCase__ , UpperCAmelCase__ ) , provider=UpperCAmelCase__ , sess_options=UpperCAmelCase__ ) _a : Optional[int] = Path(UpperCAmelCase__ ) # load model from hub else: # download model _a : Union[str, Any] = hf_hub_download( repo_id=UpperCAmelCase__ , filename=UpperCAmelCase__ , use_auth_token=UpperCAmelCase__ , revision=UpperCAmelCase__ , cache_dir=UpperCAmelCase__ , force_download=UpperCAmelCase__ , ) _a : Optional[int] = Path(UpperCAmelCase__ ).parent _a : Union[str, Any] = Path(UpperCAmelCase__ ).name _a : int = OnnxRuntimeModel.load_model(UpperCAmelCase__ , provider=UpperCAmelCase__ , sess_options=UpperCAmelCase__ ) return cls(model=UpperCAmelCase__ , **UpperCAmelCase__ ) @classmethod def _lowercase ( cls : Tuple , UpperCAmelCase__ : Union[str, Path] , UpperCAmelCase__ : bool = True , UpperCAmelCase__ : Optional[str] = None , UpperCAmelCase__ : Optional[str] = None , **UpperCAmelCase__ : Union[str, Any] , ) -> str: _a : str = None if len(str(UpperCAmelCase__ ).split("""@""" ) ) == 2: _a , _a : List[str] = model_id.split("""@""" ) return cls._from_pretrained( model_id=UpperCAmelCase__ , revision=UpperCAmelCase__ , cache_dir=UpperCAmelCase__ , force_download=UpperCAmelCase__ , use_auth_token=UpperCAmelCase__ , **UpperCAmelCase__ , )
324
"""simple docstring""" from math import factorial def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' if successes > trials: raise ValueError("""successes must be lower or equal to trials""" ) if trials < 0 or successes < 0: raise ValueError("""the function is defined for non-negative integers""" ) if not isinstance(UpperCamelCase__ , UpperCamelCase__ ) or not isinstance(UpperCamelCase__ , UpperCamelCase__ ): raise ValueError("""the function is defined for non-negative integers""" ) if not 0 < prob < 1: raise ValueError("""prob has to be in range of 1 - 0""" ) _a : Optional[int] = (prob**successes) * ((1 - prob) ** (trials - successes)) # Calculate the binomial coefficient: n! / k!(n-k)! _a : Optional[int] = float(factorial(UpperCamelCase__ ) ) coefficient /= factorial(UpperCamelCase__ ) * factorial(trials - successes ) return probability * coefficient if __name__ == "__main__": from doctest import testmod testmod() print('Probability of 2 successes out of 4 trails') print('with probability of 0.75 is:', end=' ') print(binomial_distribution(2, 4, 0.75))
324
1
"""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, BatchEncoding, PreTrainedTokenizer from ...utils import logging _snake_case = logging.get_logger(__name__) _snake_case = '▁' _snake_case = {'vocab_file': 'sentencepiece.bpe.model'} _snake_case = { 'vocab_file': { 'facebook/nllb-200-distilled-600M': ( 'https://huggingface.co/facebook/nllb-200-distilled-600M/blob/main/sentencepiece.bpe.model' ), } } _snake_case = { 'facebook/nllb-200-distilled-600M': 1024, } # fmt: off _snake_case = ['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 UpperCamelCase ( snake_case_ ): UpperCamelCase : str = VOCAB_FILES_NAMES UpperCamelCase : Tuple = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCamelCase : int = PRETRAINED_VOCAB_FILES_MAP UpperCamelCase : Union[str, Any] = ['''input_ids''', '''attention_mask'''] UpperCamelCase : List[int] = [] UpperCamelCase : List[int] = [] def __init__( self : Optional[int] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Union[str, Any]="<s>" , UpperCAmelCase__ : Union[str, Any]="</s>" , UpperCAmelCase__ : List[Any]="</s>" , UpperCAmelCase__ : Any="<s>" , UpperCAmelCase__ : Tuple="<unk>" , UpperCAmelCase__ : Tuple="<pad>" , UpperCAmelCase__ : Optional[int]="<mask>" , UpperCAmelCase__ : Union[str, Any]=None , UpperCAmelCase__ : Union[str, Any]=None , UpperCAmelCase__ : Union[str, Any]=None , UpperCAmelCase__ : Optional[Dict[str, Any]] = None , UpperCAmelCase__ : List[str]=None , UpperCAmelCase__ : List[str]=False , **UpperCAmelCase__ : List[Any] , ) -> Union[str, Any]: # Mask token behave like a normal word, i.e. include the space before it _a : Union[str, Any] = AddedToken(UpperCAmelCase__ , lstrip=UpperCAmelCase__ , rstrip=UpperCAmelCase__ ) if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ) else mask_token _a : Any = {} if sp_model_kwargs is None else sp_model_kwargs _a : str = legacy_behaviour super().__init__( bos_token=UpperCAmelCase__ , eos_token=UpperCAmelCase__ , unk_token=UpperCAmelCase__ , sep_token=UpperCAmelCase__ , cls_token=UpperCAmelCase__ , pad_token=UpperCAmelCase__ , mask_token=UpperCAmelCase__ , tokenizer_file=UpperCAmelCase__ , src_lang=UpperCAmelCase__ , tgt_lang=UpperCAmelCase__ , additional_special_tokens=UpperCAmelCase__ , sp_model_kwargs=self.sp_model_kwargs , legacy_behaviour=UpperCAmelCase__ , **UpperCAmelCase__ , ) _a : Optional[int] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(UpperCAmelCase__ ) ) _a : Optional[Any] = 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>' | 'an' | '▁n' | '▁m' | '▁t' | '▁k' | '▁a' # spm | '<unk>' | '<s>' | '</s>' | 'an' | '▁n' | '▁m' | '▁t' | '▁k' | '▁a' | '▁s' # Mimic fairseq token-to-id alignment for the first 4 token _a : List[str] = {"""<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 _a : int = 1 _a : List[str] = len(self.sp_model ) _a : List[str] = { code: self.sp_model_size + i + self.fairseq_offset for i, code in enumerate(UpperCAmelCase__ ) } _a : int = {v: k for k, v in self.lang_code_to_id.items()} _a : Optional[int] = len(self.sp_model ) + len(self.lang_code_to_id ) + self.fairseq_offset self.fairseq_tokens_to_ids.update(self.lang_code_to_id ) _a : int = {v: k for k, v in self.fairseq_tokens_to_ids.items()} _a : Optional[Any] = list(self.lang_code_to_id.keys() ) if additional_special_tokens is not None: # Only add those special tokens if they are not already there. self._additional_special_tokens.extend( [t for t in additional_special_tokens if t not in self._additional_special_tokens] ) _a : List[str] = src_lang if src_lang is not None else """eng_Latn""" _a : List[Any] = self.lang_code_to_id[self._src_lang] _a : Dict = tgt_lang self.set_src_lang_special_tokens(self._src_lang ) def __getstate__( self : str ) -> Dict: _a : List[Any] = self.__dict__.copy() _a : Any = None _a : Any = self.sp_model.serialized_model_proto() return state def __setstate__( self : List[Any] , UpperCAmelCase__ : Union[str, Any] ) -> Optional[Any]: _a : Tuple = d # for backward compatibility if not hasattr(self , """sp_model_kwargs""" ): _a : Tuple = {} _a : Any = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.LoadFromSerializedProto(self.sp_model_proto ) @property def _lowercase ( self : List[str] ) -> Any: return len(self.sp_model ) + len(self.lang_code_to_id ) + self.fairseq_offset + 1 # Plus 1 for the mask token @property def _lowercase ( self : Optional[Any] ) -> str: return self._src_lang @src_lang.setter def _lowercase ( self : Union[str, Any] , UpperCAmelCase__ : str ) -> None: _a : List[str] = new_src_lang self.set_src_lang_special_tokens(self._src_lang ) def _lowercase ( self : List[str] , 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__ ) _a : Any = [1] * len(self.prefix_tokens ) _a : Union[str, Any] = [1] * len(self.suffix_tokens ) if token_ids_a is None: return prefix_ones + ([0] * len(UpperCAmelCase__ )) + suffix_ones return prefix_ones + ([0] * len(UpperCAmelCase__ )) + ([0] * len(UpperCAmelCase__ )) + suffix_ones def _lowercase ( self : Any , UpperCAmelCase__ : List[int] , UpperCAmelCase__ : Optional[List[int]] = None ) -> List[int]: 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 _lowercase ( self : Optional[Any] , UpperCAmelCase__ : List[int] , UpperCAmelCase__ : Optional[List[int]] = None ) -> List[int]: _a : Optional[Any] = [self.sep_token_id] _a : 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 _lowercase ( self : Optional[int] , UpperCAmelCase__ : str , UpperCAmelCase__ : str , UpperCAmelCase__ : Optional[str] , UpperCAmelCase__ : Optional[str] , **UpperCAmelCase__ : Optional[Any] ) -> Optional[int]: if src_lang is None or tgt_lang is None: raise ValueError("""Translation requires a `src_lang` and a `tgt_lang` for this model""" ) _a : List[Any] = src_lang _a : int = self(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ , return_tensors=UpperCAmelCase__ , **UpperCAmelCase__ ) _a : str = self.convert_tokens_to_ids(UpperCAmelCase__ ) _a : List[str] = tgt_lang_id return inputs def _lowercase ( self : Dict ) -> Dict: _a : Optional[Any] = {self.convert_ids_to_tokens(UpperCAmelCase__ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def _lowercase ( self : Union[str, Any] , UpperCAmelCase__ : str ) -> List[str]: return self.sp_model.encode(UpperCAmelCase__ , out_type=UpperCAmelCase__ ) def _lowercase ( self : Union[str, Any] , UpperCAmelCase__ : Union[str, Any] ) -> Dict: if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] _a : Any = 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 _lowercase ( self : Optional[Any] , UpperCAmelCase__ : Any ) -> Optional[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 _lowercase ( self : Optional[int] , UpperCAmelCase__ : List[Any] ) -> Any: _a : Tuple = """""".join(UpperCAmelCase__ ).replace(UpperCAmelCase__ , """ """ ).strip() return out_string def _lowercase ( self : Any , 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 _a : List[str] = 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: _a : Optional[int] = self.sp_model.serialized_model_proto() fi.write(UpperCAmelCase__ ) return (out_vocab_file,) def _lowercase ( self : Optional[Any] , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : str = "eng_Latn" , UpperCAmelCase__ : Optional[List[str]] = None , UpperCAmelCase__ : str = "fra_Latn" , **UpperCAmelCase__ : Union[str, Any] , ) -> BatchEncoding: _a : Dict = src_lang _a : Optional[Any] = tgt_lang return super().prepare_seqaseq_batch(UpperCAmelCase__ , UpperCAmelCase__ , **UpperCAmelCase__ ) def _lowercase ( self : Any ) -> str: return self.set_src_lang_special_tokens(self.src_lang ) def _lowercase ( self : Union[str, Any] ) -> Optional[int]: return self.set_tgt_lang_special_tokens(self.tgt_lang ) def _lowercase ( self : Union[str, Any] , UpperCAmelCase__ : Optional[Any] ) -> None: _a : Optional[Any] = self.lang_code_to_id[src_lang] if self.legacy_behaviour: _a : Any = [] _a : Dict = [self.eos_token_id, self.cur_lang_code] else: _a : str = [self.cur_lang_code] _a : Any = [self.eos_token_id] def _lowercase ( self : Tuple , UpperCAmelCase__ : str ) -> None: _a : int = self.lang_code_to_id[lang] if self.legacy_behaviour: _a : List[str] = [] _a : Union[str, Any] = [self.eos_token_id, self.cur_lang_code] else: _a : List[Any] = [self.cur_lang_code] _a : Optional[int] = [self.eos_token_id]
324
"""simple docstring""" def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' _a , _a : Dict = len(UpperCamelCase__ ), len(grid[0] ) if ( min(UpperCamelCase__ , UpperCamelCase__ ) < 0 or row == row_length or col == col_length or (row, col) in visit or grid[row][col] == 1 ): return 0 if row == row_length - 1 and col == col_length - 1: return 1 visit.add((row, col) ) _a : Any = 0 count += depth_first_search(UpperCamelCase__ , row + 1 , UpperCamelCase__ , UpperCamelCase__ ) count += depth_first_search(UpperCamelCase__ , row - 1 , UpperCamelCase__ , UpperCamelCase__ ) count += depth_first_search(UpperCamelCase__ , UpperCamelCase__ , col + 1 , UpperCamelCase__ ) count += depth_first_search(UpperCamelCase__ , UpperCamelCase__ , col - 1 , UpperCamelCase__ ) visit.remove((row, col) ) return count if __name__ == "__main__": import doctest doctest.testmod()
324
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import _LazyModule _snake_case = {'tokenization_wav2vec2_phoneme': ['Wav2Vec2PhonemeCTCTokenizer']} if TYPE_CHECKING: from .tokenization_wavaveca_phoneme import WavaVecaPhonemeCTCTokenizer else: import sys _snake_case = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
324
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) _snake_case = { 'configuration_vision_encoder_decoder': ['VisionEncoderDecoderConfig', 'VisionEncoderDecoderOnnxConfig'] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _snake_case = ['VisionEncoderDecoderModel'] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _snake_case = ['TFVisionEncoderDecoderModel'] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _snake_case = ['FlaxVisionEncoderDecoderModel'] if TYPE_CHECKING: from .configuration_vision_encoder_decoder import VisionEncoderDecoderConfig, VisionEncoderDecoderOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_vision_encoder_decoder import VisionEncoderDecoderModel try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_vision_encoder_decoder import TFVisionEncoderDecoderModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_vision_encoder_decoder import FlaxVisionEncoderDecoderModel else: import sys _snake_case = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
324
1
"""simple docstring""" 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 UpperCamelCase ( snake_case_ ): UpperCamelCase : int = '''audio-spectrogram-transformer''' def __init__( self : int , UpperCAmelCase__ : str=768 , UpperCAmelCase__ : List[Any]=12 , UpperCAmelCase__ : str=12 , UpperCAmelCase__ : Optional[int]=3072 , UpperCAmelCase__ : Dict="gelu" , UpperCAmelCase__ : Tuple=0.0 , UpperCAmelCase__ : str=0.0 , UpperCAmelCase__ : Tuple=0.0_2 , UpperCAmelCase__ : Any=1E-12 , UpperCAmelCase__ : Tuple=16 , UpperCAmelCase__ : Dict=True , UpperCAmelCase__ : Any=10 , UpperCAmelCase__ : Union[str, Any]=10 , UpperCAmelCase__ : List[str]=1024 , UpperCAmelCase__ : Any=128 , **UpperCAmelCase__ : Tuple , ) -> List[str]: super().__init__(**UpperCAmelCase__ ) _a : str = hidden_size _a : Tuple = num_hidden_layers _a : int = num_attention_heads _a : int = intermediate_size _a : Optional[int] = hidden_act _a : Union[str, Any] = hidden_dropout_prob _a : int = attention_probs_dropout_prob _a : List[Any] = initializer_range _a : Any = layer_norm_eps _a : int = patch_size _a : int = qkv_bias _a : Any = frequency_stride _a : Union[str, Any] = time_stride _a : Optional[int] = max_length _a : int = num_mel_bins
324
"""simple docstring""" from __future__ import annotations import time _snake_case = list[tuple[int, int]] _snake_case = [ [0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles [0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0], [1, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0], ] _snake_case = [[-1, 0], [0, -1], [1, 0], [0, 1]] # up, left, down, right class UpperCamelCase : def __init__( self : Optional[int] , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : Node | None ) -> List[str]: _a : int = pos_x _a : Union[str, Any] = pos_y _a : Tuple = (pos_y, pos_x) _a : Tuple = goal_x _a : int = goal_y _a : str = parent class UpperCamelCase : def __init__( self : List[Any] , UpperCAmelCase__ : tuple[int, int] , UpperCAmelCase__ : tuple[int, int] ) -> List[str]: _a : List[Any] = Node(start[1] , start[0] , goal[1] , goal[0] , UpperCAmelCase__ ) _a : List[str] = Node(goal[1] , goal[0] , goal[1] , goal[0] , UpperCAmelCase__ ) _a : Optional[int] = [self.start] _a : Tuple = False def _lowercase ( self : str ) -> Path | None: while self.node_queue: _a : Tuple = self.node_queue.pop(0 ) if current_node.pos == self.target.pos: _a : Dict = True return self.retrace_path(UpperCAmelCase__ ) _a : Tuple = self.get_successors(UpperCAmelCase__ ) for node in successors: self.node_queue.append(UpperCAmelCase__ ) if not self.reached: return [self.start.pos] return None def _lowercase ( self : Optional[int] , UpperCAmelCase__ : Node ) -> list[Node]: _a : Optional[Any] = [] for action in delta: _a : str = parent.pos_x + action[1] _a : List[Any] = parent.pos_y + action[0] if not (0 <= pos_x <= len(grid[0] ) - 1 and 0 <= pos_y <= len(UpperCAmelCase__ ) - 1): continue if grid[pos_y][pos_x] != 0: continue successors.append( Node(UpperCAmelCase__ , UpperCAmelCase__ , self.target.pos_y , self.target.pos_x , UpperCAmelCase__ ) ) return successors def _lowercase ( self : List[Any] , UpperCAmelCase__ : Node | None ) -> Path: _a : Dict = node _a : List[str] = [] while current_node is not None: path.append((current_node.pos_y, current_node.pos_x) ) _a : Any = current_node.parent path.reverse() return path class UpperCamelCase : def __init__( self : List[str] , UpperCAmelCase__ : int , UpperCAmelCase__ : List[Any] ) -> Any: _a : Dict = BreadthFirstSearch(UpperCAmelCase__ , UpperCAmelCase__ ) _a : Optional[int] = BreadthFirstSearch(UpperCAmelCase__ , UpperCAmelCase__ ) _a : Dict = False def _lowercase ( self : Any ) -> Path | None: while self.fwd_bfs.node_queue or self.bwd_bfs.node_queue: _a : List[Any] = self.fwd_bfs.node_queue.pop(0 ) _a : Union[str, Any] = self.bwd_bfs.node_queue.pop(0 ) if current_bwd_node.pos == current_fwd_node.pos: _a : Optional[int] = True return self.retrace_bidirectional_path( UpperCAmelCase__ , UpperCAmelCase__ ) _a : List[str] = current_bwd_node _a : int = current_fwd_node _a : Optional[Any] = { self.fwd_bfs: self.fwd_bfs.get_successors(UpperCAmelCase__ ), self.bwd_bfs: self.bwd_bfs.get_successors(UpperCAmelCase__ ), } for bfs in [self.fwd_bfs, self.bwd_bfs]: for node in successors[bfs]: bfs.node_queue.append(UpperCAmelCase__ ) if not self.reached: return [self.fwd_bfs.start.pos] return None def _lowercase ( self : Optional[int] , UpperCAmelCase__ : Node , UpperCAmelCase__ : Node ) -> Path: _a : str = self.fwd_bfs.retrace_path(UpperCAmelCase__ ) _a : List[Any] = self.bwd_bfs.retrace_path(UpperCAmelCase__ ) bwd_path.pop() bwd_path.reverse() _a : Tuple = fwd_path + bwd_path return path if __name__ == "__main__": # all coordinates are given in format [y,x] import doctest doctest.testmod() _snake_case = (0, 0) _snake_case = (len(grid) - 1, len(grid[0]) - 1) for elem in grid: print(elem) _snake_case = time.time() _snake_case = BreadthFirstSearch(init, goal) _snake_case = bfs.search() _snake_case = time.time() - start_bfs_time print('Unidirectional BFS computation time : ', bfs_time) _snake_case = time.time() _snake_case = BidirectionalBreadthFirstSearch(init, goal) _snake_case = bd_bfs.search() _snake_case = time.time() - start_bd_bfs_time print('Bidirectional BFS computation time : ', bd_bfs_time)
324
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available _snake_case = { 'configuration_biogpt': ['BIOGPT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'BioGptConfig'], 'tokenization_biogpt': ['BioGptTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _snake_case = [ 'BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST', 'BioGptForCausalLM', 'BioGptForTokenClassification', 'BioGptForSequenceClassification', 'BioGptModel', 'BioGptPreTrainedModel', ] if TYPE_CHECKING: from .configuration_biogpt import BIOGPT_PRETRAINED_CONFIG_ARCHIVE_MAP, BioGptConfig from .tokenization_biogpt import BioGptTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_biogpt import ( BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST, BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification, BioGptModel, BioGptPreTrainedModel, ) else: import sys _snake_case = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
324
"""simple docstring""" import logging import math import os from dataclasses import dataclass, field from glob import glob from typing import Optional from torch.utils.data import ConcatDataset import transformers from transformers import ( CONFIG_MAPPING, MODEL_WITH_LM_HEAD_MAPPING, AutoConfig, AutoModelWithLMHead, AutoTokenizer, DataCollatorForLanguageModeling, DataCollatorForPermutationLanguageModeling, DataCollatorForWholeWordMask, HfArgumentParser, LineByLineTextDataset, LineByLineWithRefDataset, PreTrainedTokenizer, TextDataset, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import is_main_process _snake_case = logging.getLogger(__name__) _snake_case = list(MODEL_WITH_LM_HEAD_MAPPING.keys()) _snake_case = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES) @dataclass class UpperCamelCase : UpperCamelCase : Optional[str] = field( default=snake_case_ , metadata={ '''help''': ( '''The model checkpoint for weights initialization. Leave None if you want to train a model from''' ''' scratch.''' ) } , ) UpperCamelCase : Optional[str] = field( default=snake_case_ , metadata={'''help''': '''If training from scratch, pass a model type from the list: ''' + ''', '''.join(snake_case_ )} , ) UpperCamelCase : Optional[str] = field( default=snake_case_ , metadata={'''help''': '''Pretrained config name or path if not the same as model_name'''} ) UpperCamelCase : Optional[str] = field( default=snake_case_ , metadata={'''help''': '''Pretrained tokenizer name or path if not the same as model_name'''} ) UpperCamelCase : Optional[str] = field( default=snake_case_ , metadata={'''help''': '''Where do you want to store the pretrained models downloaded from huggingface.co'''} , ) @dataclass class UpperCamelCase : UpperCamelCase : Optional[str] = field( default=snake_case_ , metadata={'''help''': '''The input training data file (a text file).'''} ) UpperCamelCase : Optional[str] = field( default=snake_case_ , metadata={ '''help''': ( '''The input training data files (multiple files in glob format). ''' '''Very often splitting large files to smaller files can prevent tokenizer going out of memory''' ) } , ) UpperCamelCase : Optional[str] = field( default=snake_case_ , metadata={'''help''': '''An optional input evaluation data file to evaluate the perplexity on (a text file).'''} , ) UpperCamelCase : Optional[str] = field( default=snake_case_ , metadata={'''help''': '''An optional input train ref data file for whole word mask in Chinese.'''} , ) UpperCamelCase : Optional[str] = field( default=snake_case_ , metadata={'''help''': '''An optional input eval ref data file for whole word mask in Chinese.'''} , ) UpperCamelCase : bool = field( default=snake_case_ , metadata={'''help''': '''Whether distinct lines of text in the dataset are to be handled as distinct sequences.'''} , ) UpperCamelCase : bool = field( default=snake_case_ , metadata={'''help''': '''Train with masked-language modeling loss instead of language modeling.'''} ) UpperCamelCase : bool = field(default=snake_case_ , metadata={'''help''': '''Whether ot not to use whole word mask.'''} ) UpperCamelCase : float = field( default=0.1_5 , metadata={'''help''': '''Ratio of tokens to mask for masked language modeling loss'''} ) UpperCamelCase : float = field( default=1 / 6 , metadata={ '''help''': ( '''Ratio of length of a span of masked tokens to surrounding context length for permutation language''' ''' modeling.''' ) } , ) UpperCamelCase : int = field( default=5 , metadata={'''help''': '''Maximum length of a span of masked tokens for permutation language modeling.'''} ) UpperCamelCase : int = field( default=-1 , metadata={ '''help''': ( '''Optional input sequence length after tokenization.''' '''The training dataset will be truncated in block of this size for training.''' '''Default to the model max input length for single sentence inputs (take into account special tokens).''' ) } , ) UpperCamelCase : bool = field( default=snake_case_ , metadata={'''help''': '''Overwrite the cached training and evaluation sets'''} ) def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = False , UpperCamelCase__ = None , ): '''simple docstring''' def _dataset(UpperCamelCase__ , UpperCamelCase__=None ): if args.line_by_line: if ref_path is not None: if not args.whole_word_mask or not args.mlm: raise ValueError("""You need to set world whole masking and mlm to True for Chinese Whole Word Mask""" ) return LineByLineWithRefDataset( tokenizer=UpperCamelCase__ , file_path=UpperCamelCase__ , block_size=args.block_size , ref_path=UpperCamelCase__ , ) return LineByLineTextDataset(tokenizer=UpperCamelCase__ , file_path=UpperCamelCase__ , block_size=args.block_size ) else: return TextDataset( tokenizer=UpperCamelCase__ , file_path=UpperCamelCase__ , block_size=args.block_size , overwrite_cache=args.overwrite_cache , cache_dir=UpperCamelCase__ , ) if evaluate: return _dataset(args.eval_data_file , args.eval_ref_file ) elif args.train_data_files: return ConcatDataset([_dataset(UpperCamelCase__ ) for f in glob(args.train_data_files )] ) else: return _dataset(args.train_data_file , args.train_ref_file ) def lowerCAmelCase__ ( ): '''simple docstring''' # See all possible arguments in src/transformers/training_args.py # or by passing the --help flag to this script. # We now keep distinct sets of args, for a cleaner separation of concerns. _a : Any = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) _a , _a , _a : List[str] = parser.parse_args_into_dataclasses() if data_args.eval_data_file is None and training_args.do_eval: raise ValueError( """Cannot do evaluation without an evaluation data file. Either supply a file to --eval_data_file """ """or remove the --do_eval argument.""" ) if ( os.path.exists(training_args.output_dir ) and os.listdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir ): raise ValueError( F"""Output directory ({training_args.output_dir}) already exists and is not empty. Use""" """ --overwrite_output_dir to overcome.""" ) # Setup logging logging.basicConfig( format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""" , datefmt="""%m/%d/%Y %H:%M:%S""" , level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN , ) logger.warning( """Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s""" , training_args.local_rank , training_args.device , training_args.n_gpu , bool(training_args.local_rank != -1 ) , training_args.fpaa , ) # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank ): transformers.utils.logging.set_verbosity_info() transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() logger.info("""Training/evaluation parameters %s""" , UpperCamelCase__ ) # Set seed set_seed(training_args.seed ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. if model_args.config_name: _a : str = AutoConfig.from_pretrained(model_args.config_name , cache_dir=model_args.cache_dir ) elif model_args.model_name_or_path: _a : Union[str, Any] = AutoConfig.from_pretrained(model_args.model_name_or_path , cache_dir=model_args.cache_dir ) else: _a : str = CONFIG_MAPPING[model_args.model_type]() logger.warning("""You are instantiating a new config instance from scratch.""" ) if model_args.tokenizer_name: _a : List[str] = AutoTokenizer.from_pretrained(model_args.tokenizer_name , cache_dir=model_args.cache_dir ) elif model_args.model_name_or_path: _a : Union[str, Any] = AutoTokenizer.from_pretrained(model_args.model_name_or_path , cache_dir=model_args.cache_dir ) else: raise ValueError( """You are instantiating a new tokenizer from scratch. This is not supported, but you can do it from another""" """ script, save it,and load it from here, using --tokenizer_name""" ) if model_args.model_name_or_path: _a : Optional[Any] = AutoModelWithLMHead.from_pretrained( model_args.model_name_or_path , from_tf=bool(""".ckpt""" in model_args.model_name_or_path ) , config=UpperCamelCase__ , cache_dir=model_args.cache_dir , ) else: logger.info("""Training new model from scratch""" ) _a : List[Any] = AutoModelWithLMHead.from_config(UpperCamelCase__ ) model.resize_token_embeddings(len(UpperCamelCase__ ) ) if config.model_type in ["bert", "roberta", "distilbert", "camembert"] and not data_args.mlm: raise ValueError( """BERT and RoBERTa-like models do not have LM heads but masked LM heads. They must be run using the""" """--mlm flag (masked language modeling).""" ) if data_args.block_size <= 0: _a : int = tokenizer.max_len # Our input block size will be the max possible for the model else: _a : Optional[Any] = min(data_args.block_size , tokenizer.max_len ) # Get datasets _a : Optional[Any] = ( get_dataset(UpperCamelCase__ , tokenizer=UpperCamelCase__ , cache_dir=model_args.cache_dir ) if training_args.do_train else None ) _a : Optional[int] = ( get_dataset(UpperCamelCase__ , tokenizer=UpperCamelCase__ , evaluate=UpperCamelCase__ , cache_dir=model_args.cache_dir ) if training_args.do_eval else None ) if config.model_type == "xlnet": _a : Any = DataCollatorForPermutationLanguageModeling( tokenizer=UpperCamelCase__ , plm_probability=data_args.plm_probability , max_span_length=data_args.max_span_length , ) else: if data_args.mlm and data_args.whole_word_mask: _a : Union[str, Any] = DataCollatorForWholeWordMask( tokenizer=UpperCamelCase__ , mlm_probability=data_args.mlm_probability ) else: _a : str = DataCollatorForLanguageModeling( tokenizer=UpperCamelCase__ , mlm=data_args.mlm , mlm_probability=data_args.mlm_probability ) # Initialize our Trainer _a : Union[str, Any] = Trainer( model=UpperCamelCase__ , args=UpperCamelCase__ , data_collator=UpperCamelCase__ , train_dataset=UpperCamelCase__ , eval_dataset=UpperCamelCase__ , prediction_loss_only=UpperCamelCase__ , ) # Training if training_args.do_train: _a : Optional[Any] = ( model_args.model_name_or_path if model_args.model_name_or_path is not None and os.path.isdir(model_args.model_name_or_path ) else None ) trainer.train(model_path=UpperCamelCase__ ) trainer.save_model() # For convenience, we also re-save the tokenizer to the same directory, # so that you can share your model easily on huggingface.co/models =) if trainer.is_world_master(): tokenizer.save_pretrained(training_args.output_dir ) # Evaluation _a : Union[str, Any] = {} if training_args.do_eval: logger.info("""*** Evaluate ***""" ) _a : int = trainer.evaluate() _a : Dict = math.exp(eval_output["""eval_loss"""] ) _a : Union[str, Any] = {"""perplexity""": perplexity} _a : Optional[Any] = os.path.join(training_args.output_dir , """eval_results_lm.txt""" ) if trainer.is_world_master(): with open(UpperCamelCase__ , """w""" ) as writer: logger.info("""***** Eval results *****""" ) for key in sorted(result.keys() ): logger.info(""" %s = %s""" , UpperCamelCase__ , str(result[key] ) ) writer.write("""%s = %s\n""" % (key, str(result[key] )) ) results.update(UpperCamelCase__ ) return results def lowerCAmelCase__ ( UpperCamelCase__ ): '''simple docstring''' # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
324
1
"""simple docstring""" import os import pytest import yaml from datasets.features.features import Features, Value from datasets.info import DatasetInfo, DatasetInfosDict @pytest.mark.parametrize( """files""" , [ ["""full:README.md""", """dataset_infos.json"""], ["""empty:README.md""", """dataset_infos.json"""], ["""dataset_infos.json"""], ["""full:README.md"""], ] , ) def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' _a : Dict = tmp_path_factory.mktemp("""dset_infos_dir""" ) if "full:README.md" in files: with open(dataset_infos_dir / """README.md""" , """w""" ) as f: f.write("""---\ndataset_info:\n dataset_size: 42\n---""" ) if "empty:README.md" in files: with open(dataset_infos_dir / """README.md""" , """w""" ) as f: f.write("""""" ) # we want to support dataset_infos.json for backward compatibility if "dataset_infos.json" in files: with open(dataset_infos_dir / """dataset_infos.json""" , """w""" ) as f: f.write("""{\"default\": {\"dataset_size\": 42}}""" ) _a : Dict = DatasetInfosDict.from_directory(UpperCamelCase__ ) assert dataset_infos assert dataset_infos["default"].dataset_size == 4_2 @pytest.mark.parametrize( """dataset_info""" , [ DatasetInfo(), DatasetInfo( description="""foo""" , features=Features({"""a""": Value("""int32""" )} ) , builder_name="""builder""" , config_name="""config""" , version="""1.0.0""" , splits=[{"""name""": """train"""}] , download_size=4_2 , ), ] , ) def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' _a : Optional[int] = str(UpperCamelCase__ ) dataset_info.write_to_directory(UpperCamelCase__ ) _a : Any = DatasetInfo.from_directory(UpperCamelCase__ ) assert dataset_info == reloaded assert os.path.exists(os.path.join(UpperCamelCase__ , """dataset_info.json""" ) ) def lowerCAmelCase__ ( ): '''simple docstring''' _a : Dict = DatasetInfo( description="""foo""" , citation="""bar""" , homepage="""https://foo.bar""" , license="""CC0""" , features=Features({"""a""": Value("""int32""" )} ) , post_processed={} , supervised_keys=() , task_templates=[] , builder_name="""builder""" , config_name="""config""" , version="""1.0.0""" , splits=[{"""name""": """train""", """num_examples""": 4_2}] , download_checksums={} , download_size=1_3_3_7 , post_processing_size=4_4_2 , dataset_size=1_2_3_4 , size_in_bytes=1_3_3_7 + 4_4_2 + 1_2_3_4 , ) _a : int = dataset_info._to_yaml_dict() assert sorted(UpperCamelCase__ ) == sorted(DatasetInfo._INCLUDED_INFO_IN_YAML ) for key in DatasetInfo._INCLUDED_INFO_IN_YAML: assert key in dataset_info_yaml_dict assert isinstance(dataset_info_yaml_dict[key] , (list, dict, int, str) ) _a : List[str] = yaml.safe_dump(UpperCamelCase__ ) _a : Optional[int] = yaml.safe_load(UpperCamelCase__ ) assert dataset_info_yaml_dict == reloaded def lowerCAmelCase__ ( ): '''simple docstring''' _a : List[Any] = DatasetInfo() _a : Any = dataset_info._to_yaml_dict() assert dataset_info_yaml_dict == {} @pytest.mark.parametrize( """dataset_infos_dict""" , [ DatasetInfosDict(), DatasetInfosDict({"""default""": DatasetInfo()} ), DatasetInfosDict({"""my_config_name""": DatasetInfo()} ), DatasetInfosDict( { """default""": DatasetInfo( description="""foo""" , features=Features({"""a""": Value("""int32""" )} ) , builder_name="""builder""" , config_name="""config""" , version="""1.0.0""" , splits=[{"""name""": """train"""}] , download_size=4_2 , ) } ), DatasetInfosDict( { """v1""": DatasetInfo(dataset_size=4_2 ), """v2""": DatasetInfo(dataset_size=1_3_3_7 ), } ), ] , ) def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' _a : List[Any] = str(UpperCamelCase__ ) dataset_infos_dict.write_to_directory(UpperCamelCase__ ) _a : List[Any] = DatasetInfosDict.from_directory(UpperCamelCase__ ) # the config_name of the dataset_infos_dict take over the attribute for config_name, dataset_info in dataset_infos_dict.items(): _a : str = config_name # the yaml representation doesn't include fields like description or citation # so we just test that we can recover what we can from the yaml _a : Dict = DatasetInfo._from_yaml_dict(dataset_info._to_yaml_dict() ) assert dataset_infos_dict == reloaded if dataset_infos_dict: assert os.path.exists(os.path.join(UpperCamelCase__ , """README.md""" ) )
324
"""simple docstring""" import argparse import os from pathlib import Path from typing import Dict import tensorflow as tf import torch from tqdm import tqdm from transformers import PegasusConfig, PegasusForConditionalGeneration, PegasusTokenizer from transformers.models.pegasus.configuration_pegasus import DEFAULTS, task_specific_params _snake_case = [ # replace left string with right string to get the relevant state_dict key (identical state dict to bart) ['memory_attention', 'encoder_attn'], ['attention', 'attn'], ['/', '.'], ['.LayerNorm.gamma', '_layer_norm.weight'], ['.LayerNorm.beta', '_layer_norm.bias'], ['r.layer_', 'r.layers.'], ['output_proj', 'out_proj'], ['ffn.dense_1.', 'fc2.'], ['ffn.dense.', 'fc1.'], ['ffn_layer_norm', 'final_layer_norm'], ['kernel', 'weight'], ['encoder_layer_norm.', 'encoder.layer_norm.'], ['decoder_layer_norm.', 'decoder.layer_norm.'], ['embeddings.weights', 'shared.weight'], ] def lowerCAmelCase__ ( UpperCamelCase__ ): '''simple docstring''' for pegasus_name, hf_name in PATTERNS: _a : Optional[Any] = k.replace(UpperCamelCase__ , UpperCamelCase__ ) return k def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' _a : Union[str, Any] = DEFAULTS.copy() cfg_kwargs.update(UpperCamelCase__ ) _a : Optional[Any] = PegasusConfig(**UpperCamelCase__ ) _a : Tuple = PegasusForConditionalGeneration(UpperCamelCase__ ) _a : str = torch_model.model.state_dict() _a : Union[str, Any] = {} for k, v in tf_weights.items(): _a : Any = rename_state_dict_key(UpperCamelCase__ ) if new_k not in sd: raise ValueError(F"""could not find new key {new_k} in state dict. (converted from {k})""" ) if "dense" in k or "proj" in new_k: _a : str = v.T _a : int = torch.tensor(UpperCamelCase__ , dtype=sd[new_k].dtype ) assert v.shape == sd[new_k].shape, F"""{new_k}, {k}, {v.shape}, {sd[new_k].shape}""" # make sure embedding.padding_idx is respected _a : Union[str, Any] = torch.zeros_like(mapping["""shared.weight"""][cfg.pad_token_id + 1] ) _a : str = mapping["""shared.weight"""] _a : Union[str, Any] = mapping["""shared.weight"""] _a : Optional[Any] = {k: torch.zeros_like(UpperCamelCase__ ) for k, v in sd.items() if k.endswith("""bias""" ) and k not in mapping} mapping.update(**UpperCamelCase__ ) _a , _a : int = torch_model.model.load_state_dict(UpperCamelCase__ , strict=UpperCamelCase__ ) _a : Optional[Any] = [ k for k in missing if k not in ["""encoder.embed_positions.weight""", """decoder.embed_positions.weight"""] ] assert unexpected_missing == [], F"""no matches found for the following torch keys {unexpected_missing}""" assert extra == [], F"""no matches found for the following tf keys {extra}""" return torch_model def lowerCAmelCase__ ( UpperCamelCase__="./ckpt/aeslc/model.ckpt-32000" ): '''simple docstring''' _a : List[Any] = tf.train.list_variables(UpperCamelCase__ ) _a : Optional[int] = {} _a : Dict = ["""Adafactor""", """global_step"""] for name, shape in tqdm(UpperCamelCase__ , desc="""converting tf checkpoint to dict""" ): _a : Optional[Any] = any(pat in name for pat in ignore_name ) if skip_key: continue _a : str = tf.train.load_variable(UpperCamelCase__ , UpperCamelCase__ ) _a : int = array return tf_weights def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' # save tokenizer first _a : Dict = Path(UpperCamelCase__ ).parent.name _a : Optional[Any] = task_specific_params[F"""summarization_{dataset}"""]["""max_position_embeddings"""] _a : Tuple = PegasusTokenizer.from_pretrained("""sshleifer/pegasus""" , model_max_length=UpperCamelCase__ ) assert tok.model_max_length == desired_max_model_length tok.save_pretrained(UpperCamelCase__ ) # convert model _a : List[Any] = get_tf_weights_as_numpy(UpperCamelCase__ ) _a : Dict = task_specific_params[F"""summarization_{dataset}"""] if dataset == "large": _a : Tuple = task_specific_params _a : Optional[int] = convert_pegasus(UpperCamelCase__ , UpperCamelCase__ ) torch_model.save_pretrained(UpperCamelCase__ ) _a : Dict = torch_model.state_dict() sd.pop("""model.decoder.embed_positions.weight""" ) sd.pop("""model.encoder.embed_positions.weight""" ) torch.save(UpperCamelCase__ , Path(UpperCamelCase__ ) / """pytorch_model.bin""" ) if __name__ == "__main__": _snake_case = argparse.ArgumentParser() # Required parameters parser.add_argument('tf_ckpt_path', type=str, help='passed to tf.train.list_variables') parser.add_argument('save_dir', default=None, type=str, help='Path to the output PyTorch model.') _snake_case = parser.parse_args() if args.save_dir is None: _snake_case = Path(args.tf_ckpt_path).parent.name _snake_case = os.path.join('pegasus', dataset) convert_pegasus_ckpt_to_pytorch(args.tf_ckpt_path, args.save_dir)
324
1
"""simple docstring""" from dataclasses import dataclass from typing import List, Optional, Union import numpy as np import torch from ...utils import BaseOutput, OptionalDependencyNotAvailable, is_torch_available, is_transformers_available @dataclass class UpperCamelCase ( snake_case_ ): UpperCamelCase : Union[List[np.ndarray], torch.FloatTensor] try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import * # noqa F403 else: from .pipeline_text_to_video_synth import TextToVideoSDPipeline from .pipeline_text_to_video_synth_imgaimg import VideoToVideoSDPipeline # noqa: F401 from .pipeline_text_to_video_zero import TextToVideoZeroPipeline
324
"""simple docstring""" import gc import random import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTextModelWithProjection, CLIPTokenizer from diffusers import ( AutoencoderKL, DiffusionPipeline, EulerDiscreteScheduler, StableDiffusionXLImgaImgPipeline, UNetaDConditionModel, ) from diffusers.utils import floats_tensor, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import ( IMAGE_TO_IMAGE_IMAGE_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class UpperCamelCase ( snake_case_ , snake_case_ , unittest.TestCase ): UpperCamelCase : Union[str, Any] = StableDiffusionXLImgaImgPipeline UpperCamelCase : Any = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'''height''', '''width'''} UpperCamelCase : Tuple = PipelineTesterMixin.required_optional_params - {'''latents'''} UpperCamelCase : int = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS UpperCamelCase : Optional[Any] = IMAGE_TO_IMAGE_IMAGE_PARAMS UpperCamelCase : Optional[Any] = IMAGE_TO_IMAGE_IMAGE_PARAMS def _lowercase ( self : Any ) -> List[Any]: torch.manual_seed(0 ) _a : str = 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""") , attention_head_dim=(2, 4) , use_linear_projection=UpperCAmelCase__ , addition_embed_type="""text_time""" , addition_time_embed_dim=8 , transformer_layers_per_block=(1, 2) , projection_class_embeddings_input_dim=80 , cross_attention_dim=64 , ) _a : Union[str, Any] = EulerDiscreteScheduler( beta_start=0.0_0_0_8_5 , beta_end=0.0_1_2 , steps_offset=1 , beta_schedule="""scaled_linear""" , timestep_spacing="""leading""" , ) torch.manual_seed(0 ) _a : List[str] = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , sample_size=128 , ) torch.manual_seed(0 ) _a : int = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , hidden_act="""gelu""" , projection_dim=32 , ) _a : Tuple = CLIPTextModel(UpperCAmelCase__ ) _a : str = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" , local_files_only=UpperCAmelCase__ ) _a : Dict = CLIPTextModelWithProjection(UpperCAmelCase__ ) _a : Dict = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" , local_files_only=UpperCAmelCase__ ) _a : Any = { """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """text_encoder_2""": text_encoder_a, """tokenizer_2""": tokenizer_a, # "safety_checker": None, # "feature_extractor": None, } return components def _lowercase ( self : List[Any] , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : int=0 ) -> int: _a : Dict = floats_tensor((1, 3, 32, 32) , rng=random.Random(UpperCAmelCase__ ) ).to(UpperCAmelCase__ ) _a : Any = image / 2 + 0.5 if str(UpperCAmelCase__ ).startswith("""mps""" ): _a : Any = torch.manual_seed(UpperCAmelCase__ ) else: _a : Tuple = torch.Generator(device=UpperCAmelCase__ ).manual_seed(UpperCAmelCase__ ) _a : Optional[Any] = { """prompt""": """A painting of a squirrel eating a burger""", """image""": image, """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 5.0, """output_type""": """numpy""", """strength""": 0.7_5, } return inputs def _lowercase ( self : Any ) -> List[Any]: _a : Union[str, Any] = """cpu""" # ensure determinism for the device-dependent torch.Generator _a : Dict = self.get_dummy_components() _a : List[Any] = StableDiffusionXLImgaImgPipeline(**UpperCAmelCase__ ) _a : Union[str, Any] = sd_pipe.to(UpperCAmelCase__ ) sd_pipe.set_progress_bar_config(disable=UpperCAmelCase__ ) _a : List[str] = self.get_dummy_inputs(UpperCAmelCase__ ) _a : List[str] = sd_pipe(**UpperCAmelCase__ ).images _a : Union[str, Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) _a : List[str] = np.array([0.4_6_5_6, 0.4_8_4_0, 0.4_4_3_9, 0.6_6_9_8, 0.5_5_7_4, 0.4_5_2_4, 0.5_7_9_9, 0.5_9_4_3, 0.5_1_6_5] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def _lowercase ( self : Any ) -> Any: super().test_attention_slicing_forward_pass(expected_max_diff=3E-3 ) def _lowercase ( self : List[Any] ) -> Optional[Any]: super().test_inference_batch_single_identical(expected_max_diff=3E-3 ) def _lowercase ( self : Any ) -> Any: pass def _lowercase ( self : Tuple ) -> Union[str, Any]: _a : int = self.get_dummy_components() _a : Any = StableDiffusionXLImgaImgPipeline(**UpperCAmelCase__ ) _a : Dict = sd_pipe.to(UpperCAmelCase__ ) _a : List[str] = sd_pipe.to(UpperCAmelCase__ ) sd_pipe.set_progress_bar_config(disable=UpperCAmelCase__ ) # forward without prompt embeds _a : int = self.get_dummy_inputs(UpperCAmelCase__ ) _a : List[str] = 3 * ["""this is a negative prompt"""] _a : Dict = negative_prompt _a : Dict = 3 * [inputs["""prompt"""]] _a : Optional[Any] = sd_pipe(**UpperCAmelCase__ ) _a : Tuple = output.images[0, -3:, -3:, -1] # forward with prompt embeds _a : int = self.get_dummy_inputs(UpperCAmelCase__ ) _a : Union[str, Any] = 3 * ["""this is a negative prompt"""] _a : int = 3 * [inputs.pop("""prompt""" )] ( ( _a ) , ( _a ) , ( _a ) , ( _a ) , ) : List[str] = sd_pipe.encode_prompt(UpperCAmelCase__ , negative_prompt=UpperCAmelCase__ ) _a : Tuple = sd_pipe( **UpperCAmelCase__ , prompt_embeds=UpperCAmelCase__ , negative_prompt_embeds=UpperCAmelCase__ , pooled_prompt_embeds=UpperCAmelCase__ , negative_pooled_prompt_embeds=UpperCAmelCase__ , ) _a : Dict = output.images[0, -3:, -3:, -1] # make sure that it's equal assert np.abs(image_slice_a.flatten() - image_slice_a.flatten() ).max() < 1E-4 @slow @require_torch_gpu class UpperCamelCase ( unittest.TestCase ): def _lowercase ( self : List[str] ) -> Union[str, Any]: super().tearDown() gc.collect() torch.cuda.empty_cache() def _lowercase ( self : List[str] , UpperCAmelCase__ : str , UpperCAmelCase__ : str="cpu" , UpperCAmelCase__ : str=torch.floataa , UpperCAmelCase__ : List[Any]=0 ) -> List[str]: _a : List[str] = torch.Generator(device=UpperCAmelCase__ ).manual_seed(UpperCAmelCase__ ) _a : Union[str, Any] = np.random.RandomState(UpperCAmelCase__ ).standard_normal((1, 4, 64, 64) ) _a : List[Any] = torch.from_numpy(UpperCAmelCase__ ).to(device=UpperCAmelCase__ , dtype=UpperCAmelCase__ ) _a : Any = { """prompt""": """a photograph of an astronaut riding a horse""", """latents""": latents, """generator""": generator, """num_inference_steps""": 3, """guidance_scale""": 7.5, """output_type""": """numpy""", } return inputs def _lowercase ( self : int ) -> Union[str, Any]: _a : Union[str, Any] = DiffusionPipeline.from_pretrained("""stabilityai/stable-diffusion-2-base""" ) pipe.to(UpperCAmelCase__ ) pipe.set_progress_bar_config(disable=UpperCAmelCase__ ) _a : List[str] = self.get_inputs(UpperCAmelCase__ ) _a : Tuple = pipe(**UpperCAmelCase__ ).images _a : List[str] = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 512, 512, 3) _a : int = np.array([0.4_9_4_9_3, 0.4_7_8_9_6, 0.4_0_7_9_8, 0.5_4_2_1_4, 0.5_3_2_1_2, 0.4_8_2_0_2, 0.4_7_6_5_6, 0.4_6_3_2_9, 0.4_8_5_0_6] ) assert np.abs(image_slice - expected_slice ).max() < 7E-3
324
1
"""simple docstring""" import warnings from typing import Dict, List, Optional, Tuple from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging _snake_case = logging.get_logger(__name__) class UpperCamelCase ( snake_case_ ): UpperCamelCase : Dict = ['''input_ids''', '''attention_mask'''] def __init__( self : Tuple , UpperCAmelCase__ : Union[str, Any]="</s>" , UpperCAmelCase__ : Optional[Any]="<unk>" , UpperCAmelCase__ : Any="<pad>" , UpperCAmelCase__ : Any=125 , UpperCAmelCase__ : Optional[int]=None , **UpperCAmelCase__ : Any , ) -> None: # Add extra_ids to the special token list if extra_ids > 0 and additional_special_tokens is None: _a : Union[str, Any] = [f"""<extra_id_{i}>""" for i in range(UpperCAmelCase__ )] elif extra_ids > 0 and additional_special_tokens is not None: # Check that we have the right number of extra_id special tokens _a : List[str] = len(set(filter(lambda UpperCAmelCase__ : bool("""extra_id""" in str(UpperCAmelCase__ ) ) , UpperCAmelCase__ ) ) ) if extra_tokens != extra_ids: raise ValueError( f"""Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are""" """ provided to ByT5Tokenizer. In this case the additional_special_tokens must include the""" """ extra_ids tokens""" ) _a : int = AddedToken(UpperCAmelCase__ , lstrip=UpperCAmelCase__ , rstrip=UpperCAmelCase__ ) if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ) else pad_token _a : int = AddedToken(UpperCAmelCase__ , lstrip=UpperCAmelCase__ , rstrip=UpperCAmelCase__ ) if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ) else eos_token _a : List[str] = AddedToken(UpperCAmelCase__ , lstrip=UpperCAmelCase__ , rstrip=UpperCAmelCase__ ) if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ) else unk_token super().__init__( eos_token=UpperCAmelCase__ , unk_token=UpperCAmelCase__ , pad_token=UpperCAmelCase__ , extra_ids=UpperCAmelCase__ , additional_special_tokens=UpperCAmelCase__ , **UpperCAmelCase__ , ) _a : Optional[int] = extra_ids _a : Optional[Any] = 2**8 # utf is 8 bits # define special tokens dict _a : Dict[int, str] = { self.pad_token: 0, self.eos_token: 1, self.unk_token: 2, } _a : Union[str, Any] = len(self.special_tokens_encoder ) _a : int = len(UpperCAmelCase__ ) for i, token in enumerate(UpperCAmelCase__ ): _a : Optional[int] = self.vocab_size + i - n _a : Dict[str, int] = {v: k for k, v in self.special_tokens_encoder.items()} @property def _lowercase ( self : Any ) -> Tuple: return self._utf_vocab_size + self._num_special_tokens + self._extra_ids def _lowercase ( self : List[str] , 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__ ) # normal case: some special tokens if token_ids_a is None: return ([0] * len(UpperCAmelCase__ )) + [1] return ([0] * len(UpperCAmelCase__ )) + [1] + ([0] * len(UpperCAmelCase__ )) + [1] def _lowercase ( self : Optional[int] , UpperCAmelCase__ : List[int] ) -> List[int]: if len(UpperCAmelCase__ ) > 0 and token_ids[-1] == self.eos_token_id: warnings.warn( f"""This sequence already has {self.eos_token}. In future versions this behavior may lead to duplicated""" """ eos tokens being added.""" ) return token_ids else: return token_ids + [self.eos_token_id] def _lowercase ( self : List[str] , UpperCAmelCase__ : List[int] , UpperCAmelCase__ : Optional[List[int]] = None ) -> List[int]: _a : Any = [self.eos_token_id] if token_ids_a is None: return len(token_ids_a + eos ) * [0] return len(token_ids_a + eos + token_ids_a + eos ) * [0] def _lowercase ( self : Optional[int] , UpperCAmelCase__ : List[int] , UpperCAmelCase__ : Optional[List[int]] = None ) -> List[int]: _a : int = self._add_eos_if_not_present(UpperCAmelCase__ ) if token_ids_a is None: return token_ids_a else: _a : Union[str, Any] = self._add_eos_if_not_present(UpperCAmelCase__ ) return token_ids_a + token_ids_a def _lowercase ( self : List[Any] , UpperCAmelCase__ : str ) -> List[str]: _a : List[str] = [chr(UpperCAmelCase__ ) for i in text.encode("""utf-8""" )] return tokens def _lowercase ( self : Any , UpperCAmelCase__ : Optional[int] ) -> Union[str, Any]: if token in self.special_tokens_encoder: _a : List[Any] = self.special_tokens_encoder[token] elif token in self.added_tokens_encoder: _a : Optional[Any] = self.added_tokens_encoder[token] elif len(UpperCAmelCase__ ) != 1: _a : Dict = self.unk_token_id else: _a : int = ord(UpperCAmelCase__ ) + self._num_special_tokens return token_id def _lowercase ( self : Tuple , UpperCAmelCase__ : Optional[Any] ) -> int: if index in self.special_tokens_decoder: _a : int = self.special_tokens_decoder[index] else: _a : Optional[Any] = chr(index - self._num_special_tokens ) return token def _lowercase ( self : Union[str, Any] , UpperCAmelCase__ : List[str] ) -> Optional[Any]: _a : Union[str, Any] = B"""""" for token in tokens: if token in self.special_tokens_decoder: _a : Dict = self.special_tokens_decoder[token].encode("""utf-8""" ) elif token in self.added_tokens_decoder: _a : str = self.special_tokens_decoder[token].encode("""utf-8""" ) elif token in self.special_tokens_encoder: _a : Optional[int] = token.encode("""utf-8""" ) elif token in self.added_tokens_encoder: _a : List[Any] = token.encode("""utf-8""" ) else: _a : int = bytes([ord(UpperCAmelCase__ )] ) bstring += tok_string _a : List[str] = bstring.decode("""utf-8""" , errors="""ignore""" ) return string def _lowercase ( self : Any , UpperCAmelCase__ : str , UpperCAmelCase__ : Optional[str] = None ) -> Tuple[str]: return ()
324
"""simple docstring""" import argparse import json from dataclasses import dataclass, field from functools import partial from pathlib import Path from typing import List import timm import torch import torch.nn as nn from huggingface_hub import hf_hub_download from torch import Tensor from transformers import AutoImageProcessor, ResNetConfig, ResNetForImageClassification from transformers.utils import logging logging.set_verbosity_info() _snake_case = logging.get_logger() @dataclass class UpperCamelCase : UpperCamelCase : nn.Module UpperCamelCase : List[nn.Module] = field(default_factory=snake_case_ ) UpperCamelCase : list = field(default_factory=snake_case_ ) def _lowercase ( self : List[Any] , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : Tensor , UpperCAmelCase__ : Tensor ) -> Any: _a : int = len(list(m.modules() ) ) == 1 or isinstance(UpperCAmelCase__ , nn.Convad ) or isinstance(UpperCAmelCase__ , nn.BatchNormad ) if has_not_submodules: self.traced.append(UpperCAmelCase__ ) def __call__( self : Tuple , UpperCAmelCase__ : Tensor ) -> Tuple: for m in self.module.modules(): self.handles.append(m.register_forward_hook(self._forward_hook ) ) self.module(UpperCAmelCase__ ) [x.remove() for x in self.handles] return self @property def _lowercase ( self : Optional[int] ) -> int: # check the len of the state_dict keys to see if we have learnable params return list(filter(lambda UpperCAmelCase__ : len(list(x.state_dict().keys() ) ) > 0 , self.traced ) ) @dataclass class UpperCamelCase : UpperCamelCase : nn.Module UpperCamelCase : nn.Module UpperCamelCase : int = 0 UpperCamelCase : List = field(default_factory=snake_case_ ) UpperCamelCase : List = field(default_factory=snake_case_ ) def __call__( self : Optional[Any] , UpperCAmelCase__ : Tensor ) -> Tuple: _a : Union[str, Any] = Tracker(self.dest )(UpperCAmelCase__ ).parametrized _a : List[Any] = Tracker(self.src )(UpperCAmelCase__ ).parametrized _a : Tuple = list(filter(lambda UpperCAmelCase__ : type(UpperCAmelCase__ ) not in self.src_skip , UpperCAmelCase__ ) ) _a : Union[str, Any] = list(filter(lambda UpperCAmelCase__ : type(UpperCAmelCase__ ) not in self.dest_skip , UpperCAmelCase__ ) ) if len(UpperCAmelCase__ ) != len(UpperCAmelCase__ ): raise Exception( f"""Numbers of operations are different. Source module has {len(UpperCAmelCase__ )} operations while""" f""" destination module has {len(UpperCAmelCase__ )}.""" ) for dest_m, src_m in zip(UpperCAmelCase__ , UpperCAmelCase__ ): dest_m.load_state_dict(src_m.state_dict() ) if self.verbose == 1: print(f"""Transfered from={src_m} to={dest_m}""" ) def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = True ): '''simple docstring''' print(F"""Converting {name}...""" ) with torch.no_grad(): _a : List[str] = timm.create_model(UpperCamelCase__ , pretrained=UpperCamelCase__ ).eval() _a : str = ResNetForImageClassification(UpperCamelCase__ ).eval() _a : List[str] = ModuleTransfer(src=UpperCamelCase__ , dest=UpperCamelCase__ ) _a : List[str] = torch.randn((1, 3, 2_2_4, 2_2_4) ) module_transfer(UpperCamelCase__ ) assert torch.allclose(from_model(UpperCamelCase__ ) , our_model(UpperCamelCase__ ).logits ), "The model logits don't match the original one." _a : Dict = F"""resnet{'-'.join(name.split('resnet' ) )}""" print(UpperCamelCase__ ) if push_to_hub: our_model.push_to_hub( repo_path_or_name=save_directory / checkpoint_name , commit_message="""Add model""" , use_temp_dir=UpperCamelCase__ , ) # we can use the convnext one _a : Optional[Any] = AutoImageProcessor.from_pretrained("""facebook/convnext-base-224-22k-1k""" ) image_processor.push_to_hub( repo_path_or_name=save_directory / checkpoint_name , commit_message="""Add image processor""" , use_temp_dir=UpperCamelCase__ , ) print(F"""Pushed {checkpoint_name}""" ) def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ = None , UpperCamelCase__ = True ): '''simple docstring''' _a : Any = """imagenet-1k-id2label.json""" _a : Optional[int] = 1_0_0_0 _a : Any = (1, num_labels) _a : Union[str, Any] = """huggingface/label-files""" _a : Tuple = num_labels _a : Optional[int] = json.load(open(hf_hub_download(UpperCamelCase__ , UpperCamelCase__ , repo_type="""dataset""" ) , """r""" ) ) _a : Optional[Any] = {int(UpperCamelCase__ ): v for k, v in idalabel.items()} _a : Any = idalabel _a : Tuple = {v: k for k, v in idalabel.items()} _a : List[str] = partial(UpperCamelCase__ , num_labels=UpperCamelCase__ , idalabel=UpperCamelCase__ , labelaid=UpperCamelCase__ ) _a : Union[str, Any] = { """resnet18""": ImageNetPreTrainedConfig( depths=[2, 2, 2, 2] , hidden_sizes=[6_4, 1_2_8, 2_5_6, 5_1_2] , layer_type="""basic""" ), """resnet26""": ImageNetPreTrainedConfig( depths=[2, 2, 2, 2] , hidden_sizes=[2_5_6, 5_1_2, 1_0_2_4, 2_0_4_8] , layer_type="""bottleneck""" ), """resnet34""": ImageNetPreTrainedConfig( depths=[3, 4, 6, 3] , hidden_sizes=[6_4, 1_2_8, 2_5_6, 5_1_2] , layer_type="""basic""" ), """resnet50""": ImageNetPreTrainedConfig( depths=[3, 4, 6, 3] , hidden_sizes=[2_5_6, 5_1_2, 1_0_2_4, 2_0_4_8] , layer_type="""bottleneck""" ), """resnet101""": ImageNetPreTrainedConfig( depths=[3, 4, 2_3, 3] , hidden_sizes=[2_5_6, 5_1_2, 1_0_2_4, 2_0_4_8] , layer_type="""bottleneck""" ), """resnet152""": ImageNetPreTrainedConfig( depths=[3, 8, 3_6, 3] , hidden_sizes=[2_5_6, 5_1_2, 1_0_2_4, 2_0_4_8] , layer_type="""bottleneck""" ), } if model_name: convert_weight_and_push(UpperCamelCase__ , names_to_config[model_name] , UpperCamelCase__ , UpperCamelCase__ ) else: for model_name, config in names_to_config.items(): convert_weight_and_push(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) return config, expected_shape if __name__ == "__main__": _snake_case = argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default=None, type=str, help=( 'The name of the model you wish to convert, it must be one of the supported resnet* architecture,' ' currently: resnet18,26,34,50,101,152. If `None`, all of them will the converted.' ), ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=Path, required=True, help='Path to the output PyTorch model directory.', ) parser.add_argument( '--push_to_hub', default=True, type=bool, required=False, help='If True, push model and image processor to the hub.', ) _snake_case = parser.parse_args() _snake_case = args.pytorch_dump_folder_path pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True) convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)
324
1
"""simple docstring""" import numpy as np def lowerCAmelCase__ ( UpperCamelCase__ ): '''simple docstring''' return 1 / (1 + np.exp(-vector )) def lowerCAmelCase__ ( UpperCamelCase__ ): '''simple docstring''' return vector * sigmoid(1.702 * vector ) if __name__ == "__main__": import doctest doctest.testmod()
324
"""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, )
324
1
"""simple docstring""" from maths.is_square_free import is_square_free from maths.prime_factors import prime_factors def lowerCAmelCase__ ( UpperCamelCase__ ): '''simple docstring''' _a : Tuple = prime_factors(UpperCamelCase__ ) if is_square_free(UpperCamelCase__ ): return -1 if len(UpperCamelCase__ ) % 2 else 1 return 0 if __name__ == "__main__": import doctest doctest.testmod()
324
"""simple docstring""" _snake_case = 8.31_44_62 # Unit - J mol-1 K-1 def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' if moles < 0 or kelvin < 0 or volume < 0: raise ValueError("""Invalid inputs. Enter positive value.""" ) return moles * kelvin * UNIVERSAL_GAS_CONSTANT / volume def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' if moles < 0 or kelvin < 0 or pressure < 0: raise ValueError("""Invalid inputs. Enter positive value.""" ) return moles * kelvin * UNIVERSAL_GAS_CONSTANT / pressure if __name__ == "__main__": from doctest import testmod testmod()
324
1
"""simple docstring""" 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 ): @property def _lowercase ( self : Optional[int] ) -> Union[str, Any]: torch.manual_seed(0 ) _a : List[str] = 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 _lowercase ( self : Dict ) -> Dict: _a : str = self.dummy_uncond_unet _a : Optional[int] = KarrasVeScheduler() _a : List[str] = KarrasVePipeline(unet=UpperCAmelCase__ , scheduler=UpperCAmelCase__ ) pipe.to(UpperCAmelCase__ ) pipe.set_progress_bar_config(disable=UpperCAmelCase__ ) _a : int = torch.manual_seed(0 ) _a : List[Any] = pipe(num_inference_steps=2 , generator=UpperCAmelCase__ , output_type="""numpy""" ).images _a : Tuple = torch.manual_seed(0 ) _a : int = pipe(num_inference_steps=2 , generator=UpperCAmelCase__ , output_type="""numpy""" , return_dict=UpperCAmelCase__ )[0] _a : int = image[0, -3:, -3:, -1] _a : Optional[int] = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) _a : str = 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 ): def _lowercase ( self : Tuple ) -> List[str]: _a : Optional[Any] = """google/ncsnpp-celebahq-256""" _a : Any = UNetaDModel.from_pretrained(UpperCAmelCase__ ) _a : Dict = KarrasVeScheduler() _a : int = KarrasVePipeline(unet=UpperCAmelCase__ , scheduler=UpperCAmelCase__ ) pipe.to(UpperCAmelCase__ ) pipe.set_progress_bar_config(disable=UpperCAmelCase__ ) _a : Optional[int] = torch.manual_seed(0 ) _a : Tuple = pipe(num_inference_steps=20 , generator=UpperCAmelCase__ , output_type="""numpy""" ).images _a : List[str] = image[0, -3:, -3:, -1] assert image.shape == (1, 256, 256, 3) _a : Optional[int] = np.array([0.5_7_8, 0.5_8_1_1, 0.5_9_2_4, 0.5_8_0_9, 0.5_8_7, 0.5_8_8_6, 0.5_8_6_1, 0.5_8_0_2, 0.5_8_6] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
324
"""simple docstring""" import argparse import dataclasses import json import logging import os import shutil from typing import List, Optional import datasets from accelerate import Accelerator from datasets import load_dataset from finetuning import finetune from tqdm.auto import tqdm import transformers from transformers import AutoConfig, set_seed from transformers.trainer_utils import IntervalStrategy _snake_case = logging.getLogger(__name__) _snake_case = 'pytorch_model.bin' @dataclasses.dataclass class UpperCamelCase : UpperCamelCase : str = dataclasses.field( metadata={'''help''': '''Path to pretrained model or model identifier from huggingface.co/models.'''} ) UpperCamelCase : Optional[str] = dataclasses.field( default=snake_case_ , metadata={'''help''': '''Where do you want to store the pretrained models downloaded from huggingface.co.'''} , ) @dataclasses.dataclass class UpperCamelCase : UpperCamelCase : str = dataclasses.field(metadata={'''help''': '''A csv or a json file containing the training data.'''} ) UpperCamelCase : str = dataclasses.field(metadata={'''help''': '''A csv or a json file containing the data to predict on.'''} ) UpperCamelCase : Optional[str] = dataclasses.field( default=snake_case_ , metadata={'''help''': '''A csv or a json file containing the validation data.'''} ) UpperCamelCase : Optional[str] = dataclasses.field( default=snake_case_ , metadata={'''help''': '''The name of the task to train on.'''} , ) UpperCamelCase : Optional[List[str]] = dataclasses.field( default=snake_case_ , metadata={'''help''': '''The list of labels for the task.'''} ) @dataclasses.dataclass class UpperCamelCase : UpperCamelCase : str = dataclasses.field( metadata={'''help''': '''The output directory where the model predictions and checkpoints will be written.'''} ) UpperCamelCase : Optional[str] = dataclasses.field( default='''accuracy''' , metadata={'''help''': '''The evaluation metric used for the task.'''} ) UpperCamelCase : Optional[str] = dataclasses.field( default='''no''' , metadata={ '''help''': '''The evaluation strategy to adopt during training. Possible values are: ["no", "step", "epoch]''' } , ) UpperCamelCase : Optional[int] = dataclasses.field( default=10 , metadata={'''help''': '''Number of evaluation calls with no improvement after which training will be stopped.'''} , ) UpperCamelCase : Optional[float] = dataclasses.field( default=0.0 , metadata={ '''help''': '''How much the specified evaluation metric must improve to satisfy early stopping conditions.''' } , ) UpperCamelCase : Optional[bool] = dataclasses.field( default=snake_case_ , metadata={'''help''': '''Whether to filter the pseudo-labeled data based on the confidence score.'''} , ) UpperCamelCase : Optional[bool] = dataclasses.field( default=snake_case_ , metadata={'''help''': '''Whether to filter the pseudo-labeled data based on the validation performance.'''} , ) UpperCamelCase : Optional[bool] = dataclasses.field( default=snake_case_ , metadata={'''help''': '''Whether to fine-tune on labeled data after pseudo training.'''} , ) UpperCamelCase : Optional[float] = dataclasses.field( default=0.0 , metadata={'''help''': '''Confidence threshold for pseudo-labeled data filtering.'''} , ) UpperCamelCase : Optional[int] = dataclasses.field( default=100 , metadata={'''help''': '''Number of evaluation calls with no improvement after which training will be stopped.'''} , ) UpperCamelCase : Optional[int] = dataclasses.field( default=snake_case_ , metadata={'''help''': '''Random seed for initialization.'''} , ) def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' _a : Optional[int] = datasets.concatenate_datasets([infer_input, infer_output] , axis=1 ) if args.do_filter_by_confidence: _a : Union[str, Any] = dataset.filter(lambda UpperCamelCase__ : example["probability"] > args.confidence_threshold ) if args.do_filter_by_val_performance: assert eval_result >= 0.0 and eval_result <= 1.0 _a : Any = int(eval_result * len(UpperCamelCase__ ) ) print(UpperCamelCase__ ) _a : str = dataset.sort("""probability""" , reverse=UpperCamelCase__ ) _a : Any = dataset.select(range(UpperCamelCase__ ) ) _a : Tuple = dataset.remove_columns(["""label""", """probability"""] ) _a : Optional[Any] = dataset.rename_column("""prediction""" , """label""" ) _a : Dict = dataset.map(lambda UpperCamelCase__ : {"label": idalabel[example["label"]]} ) _a : Union[str, Any] = dataset.shuffle(seed=args.seed ) _a : Optional[int] = os.path.join(UpperCamelCase__ , F"""train_pseudo.{args.data_file_extension}""" ) if args.data_file_extension == "csv": dataset.to_csv(UpperCamelCase__ , index=UpperCamelCase__ ) else: dataset.to_json(UpperCamelCase__ ) def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , **UpperCamelCase__ ): '''simple docstring''' _a : Optional[int] = Accelerator() # Make one log on every process with the configuration for debugging. logging.basicConfig( format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""" , datefmt="""%m/%d/%Y %H:%M:%S""" , level=logging.INFO , ) logger.info(accelerator.state ) # Setup logging, we only want one process per machine to log things on the # screen. accelerator.is_local_main_process is only True for one process per # machine. logger.setLevel(logging.INFO if accelerator.is_local_main_process else logging.ERROR ) if accelerator.is_local_main_process: datasets.utils.logging.set_verbosity_warning() transformers.utils.logging.set_verbosity_info() else: datasets.utils.logging.set_verbosity_error() transformers.utils.logging.set_verbosity_error() _a : Dict = STModelArguments(model_name_or_path=UpperCamelCase__ ) _a : Union[str, Any] = STDataArguments(train_file=UpperCamelCase__ , infer_file=UpperCamelCase__ ) _a : Any = STTrainingArguments(output_dir=UpperCamelCase__ ) _a : Any = argparse.Namespace() for arg_class in (model_args, data_args, training_args): for key, value in vars(UpperCamelCase__ ).items(): setattr(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) for key, value in kwargs.items(): if hasattr(UpperCamelCase__ , UpperCamelCase__ ): setattr(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) # Sanity checks _a : Union[str, Any] = {} _a : Tuple = None # You need to provide the training data and the data to predict on assert args.train_file is not None assert args.infer_file is not None _a : int = args.train_file _a : List[Any] = args.infer_file if args.evaluation_strategy != IntervalStrategy.NO.value: assert args.eval_file is not None _a : Union[str, Any] = args.eval_file for key in data_files: _a : Optional[Any] = data_files[key].split(""".""" )[-1] assert extension in ["csv", "json"], F"""`{key}_file` should be a csv or a json file.""" if args.data_file_extension is None: _a : str = extension else: assert extension == args.data_file_extension, F"""`{key}_file` should be a {args.data_file_extension} file`.""" assert ( args.eval_metric in datasets.list_metrics() ), F"""{args.eval_metric} not in the list of supported metrics {datasets.list_metrics()}.""" # If passed along, set the training seed now. if args.seed is not None: set_seed(args.seed ) logger.info("""Creating the initial data directory for self-training...""" ) _a : Tuple = F"""{args.output_dir}/self-train_iter-{{}}""".format _a : Dict = data_dir_format(0 ) if accelerator.is_main_process: if args.output_dir is not None: os.makedirs(args.output_dir , exist_ok=UpperCamelCase__ ) os.makedirs(UpperCamelCase__ , exist_ok=UpperCamelCase__ ) accelerator.wait_for_everyone() _a : str = None _a : int = None _a : str = 0 _a : List[Any] = False # Show the progress bar _a : List[Any] = tqdm(range(args.max_selftrain_iterations ) , disable=not accelerator.is_local_main_process ) # Self-train for iteration in range(0 , int(args.max_selftrain_iterations ) ): _a : Union[str, Any] = data_dir_format(UpperCamelCase__ ) assert os.path.exists(UpperCamelCase__ ) # Stage 1: initial fine-tuning for iteration = 0 or pseudo-training for # iteration > 0 _a : str = os.path.join(UpperCamelCase__ , """stage-1""" ) _a : Tuple = { """accelerator""": accelerator, """model_name_or_path""": args.model_name_or_path, """cache_dir""": args.cache_dir, """do_train""": True, """train_file""": data_files["""train"""] if iteration == 0 else data_files["""train_pseudo"""], """do_eval""": True if args.eval_file is not None else False, """eval_file""": data_files["""eval"""], """do_predict""": True, """infer_file""": data_files["""infer"""], """task_name""": args.task_name, """label_list""": args.label_list, """output_dir""": current_output_dir, """eval_metric""": args.eval_metric, """evaluation_strategy""": args.evaluation_strategy, """early_stopping_patience""": args.early_stopping_patience, """early_stopping_threshold""": args.early_stopping_threshold, """seed""": args.seed, } # Add additional training arguments for key, value in kwargs.items(): if key not in arguments_dict and not hasattr(UpperCamelCase__ , UpperCamelCase__ ): arguments_dict.update({key: value} ) _a : int = os.path.join(UpperCamelCase__ , """best-checkpoint""" , UpperCamelCase__ ) if os.path.exists(UpperCamelCase__ ): logger.info( """Found existing model checkpoint at %s. Skipping self-training: iteration: %d, stage: 1.""" , UpperCamelCase__ , UpperCamelCase__ , ) else: logger.info("""***** Running self-training: iteration: %d, stage: 1 *****""" , UpperCamelCase__ ) finetune(**UpperCamelCase__ ) accelerator.wait_for_everyone() assert os.path.exists(UpperCamelCase__ ) logger.info("""Self-training job completed: iteration: %d, stage: 1.""" , UpperCamelCase__ ) if iteration > 0 and args.finetune_on_labeled_data: # Stage 2 (optional): fine-tuning on the original labeled data _a : Dict = os.path.join(UpperCamelCase__ , """best-checkpoint""" ) _a : List[str] = os.path.join(UpperCamelCase__ , """stage-2""" ) # Update arguments_dict _a : int = model_path _a : Dict = data_files["""train"""] _a : int = current_output_dir _a : Any = os.path.join(UpperCamelCase__ , """best-checkpoint""" , UpperCamelCase__ ) if os.path.exists(UpperCamelCase__ ): logger.info( """Found existing model checkpoint at %s. Skipping self-training: iteration: %d, stage: 2.""" , UpperCamelCase__ , UpperCamelCase__ , ) else: logger.info("""***** Running self-training: iteration: %d, stage: 2 *****""" , UpperCamelCase__ ) finetune(**UpperCamelCase__ ) accelerator.wait_for_everyone() assert os.path.exists(UpperCamelCase__ ) logger.info("""Self-training job completed: iteration: %d, stage: 2.""" , UpperCamelCase__ ) _a : List[Any] = iteration _a : int = data_dir_format(iteration + 1 ) _a : Dict = AutoConfig.from_pretrained(os.path.join(UpperCamelCase__ , """best-checkpoint""" ) ) _a : Union[str, Any] = config.idalabel _a : Any = os.path.join(UpperCamelCase__ , """eval_results_best-checkpoint.json""" ) _a : Any = os.path.join(UpperCamelCase__ , """test_results_best-checkpoint.json""" ) assert os.path.exists(UpperCamelCase__ ) with open(UpperCamelCase__ , """r""" ) as f: _a : Tuple = float(json.load(UpperCamelCase__ )[args.eval_metric] ) _a : Dict = os.path.join(UpperCamelCase__ , """infer_output_best-checkpoint.csv""" ) assert os.path.exists(UpperCamelCase__ ) # Loading the dataset from local csv or json files. _a : List[Any] = load_dataset(args.data_file_extension , data_files={"""data""": data_files["""infer"""]} )["""data"""] _a : Any = load_dataset("""csv""" , data_files={"""data""": infer_output_file} )["""data"""] if accelerator.is_main_process: os.makedirs(UpperCamelCase__ , exist_ok=UpperCamelCase__ ) shutil.copy(UpperCamelCase__ , os.path.join(UpperCamelCase__ , F"""eval_results_iter-{iteration}.json""" ) ) if os.path.exists(UpperCamelCase__ ): shutil.copy(UpperCamelCase__ , os.path.join(UpperCamelCase__ , F"""test_results_iter-{iteration}.json""" ) ) create_pseudo_labeled_data(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) accelerator.wait_for_everyone() _a : List[str] = os.path.join(UpperCamelCase__ , F"""train_pseudo.{args.data_file_extension}""" ) if args.evaluation_strategy != IntervalStrategy.NO.value: _a : Any = eval_result if best_iteration is None: _a : Union[str, Any] = new_iteration _a : str = new_eval_result else: if new_eval_result - best_eval_result > args.early_stopping_threshold: _a : Union[str, Any] = new_iteration _a : List[str] = new_eval_result _a : Optional[Any] = 0 else: if new_eval_result == best_eval_result: _a : Tuple = new_iteration _a : List[Any] = new_eval_result early_stopping_patience_counter += 1 if early_stopping_patience_counter >= args.early_stopping_patience: _a : Union[str, Any] = True progress_bar.update(1 ) if should_training_stop: break if best_iteration is not None: # Save the best iteration logger.info("""Best iteration: %d""" , UpperCamelCase__ ) logger.info("""Best evaluation result: %s = %f""" , args.eval_metric , UpperCamelCase__ ) accelerator.wait_for_everyone() if accelerator.is_main_process: shutil.copy( os.path.join(UpperCamelCase__ , F"""eval_results_iter-{iteration}.json""" ) , os.path.join(UpperCamelCase__ , """eval_results_best-iteration.json""" ) , ) else: # Assume that the last iteration is the best logger.info("""Best iteration: %d""" , args.max_selftrain_iterations - 1 ) logger.info("""Best evaluation result: %s = %f""" , args.eval_metric , UpperCamelCase__ ) accelerator.wait_for_everyone() if accelerator.is_main_process: shutil.copy( os.path.join(UpperCamelCase__ , F"""eval_results_iter-{args.max_selftrain_iterations - 1}.json""" ) , os.path.join(UpperCamelCase__ , """eval_results_best-iteration.json""" ) , )
324
1
"""simple docstring""" from ..utils import DummyObject, requires_backends class UpperCamelCase ( metaclass=snake_case_ ): UpperCamelCase : str = ['''speech'''] def __init__( self : Optional[Any] , *UpperCAmelCase__ : List[Any] , **UpperCAmelCase__ : List[Any] ) -> List[str]: requires_backends(self , ["""speech"""] ) class UpperCamelCase ( metaclass=snake_case_ ): UpperCamelCase : Union[str, Any] = ['''speech'''] def __init__( self : List[str] , *UpperCAmelCase__ : Union[str, Any] , **UpperCAmelCase__ : List[Any] ) -> List[Any]: requires_backends(self , ["""speech"""] )
324
"""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_camembert import CamembertTokenizer else: _snake_case = None _snake_case = logging.get_logger(__name__) _snake_case = {'vocab_file': 'sentencepiece.bpe.model', 'tokenizer_file': 'tokenizer.json'} _snake_case = { 'vocab_file': { 'camembert-base': 'https://huggingface.co/camembert-base/resolve/main/sentencepiece.bpe.model', }, 'tokenizer_file': { 'camembert-base': 'https://huggingface.co/camembert-base/resolve/main/tokenizer.json', }, } _snake_case = { 'camembert-base': 512, } _snake_case = '▁' class UpperCamelCase ( snake_case_ ): UpperCamelCase : Any = VOCAB_FILES_NAMES UpperCamelCase : Union[str, Any] = PRETRAINED_VOCAB_FILES_MAP UpperCamelCase : Union[str, Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCamelCase : Dict = ['''input_ids''', '''attention_mask'''] UpperCamelCase : Optional[Any] = CamembertTokenizer def __init__( self : int , UpperCAmelCase__ : List[Any]=None , UpperCAmelCase__ : Optional[int]=None , UpperCAmelCase__ : Optional[Any]="<s>" , UpperCAmelCase__ : Optional[int]="</s>" , UpperCAmelCase__ : Tuple="</s>" , UpperCAmelCase__ : Tuple="<s>" , UpperCAmelCase__ : Tuple="<unk>" , UpperCAmelCase__ : Tuple="<pad>" , UpperCAmelCase__ : int="<mask>" , UpperCAmelCase__ : Optional[int]=["<s>NOTUSED", "</s>NOTUSED"] , **UpperCAmelCase__ : Optional[Any] , ) -> Union[str, Any]: # Mask token behave like a normal word, i.e. include the space before it _a : List[Any] = AddedToken(UpperCAmelCase__ , lstrip=UpperCAmelCase__ , rstrip=UpperCAmelCase__ ) if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ) else mask_token super().__init__( UpperCAmelCase__ , tokenizer_file=UpperCAmelCase__ , bos_token=UpperCAmelCase__ , eos_token=UpperCAmelCase__ , sep_token=UpperCAmelCase__ , cls_token=UpperCAmelCase__ , unk_token=UpperCAmelCase__ , pad_token=UpperCAmelCase__ , mask_token=UpperCAmelCase__ , additional_special_tokens=UpperCAmelCase__ , **UpperCAmelCase__ , ) _a : int = vocab_file _a : int = False if not self.vocab_file else True def _lowercase ( self : Union[str, Any] , 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] _a : List[Any] = [self.cls_token_id] _a : Dict = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def _lowercase ( self : Optional[int] , UpperCAmelCase__ : List[int] , UpperCAmelCase__ : Optional[List[int]] = None ) -> List[int]: _a : Union[str, Any] = [self.sep_token_id] _a : 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 _lowercase ( self : Optional[int] , UpperCAmelCase__ : str , UpperCAmelCase__ : Optional[str] = None ) -> Tuple[str]: 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(UpperCAmelCase__ ): logger.error(f"""Vocabulary path ({save_directory}) should be a directory""" ) return _a : List[str] = 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,)
324
1
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging _snake_case = logging.get_logger(__name__) _snake_case = { '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 UpperCamelCase ( snake_case_ ): UpperCamelCase : Union[str, Any] = '''visual_bert''' def __init__( self : str , UpperCAmelCase__ : Optional[int]=30522 , UpperCAmelCase__ : List[str]=768 , UpperCAmelCase__ : List[str]=512 , UpperCAmelCase__ : List[Any]=12 , UpperCAmelCase__ : int=12 , UpperCAmelCase__ : List[str]=3072 , UpperCAmelCase__ : List[Any]="gelu" , UpperCAmelCase__ : Optional[int]=0.1 , UpperCAmelCase__ : str=0.1 , UpperCAmelCase__ : int=512 , UpperCAmelCase__ : Union[str, Any]=2 , UpperCAmelCase__ : List[Any]=0.0_2 , UpperCAmelCase__ : int=1E-12 , UpperCAmelCase__ : Any=False , UpperCAmelCase__ : int=True , UpperCAmelCase__ : Dict=1 , UpperCAmelCase__ : int=0 , UpperCAmelCase__ : Optional[int]=2 , **UpperCAmelCase__ : List[Any] , ) -> Dict: super().__init__(pad_token_id=UpperCAmelCase__ , bos_token_id=UpperCAmelCase__ , eos_token_id=UpperCAmelCase__ , **UpperCAmelCase__ ) _a : List[str] = vocab_size _a : Any = max_position_embeddings _a : Union[str, Any] = hidden_size _a : int = visual_embedding_dim _a : List[str] = num_hidden_layers _a : str = num_attention_heads _a : Union[str, Any] = intermediate_size _a : Tuple = hidden_act _a : Optional[int] = hidden_dropout_prob _a : List[str] = attention_probs_dropout_prob _a : Dict = initializer_range _a : Optional[Any] = type_vocab_size _a : Dict = layer_norm_eps _a : Dict = bypass_transformer _a : Optional[Any] = special_visual_initialize
324
"""simple docstring""" from typing import List, Optional, Union import numpy as np import PIL.Image from ...image_processing_utils import BaseImageProcessor, BatchFeature from ...image_transforms import rescale, resize, to_channel_dimension_format from ...image_utils import ( ChannelDimension, PILImageResampling, get_image_size, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, logging _snake_case = logging.get_logger(__name__) class UpperCamelCase ( snake_case_ ): UpperCamelCase : Dict = ['''pixel_values'''] def __init__( self : Any , UpperCAmelCase__ : bool = True , UpperCAmelCase__ : int = 32 , UpperCAmelCase__ : Optional[Any]=PILImageResampling.BILINEAR , UpperCAmelCase__ : bool = True , **UpperCAmelCase__ : List[str] , ) -> None: _a : int = do_resize _a : Union[str, Any] = do_rescale _a : Any = size_divisor _a : Any = resample super().__init__(**UpperCAmelCase__ ) def _lowercase ( self : Tuple , UpperCAmelCase__ : np.ndarray , UpperCAmelCase__ : int , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Optional[ChannelDimension] = None , **UpperCAmelCase__ : Optional[Any] ) -> np.ndarray: _a , _a : Tuple = get_image_size(UpperCAmelCase__ ) # Rounds the height and width down to the closest multiple of size_divisor _a : Optional[Any] = height // size_divisor * size_divisor _a : Union[str, Any] = width // size_divisor * size_divisor _a : Any = resize(UpperCAmelCase__ , (new_h, new_w) , resample=UpperCAmelCase__ , data_format=UpperCAmelCase__ , **UpperCAmelCase__ ) return image def _lowercase ( self : Union[str, Any] , UpperCAmelCase__ : np.ndarray , UpperCAmelCase__ : float , UpperCAmelCase__ : Optional[ChannelDimension] = None , **UpperCAmelCase__ : Optional[int] ) -> np.ndarray: return rescale(image=UpperCAmelCase__ , scale=UpperCAmelCase__ , data_format=UpperCAmelCase__ , **UpperCAmelCase__ ) def _lowercase ( self : Optional[int] , UpperCAmelCase__ : Union["PIL.Image.Image", TensorType, List["PIL.Image.Image"], List[TensorType]] , UpperCAmelCase__ : Optional[bool] = None , UpperCAmelCase__ : Optional[int] = None , UpperCAmelCase__ : int=None , UpperCAmelCase__ : Optional[bool] = None , UpperCAmelCase__ : Optional[Union[TensorType, str]] = None , UpperCAmelCase__ : ChannelDimension = ChannelDimension.FIRST , **UpperCAmelCase__ : int , ) -> BatchFeature: _a : Dict = do_resize if do_resize is not None else self.do_resize _a : Optional[int] = do_rescale if do_rescale is not None else self.do_rescale _a : str = size_divisor if size_divisor is not None else self.size_divisor _a : Any = resample if resample is not None else self.resample if do_resize and size_divisor is None: raise ValueError("""size_divisor is required for resizing""" ) _a : List[str] = make_list_of_images(UpperCAmelCase__ ) if not valid_images(UpperCAmelCase__ ): raise ValueError("""Invalid image(s)""" ) # All transformations expect numpy arrays. _a : Tuple = [to_numpy_array(UpperCAmelCase__ ) for img in images] if do_resize: _a : Optional[int] = [self.resize(UpperCAmelCase__ , size_divisor=UpperCAmelCase__ , resample=UpperCAmelCase__ ) for image in images] if do_rescale: _a : str = [self.rescale(UpperCAmelCase__ , scale=1 / 255 ) for image in images] _a : Any = [to_channel_dimension_format(UpperCAmelCase__ , UpperCAmelCase__ ) for image in images] _a : Optional[int] = {"""pixel_values""": images} return BatchFeature(data=UpperCAmelCase__ , tensor_type=UpperCAmelCase__ )
324
1
"""simple docstring""" # Lint as: python3 # pylint: enable=line-too-long # pylint: disable=g-import-not-at-top,g-bad-import-order,wrong-import-position _snake_case = '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 _snake_case = concatenate_datasets _snake_case = DownloadConfig _snake_case = DownloadManager _snake_case = DownloadMode _snake_case = DownloadConfig _snake_case = DownloadMode _snake_case = DownloadManager del _arrow_dataset, _utils, _deprecated_download_manager
324
"""simple docstring""" 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 ): @property def _lowercase ( self : Optional[int] ) -> Union[str, Any]: torch.manual_seed(0 ) _a : List[str] = 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 _lowercase ( self : Dict ) -> Dict: _a : str = self.dummy_uncond_unet _a : Optional[int] = KarrasVeScheduler() _a : List[str] = KarrasVePipeline(unet=UpperCAmelCase__ , scheduler=UpperCAmelCase__ ) pipe.to(UpperCAmelCase__ ) pipe.set_progress_bar_config(disable=UpperCAmelCase__ ) _a : int = torch.manual_seed(0 ) _a : List[Any] = pipe(num_inference_steps=2 , generator=UpperCAmelCase__ , output_type="""numpy""" ).images _a : Tuple = torch.manual_seed(0 ) _a : int = pipe(num_inference_steps=2 , generator=UpperCAmelCase__ , output_type="""numpy""" , return_dict=UpperCAmelCase__ )[0] _a : int = image[0, -3:, -3:, -1] _a : Optional[int] = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) _a : str = 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 ): def _lowercase ( self : Tuple ) -> List[str]: _a : Optional[Any] = """google/ncsnpp-celebahq-256""" _a : Any = UNetaDModel.from_pretrained(UpperCAmelCase__ ) _a : Dict = KarrasVeScheduler() _a : int = KarrasVePipeline(unet=UpperCAmelCase__ , scheduler=UpperCAmelCase__ ) pipe.to(UpperCAmelCase__ ) pipe.set_progress_bar_config(disable=UpperCAmelCase__ ) _a : Optional[int] = torch.manual_seed(0 ) _a : Tuple = pipe(num_inference_steps=20 , generator=UpperCAmelCase__ , output_type="""numpy""" ).images _a : List[str] = image[0, -3:, -3:, -1] assert image.shape == (1, 256, 256, 3) _a : Optional[int] = np.array([0.5_7_8, 0.5_8_1_1, 0.5_9_2_4, 0.5_8_0_9, 0.5_8_7, 0.5_8_8_6, 0.5_8_6_1, 0.5_8_0_2, 0.5_8_6] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
324
1
"""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 how to properly calculate the metrics on the # validation dataset when in a distributed system, 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 # ######################################################################## _snake_case = 16 _snake_case = 32 def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ = 1_6 ): '''simple docstring''' _a : str = AutoTokenizer.from_pretrained("""bert-base-cased""" ) _a : Dict = load_dataset("""glue""" , """mrpc""" ) def tokenize_function(UpperCamelCase__ ): # max_length=None => use the model max length (it's actually the default) _a : Optional[int] = 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(): _a : Tuple = 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 _a : List[Any] = tokenized_datasets.rename_column("""label""" , """labels""" ) def collate_fn(UpperCamelCase__ ): # On TPU it's best to pad everything to the same length or training will be very slow. _a : Union[str, Any] = 1_2_8 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": _a : int = 1_6 elif accelerator.mixed_precision != "no": _a : int = 8 else: _a : str = None return tokenizer.pad( UpperCamelCase__ , padding="""longest""" , max_length=UpperCamelCase__ , pad_to_multiple_of=UpperCamelCase__ , return_tensors="""pt""" , ) # Instantiate dataloaders. _a : int = DataLoader( tokenized_datasets["""train"""] , shuffle=UpperCamelCase__ , collate_fn=UpperCamelCase__ , batch_size=UpperCamelCase__ ) _a : List[str] = 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 _snake_case = mocked_dataloaders # noqa: F811 def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' # For testing only if os.environ.get("""TESTING_MOCKED_DATALOADERS""" , UpperCamelCase__ ) == "1": _a : str = 2 # Initialize accelerator _a : int = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs _a : Any = config["""lr"""] _a : Union[str, Any] = int(config["""num_epochs"""] ) _a : str = int(config["""seed"""] ) _a : List[Any] = int(config["""batch_size"""] ) _a : Tuple = evaluate.load("""glue""" , """mrpc""" ) # If the batch size is too big we use gradient accumulation _a : Optional[Any] = 1 if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU: _a : Optional[Any] = batch_size // MAX_GPU_BATCH_SIZE _a : str = MAX_GPU_BATCH_SIZE set_seed(UpperCamelCase__ ) _a , _a : Optional[int] = get_dataloaders(UpperCamelCase__ , UpperCamelCase__ ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) _a : int = 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). _a : List[str] = model.to(accelerator.device ) # Instantiate optimizer _a : List[str] = AdamW(params=model.parameters() , lr=UpperCamelCase__ ) # Instantiate scheduler _a : List[str] = get_linear_schedule_with_warmup( optimizer=UpperCamelCase__ , num_warmup_steps=1_0_0 , 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. _a , _a , _a , _a , _a : Optional[Any] = accelerator.prepare( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) # Now we train the model for epoch in range(UpperCamelCase__ ): model.train() for step, batch in enumerate(UpperCamelCase__ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) _a : Optional[Any] = model(**UpperCamelCase__ ) _a : str = outputs.loss _a : Optional[int] = loss / gradient_accumulation_steps accelerator.backward(UpperCamelCase__ ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() _a : Union[str, Any] = 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 ) with torch.no_grad(): _a : Dict = model(**UpperCamelCase__ ) _a : Optional[Any] = outputs.logits.argmax(dim=-1 ) _a , _a : int = accelerator.gather((predictions, batch["""labels"""]) ) # New Code # # First we check if it's a distributed system if accelerator.use_distributed: # Then see if we're on the last batch of our eval dataloader if step == len(UpperCamelCase__ ) - 1: # Last batch needs to be truncated on distributed systems as it contains additional samples _a : str = predictions[: len(eval_dataloader.dataset ) - samples_seen] _a : int = references[: len(eval_dataloader.dataset ) - samples_seen] else: # Otherwise we add the number of samples seen samples_seen += references.shape[0] # All of this can be avoided if you use `Accelerator.gather_for_metrics` instead of `Accelerator.gather`: # accelerator.gather_for_metrics((predictions, batch["labels"])) metric.add_batch( predictions=UpperCamelCase__ , references=UpperCamelCase__ , ) _a : int = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F"""epoch {epoch}:""" , UpperCamelCase__ ) def lowerCAmelCase__ ( ): '''simple docstring''' _a : Tuple = 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.""" ) _a : Optional[Any] = parser.parse_args() _a : Tuple = {"""lr""": 2e-5, """num_epochs""": 3, """seed""": 4_2, """batch_size""": 1_6} training_function(UpperCamelCase__ , UpperCamelCase__ ) if __name__ == "__main__": main()
324
"""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 how to properly calculate the metrics on the # validation dataset when in a distributed system, 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 # ######################################################################## _snake_case = 16 _snake_case = 32 def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ = 1_6 ): '''simple docstring''' _a : str = AutoTokenizer.from_pretrained("""bert-base-cased""" ) _a : Dict = load_dataset("""glue""" , """mrpc""" ) def tokenize_function(UpperCamelCase__ ): # max_length=None => use the model max length (it's actually the default) _a : Optional[int] = 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(): _a : Tuple = 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 _a : List[Any] = tokenized_datasets.rename_column("""label""" , """labels""" ) def collate_fn(UpperCamelCase__ ): # On TPU it's best to pad everything to the same length or training will be very slow. _a : Union[str, Any] = 1_2_8 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": _a : int = 1_6 elif accelerator.mixed_precision != "no": _a : int = 8 else: _a : str = None return tokenizer.pad( UpperCamelCase__ , padding="""longest""" , max_length=UpperCamelCase__ , pad_to_multiple_of=UpperCamelCase__ , return_tensors="""pt""" , ) # Instantiate dataloaders. _a : int = DataLoader( tokenized_datasets["""train"""] , shuffle=UpperCamelCase__ , collate_fn=UpperCamelCase__ , batch_size=UpperCamelCase__ ) _a : List[str] = 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 _snake_case = mocked_dataloaders # noqa: F811 def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' # For testing only if os.environ.get("""TESTING_MOCKED_DATALOADERS""" , UpperCamelCase__ ) == "1": _a : str = 2 # Initialize accelerator _a : int = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs _a : Any = config["""lr"""] _a : Union[str, Any] = int(config["""num_epochs"""] ) _a : str = int(config["""seed"""] ) _a : List[Any] = int(config["""batch_size"""] ) _a : Tuple = evaluate.load("""glue""" , """mrpc""" ) # If the batch size is too big we use gradient accumulation _a : Optional[Any] = 1 if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU: _a : Optional[Any] = batch_size // MAX_GPU_BATCH_SIZE _a : str = MAX_GPU_BATCH_SIZE set_seed(UpperCamelCase__ ) _a , _a : Optional[int] = get_dataloaders(UpperCamelCase__ , UpperCamelCase__ ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) _a : int = 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). _a : List[str] = model.to(accelerator.device ) # Instantiate optimizer _a : List[str] = AdamW(params=model.parameters() , lr=UpperCamelCase__ ) # Instantiate scheduler _a : List[str] = get_linear_schedule_with_warmup( optimizer=UpperCamelCase__ , num_warmup_steps=1_0_0 , 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. _a , _a , _a , _a , _a : Optional[Any] = accelerator.prepare( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) # Now we train the model for epoch in range(UpperCamelCase__ ): model.train() for step, batch in enumerate(UpperCamelCase__ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) _a : Optional[Any] = model(**UpperCamelCase__ ) _a : str = outputs.loss _a : Optional[int] = loss / gradient_accumulation_steps accelerator.backward(UpperCamelCase__ ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() _a : Union[str, Any] = 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 ) with torch.no_grad(): _a : Dict = model(**UpperCamelCase__ ) _a : Optional[Any] = outputs.logits.argmax(dim=-1 ) _a , _a : int = accelerator.gather((predictions, batch["""labels"""]) ) # New Code # # First we check if it's a distributed system if accelerator.use_distributed: # Then see if we're on the last batch of our eval dataloader if step == len(UpperCamelCase__ ) - 1: # Last batch needs to be truncated on distributed systems as it contains additional samples _a : str = predictions[: len(eval_dataloader.dataset ) - samples_seen] _a : int = references[: len(eval_dataloader.dataset ) - samples_seen] else: # Otherwise we add the number of samples seen samples_seen += references.shape[0] # All of this can be avoided if you use `Accelerator.gather_for_metrics` instead of `Accelerator.gather`: # accelerator.gather_for_metrics((predictions, batch["labels"])) metric.add_batch( predictions=UpperCamelCase__ , references=UpperCamelCase__ , ) _a : int = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F"""epoch {epoch}:""" , UpperCamelCase__ ) def lowerCAmelCase__ ( ): '''simple docstring''' _a : Tuple = 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.""" ) _a : Optional[Any] = parser.parse_args() _a : Tuple = {"""lr""": 2e-5, """num_epochs""": 3, """seed""": 4_2, """batch_size""": 1_6} training_function(UpperCamelCase__ , UpperCamelCase__ ) if __name__ == "__main__": main()
324
1
"""simple docstring""" import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch if is_torch_available(): import torch from transformers.generation import DisjunctiveConstraint @require_torch class UpperCamelCase ( unittest.TestCase ): def _lowercase ( self : Tuple ) -> List[str]: # For consistency across different places the DisjunctiveConstraint is called, # dc.token_ids is a list of integers. It is also initialized only by integers. _a : Optional[Any] = [[1, 2, 4], [1, 2, 3, 4]] _a : Optional[int] = DisjunctiveConstraint(UpperCAmelCase__ ) self.assertTrue(isinstance(dc.token_ids , UpperCAmelCase__ ) ) with self.assertRaises(UpperCAmelCase__ ): DisjunctiveConstraint(torch.LongTensor([[1, 2, 4], [1, 2, 3]] ) ) with self.assertRaises(UpperCAmelCase__ ): DisjunctiveConstraint([torch.LongTensor([1, 2, 4] ), torch.LongTensor([1, 2, 3, 4, 5] )] ) def _lowercase ( self : str ) -> Optional[Any]: # We can't have constraints that are complete subsets of another. This leads to a preverse # interpretation of "constraint fulfillment": does generating [1,2,3] fulfill the constraint? # It would mean that it generated [1,2] which fulfills it, but it's in the middle of potentially # fulfilling [1,2,3,4]. If we believe that [1,2,3] does fulfill the constraint, then the algorithm # will necessarily never reach [1,2,3,4], giving users a false sense of control (better to just not allow it). _a : List[str] = [[1, 2], [1, 2, 3, 4]] with self.assertRaises(UpperCAmelCase__ ): DisjunctiveConstraint(UpperCAmelCase__ ) # fails here def _lowercase ( self : Union[str, Any] ) -> List[Any]: _a : int = [[1, 2, 3], [1, 2, 4]] _a : List[Any] = DisjunctiveConstraint(UpperCAmelCase__ ) _a , _a , _a : int = dc.update(1 ) _a : str = stepped is True and completed is False and reset is False self.assertTrue(UpperCAmelCase__ ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1] ) _a , _a , _a : Optional[int] = dc.update(2 ) _a : Optional[Any] = stepped is True and completed is False and reset is False self.assertTrue(UpperCAmelCase__ ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2] ) _a , _a , _a : List[str] = dc.update(3 ) _a : Tuple = stepped is True and completed is True and reset is False self.assertTrue(UpperCAmelCase__ ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.current_seq == [1, 2, 3] ) def _lowercase ( self : Union[str, Any] ) -> int: _a : List[Any] = [[1, 2, 3], [1, 2, 4, 5], [1, 2, 5]] _a : Dict = DisjunctiveConstraint(UpperCAmelCase__ ) _a , _a , _a : str = dc.update(1 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1] ) _a , _a , _a : str = dc.update(2 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2] ) _a , _a , _a : Any = dc.update(4 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2, 4] ) _a , _a , _a : Any = dc.update(5 ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.current_seq == [1, 2, 4, 5] ) dc.reset() _a , _a , _a : List[str] = dc.update(1 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.remaining() == 3 ) self.assertTrue(dc.current_seq == [1] ) _a , _a , _a : Dict = dc.update(2 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.remaining() == 2 ) self.assertTrue(dc.current_seq == [1, 2] ) _a , _a , _a : Dict = dc.update(5 ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.remaining() == 0 ) self.assertTrue(dc.current_seq == [1, 2, 5] )
324
"""simple docstring""" import numpy as np def lowerCAmelCase__ ( UpperCamelCase__ ): '''simple docstring''' return 1 / (1 + np.exp(-vector )) def lowerCAmelCase__ ( UpperCamelCase__ ): '''simple docstring''' return vector * sigmoid(1.702 * vector ) if __name__ == "__main__": import doctest doctest.testmod()
324
1
"""simple docstring""" from __future__ import annotations def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ = None , UpperCamelCase__ = None , UpperCamelCase__ = False , ): '''simple docstring''' _a : Optional[Any] = cipher_alphabet or [chr(UpperCamelCase__ ) for i in range(9_7 , 1_2_3 )] # If the argument is None or the user provided an empty dictionary if not frequencies_dict: # Frequencies of letters in the english language (how much they show up) _a : Optional[int] = { """a""": 0.08_497, """b""": 0.01_492, """c""": 0.02_202, """d""": 0.04_253, """e""": 0.11_162, """f""": 0.02_228, """g""": 0.02_015, """h""": 0.06_094, """i""": 0.07_546, """j""": 0.00_153, """k""": 0.01_292, """l""": 0.04_025, """m""": 0.02_406, """n""": 0.06_749, """o""": 0.07_507, """p""": 0.01_929, """q""": 0.00_095, """r""": 0.07_587, """s""": 0.06_327, """t""": 0.09_356, """u""": 0.02_758, """v""": 0.00_978, """w""": 0.02_560, """x""": 0.00_150, """y""": 0.01_994, """z""": 0.00_077, } else: # Custom frequencies dictionary _a : str = frequencies_dict if not case_sensitive: _a : List[Any] = ciphertext.lower() # Chi squared statistic values _a : dict[int, tuple[float, str]] = {} # cycle through all of the shifts for shift in range(len(UpperCamelCase__ ) ): _a : List[str] = """""" # decrypt the message with the shift for letter in ciphertext: try: # Try to index the letter in the alphabet _a : Dict = (alphabet_letters.index(letter.lower() ) - shift) % len( UpperCamelCase__ ) decrypted_with_shift += ( alphabet_letters[new_key].upper() if case_sensitive and letter.isupper() else alphabet_letters[new_key] ) except ValueError: # Append the character if it isn't in the alphabet decrypted_with_shift += letter _a : Tuple = 0.0 # Loop through each letter in the decoded message with the shift for letter in decrypted_with_shift: if case_sensitive: _a : Any = letter.lower() if letter in frequencies: # Get the amount of times the letter occurs in the message _a : Dict = decrypted_with_shift.lower().count(UpperCamelCase__ ) # Get the excepcted amount of times the letter should appear based # on letter frequencies _a : int = frequencies[letter] * occurrences # Complete the chi squared statistic formula _a : int = ((occurrences - expected) ** 2) / expected # Add the margin of error to the total chi squared statistic chi_squared_statistic += chi_letter_value else: if letter.lower() in frequencies: # Get the amount of times the letter occurs in the message _a : Optional[int] = decrypted_with_shift.count(UpperCamelCase__ ) # Get the excepcted amount of times the letter should appear based # on letter frequencies _a : Optional[int] = frequencies[letter] * occurrences # Complete the chi squared statistic formula _a : List[Any] = ((occurrences - expected) ** 2) / expected # Add the margin of error to the total chi squared statistic chi_squared_statistic += chi_letter_value # Add the data to the chi_squared_statistic_values dictionary _a : Any = ( chi_squared_statistic, decrypted_with_shift, ) # Get the most likely cipher by finding the cipher with the smallest chi squared # statistic def chi_squared_statistic_values_sorting_key(UpperCamelCase__ ) -> tuple[float, str]: return chi_squared_statistic_values[key] _a : int = min( UpperCamelCase__ , key=UpperCamelCase__ , ) # Get all the data from the most likely cipher (key, decoded message) ( ( _a ) , ( _a ) , ) : Optional[Any] = chi_squared_statistic_values[most_likely_cipher] # Return the data on the most likely shift return ( most_likely_cipher, most_likely_cipher_chi_squared_value, decoded_most_likely_cipher, )
324
"""simple docstring""" import unittest from transformers import CamembertTokenizer, CamembertTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.utils import is_torch_available from ...test_tokenization_common import TokenizerTesterMixin _snake_case = get_tests_dir('fixtures/test_sentencepiece.model') _snake_case = get_tests_dir('fixtures/test_sentencepiece_bpe.model') _snake_case = 'pt' if is_torch_available() else 'tf' @require_sentencepiece @require_tokenizers class UpperCamelCase ( snake_case_ , unittest.TestCase ): UpperCamelCase : str = CamembertTokenizer UpperCamelCase : List[Any] = CamembertTokenizerFast UpperCamelCase : Optional[int] = True UpperCamelCase : Union[str, Any] = True def _lowercase ( self : List[Any] ) -> Union[str, Any]: super().setUp() # We have a SentencePiece fixture for testing _a : List[Any] = CamembertTokenizer(UpperCAmelCase__ ) tokenizer.save_pretrained(self.tmpdirname ) def _lowercase ( self : List[str] ) -> Tuple: _a : Optional[Any] = """<pad>""" _a : Tuple = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(UpperCAmelCase__ ) , UpperCAmelCase__ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(UpperCAmelCase__ ) , UpperCAmelCase__ ) def _lowercase ( self : Union[str, Any] ) -> str: _a : List[str] = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , """<s>NOTUSED""" ) self.assertEqual(vocab_keys[1] , """<pad>""" ) self.assertEqual(vocab_keys[-1] , """<mask>""" ) self.assertEqual(len(UpperCAmelCase__ ) , 1004 ) def _lowercase ( self : List[str] ) -> List[Any]: self.assertEqual(self.get_tokenizer().vocab_size , 1005 ) def _lowercase ( self : Union[str, Any] ) -> str: _a : Tuple = CamembertTokenizer(UpperCAmelCase__ ) tokenizer.save_pretrained(self.tmpdirname ) _a : List[Any] = CamembertTokenizerFast.from_pretrained(self.tmpdirname ) _a : Any = """I was born in 92000, and this is falsé.""" _a : Union[str, Any] = tokenizer.encode(UpperCAmelCase__ ) _a : Dict = rust_tokenizer.encode(UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) _a : Tuple = tokenizer.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) _a : List[Any] = rust_tokenizer.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) # <unk> tokens are not the same for `rust` than for `slow`. # Because spm gives back raw token instead of `unk` in EncodeAsPieces # tokens = tokenizer.tokenize(sequence) _a : List[str] = tokenizer.convert_ids_to_tokens(UpperCAmelCase__ ) _a : int = rust_tokenizer.tokenize(UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) def _lowercase ( self : Dict ) -> List[str]: if not self.test_rust_tokenizer: return _a : Optional[int] = self.get_tokenizer() _a : Tuple = self.get_rust_tokenizer() _a : List[Any] = """I was born in 92000, and this is falsé.""" _a : List[str] = tokenizer.tokenize(UpperCAmelCase__ ) _a : Union[str, Any] = rust_tokenizer.tokenize(UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) _a : int = tokenizer.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) _a : Optional[int] = rust_tokenizer.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) _a : int = self.get_rust_tokenizer() _a : Optional[Any] = tokenizer.encode(UpperCAmelCase__ ) _a : Dict = rust_tokenizer.encode(UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) @slow def _lowercase ( self : Tuple ) -> List[Any]: # fmt: off _a : Dict = {"""input_ids""": [[5, 54, 7196, 297, 30, 23, 776, 18, 11, 3215, 3705, 8252, 22, 3164, 1181, 2116, 29, 16, 813, 25, 791, 3314, 20, 3446, 38, 27575, 120, 6, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [5, 468, 17, 11, 9088, 20, 1517, 8, 22804, 18818, 10, 38, 629, 607, 607, 142, 19, 7196, 867, 56, 10326, 24, 2267, 20, 416, 5072, 15612, 233, 734, 7, 2399, 27, 16, 3015, 1649, 7, 24, 20, 4338, 2399, 27, 13, 3400, 14, 13, 6189, 8, 930, 9, 6]], """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, 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, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]} # noqa: E501 # fmt: on # camembert is a french model. So we also use french texts. _a : Union[str, Any] = [ """Le transformeur est un modèle d'apprentissage profond introduit en 2017, """ """utilisé principalement dans le domaine du traitement automatique des langues (TAL).""", """À l'instar des réseaux de neurones récurrents (RNN), les transformeurs sont conçus """ """pour gérer des données séquentielles, telles que le langage naturel, pour des tâches """ """telles que la traduction et la synthèse de texte.""", ] self.tokenizer_integration_test_util( expected_encoding=UpperCAmelCase__ , model_name="""camembert-base""" , revision="""3a0641d9a1aeb7e848a74299e7e4c4bca216b4cf""" , sequences=UpperCAmelCase__ , )
324
1
"""simple docstring""" 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 , snake_case_ ): def _lowercase ( self : int ) -> int: _a : Optional[Any] = load_tool("""text-to-speech""" ) self.tool.setup() def _lowercase ( self : List[str] ) -> Union[str, Any]: # SpeechT5 isn't deterministic torch.manual_seed(0 ) _a : str = self.tool("""hey""" ) _a : List[str] = result.to_raw() self.assertTrue( torch.allclose( resulting_tensor[:3] , torch.tensor([-0.0_0_0_5_9_6_6_6_6_8_8_3_2_1_1_5_8_2_9, -0.0_0_0_3_6_5_7_6_4_0_1_9_0_7_9_5_0_6_4, -0.0_0_0_1_3_4_3_9_5_0_2_7_9_9_8_8_3_4_8_5] ) , ) ) def _lowercase ( self : Optional[int] ) -> Optional[Any]: # SpeechT5 isn't deterministic torch.manual_seed(0 ) _a : int = self.tool("""hey""" ) _a : str = result.to_raw() self.assertTrue( torch.allclose( resulting_tensor[:3] , torch.tensor([-0.0_0_0_5_9_6_6_6_6_8_8_3_2_1_1_5_8_2_9, -0.0_0_0_3_6_5_7_6_4_0_1_9_0_7_9_5_0_6_4, -0.0_0_0_1_3_4_3_9_5_0_2_7_9_9_8_8_3_4_8_5] ) , ) )
324
"""simple docstring""" import argparse import collections import os import re import tempfile import pandas as pd from datasets import Dataset from huggingface_hub import hf_hub_download, upload_folder from transformers.utils import direct_transformers_import # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/update_metadata.py _snake_case = 'src/transformers' # This is to make sure the transformers module imported is the one in the repo. _snake_case = direct_transformers_import(TRANSFORMERS_PATH) # Regexes that match TF/Flax/PT model names. _snake_case = re.compile(r'TF(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)') _snake_case = re.compile(r'Flax(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)') # Will match any TF or Flax model too so need to be in an else branch afterthe two previous regexes. _snake_case = re.compile(r'(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)') # Fill this with tuples (pipeline_tag, model_mapping, auto_model) _snake_case = [ ('pretraining', 'MODEL_FOR_PRETRAINING_MAPPING_NAMES', 'AutoModelForPreTraining'), ('feature-extraction', 'MODEL_MAPPING_NAMES', 'AutoModel'), ('audio-classification', 'MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES', 'AutoModelForAudioClassification'), ('text-generation', 'MODEL_FOR_CAUSAL_LM_MAPPING_NAMES', 'AutoModelForCausalLM'), ('automatic-speech-recognition', 'MODEL_FOR_CTC_MAPPING_NAMES', 'AutoModelForCTC'), ('image-classification', 'MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES', 'AutoModelForImageClassification'), ('image-segmentation', 'MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES', 'AutoModelForImageSegmentation'), ('fill-mask', 'MODEL_FOR_MASKED_LM_MAPPING_NAMES', 'AutoModelForMaskedLM'), ('object-detection', 'MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES', 'AutoModelForObjectDetection'), ( 'zero-shot-object-detection', 'MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES', 'AutoModelForZeroShotObjectDetection', ), ('question-answering', 'MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES', 'AutoModelForQuestionAnswering'), ('text2text-generation', 'MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES', 'AutoModelForSeq2SeqLM'), ('text-classification', 'MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES', 'AutoModelForSequenceClassification'), ('automatic-speech-recognition', 'MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES', 'AutoModelForSpeechSeq2Seq'), ( 'table-question-answering', 'MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING_NAMES', 'AutoModelForTableQuestionAnswering', ), ('token-classification', 'MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES', 'AutoModelForTokenClassification'), ('multiple-choice', 'MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES', 'AutoModelForMultipleChoice'), ( 'next-sentence-prediction', 'MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING_NAMES', 'AutoModelForNextSentencePrediction', ), ( 'audio-frame-classification', 'MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES', 'AutoModelForAudioFrameClassification', ), ('audio-xvector', 'MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES', 'AutoModelForAudioXVector'), ( 'document-question-answering', 'MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES', 'AutoModelForDocumentQuestionAnswering', ), ( 'visual-question-answering', 'MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING_NAMES', 'AutoModelForVisualQuestionAnswering', ), ('image-to-text', 'MODEL_FOR_FOR_VISION_2_SEQ_MAPPING_NAMES', 'AutoModelForVision2Seq'), ( 'zero-shot-image-classification', 'MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING_NAMES', 'AutoModelForZeroShotImageClassification', ), ('depth-estimation', 'MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES', 'AutoModelForDepthEstimation'), ('video-classification', 'MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING_NAMES', 'AutoModelForVideoClassification'), ('mask-generation', 'MODEL_FOR_MASK_GENERATION_MAPPING_NAMES', 'AutoModelForMaskGeneration'), ] def lowerCAmelCase__ ( UpperCamelCase__ ): '''simple docstring''' _a : Dict = re.finditer(""".+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)""" , UpperCamelCase__ ) return [m.group(0 ) for m in matches] def lowerCAmelCase__ ( ): '''simple docstring''' _a : Tuple = transformers_module.models.auto.configuration_auto.CONFIG_MAPPING_NAMES _a : Optional[int] = { config.replace("""Config""" , """""" ): model_type for model_type, config in config_maping_names.items() } # Dictionaries flagging if each model prefix has a backend in PT/TF/Flax. _a : List[Any] = collections.defaultdict(UpperCamelCase__ ) _a : List[str] = collections.defaultdict(UpperCamelCase__ ) _a : Tuple = collections.defaultdict(UpperCamelCase__ ) # Let's lookup through all transformers object (once) and find if models are supported by a given backend. for attr_name in dir(UpperCamelCase__ ): _a : str = None if _re_tf_models.match(UpperCamelCase__ ) is not None: _a : List[Any] = tf_models _a : int = _re_tf_models.match(UpperCamelCase__ ).groups()[0] elif _re_flax_models.match(UpperCamelCase__ ) is not None: _a : Any = flax_models _a : Any = _re_flax_models.match(UpperCamelCase__ ).groups()[0] elif _re_pt_models.match(UpperCamelCase__ ) is not None: _a : int = pt_models _a : int = _re_pt_models.match(UpperCamelCase__ ).groups()[0] if lookup_dict is not None: while len(UpperCamelCase__ ) > 0: if attr_name in model_prefix_to_model_type: _a : Optional[int] = True break # Try again after removing the last word in the name _a : List[Any] = """""".join(camel_case_split(UpperCamelCase__ )[:-1] ) _a : Optional[int] = set(list(pt_models.keys() ) + list(tf_models.keys() ) + list(flax_models.keys() ) ) _a : Dict = list(UpperCamelCase__ ) all_models.sort() _a : str = {"""model_type""": all_models} _a : List[Any] = [pt_models[t] for t in all_models] _a : str = [tf_models[t] for t in all_models] _a : Optional[int] = [flax_models[t] for t in all_models] # Now let's use the auto-mapping names to make sure _a : str = {} for t in all_models: if t in transformers_module.models.auto.processing_auto.PROCESSOR_MAPPING_NAMES: _a : List[str] = """AutoProcessor""" elif t in transformers_module.models.auto.tokenization_auto.TOKENIZER_MAPPING_NAMES: _a : str = """AutoTokenizer""" elif t in transformers_module.models.auto.feature_extraction_auto.FEATURE_EXTRACTOR_MAPPING_NAMES: _a : int = """AutoFeatureExtractor""" else: # Default to AutoTokenizer if a model has nothing, for backward compatibility. _a : int = """AutoTokenizer""" _a : Any = [processors[t] for t in all_models] return pd.DataFrame(UpperCamelCase__ ) def lowerCAmelCase__ ( UpperCamelCase__ ): '''simple docstring''' _a : List[Any] = [ transformers_module.models.auto.modeling_auto, transformers_module.models.auto.modeling_tf_auto, transformers_module.models.auto.modeling_flax_auto, ] for pipeline_tag, model_mapping, auto_class in PIPELINE_TAGS_AND_AUTO_MODELS: _a : List[Any] = [model_mapping, F"""TF_{model_mapping}""", F"""FLAX_{model_mapping}"""] _a : Union[str, Any] = [auto_class, F"""TF_{auto_class}""", F"""Flax_{auto_class}"""] # Loop through all three frameworks for module, cls, mapping in zip(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): # The type of pipeline may not exist in this framework if not hasattr(UpperCamelCase__ , UpperCamelCase__ ): continue # First extract all model_names _a : str = [] for name in getattr(UpperCamelCase__ , UpperCamelCase__ ).values(): if isinstance(UpperCamelCase__ , UpperCamelCase__ ): model_names.append(UpperCamelCase__ ) else: model_names.extend(list(UpperCamelCase__ ) ) # Add pipeline tag and auto model class for those models table.update({model_name: (pipeline_tag, cls) for model_name in model_names} ) return table def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' _a : Dict = get_frameworks_table() _a : Optional[Any] = Dataset.from_pandas(UpperCamelCase__ ) _a : Any = hf_hub_download( """huggingface/transformers-metadata""" , """pipeline_tags.json""" , repo_type="""dataset""" , token=UpperCamelCase__ ) _a : List[Any] = Dataset.from_json(UpperCamelCase__ ) _a : List[str] = { tags_dataset[i]["""model_class"""]: (tags_dataset[i]["""pipeline_tag"""], tags_dataset[i]["""auto_class"""]) for i in range(len(UpperCamelCase__ ) ) } _a : str = update_pipeline_and_auto_class_table(UpperCamelCase__ ) # Sort the model classes to avoid some nondeterministic updates to create false update commits. _a : int = sorted(table.keys() ) _a : Union[str, Any] = pd.DataFrame( { """model_class""": model_classes, """pipeline_tag""": [table[m][0] for m in model_classes], """auto_class""": [table[m][1] for m in model_classes], } ) _a : Dict = Dataset.from_pandas(UpperCamelCase__ ) with tempfile.TemporaryDirectory() as tmp_dir: frameworks_dataset.to_json(os.path.join(UpperCamelCase__ , """frameworks.json""" ) ) tags_dataset.to_json(os.path.join(UpperCamelCase__ , """pipeline_tags.json""" ) ) if commit_sha is not None: _a : List[str] = ( F"""Update with commit {commit_sha}\n\nSee: """ F"""https://github.com/huggingface/transformers/commit/{commit_sha}""" ) else: _a : Optional[Any] = """Update""" upload_folder( repo_id="""huggingface/transformers-metadata""" , folder_path=UpperCamelCase__ , repo_type="""dataset""" , token=UpperCamelCase__ , commit_message=UpperCamelCase__ , ) def lowerCAmelCase__ ( ): '''simple docstring''' _a : List[str] = {tag: cls for tag, _, cls in PIPELINE_TAGS_AND_AUTO_MODELS} _a : Any = transformers_module.pipelines.SUPPORTED_TASKS _a : List[str] = [] for key in pipeline_tasks: if key not in in_table: _a : Tuple = pipeline_tasks[key]["""pt"""] if isinstance(UpperCamelCase__ , (list, tuple) ): _a : Dict = model[0] _a : List[str] = model.__name__ if model not in in_table.values(): missing.append(UpperCamelCase__ ) if len(UpperCamelCase__ ) > 0: _a : Union[str, Any] = """, """.join(UpperCamelCase__ ) raise ValueError( """The following pipeline tags are not present in the `PIPELINE_TAGS_AND_AUTO_MODELS` constant inside """ F"""`utils/update_metadata.py`: {msg}. Please add them!""" ) if __name__ == "__main__": _snake_case = argparse.ArgumentParser() parser.add_argument('--token', type=str, help='The token to use to push to the transformers-metadata dataset.') parser.add_argument('--commit_sha', type=str, help='The sha of the commit going with this update.') parser.add_argument('--check-only', action='store_true', help='Activate to just check all pipelines are present.') _snake_case = parser.parse_args() if args.check_only: check_pipeline_tags() else: update_metadata(args.token, args.commit_sha)
324
1
"""simple docstring""" _snake_case = '\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' _snake_case = [{'type': 'code', 'content': INSTALL_CONTENT}] _snake_case = { '{processor_class}': 'FakeProcessorClass', '{model_class}': 'FakeModelClass', '{object_class}': 'FakeObjectClass', }
324
"""simple docstring""" import os import pytest import yaml from datasets.features.features import Features, Value from datasets.info import DatasetInfo, DatasetInfosDict @pytest.mark.parametrize( """files""" , [ ["""full:README.md""", """dataset_infos.json"""], ["""empty:README.md""", """dataset_infos.json"""], ["""dataset_infos.json"""], ["""full:README.md"""], ] , ) def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' _a : Dict = tmp_path_factory.mktemp("""dset_infos_dir""" ) if "full:README.md" in files: with open(dataset_infos_dir / """README.md""" , """w""" ) as f: f.write("""---\ndataset_info:\n dataset_size: 42\n---""" ) if "empty:README.md" in files: with open(dataset_infos_dir / """README.md""" , """w""" ) as f: f.write("""""" ) # we want to support dataset_infos.json for backward compatibility if "dataset_infos.json" in files: with open(dataset_infos_dir / """dataset_infos.json""" , """w""" ) as f: f.write("""{\"default\": {\"dataset_size\": 42}}""" ) _a : Dict = DatasetInfosDict.from_directory(UpperCamelCase__ ) assert dataset_infos assert dataset_infos["default"].dataset_size == 4_2 @pytest.mark.parametrize( """dataset_info""" , [ DatasetInfo(), DatasetInfo( description="""foo""" , features=Features({"""a""": Value("""int32""" )} ) , builder_name="""builder""" , config_name="""config""" , version="""1.0.0""" , splits=[{"""name""": """train"""}] , download_size=4_2 , ), ] , ) def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' _a : Optional[int] = str(UpperCamelCase__ ) dataset_info.write_to_directory(UpperCamelCase__ ) _a : Any = DatasetInfo.from_directory(UpperCamelCase__ ) assert dataset_info == reloaded assert os.path.exists(os.path.join(UpperCamelCase__ , """dataset_info.json""" ) ) def lowerCAmelCase__ ( ): '''simple docstring''' _a : Dict = DatasetInfo( description="""foo""" , citation="""bar""" , homepage="""https://foo.bar""" , license="""CC0""" , features=Features({"""a""": Value("""int32""" )} ) , post_processed={} , supervised_keys=() , task_templates=[] , builder_name="""builder""" , config_name="""config""" , version="""1.0.0""" , splits=[{"""name""": """train""", """num_examples""": 4_2}] , download_checksums={} , download_size=1_3_3_7 , post_processing_size=4_4_2 , dataset_size=1_2_3_4 , size_in_bytes=1_3_3_7 + 4_4_2 + 1_2_3_4 , ) _a : int = dataset_info._to_yaml_dict() assert sorted(UpperCamelCase__ ) == sorted(DatasetInfo._INCLUDED_INFO_IN_YAML ) for key in DatasetInfo._INCLUDED_INFO_IN_YAML: assert key in dataset_info_yaml_dict assert isinstance(dataset_info_yaml_dict[key] , (list, dict, int, str) ) _a : List[str] = yaml.safe_dump(UpperCamelCase__ ) _a : Optional[int] = yaml.safe_load(UpperCamelCase__ ) assert dataset_info_yaml_dict == reloaded def lowerCAmelCase__ ( ): '''simple docstring''' _a : List[Any] = DatasetInfo() _a : Any = dataset_info._to_yaml_dict() assert dataset_info_yaml_dict == {} @pytest.mark.parametrize( """dataset_infos_dict""" , [ DatasetInfosDict(), DatasetInfosDict({"""default""": DatasetInfo()} ), DatasetInfosDict({"""my_config_name""": DatasetInfo()} ), DatasetInfosDict( { """default""": DatasetInfo( description="""foo""" , features=Features({"""a""": Value("""int32""" )} ) , builder_name="""builder""" , config_name="""config""" , version="""1.0.0""" , splits=[{"""name""": """train"""}] , download_size=4_2 , ) } ), DatasetInfosDict( { """v1""": DatasetInfo(dataset_size=4_2 ), """v2""": DatasetInfo(dataset_size=1_3_3_7 ), } ), ] , ) def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' _a : List[Any] = str(UpperCamelCase__ ) dataset_infos_dict.write_to_directory(UpperCamelCase__ ) _a : List[Any] = DatasetInfosDict.from_directory(UpperCamelCase__ ) # the config_name of the dataset_infos_dict take over the attribute for config_name, dataset_info in dataset_infos_dict.items(): _a : str = config_name # the yaml representation doesn't include fields like description or citation # so we just test that we can recover what we can from the yaml _a : Dict = DatasetInfo._from_yaml_dict(dataset_info._to_yaml_dict() ) assert dataset_infos_dict == reloaded if dataset_infos_dict: assert os.path.exists(os.path.join(UpperCamelCase__ , """README.md""" ) )
324
1
"""simple docstring""" import unittest import numpy as np from transformers import MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING, TF_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING from transformers.pipelines import AudioClassificationPipeline, pipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_tf, require_torch, require_torchaudio, slow, ) from .test_pipelines_common import ANY @is_pipeline_test class UpperCamelCase ( unittest.TestCase ): UpperCamelCase : Optional[Any] = MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING UpperCamelCase : List[str] = TF_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING def _lowercase ( self : str , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : int , UpperCAmelCase__ : Any ) -> Optional[Any]: _a : Optional[Any] = AudioClassificationPipeline(model=UpperCAmelCase__ , feature_extractor=UpperCAmelCase__ ) # test with a raw waveform _a : Tuple = np.zeros((34000,) ) _a : Optional[Any] = np.zeros((14000,) ) return audio_classifier, [audioa, audio] def _lowercase ( self : Dict , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Union[str, Any] ) -> int: _a , _a : Union[str, Any] = examples _a : Optional[Any] = audio_classifier(UpperCAmelCase__ ) # by default a model is initialized with num_labels=2 self.assertEqual( UpperCAmelCase__ , [ {"""score""": ANY(UpperCAmelCase__ ), """label""": ANY(UpperCAmelCase__ )}, {"""score""": ANY(UpperCAmelCase__ ), """label""": ANY(UpperCAmelCase__ )}, ] , ) _a : List[str] = audio_classifier(UpperCAmelCase__ , top_k=1 ) self.assertEqual( UpperCAmelCase__ , [ {"""score""": ANY(UpperCAmelCase__ ), """label""": ANY(UpperCAmelCase__ )}, ] , ) self.run_torchaudio(UpperCAmelCase__ ) @require_torchaudio def _lowercase ( self : str , UpperCAmelCase__ : List[str] ) -> List[Any]: import datasets # test with a local file _a : Any = datasets.load_dataset("""hf-internal-testing/librispeech_asr_dummy""" , """clean""" , split="""validation""" ) _a : int = dataset[0]["""audio"""]["""array"""] _a : List[Any] = audio_classifier(UpperCAmelCase__ ) self.assertEqual( UpperCAmelCase__ , [ {"""score""": ANY(UpperCAmelCase__ ), """label""": ANY(UpperCAmelCase__ )}, {"""score""": ANY(UpperCAmelCase__ ), """label""": ANY(UpperCAmelCase__ )}, ] , ) @require_torch def _lowercase ( self : Tuple ) -> Any: _a : str = """anton-l/wav2vec2-random-tiny-classifier""" _a : str = pipeline("""audio-classification""" , model=UpperCAmelCase__ ) _a : Optional[int] = np.ones((8000,) ) _a : Any = audio_classifier(UpperCAmelCase__ , top_k=4 ) _a : int = [ {"""score""": 0.0_8_4_2, """label""": """no"""}, {"""score""": 0.0_8_3_8, """label""": """up"""}, {"""score""": 0.0_8_3_7, """label""": """go"""}, {"""score""": 0.0_8_3_4, """label""": """right"""}, ] _a : List[Any] = [ {"""score""": 0.0_8_4_5, """label""": """stop"""}, {"""score""": 0.0_8_4_4, """label""": """on"""}, {"""score""": 0.0_8_4_1, """label""": """right"""}, {"""score""": 0.0_8_3_4, """label""": """left"""}, ] self.assertIn(nested_simplify(UpperCAmelCase__ , decimals=4 ) , [EXPECTED_OUTPUT, EXPECTED_OUTPUT_PT_2] ) _a : Tuple = {"""array""": np.ones((8000,) ), """sampling_rate""": audio_classifier.feature_extractor.sampling_rate} _a : Tuple = audio_classifier(UpperCAmelCase__ , top_k=4 ) self.assertIn(nested_simplify(UpperCAmelCase__ , decimals=4 ) , [EXPECTED_OUTPUT, EXPECTED_OUTPUT_PT_2] ) @require_torch @slow def _lowercase ( self : str ) -> List[Any]: import datasets _a : List[Any] = """superb/wav2vec2-base-superb-ks""" _a : List[str] = pipeline("""audio-classification""" , model=UpperCAmelCase__ ) _a : Optional[Any] = datasets.load_dataset("""anton-l/superb_dummy""" , """ks""" , split="""test""" ) _a : List[Any] = np.array(dataset[3]["""speech"""] , dtype=np.floataa ) _a : List[str] = audio_classifier(UpperCAmelCase__ , top_k=4 ) self.assertEqual( nested_simplify(UpperCAmelCase__ , decimals=3 ) , [ {"""score""": 0.9_8_1, """label""": """go"""}, {"""score""": 0.0_0_7, """label""": """up"""}, {"""score""": 0.0_0_6, """label""": """_unknown_"""}, {"""score""": 0.0_0_1, """label""": """down"""}, ] , ) @require_tf @unittest.skip("""Audio classification is not implemented for TF""" ) def _lowercase ( self : Tuple ) -> Union[str, Any]: pass
324
"""simple docstring""" 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 , snake_case_ ): def _lowercase ( self : int ) -> int: _a : Optional[Any] = load_tool("""text-to-speech""" ) self.tool.setup() def _lowercase ( self : List[str] ) -> Union[str, Any]: # SpeechT5 isn't deterministic torch.manual_seed(0 ) _a : str = self.tool("""hey""" ) _a : List[str] = result.to_raw() self.assertTrue( torch.allclose( resulting_tensor[:3] , torch.tensor([-0.0_0_0_5_9_6_6_6_6_8_8_3_2_1_1_5_8_2_9, -0.0_0_0_3_6_5_7_6_4_0_1_9_0_7_9_5_0_6_4, -0.0_0_0_1_3_4_3_9_5_0_2_7_9_9_8_8_3_4_8_5] ) , ) ) def _lowercase ( self : Optional[int] ) -> Optional[Any]: # SpeechT5 isn't deterministic torch.manual_seed(0 ) _a : int = self.tool("""hey""" ) _a : str = result.to_raw() self.assertTrue( torch.allclose( resulting_tensor[:3] , torch.tensor([-0.0_0_0_5_9_6_6_6_6_8_8_3_2_1_1_5_8_2_9, -0.0_0_0_3_6_5_7_6_4_0_1_9_0_7_9_5_0_6_4, -0.0_0_0_1_3_4_3_9_5_0_2_7_9_9_8_8_3_4_8_5] ) , ) )
324
1
"""simple docstring""" import argparse import json from typing import List from ltp import LTP from transformers import BertTokenizer def lowerCAmelCase__ ( UpperCamelCase__ ): '''simple docstring''' # 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 >= 0x4_e_0_0 and cp <= 0x9_f_f_f) or (cp >= 0x3_4_0_0 and cp <= 0x4_d_b_f) # or (cp >= 0x2_0_0_0_0 and cp <= 0x2_a_6_d_f) # or (cp >= 0x2_a_7_0_0 and cp <= 0x2_b_7_3_f) # or (cp >= 0x2_b_7_4_0 and cp <= 0x2_b_8_1_f) # or (cp >= 0x2_b_8_2_0 and cp <= 0x2_c_e_a_f) # or (cp >= 0xf_9_0_0 and cp <= 0xf_a_f_f) or (cp >= 0x2_f_8_0_0 and cp <= 0x2_f_a_1_f) # ): # return True return False def lowerCAmelCase__ ( UpperCamelCase__ ): '''simple docstring''' # word like '180' or '身高' or '神' for char in word: _a : str = ord(UpperCamelCase__ ) if not _is_chinese_char(UpperCamelCase__ ): return 0 return 1 def lowerCAmelCase__ ( UpperCamelCase__ ): '''simple docstring''' _a : Any = set() for token in tokens: _a : List[str] = len(UpperCamelCase__ ) > 1 and is_chinese(UpperCamelCase__ ) if chinese_word: word_set.add(UpperCamelCase__ ) _a : Optional[int] = list(UpperCamelCase__ ) return word_list def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' if not chinese_word_set: return bert_tokens _a : Union[str, Any] = max([len(UpperCamelCase__ ) for w in chinese_word_set] ) _a : Tuple = bert_tokens _a , _a : List[str] = 0, len(UpperCamelCase__ ) while start < end: _a : Optional[Any] = True if is_chinese(bert_word[start] ): _a : List[Any] = min(end - start , UpperCamelCase__ ) for i in range(UpperCamelCase__ , 1 , -1 ): _a : Optional[Any] = """""".join(bert_word[start : start + i] ) if whole_word in chinese_word_set: for j in range(start + 1 , start + i ): _a : Tuple = """##""" + bert_word[j] _a : Any = start + i _a : Tuple = False break if single_word: start += 1 return bert_word def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' _a : Optional[Any] = [] for i in range(0 , len(UpperCamelCase__ ) , 1_0_0 ): _a : Optional[int] = ltp_tokenizer.seg(lines[i : i + 1_0_0] )[0] _a : Dict = [get_chinese_word(UpperCamelCase__ ) for r in res] ltp_res.extend(UpperCamelCase__ ) assert len(UpperCamelCase__ ) == len(UpperCamelCase__ ) _a : Optional[Any] = [] for i in range(0 , len(UpperCamelCase__ ) , 1_0_0 ): _a : Optional[Any] = bert_tokenizer(lines[i : i + 1_0_0] , add_special_tokens=UpperCamelCase__ , truncation=UpperCamelCase__ , max_length=5_1_2 ) bert_res.extend(res["""input_ids"""] ) assert len(UpperCamelCase__ ) == len(UpperCamelCase__ ) _a : int = [] for input_ids, chinese_word in zip(UpperCamelCase__ , UpperCamelCase__ ): _a : Any = [] for id in input_ids: _a : List[str] = bert_tokenizer._convert_id_to_token(UpperCamelCase__ ) input_tokens.append(UpperCamelCase__ ) _a : int = add_sub_symbol(UpperCamelCase__ , UpperCamelCase__ ) _a : Optional[Any] = [] # We only save pos of chinese subwords start with ##, which mean is part of a whole word. for i, token in enumerate(UpperCamelCase__ ): if token[:2] == "##": _a : Dict = token[2:] # save chinese tokens' pos if len(UpperCamelCase__ ) == 1 and _is_chinese_char(ord(UpperCamelCase__ ) ): ref_id.append(UpperCamelCase__ ) ref_ids.append(UpperCamelCase__ ) assert len(UpperCamelCase__ ) == len(UpperCamelCase__ ) return ref_ids def lowerCAmelCase__ ( UpperCamelCase__ ): '''simple docstring''' # 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: _a : Optional[Any] = f.readlines() _a : List[str] = [line.strip() for line in data if len(UpperCamelCase__ ) > 0 and not line.isspace()] # avoid delimiter like '\u2029' _a : int = LTP(args.ltp ) # faster in GPU device _a : Any = BertTokenizer.from_pretrained(args.bert ) _a : Union[str, Any] = prepare_ref(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) with open(args.save_path , """w""" , encoding="""utf-8""" ) as f: _a : int = [json.dumps(UpperCamelCase__ ) + """\n""" for ref in ref_ids] f.writelines(UpperCamelCase__ ) if __name__ == "__main__": _snake_case = argparse.ArgumentParser(description='prepare_chinese_ref') parser.add_argument( '--file_name', type=str, default='./resources/chinese-demo.txt', help='file need process, same as training data in lm', ) parser.add_argument( '--ltp', type=str, default='./resources/ltp', help='resources for LTP tokenizer, usually a path' ) parser.add_argument('--bert', type=str, default='./resources/robert', help='resources for Bert tokenizer') parser.add_argument('--save_path', type=str, default='./resources/ref.txt', help='path to save res') _snake_case = parser.parse_args() main(args)
324
"""simple docstring""" import copy import json import os import tempfile from transformers import is_torch_available from .test_configuration_utils import config_common_kwargs class UpperCamelCase ( snake_case_ ): def __init__( self : Union[str, Any] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : int=None , UpperCAmelCase__ : Optional[Any]=True , UpperCAmelCase__ : List[str]=None , **UpperCAmelCase__ : str ) -> int: _a : str = parent _a : Union[str, Any] = config_class _a : List[Any] = has_text_modality _a : List[Any] = kwargs _a : List[Any] = common_properties def _lowercase ( self : int ) -> Tuple: _a : List[str] = self.config_class(**self.inputs_dict ) _a : Dict = ( ["""hidden_size""", """num_attention_heads""", """num_hidden_layers"""] if self.common_properties is None else self.common_properties ) # Add common fields for text models if self.has_text_modality: common_properties.extend(["""vocab_size"""] ) # Test that config has the common properties as getters for prop in common_properties: self.parent.assertTrue(hasattr(UpperCAmelCase__ , UpperCAmelCase__ ) , msg=f"""`{prop}` does not exist""" ) # Test that config has the common properties as setter for idx, name in enumerate(UpperCAmelCase__ ): try: setattr(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) self.parent.assertEqual( getattr(UpperCAmelCase__ , UpperCAmelCase__ ) , UpperCAmelCase__ , msg=f"""`{name} value {idx} expected, but was {getattr(UpperCAmelCase__ , UpperCAmelCase__ )}""" ) except NotImplementedError: # Some models might not be able to implement setters for common_properties # In that case, a NotImplementedError is raised pass # Test if config class can be called with Config(prop_name=..) for idx, name in enumerate(UpperCAmelCase__ ): try: _a : Optional[int] = self.config_class(**{name: idx} ) self.parent.assertEqual( getattr(UpperCAmelCase__ , UpperCAmelCase__ ) , UpperCAmelCase__ , msg=f"""`{name} value {idx} expected, but was {getattr(UpperCAmelCase__ , UpperCAmelCase__ )}""" ) except NotImplementedError: # Some models might not be able to implement setters for common_properties # In that case, a NotImplementedError is raised pass def _lowercase ( self : Optional[int] ) -> Optional[Any]: _a : Optional[Any] = self.config_class(**self.inputs_dict ) _a : List[str] = json.loads(config.to_json_string() ) for key, value in self.inputs_dict.items(): self.parent.assertEqual(obj[key] , UpperCAmelCase__ ) def _lowercase ( self : int ) -> List[str]: _a : Optional[Any] = self.config_class(**self.inputs_dict ) with tempfile.TemporaryDirectory() as tmpdirname: _a : Tuple = os.path.join(UpperCAmelCase__ , """config.json""" ) config_first.to_json_file(UpperCAmelCase__ ) _a : List[str] = self.config_class.from_json_file(UpperCAmelCase__ ) self.parent.assertEqual(config_second.to_dict() , config_first.to_dict() ) def _lowercase ( self : Union[str, Any] ) -> Dict: _a : Dict = self.config_class(**self.inputs_dict ) with tempfile.TemporaryDirectory() as tmpdirname: config_first.save_pretrained(UpperCAmelCase__ ) _a : Dict = self.config_class.from_pretrained(UpperCAmelCase__ ) self.parent.assertEqual(config_second.to_dict() , config_first.to_dict() ) def _lowercase ( self : Dict ) -> Tuple: _a : List[Any] = self.config_class(**self.inputs_dict ) _a : Any = """test""" with tempfile.TemporaryDirectory() as tmpdirname: _a : List[Any] = os.path.join(UpperCAmelCase__ , UpperCAmelCase__ ) config_first.save_pretrained(UpperCAmelCase__ ) _a : List[Any] = self.config_class.from_pretrained(UpperCAmelCase__ , subfolder=UpperCAmelCase__ ) self.parent.assertEqual(config_second.to_dict() , config_first.to_dict() ) def _lowercase ( self : List[str] ) -> Union[str, Any]: _a : Tuple = self.config_class(**self.inputs_dict , num_labels=5 ) self.parent.assertEqual(len(config.idalabel ) , 5 ) self.parent.assertEqual(len(config.labelaid ) , 5 ) _a : Union[str, Any] = 3 self.parent.assertEqual(len(config.idalabel ) , 3 ) self.parent.assertEqual(len(config.labelaid ) , 3 ) def _lowercase ( self : Tuple ) -> List[str]: if self.config_class.is_composition: return _a : str = self.config_class() self.parent.assertIsNotNone(UpperCAmelCase__ ) def _lowercase ( self : List[Any] ) -> Optional[Any]: _a : Dict = copy.deepcopy(UpperCAmelCase__ ) _a : Any = self.config_class(**UpperCAmelCase__ ) _a : str = [] for key, value in config_common_kwargs.items(): if key == "torch_dtype": if not is_torch_available(): continue else: import torch if config.torch_dtype != torch.floataa: wrong_values.append(("""torch_dtype""", config.torch_dtype, torch.floataa) ) elif getattr(UpperCAmelCase__ , UpperCAmelCase__ ) != value: wrong_values.append((key, getattr(UpperCAmelCase__ , UpperCAmelCase__ ), value) ) if len(UpperCAmelCase__ ) > 0: _a : List[Any] = """\n""".join([f"""- {v[0]}: got {v[1]} instead of {v[2]}""" for v in wrong_values] ) raise ValueError(f"""The following keys were not properly set in the config:\n{errors}""" ) def _lowercase ( self : int ) -> Union[str, Any]: self.create_and_test_config_common_properties() self.create_and_test_config_to_json_string() self.create_and_test_config_to_json_file() self.create_and_test_config_from_and_save_pretrained() self.create_and_test_config_from_and_save_pretrained_subfolder() self.create_and_test_config_with_num_labels() self.check_config_can_be_init_without_params() self.check_config_arguments_init()
324
1
"""simple docstring""" from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import KandinskyPipeline, KandinskyPriorPipeline else: from .pipeline_kandinsky import KandinskyPipeline from .pipeline_kandinsky_imgaimg import KandinskyImgaImgPipeline from .pipeline_kandinsky_inpaint import KandinskyInpaintPipeline from .pipeline_kandinsky_prior import KandinskyPriorPipeline, KandinskyPriorPipelineOutput from .text_encoder import MultilingualCLIP
324
"""simple docstring""" import os from huggingface_hub.constants import HUGGINGFACE_HUB_CACHE, hf_cache_home _snake_case = HUGGINGFACE_HUB_CACHE _snake_case = 'config.json' _snake_case = 'diffusion_pytorch_model.bin' _snake_case = 'diffusion_flax_model.msgpack' _snake_case = 'model.onnx' _snake_case = 'diffusion_pytorch_model.safetensors' _snake_case = 'weights.pb' _snake_case = 'https://huggingface.co' _snake_case = default_cache_path _snake_case = 'diffusers_modules' _snake_case = os.getenv('HF_MODULES_CACHE', os.path.join(hf_cache_home, 'modules')) _snake_case = ['fp16', 'non-ema'] _snake_case = '.self_attn'
324
1
"""simple docstring""" import argparse import torch from transformers import BertConfig, BertForPreTraining, load_tf_weights_in_bert from transformers.utils import logging logging.set_verbosity_info() def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' # Initialise PyTorch model _a : Any = BertConfig.from_json_file(UpperCamelCase__ ) print(F"""Building PyTorch model from configuration: {config}""" ) _a : str = BertForPreTraining(UpperCamelCase__ ) # Load weights from tf checkpoint load_tf_weights_in_bert(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) # Save pytorch-model print(F"""Save PyTorch model to {pytorch_dump_path}""" ) torch.save(model.state_dict() , UpperCamelCase__ ) if __name__ == "__main__": _snake_case = argparse.ArgumentParser() # Required parameters parser.add_argument( '--tf_checkpoint_path', default=None, type=str, required=True, help='Path to the TensorFlow checkpoint path.' ) parser.add_argument( '--bert_config_file', default=None, type=str, required=True, help=( 'The config json file corresponding to the pre-trained BERT model. \n' 'This specifies the model architecture.' ), ) parser.add_argument( '--pytorch_dump_path', default=None, type=str, required=True, help='Path to the output PyTorch model.' ) _snake_case = parser.parse_args() convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.bert_config_file, args.pytorch_dump_path)
324
"""simple docstring""" from math import factorial def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' if successes > trials: raise ValueError("""successes must be lower or equal to trials""" ) if trials < 0 or successes < 0: raise ValueError("""the function is defined for non-negative integers""" ) if not isinstance(UpperCamelCase__ , UpperCamelCase__ ) or not isinstance(UpperCamelCase__ , UpperCamelCase__ ): raise ValueError("""the function is defined for non-negative integers""" ) if not 0 < prob < 1: raise ValueError("""prob has to be in range of 1 - 0""" ) _a : Optional[int] = (prob**successes) * ((1 - prob) ** (trials - successes)) # Calculate the binomial coefficient: n! / k!(n-k)! _a : Optional[int] = float(factorial(UpperCamelCase__ ) ) coefficient /= factorial(UpperCamelCase__ ) * factorial(trials - successes ) return probability * coefficient if __name__ == "__main__": from doctest import testmod testmod() print('Probability of 2 successes out of 4 trails') print('with probability of 0.75 is:', end=' ') print(binomial_distribution(2, 4, 0.75))
324
1
"""simple docstring""" from __future__ import annotations def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' if (direction == 1 and array[indexa] > array[indexa]) or ( direction == 0 and array[indexa] < array[indexa] ): _a , _a : str = array[indexa], array[indexa] def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' if length > 1: _a : Optional[Any] = int(length / 2 ) for i in range(UpperCamelCase__ , low + middle ): comp_and_swap(UpperCamelCase__ , UpperCamelCase__ , i + middle , UpperCamelCase__ ) bitonic_merge(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) bitonic_merge(UpperCamelCase__ , low + middle , UpperCamelCase__ , UpperCamelCase__ ) def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' if length > 1: _a : List[str] = int(length / 2 ) bitonic_sort(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , 1 ) bitonic_sort(UpperCamelCase__ , low + middle , UpperCamelCase__ , 0 ) bitonic_merge(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) if __name__ == "__main__": _snake_case = input('Enter numbers separated by a comma:\n').strip() _snake_case = [int(item.strip()) for item in user_input.split(',')] bitonic_sort(unsorted, 0, len(unsorted), 1) print('\nSorted array in ascending order is: ', end='') print(*unsorted, sep=', ') bitonic_merge(unsorted, 0, len(unsorted), 0) print('Sorted array in descending order is: ', end='') print(*unsorted, sep=', ')
324
"""simple docstring""" def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' _a , _a : Dict = len(UpperCamelCase__ ), len(grid[0] ) if ( min(UpperCamelCase__ , UpperCamelCase__ ) < 0 or row == row_length or col == col_length or (row, col) in visit or grid[row][col] == 1 ): return 0 if row == row_length - 1 and col == col_length - 1: return 1 visit.add((row, col) ) _a : Any = 0 count += depth_first_search(UpperCamelCase__ , row + 1 , UpperCamelCase__ , UpperCamelCase__ ) count += depth_first_search(UpperCamelCase__ , row - 1 , UpperCamelCase__ , UpperCamelCase__ ) count += depth_first_search(UpperCamelCase__ , UpperCamelCase__ , col + 1 , UpperCamelCase__ ) count += depth_first_search(UpperCamelCase__ , UpperCamelCase__ , col - 1 , UpperCamelCase__ ) visit.remove((row, col) ) return count if __name__ == "__main__": import doctest doctest.testmod()
324
1
"""simple docstring""" import copy import json import os import tempfile from transformers import is_torch_available from .test_configuration_utils import config_common_kwargs class UpperCamelCase ( snake_case_ ): def __init__( self : Union[str, Any] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : int=None , UpperCAmelCase__ : Optional[Any]=True , UpperCAmelCase__ : List[str]=None , **UpperCAmelCase__ : str ) -> int: _a : str = parent _a : Union[str, Any] = config_class _a : List[Any] = has_text_modality _a : List[Any] = kwargs _a : List[Any] = common_properties def _lowercase ( self : int ) -> Tuple: _a : List[str] = self.config_class(**self.inputs_dict ) _a : Dict = ( ["""hidden_size""", """num_attention_heads""", """num_hidden_layers"""] if self.common_properties is None else self.common_properties ) # Add common fields for text models if self.has_text_modality: common_properties.extend(["""vocab_size"""] ) # Test that config has the common properties as getters for prop in common_properties: self.parent.assertTrue(hasattr(UpperCAmelCase__ , UpperCAmelCase__ ) , msg=f"""`{prop}` does not exist""" ) # Test that config has the common properties as setter for idx, name in enumerate(UpperCAmelCase__ ): try: setattr(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) self.parent.assertEqual( getattr(UpperCAmelCase__ , UpperCAmelCase__ ) , UpperCAmelCase__ , msg=f"""`{name} value {idx} expected, but was {getattr(UpperCAmelCase__ , UpperCAmelCase__ )}""" ) except NotImplementedError: # Some models might not be able to implement setters for common_properties # In that case, a NotImplementedError is raised pass # Test if config class can be called with Config(prop_name=..) for idx, name in enumerate(UpperCAmelCase__ ): try: _a : Optional[int] = self.config_class(**{name: idx} ) self.parent.assertEqual( getattr(UpperCAmelCase__ , UpperCAmelCase__ ) , UpperCAmelCase__ , msg=f"""`{name} value {idx} expected, but was {getattr(UpperCAmelCase__ , UpperCAmelCase__ )}""" ) except NotImplementedError: # Some models might not be able to implement setters for common_properties # In that case, a NotImplementedError is raised pass def _lowercase ( self : Optional[int] ) -> Optional[Any]: _a : Optional[Any] = self.config_class(**self.inputs_dict ) _a : List[str] = json.loads(config.to_json_string() ) for key, value in self.inputs_dict.items(): self.parent.assertEqual(obj[key] , UpperCAmelCase__ ) def _lowercase ( self : int ) -> List[str]: _a : Optional[Any] = self.config_class(**self.inputs_dict ) with tempfile.TemporaryDirectory() as tmpdirname: _a : Tuple = os.path.join(UpperCAmelCase__ , """config.json""" ) config_first.to_json_file(UpperCAmelCase__ ) _a : List[str] = self.config_class.from_json_file(UpperCAmelCase__ ) self.parent.assertEqual(config_second.to_dict() , config_first.to_dict() ) def _lowercase ( self : Union[str, Any] ) -> Dict: _a : Dict = self.config_class(**self.inputs_dict ) with tempfile.TemporaryDirectory() as tmpdirname: config_first.save_pretrained(UpperCAmelCase__ ) _a : Dict = self.config_class.from_pretrained(UpperCAmelCase__ ) self.parent.assertEqual(config_second.to_dict() , config_first.to_dict() ) def _lowercase ( self : Dict ) -> Tuple: _a : List[Any] = self.config_class(**self.inputs_dict ) _a : Any = """test""" with tempfile.TemporaryDirectory() as tmpdirname: _a : List[Any] = os.path.join(UpperCAmelCase__ , UpperCAmelCase__ ) config_first.save_pretrained(UpperCAmelCase__ ) _a : List[Any] = self.config_class.from_pretrained(UpperCAmelCase__ , subfolder=UpperCAmelCase__ ) self.parent.assertEqual(config_second.to_dict() , config_first.to_dict() ) def _lowercase ( self : List[str] ) -> Union[str, Any]: _a : Tuple = self.config_class(**self.inputs_dict , num_labels=5 ) self.parent.assertEqual(len(config.idalabel ) , 5 ) self.parent.assertEqual(len(config.labelaid ) , 5 ) _a : Union[str, Any] = 3 self.parent.assertEqual(len(config.idalabel ) , 3 ) self.parent.assertEqual(len(config.labelaid ) , 3 ) def _lowercase ( self : Tuple ) -> List[str]: if self.config_class.is_composition: return _a : str = self.config_class() self.parent.assertIsNotNone(UpperCAmelCase__ ) def _lowercase ( self : List[Any] ) -> Optional[Any]: _a : Dict = copy.deepcopy(UpperCAmelCase__ ) _a : Any = self.config_class(**UpperCAmelCase__ ) _a : str = [] for key, value in config_common_kwargs.items(): if key == "torch_dtype": if not is_torch_available(): continue else: import torch if config.torch_dtype != torch.floataa: wrong_values.append(("""torch_dtype""", config.torch_dtype, torch.floataa) ) elif getattr(UpperCAmelCase__ , UpperCAmelCase__ ) != value: wrong_values.append((key, getattr(UpperCAmelCase__ , UpperCAmelCase__ ), value) ) if len(UpperCAmelCase__ ) > 0: _a : List[Any] = """\n""".join([f"""- {v[0]}: got {v[1]} instead of {v[2]}""" for v in wrong_values] ) raise ValueError(f"""The following keys were not properly set in the config:\n{errors}""" ) def _lowercase ( self : int ) -> Union[str, Any]: self.create_and_test_config_common_properties() self.create_and_test_config_to_json_string() self.create_and_test_config_to_json_file() self.create_and_test_config_from_and_save_pretrained() self.create_and_test_config_from_and_save_pretrained_subfolder() self.create_and_test_config_with_num_labels() self.check_config_can_be_init_without_params() self.check_config_arguments_init()
324
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) _snake_case = { 'configuration_vision_encoder_decoder': ['VisionEncoderDecoderConfig', 'VisionEncoderDecoderOnnxConfig'] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _snake_case = ['VisionEncoderDecoderModel'] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _snake_case = ['TFVisionEncoderDecoderModel'] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _snake_case = ['FlaxVisionEncoderDecoderModel'] if TYPE_CHECKING: from .configuration_vision_encoder_decoder import VisionEncoderDecoderConfig, VisionEncoderDecoderOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_vision_encoder_decoder import VisionEncoderDecoderModel try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_vision_encoder_decoder import TFVisionEncoderDecoderModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_vision_encoder_decoder import FlaxVisionEncoderDecoderModel else: import sys _snake_case = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
324
1
"""simple docstring""" # 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. import torch from ..models.auto import AutoModelForSequenceClassification, AutoTokenizer from .base import PipelineTool class UpperCamelCase ( snake_case_ ): UpperCamelCase : int = '''facebook/bart-large-mnli''' UpperCamelCase : List[Any] = ( '''This is a tool that classifies an English text using provided labels. It takes two inputs: `text`, which ''' '''should be the text to classify, and `labels`, which should be the list of labels to use for classification. ''' '''It returns the most likely label in the list of provided `labels` for the input text.''' ) UpperCamelCase : Any = '''text_classifier''' UpperCamelCase : List[str] = AutoTokenizer UpperCamelCase : Dict = AutoModelForSequenceClassification UpperCamelCase : List[Any] = ['''text''', ['''text''']] UpperCamelCase : Dict = ['''text'''] def _lowercase ( self : Optional[int] ) -> Dict: super().setup() _a : Tuple = self.model.config _a : int = -1 for idx, label in config.idalabel.items(): if label.lower().startswith("""entail""" ): _a : List[Any] = int(UpperCAmelCase__ ) if self.entailment_id == -1: raise ValueError("""Could not determine the entailment ID from the model config, please pass it at init.""" ) def _lowercase ( self : Optional[Any] , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : List[Any] ) -> int: _a : Optional[int] = labels return self.pre_processor( [text] * len(UpperCAmelCase__ ) , [f"""This example is {label}""" for label in labels] , return_tensors="""pt""" , padding="""max_length""" , ) def _lowercase ( self : List[Any] , UpperCAmelCase__ : Any ) -> str: _a : str = outputs.logits _a : Optional[int] = torch.argmax(logits[:, 2] ).item() return self._labels[label_id]
324
"""simple docstring""" from __future__ import annotations import time _snake_case = list[tuple[int, int]] _snake_case = [ [0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles [0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0], [1, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0], ] _snake_case = [[-1, 0], [0, -1], [1, 0], [0, 1]] # up, left, down, right class UpperCamelCase : def __init__( self : Optional[int] , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : Node | None ) -> List[str]: _a : int = pos_x _a : Union[str, Any] = pos_y _a : Tuple = (pos_y, pos_x) _a : Tuple = goal_x _a : int = goal_y _a : str = parent class UpperCamelCase : def __init__( self : List[Any] , UpperCAmelCase__ : tuple[int, int] , UpperCAmelCase__ : tuple[int, int] ) -> List[str]: _a : List[Any] = Node(start[1] , start[0] , goal[1] , goal[0] , UpperCAmelCase__ ) _a : List[str] = Node(goal[1] , goal[0] , goal[1] , goal[0] , UpperCAmelCase__ ) _a : Optional[int] = [self.start] _a : Tuple = False def _lowercase ( self : str ) -> Path | None: while self.node_queue: _a : Tuple = self.node_queue.pop(0 ) if current_node.pos == self.target.pos: _a : Dict = True return self.retrace_path(UpperCAmelCase__ ) _a : Tuple = self.get_successors(UpperCAmelCase__ ) for node in successors: self.node_queue.append(UpperCAmelCase__ ) if not self.reached: return [self.start.pos] return None def _lowercase ( self : Optional[int] , UpperCAmelCase__ : Node ) -> list[Node]: _a : Optional[Any] = [] for action in delta: _a : str = parent.pos_x + action[1] _a : List[Any] = parent.pos_y + action[0] if not (0 <= pos_x <= len(grid[0] ) - 1 and 0 <= pos_y <= len(UpperCAmelCase__ ) - 1): continue if grid[pos_y][pos_x] != 0: continue successors.append( Node(UpperCAmelCase__ , UpperCAmelCase__ , self.target.pos_y , self.target.pos_x , UpperCAmelCase__ ) ) return successors def _lowercase ( self : List[Any] , UpperCAmelCase__ : Node | None ) -> Path: _a : Dict = node _a : List[str] = [] while current_node is not None: path.append((current_node.pos_y, current_node.pos_x) ) _a : Any = current_node.parent path.reverse() return path class UpperCamelCase : def __init__( self : List[str] , UpperCAmelCase__ : int , UpperCAmelCase__ : List[Any] ) -> Any: _a : Dict = BreadthFirstSearch(UpperCAmelCase__ , UpperCAmelCase__ ) _a : Optional[int] = BreadthFirstSearch(UpperCAmelCase__ , UpperCAmelCase__ ) _a : Dict = False def _lowercase ( self : Any ) -> Path | None: while self.fwd_bfs.node_queue or self.bwd_bfs.node_queue: _a : List[Any] = self.fwd_bfs.node_queue.pop(0 ) _a : Union[str, Any] = self.bwd_bfs.node_queue.pop(0 ) if current_bwd_node.pos == current_fwd_node.pos: _a : Optional[int] = True return self.retrace_bidirectional_path( UpperCAmelCase__ , UpperCAmelCase__ ) _a : List[str] = current_bwd_node _a : int = current_fwd_node _a : Optional[Any] = { self.fwd_bfs: self.fwd_bfs.get_successors(UpperCAmelCase__ ), self.bwd_bfs: self.bwd_bfs.get_successors(UpperCAmelCase__ ), } for bfs in [self.fwd_bfs, self.bwd_bfs]: for node in successors[bfs]: bfs.node_queue.append(UpperCAmelCase__ ) if not self.reached: return [self.fwd_bfs.start.pos] return None def _lowercase ( self : Optional[int] , UpperCAmelCase__ : Node , UpperCAmelCase__ : Node ) -> Path: _a : str = self.fwd_bfs.retrace_path(UpperCAmelCase__ ) _a : List[Any] = self.bwd_bfs.retrace_path(UpperCAmelCase__ ) bwd_path.pop() bwd_path.reverse() _a : Tuple = fwd_path + bwd_path return path if __name__ == "__main__": # all coordinates are given in format [y,x] import doctest doctest.testmod() _snake_case = (0, 0) _snake_case = (len(grid) - 1, len(grid[0]) - 1) for elem in grid: print(elem) _snake_case = time.time() _snake_case = BreadthFirstSearch(init, goal) _snake_case = bfs.search() _snake_case = time.time() - start_bfs_time print('Unidirectional BFS computation time : ', bfs_time) _snake_case = time.time() _snake_case = BidirectionalBreadthFirstSearch(init, goal) _snake_case = bd_bfs.search() _snake_case = time.time() - start_bd_bfs_time print('Bidirectional BFS computation time : ', bd_bfs_time)
324
1
"""simple docstring""" from scipy.stats import spearmanr import datasets _snake_case = '\nThe Spearman rank-order correlation coefficient is a measure of the\nrelationship between two datasets. Like other correlation coefficients,\nthis one varies between -1 and +1 with 0 implying no correlation.\nPositive correlations imply that as data in dataset x increases, so\ndoes data in dataset y. Negative correlations imply that as x increases,\ny decreases. Correlations of -1 or +1 imply an exact monotonic relationship.\n\nUnlike the Pearson correlation, the Spearman correlation does not\nassume that both datasets are normally distributed.\n\nThe p-value roughly indicates the probability of an uncorrelated system\nproducing datasets that have a Spearman correlation at least as extreme\nas the one computed from these datasets. The p-values are not entirely\nreliable but are probably reasonable for datasets larger than 500 or so.\n' _snake_case = '\nArgs:\n predictions (`List[float]`): Predicted labels, as returned by a model.\n references (`List[float]`): Ground truth labels.\n return_pvalue (`bool`): If `True`, returns the p-value. If `False`, returns\n only the spearmanr score. Defaults to `False`.\nReturns:\n spearmanr (`float`): Spearman correlation coefficient.\n p-value (`float`): p-value. **Note**: is only returned if `return_pvalue=True` is input.\nExamples:\n Example 1:\n >>> spearmanr_metric = datasets.load_metric("spearmanr")\n >>> results = spearmanr_metric.compute(references=[1, 2, 3, 4, 5], predictions=[10, 9, 2.5, 6, 4])\n >>> print(results)\n {\'spearmanr\': -0.7}\n\n Example 2:\n >>> spearmanr_metric = datasets.load_metric("spearmanr")\n >>> results = spearmanr_metric.compute(references=[1, 2, 3, 4, 5],\n ... predictions=[10, 9, 2.5, 6, 4],\n ... return_pvalue=True)\n >>> print(results[\'spearmanr\'])\n -0.7\n >>> print(round(results[\'spearmanr_pvalue\'], 2))\n 0.19\n' _snake_case = r'\\n@book{kokoska2000crc,\n title={CRC standard probability and statistics tables and formulae},\n author={Kokoska, Stephen and Zwillinger, Daniel},\n year={2000},\n publisher={Crc Press}\n}\n@article{2020SciPy-NMeth,\n author = {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, {\.I}lhan 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, Ant{\^o}nio H. and Pedregosa, Fabian and\n {van Mulbregt}, Paul and {SciPy 1.0 Contributors}},\n title = {{{SciPy} 1.0: Fundamental Algorithms for Scientific\n Computing in Python}},\n journal = {Nature Methods},\n year = {2020},\n volume = {17},\n pages = {261--272},\n adsurl = {https://rdcu.be/b08Wh},\n doi = {10.1038/s41592-019-0686-2},\n}\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class UpperCamelCase ( datasets.Metric ): def _lowercase ( self : List[Any] ) -> Any: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": datasets.Value("""float""" ), """references""": datasets.Value("""float""" ), } ) , reference_urls=["""https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.spearmanr.html"""] , ) def _lowercase ( self : Tuple , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Tuple=False ) -> int: _a : Tuple = spearmanr(UpperCAmelCase__ , UpperCAmelCase__ ) if return_pvalue: return {"spearmanr": results[0], "spearmanr_pvalue": results[1]} else: return {"spearmanr": results[0]}
324
"""simple docstring""" import logging import math import os from dataclasses import dataclass, field from glob import glob from typing import Optional from torch.utils.data import ConcatDataset import transformers from transformers import ( CONFIG_MAPPING, MODEL_WITH_LM_HEAD_MAPPING, AutoConfig, AutoModelWithLMHead, AutoTokenizer, DataCollatorForLanguageModeling, DataCollatorForPermutationLanguageModeling, DataCollatorForWholeWordMask, HfArgumentParser, LineByLineTextDataset, LineByLineWithRefDataset, PreTrainedTokenizer, TextDataset, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import is_main_process _snake_case = logging.getLogger(__name__) _snake_case = list(MODEL_WITH_LM_HEAD_MAPPING.keys()) _snake_case = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES) @dataclass class UpperCamelCase : UpperCamelCase : Optional[str] = field( default=snake_case_ , metadata={ '''help''': ( '''The model checkpoint for weights initialization. Leave None if you want to train a model from''' ''' scratch.''' ) } , ) UpperCamelCase : Optional[str] = field( default=snake_case_ , metadata={'''help''': '''If training from scratch, pass a model type from the list: ''' + ''', '''.join(snake_case_ )} , ) UpperCamelCase : Optional[str] = field( default=snake_case_ , metadata={'''help''': '''Pretrained config name or path if not the same as model_name'''} ) UpperCamelCase : Optional[str] = field( default=snake_case_ , metadata={'''help''': '''Pretrained tokenizer name or path if not the same as model_name'''} ) UpperCamelCase : Optional[str] = field( default=snake_case_ , metadata={'''help''': '''Where do you want to store the pretrained models downloaded from huggingface.co'''} , ) @dataclass class UpperCamelCase : UpperCamelCase : Optional[str] = field( default=snake_case_ , metadata={'''help''': '''The input training data file (a text file).'''} ) UpperCamelCase : Optional[str] = field( default=snake_case_ , metadata={ '''help''': ( '''The input training data files (multiple files in glob format). ''' '''Very often splitting large files to smaller files can prevent tokenizer going out of memory''' ) } , ) UpperCamelCase : Optional[str] = field( default=snake_case_ , metadata={'''help''': '''An optional input evaluation data file to evaluate the perplexity on (a text file).'''} , ) UpperCamelCase : Optional[str] = field( default=snake_case_ , metadata={'''help''': '''An optional input train ref data file for whole word mask in Chinese.'''} , ) UpperCamelCase : Optional[str] = field( default=snake_case_ , metadata={'''help''': '''An optional input eval ref data file for whole word mask in Chinese.'''} , ) UpperCamelCase : bool = field( default=snake_case_ , metadata={'''help''': '''Whether distinct lines of text in the dataset are to be handled as distinct sequences.'''} , ) UpperCamelCase : bool = field( default=snake_case_ , metadata={'''help''': '''Train with masked-language modeling loss instead of language modeling.'''} ) UpperCamelCase : bool = field(default=snake_case_ , metadata={'''help''': '''Whether ot not to use whole word mask.'''} ) UpperCamelCase : float = field( default=0.1_5 , metadata={'''help''': '''Ratio of tokens to mask for masked language modeling loss'''} ) UpperCamelCase : float = field( default=1 / 6 , metadata={ '''help''': ( '''Ratio of length of a span of masked tokens to surrounding context length for permutation language''' ''' modeling.''' ) } , ) UpperCamelCase : int = field( default=5 , metadata={'''help''': '''Maximum length of a span of masked tokens for permutation language modeling.'''} ) UpperCamelCase : int = field( default=-1 , metadata={ '''help''': ( '''Optional input sequence length after tokenization.''' '''The training dataset will be truncated in block of this size for training.''' '''Default to the model max input length for single sentence inputs (take into account special tokens).''' ) } , ) UpperCamelCase : bool = field( default=snake_case_ , metadata={'''help''': '''Overwrite the cached training and evaluation sets'''} ) def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = False , UpperCamelCase__ = None , ): '''simple docstring''' def _dataset(UpperCamelCase__ , UpperCamelCase__=None ): if args.line_by_line: if ref_path is not None: if not args.whole_word_mask or not args.mlm: raise ValueError("""You need to set world whole masking and mlm to True for Chinese Whole Word Mask""" ) return LineByLineWithRefDataset( tokenizer=UpperCamelCase__ , file_path=UpperCamelCase__ , block_size=args.block_size , ref_path=UpperCamelCase__ , ) return LineByLineTextDataset(tokenizer=UpperCamelCase__ , file_path=UpperCamelCase__ , block_size=args.block_size ) else: return TextDataset( tokenizer=UpperCamelCase__ , file_path=UpperCamelCase__ , block_size=args.block_size , overwrite_cache=args.overwrite_cache , cache_dir=UpperCamelCase__ , ) if evaluate: return _dataset(args.eval_data_file , args.eval_ref_file ) elif args.train_data_files: return ConcatDataset([_dataset(UpperCamelCase__ ) for f in glob(args.train_data_files )] ) else: return _dataset(args.train_data_file , args.train_ref_file ) def lowerCAmelCase__ ( ): '''simple docstring''' # See all possible arguments in src/transformers/training_args.py # or by passing the --help flag to this script. # We now keep distinct sets of args, for a cleaner separation of concerns. _a : Any = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) _a , _a , _a : List[str] = parser.parse_args_into_dataclasses() if data_args.eval_data_file is None and training_args.do_eval: raise ValueError( """Cannot do evaluation without an evaluation data file. Either supply a file to --eval_data_file """ """or remove the --do_eval argument.""" ) if ( os.path.exists(training_args.output_dir ) and os.listdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir ): raise ValueError( F"""Output directory ({training_args.output_dir}) already exists and is not empty. Use""" """ --overwrite_output_dir to overcome.""" ) # Setup logging logging.basicConfig( format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""" , datefmt="""%m/%d/%Y %H:%M:%S""" , level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN , ) logger.warning( """Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s""" , training_args.local_rank , training_args.device , training_args.n_gpu , bool(training_args.local_rank != -1 ) , training_args.fpaa , ) # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank ): transformers.utils.logging.set_verbosity_info() transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() logger.info("""Training/evaluation parameters %s""" , UpperCamelCase__ ) # Set seed set_seed(training_args.seed ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. if model_args.config_name: _a : str = AutoConfig.from_pretrained(model_args.config_name , cache_dir=model_args.cache_dir ) elif model_args.model_name_or_path: _a : Union[str, Any] = AutoConfig.from_pretrained(model_args.model_name_or_path , cache_dir=model_args.cache_dir ) else: _a : str = CONFIG_MAPPING[model_args.model_type]() logger.warning("""You are instantiating a new config instance from scratch.""" ) if model_args.tokenizer_name: _a : List[str] = AutoTokenizer.from_pretrained(model_args.tokenizer_name , cache_dir=model_args.cache_dir ) elif model_args.model_name_or_path: _a : Union[str, Any] = AutoTokenizer.from_pretrained(model_args.model_name_or_path , cache_dir=model_args.cache_dir ) else: raise ValueError( """You are instantiating a new tokenizer from scratch. This is not supported, but you can do it from another""" """ script, save it,and load it from here, using --tokenizer_name""" ) if model_args.model_name_or_path: _a : Optional[Any] = AutoModelWithLMHead.from_pretrained( model_args.model_name_or_path , from_tf=bool(""".ckpt""" in model_args.model_name_or_path ) , config=UpperCamelCase__ , cache_dir=model_args.cache_dir , ) else: logger.info("""Training new model from scratch""" ) _a : List[Any] = AutoModelWithLMHead.from_config(UpperCamelCase__ ) model.resize_token_embeddings(len(UpperCamelCase__ ) ) if config.model_type in ["bert", "roberta", "distilbert", "camembert"] and not data_args.mlm: raise ValueError( """BERT and RoBERTa-like models do not have LM heads but masked LM heads. They must be run using the""" """--mlm flag (masked language modeling).""" ) if data_args.block_size <= 0: _a : int = tokenizer.max_len # Our input block size will be the max possible for the model else: _a : Optional[Any] = min(data_args.block_size , tokenizer.max_len ) # Get datasets _a : Optional[Any] = ( get_dataset(UpperCamelCase__ , tokenizer=UpperCamelCase__ , cache_dir=model_args.cache_dir ) if training_args.do_train else None ) _a : Optional[int] = ( get_dataset(UpperCamelCase__ , tokenizer=UpperCamelCase__ , evaluate=UpperCamelCase__ , cache_dir=model_args.cache_dir ) if training_args.do_eval else None ) if config.model_type == "xlnet": _a : Any = DataCollatorForPermutationLanguageModeling( tokenizer=UpperCamelCase__ , plm_probability=data_args.plm_probability , max_span_length=data_args.max_span_length , ) else: if data_args.mlm and data_args.whole_word_mask: _a : Union[str, Any] = DataCollatorForWholeWordMask( tokenizer=UpperCamelCase__ , mlm_probability=data_args.mlm_probability ) else: _a : str = DataCollatorForLanguageModeling( tokenizer=UpperCamelCase__ , mlm=data_args.mlm , mlm_probability=data_args.mlm_probability ) # Initialize our Trainer _a : Union[str, Any] = Trainer( model=UpperCamelCase__ , args=UpperCamelCase__ , data_collator=UpperCamelCase__ , train_dataset=UpperCamelCase__ , eval_dataset=UpperCamelCase__ , prediction_loss_only=UpperCamelCase__ , ) # Training if training_args.do_train: _a : Optional[Any] = ( model_args.model_name_or_path if model_args.model_name_or_path is not None and os.path.isdir(model_args.model_name_or_path ) else None ) trainer.train(model_path=UpperCamelCase__ ) trainer.save_model() # For convenience, we also re-save the tokenizer to the same directory, # so that you can share your model easily on huggingface.co/models =) if trainer.is_world_master(): tokenizer.save_pretrained(training_args.output_dir ) # Evaluation _a : Union[str, Any] = {} if training_args.do_eval: logger.info("""*** Evaluate ***""" ) _a : int = trainer.evaluate() _a : Dict = math.exp(eval_output["""eval_loss"""] ) _a : Union[str, Any] = {"""perplexity""": perplexity} _a : Optional[Any] = os.path.join(training_args.output_dir , """eval_results_lm.txt""" ) if trainer.is_world_master(): with open(UpperCamelCase__ , """w""" ) as writer: logger.info("""***** Eval results *****""" ) for key in sorted(result.keys() ): logger.info(""" %s = %s""" , UpperCamelCase__ , str(result[key] ) ) writer.write("""%s = %s\n""" % (key, str(result[key] )) ) results.update(UpperCamelCase__ ) return results def lowerCAmelCase__ ( UpperCamelCase__ ): '''simple docstring''' # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
324
1
"""simple docstring""" from collections import OrderedDict from typing import TYPE_CHECKING, Any, List, Mapping, Optional, Union from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import TensorType, logging if TYPE_CHECKING: from ...onnx.config import PatchingSpec from ...tokenization_utils_base import PreTrainedTokenizerBase _snake_case = logging.get_logger(__name__) _snake_case = { 'allenai/longformer-base-4096': 'https://huggingface.co/allenai/longformer-base-4096/resolve/main/config.json', 'allenai/longformer-large-4096': 'https://huggingface.co/allenai/longformer-large-4096/resolve/main/config.json', 'allenai/longformer-large-4096-finetuned-triviaqa': ( 'https://huggingface.co/allenai/longformer-large-4096-finetuned-triviaqa/resolve/main/config.json' ), 'allenai/longformer-base-4096-extra.pos.embd.only': ( 'https://huggingface.co/allenai/longformer-base-4096-extra.pos.embd.only/resolve/main/config.json' ), 'allenai/longformer-large-4096-extra.pos.embd.only': ( 'https://huggingface.co/allenai/longformer-large-4096-extra.pos.embd.only/resolve/main/config.json' ), } class UpperCamelCase ( snake_case_ ): UpperCamelCase : Any = '''longformer''' def __init__( self : Union[str, Any] , UpperCAmelCase__ : Union[List[int], int] = 512 , UpperCAmelCase__ : int = 2 , UpperCAmelCase__ : int = 1 , UpperCAmelCase__ : int = 0 , UpperCAmelCase__ : int = 2 , UpperCAmelCase__ : int = 30522 , UpperCAmelCase__ : int = 768 , UpperCAmelCase__ : int = 12 , UpperCAmelCase__ : int = 12 , UpperCAmelCase__ : int = 3072 , UpperCAmelCase__ : str = "gelu" , UpperCAmelCase__ : float = 0.1 , UpperCAmelCase__ : float = 0.1 , UpperCAmelCase__ : int = 512 , UpperCAmelCase__ : int = 2 , UpperCAmelCase__ : float = 0.0_2 , UpperCAmelCase__ : float = 1E-12 , UpperCAmelCase__ : bool = False , **UpperCAmelCase__ : Optional[int] , ) -> Dict: super().__init__(pad_token_id=UpperCAmelCase__ , **UpperCAmelCase__ ) _a : str = attention_window _a : int = sep_token_id _a : List[str] = bos_token_id _a : int = eos_token_id _a : Optional[int] = vocab_size _a : List[Any] = hidden_size _a : Any = num_hidden_layers _a : Any = num_attention_heads _a : str = hidden_act _a : Optional[int] = intermediate_size _a : Any = hidden_dropout_prob _a : int = attention_probs_dropout_prob _a : str = max_position_embeddings _a : Tuple = type_vocab_size _a : int = initializer_range _a : int = layer_norm_eps _a : Optional[Any] = onnx_export class UpperCamelCase ( snake_case_ ): def __init__( self : Dict , UpperCAmelCase__ : "PretrainedConfig" , UpperCAmelCase__ : str = "default" , UpperCAmelCase__ : "List[PatchingSpec]" = None ) -> Dict: super().__init__(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) _a : Tuple = True @property def _lowercase ( self : Optional[Any] ) -> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": _a : Optional[int] = {0: """batch""", 1: """choice""", 2: """sequence"""} else: _a : str = {0: """batch""", 1: """sequence"""} return OrderedDict( [ ("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ("""global_attention_mask""", dynamic_axis), ] ) @property def _lowercase ( self : Dict ) -> Mapping[str, Mapping[int, str]]: _a : int = super().outputs if self.task == "default": _a : Union[str, Any] = {0: """batch"""} return outputs @property def _lowercase ( self : Union[str, Any] ) -> float: return 1E-4 @property def _lowercase ( self : Tuple ) -> int: # needs to be >= 14 to support tril operator return max(super().default_onnx_opset , 14 ) def _lowercase ( self : Any , UpperCAmelCase__ : "PreTrainedTokenizerBase" , UpperCAmelCase__ : int = -1 , UpperCAmelCase__ : int = -1 , UpperCAmelCase__ : bool = False , UpperCAmelCase__ : Optional[TensorType] = None , ) -> Mapping[str, Any]: _a : str = super().generate_dummy_inputs( preprocessor=UpperCAmelCase__ , batch_size=UpperCAmelCase__ , seq_length=UpperCAmelCase__ , is_pair=UpperCAmelCase__ , framework=UpperCAmelCase__ ) import torch # for some reason, replacing this code by inputs["global_attention_mask"] = torch.randint(2, inputs["input_ids"].shape, dtype=torch.int64) # makes the export fail randomly _a : Optional[Any] = torch.zeros_like(inputs["""input_ids"""] ) # make every second token global _a : Tuple = 1 return inputs
324
"""simple docstring""" import argparse import os from pathlib import Path from typing import Dict import tensorflow as tf import torch from tqdm import tqdm from transformers import PegasusConfig, PegasusForConditionalGeneration, PegasusTokenizer from transformers.models.pegasus.configuration_pegasus import DEFAULTS, task_specific_params _snake_case = [ # replace left string with right string to get the relevant state_dict key (identical state dict to bart) ['memory_attention', 'encoder_attn'], ['attention', 'attn'], ['/', '.'], ['.LayerNorm.gamma', '_layer_norm.weight'], ['.LayerNorm.beta', '_layer_norm.bias'], ['r.layer_', 'r.layers.'], ['output_proj', 'out_proj'], ['ffn.dense_1.', 'fc2.'], ['ffn.dense.', 'fc1.'], ['ffn_layer_norm', 'final_layer_norm'], ['kernel', 'weight'], ['encoder_layer_norm.', 'encoder.layer_norm.'], ['decoder_layer_norm.', 'decoder.layer_norm.'], ['embeddings.weights', 'shared.weight'], ] def lowerCAmelCase__ ( UpperCamelCase__ ): '''simple docstring''' for pegasus_name, hf_name in PATTERNS: _a : Optional[Any] = k.replace(UpperCamelCase__ , UpperCamelCase__ ) return k def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' _a : Union[str, Any] = DEFAULTS.copy() cfg_kwargs.update(UpperCamelCase__ ) _a : Optional[Any] = PegasusConfig(**UpperCamelCase__ ) _a : Tuple = PegasusForConditionalGeneration(UpperCamelCase__ ) _a : str = torch_model.model.state_dict() _a : Union[str, Any] = {} for k, v in tf_weights.items(): _a : Any = rename_state_dict_key(UpperCamelCase__ ) if new_k not in sd: raise ValueError(F"""could not find new key {new_k} in state dict. (converted from {k})""" ) if "dense" in k or "proj" in new_k: _a : str = v.T _a : int = torch.tensor(UpperCamelCase__ , dtype=sd[new_k].dtype ) assert v.shape == sd[new_k].shape, F"""{new_k}, {k}, {v.shape}, {sd[new_k].shape}""" # make sure embedding.padding_idx is respected _a : Union[str, Any] = torch.zeros_like(mapping["""shared.weight"""][cfg.pad_token_id + 1] ) _a : str = mapping["""shared.weight"""] _a : Union[str, Any] = mapping["""shared.weight"""] _a : Optional[Any] = {k: torch.zeros_like(UpperCamelCase__ ) for k, v in sd.items() if k.endswith("""bias""" ) and k not in mapping} mapping.update(**UpperCamelCase__ ) _a , _a : int = torch_model.model.load_state_dict(UpperCamelCase__ , strict=UpperCamelCase__ ) _a : Optional[Any] = [ k for k in missing if k not in ["""encoder.embed_positions.weight""", """decoder.embed_positions.weight"""] ] assert unexpected_missing == [], F"""no matches found for the following torch keys {unexpected_missing}""" assert extra == [], F"""no matches found for the following tf keys {extra}""" return torch_model def lowerCAmelCase__ ( UpperCamelCase__="./ckpt/aeslc/model.ckpt-32000" ): '''simple docstring''' _a : List[Any] = tf.train.list_variables(UpperCamelCase__ ) _a : Optional[int] = {} _a : Dict = ["""Adafactor""", """global_step"""] for name, shape in tqdm(UpperCamelCase__ , desc="""converting tf checkpoint to dict""" ): _a : Optional[Any] = any(pat in name for pat in ignore_name ) if skip_key: continue _a : str = tf.train.load_variable(UpperCamelCase__ , UpperCamelCase__ ) _a : int = array return tf_weights def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' # save tokenizer first _a : Dict = Path(UpperCamelCase__ ).parent.name _a : Optional[Any] = task_specific_params[F"""summarization_{dataset}"""]["""max_position_embeddings"""] _a : Tuple = PegasusTokenizer.from_pretrained("""sshleifer/pegasus""" , model_max_length=UpperCamelCase__ ) assert tok.model_max_length == desired_max_model_length tok.save_pretrained(UpperCamelCase__ ) # convert model _a : List[Any] = get_tf_weights_as_numpy(UpperCamelCase__ ) _a : Dict = task_specific_params[F"""summarization_{dataset}"""] if dataset == "large": _a : Tuple = task_specific_params _a : Optional[int] = convert_pegasus(UpperCamelCase__ , UpperCamelCase__ ) torch_model.save_pretrained(UpperCamelCase__ ) _a : Dict = torch_model.state_dict() sd.pop("""model.decoder.embed_positions.weight""" ) sd.pop("""model.encoder.embed_positions.weight""" ) torch.save(UpperCamelCase__ , Path(UpperCamelCase__ ) / """pytorch_model.bin""" ) if __name__ == "__main__": _snake_case = argparse.ArgumentParser() # Required parameters parser.add_argument('tf_ckpt_path', type=str, help='passed to tf.train.list_variables') parser.add_argument('save_dir', default=None, type=str, help='Path to the output PyTorch model.') _snake_case = parser.parse_args() if args.save_dir is None: _snake_case = Path(args.tf_ckpt_path).parent.name _snake_case = os.path.join('pegasus', dataset) convert_pegasus_ckpt_to_pytorch(args.tf_ckpt_path, args.save_dir)
324
1
"""simple docstring""" import shutil import tempfile import unittest from transformers import SPIECE_UNDERLINE, BatchEncoding, MBartTokenizer, MBartTokenizerFast, is_torch_available from transformers.testing_utils import ( get_tests_dir, nested_simplify, require_sentencepiece, require_tokenizers, require_torch, ) from ...test_tokenization_common import TokenizerTesterMixin _snake_case = get_tests_dir('fixtures/test_sentencepiece.model') if is_torch_available(): from transformers.models.mbart.modeling_mbart import shift_tokens_right _snake_case = 25_0004 _snake_case = 25_0020 @require_sentencepiece @require_tokenizers class UpperCamelCase ( snake_case_ , unittest.TestCase ): UpperCamelCase : List[Any] = MBartTokenizer UpperCamelCase : str = MBartTokenizerFast UpperCamelCase : Dict = True UpperCamelCase : Optional[int] = True def _lowercase ( self : Tuple ) -> Tuple: super().setUp() # We have a SentencePiece fixture for testing _a : Tuple = MBartTokenizer(UpperCAmelCase__ , keep_accents=UpperCAmelCase__ ) tokenizer.save_pretrained(self.tmpdirname ) def _lowercase ( self : int ) -> Optional[Any]: _a : Union[str, Any] = MBartTokenizer(UpperCAmelCase__ , keep_accents=UpperCAmelCase__ ) _a : List[str] = tokenizer.tokenize("""This is a test""" ) self.assertListEqual(UpperCAmelCase__ , ["""▁This""", """▁is""", """▁a""", """▁t""", """est"""] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(UpperCAmelCase__ ) , [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]] , ) _a : int = tokenizer.tokenize("""I was born in 92000, and this is falsé.""" ) self.assertListEqual( UpperCAmelCase__ , [ SPIECE_UNDERLINE + """I""", SPIECE_UNDERLINE + """was""", SPIECE_UNDERLINE + """b""", """or""", """n""", SPIECE_UNDERLINE + """in""", SPIECE_UNDERLINE + """""", """9""", """2""", """0""", """0""", """0""", """,""", SPIECE_UNDERLINE + """and""", SPIECE_UNDERLINE + """this""", SPIECE_UNDERLINE + """is""", SPIECE_UNDERLINE + """f""", """al""", """s""", """é""", """.""", ] , ) _a : Tuple = tokenizer.convert_tokens_to_ids(UpperCAmelCase__ ) self.assertListEqual( UpperCAmelCase__ , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, 2, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 2, 4] # ^ unk: 2 + 1 = 3 unk: 2 + 1 = 3 ^ ] , ) _a : Optional[int] = tokenizer.convert_ids_to_tokens(UpperCAmelCase__ ) self.assertListEqual( UpperCAmelCase__ , [ SPIECE_UNDERLINE + """I""", SPIECE_UNDERLINE + """was""", SPIECE_UNDERLINE + """b""", """or""", """n""", SPIECE_UNDERLINE + """in""", SPIECE_UNDERLINE + """""", """<unk>""", """2""", """0""", """0""", """0""", """,""", SPIECE_UNDERLINE + """and""", SPIECE_UNDERLINE + """this""", SPIECE_UNDERLINE + """is""", SPIECE_UNDERLINE + """f""", """al""", """s""", """<unk>""", """.""", ] , ) def _lowercase ( self : int ) -> str: if not self.test_slow_tokenizer: # as we don't have a slow version, we can't compare the outputs between slow and fast versions return _a : List[Any] = (self.rust_tokenizer_class, """hf-internal-testing/tiny-random-mbart""", {}) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): _a : Dict = self.rust_tokenizer_class.from_pretrained(UpperCAmelCase__ , **UpperCAmelCase__ ) _a : str = self.tokenizer_class.from_pretrained(UpperCAmelCase__ , **UpperCAmelCase__ ) _a : Optional[int] = tempfile.mkdtemp() _a : str = tokenizer_r.save_pretrained(UpperCAmelCase__ ) _a : str = tokenizer_p.save_pretrained(UpperCAmelCase__ ) # Checks it save with the same files + the tokenizer.json file for the fast one self.assertTrue(any("""tokenizer.json""" in f for f in tokenizer_r_files ) ) _a : Optional[Any] = tuple(f for f in tokenizer_r_files if """tokenizer.json""" not in f ) self.assertSequenceEqual(UpperCAmelCase__ , UpperCAmelCase__ ) # Checks everything loads correctly in the same way _a : str = tokenizer_r.from_pretrained(UpperCAmelCase__ ) _a : List[Any] = tokenizer_p.from_pretrained(UpperCAmelCase__ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(UpperCAmelCase__ , UpperCAmelCase__ ) ) # self.assertEqual(getattr(tokenizer_rp, key), getattr(tokenizer_pp, key)) # self.assertEqual(getattr(tokenizer_rp, key + "_id"), getattr(tokenizer_pp, key + "_id")) shutil.rmtree(UpperCAmelCase__ ) # Save tokenizer rust, legacy_format=True _a : Union[str, Any] = tempfile.mkdtemp() _a : List[Any] = tokenizer_r.save_pretrained(UpperCAmelCase__ , legacy_format=UpperCAmelCase__ ) _a : List[str] = tokenizer_p.save_pretrained(UpperCAmelCase__ ) # Checks it save with the same files self.assertSequenceEqual(UpperCAmelCase__ , UpperCAmelCase__ ) # Checks everything loads correctly in the same way _a : Dict = tokenizer_r.from_pretrained(UpperCAmelCase__ ) _a : List[str] = tokenizer_p.from_pretrained(UpperCAmelCase__ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(UpperCAmelCase__ , UpperCAmelCase__ ) ) shutil.rmtree(UpperCAmelCase__ ) # Save tokenizer rust, legacy_format=False _a : List[Any] = tempfile.mkdtemp() _a : Optional[int] = tokenizer_r.save_pretrained(UpperCAmelCase__ , legacy_format=UpperCAmelCase__ ) _a : List[str] = tokenizer_p.save_pretrained(UpperCAmelCase__ ) # Checks it saved the tokenizer.json file self.assertTrue(any("""tokenizer.json""" in f for f in tokenizer_r_files ) ) # Checks everything loads correctly in the same way _a : Any = tokenizer_r.from_pretrained(UpperCAmelCase__ ) _a : List[Any] = tokenizer_p.from_pretrained(UpperCAmelCase__ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(UpperCAmelCase__ , UpperCAmelCase__ ) ) shutil.rmtree(UpperCAmelCase__ ) @require_torch @require_sentencepiece @require_tokenizers class UpperCamelCase ( unittest.TestCase ): UpperCamelCase : Tuple = '''facebook/mbart-large-en-ro''' UpperCamelCase : Optional[Any] = [ ''' UN Chief Says There Is No Military Solution in Syria''', ''' Secretary-General Ban Ki-moon says his response to Russia\'s stepped up military support for Syria is that "there is no military solution" to the nearly five-year conflict and more weapons will only worsen the violence and misery for millions of people.''', ] UpperCamelCase : Dict = [ '''Şeful ONU declară că nu există o soluţie militară în Siria''', '''Secretarul General Ban Ki-moon declară că răspunsul său la intensificarea sprijinului militar al Rusiei''' ''' pentru Siria este că "nu există o soluţie militară" la conflictul de aproape cinci ani şi că noi arme nu vor''' ''' face decât să înrăutăţească violenţele şi mizeria pentru milioane de oameni.''', ] UpperCamelCase : Union[str, Any] = [8_274, 127_873, 25_916, 7, 8_622, 2_071, 438, 67_485, 53, 187_895, 23, 51_712, 2, EN_CODE] @classmethod def _lowercase ( cls : int ) -> Tuple: _a : MBartTokenizer = MBartTokenizer.from_pretrained( cls.checkpoint_name , src_lang="""en_XX""" , tgt_lang="""ro_RO""" ) _a : Optional[Any] = 1 return cls def _lowercase ( self : int ) -> Tuple: self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["""ar_AR"""] , 250001 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["""en_EN"""] , 250004 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["""ro_RO"""] , 250020 ) def _lowercase ( self : Union[str, Any] ) -> List[str]: _a : Tuple = self.tokenizer.batch_encode_plus(self.src_text ).input_ids[0] self.assertListEqual(self.expected_src_tokens , UpperCAmelCase__ ) def _lowercase ( self : Dict ) -> Dict: self.assertIn(UpperCAmelCase__ , self.tokenizer.all_special_ids ) _a : str = [RO_CODE, 884, 9019, 96, 9, 916, 86792, 36, 18743, 15596, 5, 2] _a : Any = self.tokenizer.decode(UpperCAmelCase__ , skip_special_tokens=UpperCAmelCase__ ) _a : Optional[Any] = self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=UpperCAmelCase__ ) self.assertEqual(UpperCAmelCase__ , UpperCAmelCase__ ) self.assertNotIn(self.tokenizer.eos_token , UpperCAmelCase__ ) def _lowercase ( self : Tuple ) -> str: _a : Dict = ["""this is gunna be a long sentence """ * 20] assert isinstance(src_text[0] , UpperCAmelCase__ ) _a : Any = 10 _a : Tuple = self.tokenizer(UpperCAmelCase__ , max_length=UpperCAmelCase__ , truncation=UpperCAmelCase__ ).input_ids[0] self.assertEqual(ids[-2] , 2 ) self.assertEqual(ids[-1] , UpperCAmelCase__ ) self.assertEqual(len(UpperCAmelCase__ ) , UpperCAmelCase__ ) def _lowercase ( self : List[str] ) -> Optional[int]: self.assertListEqual(self.tokenizer.convert_tokens_to_ids(["""<mask>""", """ar_AR"""] ) , [250026, 250001] ) def _lowercase ( self : Optional[int] ) -> List[str]: _a : Any = tempfile.mkdtemp() _a : Optional[Any] = self.tokenizer.fairseq_tokens_to_ids self.tokenizer.save_pretrained(UpperCAmelCase__ ) _a : Any = MBartTokenizer.from_pretrained(UpperCAmelCase__ ) self.assertDictEqual(new_tok.fairseq_tokens_to_ids , UpperCAmelCase__ ) @require_torch def _lowercase ( self : Union[str, Any] ) -> List[Any]: _a : Optional[int] = self.tokenizer(self.src_text , text_target=self.tgt_text , padding=UpperCAmelCase__ , return_tensors="""pt""" ) _a : List[Any] = shift_tokens_right(batch["""labels"""] , self.tokenizer.pad_token_id ) # fairseq batch: https://gist.github.com/sshleifer/cba08bc2109361a74ac3760a7e30e4f4 assert batch.input_ids[1][-2:].tolist() == [2, EN_CODE] assert batch.decoder_input_ids[1][0].tolist() == RO_CODE assert batch.decoder_input_ids[1][-1] == 2 assert batch.labels[1][-2:].tolist() == [2, RO_CODE] @require_torch def _lowercase ( self : List[str] ) -> Union[str, Any]: _a : Optional[int] = self.tokenizer( self.src_text , text_target=self.tgt_text , padding=UpperCAmelCase__ , truncation=UpperCAmelCase__ , max_length=len(self.expected_src_tokens ) , return_tensors="""pt""" , ) _a : Optional[int] = shift_tokens_right(batch["""labels"""] , self.tokenizer.pad_token_id ) self.assertIsInstance(UpperCAmelCase__ , UpperCAmelCase__ ) self.assertEqual((2, 14) , batch.input_ids.shape ) self.assertEqual((2, 14) , batch.attention_mask.shape ) _a : Optional[int] = batch.input_ids.tolist()[0] self.assertListEqual(self.expected_src_tokens , UpperCAmelCase__ ) self.assertEqual(2 , batch.decoder_input_ids[0, -1] ) # EOS # Test that special tokens are reset self.assertEqual(self.tokenizer.prefix_tokens , [] ) self.assertEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id, EN_CODE] ) def _lowercase ( self : Dict ) -> Dict: _a : Optional[int] = self.tokenizer(self.src_text , padding=UpperCAmelCase__ , truncation=UpperCAmelCase__ , max_length=3 , return_tensors="""pt""" ) _a : List[Any] = self.tokenizer( text_target=self.tgt_text , padding=UpperCAmelCase__ , truncation=UpperCAmelCase__ , max_length=10 , return_tensors="""pt""" ) _a : str = targets["""input_ids"""] _a : List[str] = shift_tokens_right(UpperCAmelCase__ , self.tokenizer.pad_token_id ) self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.decoder_input_ids.shape[1] , 10 ) @require_torch def _lowercase ( self : List[str] ) -> Union[str, Any]: _a : int = self.tokenizer._build_translation_inputs( """A test""" , return_tensors="""pt""" , src_lang="""en_XX""" , tgt_lang="""ar_AR""" ) self.assertEqual( nested_simplify(UpperCAmelCase__ ) , { # A, test, EOS, en_XX """input_ids""": [[62, 3034, 2, 250004]], """attention_mask""": [[1, 1, 1, 1]], # ar_AR """forced_bos_token_id""": 250001, } , )
324
"""simple docstring""" import gc import random import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTextModelWithProjection, CLIPTokenizer from diffusers import ( AutoencoderKL, DiffusionPipeline, EulerDiscreteScheduler, StableDiffusionXLImgaImgPipeline, UNetaDConditionModel, ) from diffusers.utils import floats_tensor, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import ( IMAGE_TO_IMAGE_IMAGE_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class UpperCamelCase ( snake_case_ , snake_case_ , unittest.TestCase ): UpperCamelCase : Union[str, Any] = StableDiffusionXLImgaImgPipeline UpperCamelCase : Any = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'''height''', '''width'''} UpperCamelCase : Tuple = PipelineTesterMixin.required_optional_params - {'''latents'''} UpperCamelCase : int = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS UpperCamelCase : Optional[Any] = IMAGE_TO_IMAGE_IMAGE_PARAMS UpperCamelCase : Optional[Any] = IMAGE_TO_IMAGE_IMAGE_PARAMS def _lowercase ( self : Any ) -> List[Any]: torch.manual_seed(0 ) _a : str = 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""") , attention_head_dim=(2, 4) , use_linear_projection=UpperCAmelCase__ , addition_embed_type="""text_time""" , addition_time_embed_dim=8 , transformer_layers_per_block=(1, 2) , projection_class_embeddings_input_dim=80 , cross_attention_dim=64 , ) _a : Union[str, Any] = EulerDiscreteScheduler( beta_start=0.0_0_0_8_5 , beta_end=0.0_1_2 , steps_offset=1 , beta_schedule="""scaled_linear""" , timestep_spacing="""leading""" , ) torch.manual_seed(0 ) _a : List[str] = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , sample_size=128 , ) torch.manual_seed(0 ) _a : int = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , hidden_act="""gelu""" , projection_dim=32 , ) _a : Tuple = CLIPTextModel(UpperCAmelCase__ ) _a : str = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" , local_files_only=UpperCAmelCase__ ) _a : Dict = CLIPTextModelWithProjection(UpperCAmelCase__ ) _a : Dict = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" , local_files_only=UpperCAmelCase__ ) _a : Any = { """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """text_encoder_2""": text_encoder_a, """tokenizer_2""": tokenizer_a, # "safety_checker": None, # "feature_extractor": None, } return components def _lowercase ( self : List[Any] , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : int=0 ) -> int: _a : Dict = floats_tensor((1, 3, 32, 32) , rng=random.Random(UpperCAmelCase__ ) ).to(UpperCAmelCase__ ) _a : Any = image / 2 + 0.5 if str(UpperCAmelCase__ ).startswith("""mps""" ): _a : Any = torch.manual_seed(UpperCAmelCase__ ) else: _a : Tuple = torch.Generator(device=UpperCAmelCase__ ).manual_seed(UpperCAmelCase__ ) _a : Optional[Any] = { """prompt""": """A painting of a squirrel eating a burger""", """image""": image, """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 5.0, """output_type""": """numpy""", """strength""": 0.7_5, } return inputs def _lowercase ( self : Any ) -> List[Any]: _a : Union[str, Any] = """cpu""" # ensure determinism for the device-dependent torch.Generator _a : Dict = self.get_dummy_components() _a : List[Any] = StableDiffusionXLImgaImgPipeline(**UpperCAmelCase__ ) _a : Union[str, Any] = sd_pipe.to(UpperCAmelCase__ ) sd_pipe.set_progress_bar_config(disable=UpperCAmelCase__ ) _a : List[str] = self.get_dummy_inputs(UpperCAmelCase__ ) _a : List[str] = sd_pipe(**UpperCAmelCase__ ).images _a : Union[str, Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) _a : List[str] = np.array([0.4_6_5_6, 0.4_8_4_0, 0.4_4_3_9, 0.6_6_9_8, 0.5_5_7_4, 0.4_5_2_4, 0.5_7_9_9, 0.5_9_4_3, 0.5_1_6_5] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def _lowercase ( self : Any ) -> Any: super().test_attention_slicing_forward_pass(expected_max_diff=3E-3 ) def _lowercase ( self : List[Any] ) -> Optional[Any]: super().test_inference_batch_single_identical(expected_max_diff=3E-3 ) def _lowercase ( self : Any ) -> Any: pass def _lowercase ( self : Tuple ) -> Union[str, Any]: _a : int = self.get_dummy_components() _a : Any = StableDiffusionXLImgaImgPipeline(**UpperCAmelCase__ ) _a : Dict = sd_pipe.to(UpperCAmelCase__ ) _a : List[str] = sd_pipe.to(UpperCAmelCase__ ) sd_pipe.set_progress_bar_config(disable=UpperCAmelCase__ ) # forward without prompt embeds _a : int = self.get_dummy_inputs(UpperCAmelCase__ ) _a : List[str] = 3 * ["""this is a negative prompt"""] _a : Dict = negative_prompt _a : Dict = 3 * [inputs["""prompt"""]] _a : Optional[Any] = sd_pipe(**UpperCAmelCase__ ) _a : Tuple = output.images[0, -3:, -3:, -1] # forward with prompt embeds _a : int = self.get_dummy_inputs(UpperCAmelCase__ ) _a : Union[str, Any] = 3 * ["""this is a negative prompt"""] _a : int = 3 * [inputs.pop("""prompt""" )] ( ( _a ) , ( _a ) , ( _a ) , ( _a ) , ) : List[str] = sd_pipe.encode_prompt(UpperCAmelCase__ , negative_prompt=UpperCAmelCase__ ) _a : Tuple = sd_pipe( **UpperCAmelCase__ , prompt_embeds=UpperCAmelCase__ , negative_prompt_embeds=UpperCAmelCase__ , pooled_prompt_embeds=UpperCAmelCase__ , negative_pooled_prompt_embeds=UpperCAmelCase__ , ) _a : Dict = output.images[0, -3:, -3:, -1] # make sure that it's equal assert np.abs(image_slice_a.flatten() - image_slice_a.flatten() ).max() < 1E-4 @slow @require_torch_gpu class UpperCamelCase ( unittest.TestCase ): def _lowercase ( self : List[str] ) -> Union[str, Any]: super().tearDown() gc.collect() torch.cuda.empty_cache() def _lowercase ( self : List[str] , UpperCAmelCase__ : str , UpperCAmelCase__ : str="cpu" , UpperCAmelCase__ : str=torch.floataa , UpperCAmelCase__ : List[Any]=0 ) -> List[str]: _a : List[str] = torch.Generator(device=UpperCAmelCase__ ).manual_seed(UpperCAmelCase__ ) _a : Union[str, Any] = np.random.RandomState(UpperCAmelCase__ ).standard_normal((1, 4, 64, 64) ) _a : List[Any] = torch.from_numpy(UpperCAmelCase__ ).to(device=UpperCAmelCase__ , dtype=UpperCAmelCase__ ) _a : Any = { """prompt""": """a photograph of an astronaut riding a horse""", """latents""": latents, """generator""": generator, """num_inference_steps""": 3, """guidance_scale""": 7.5, """output_type""": """numpy""", } return inputs def _lowercase ( self : int ) -> Union[str, Any]: _a : Union[str, Any] = DiffusionPipeline.from_pretrained("""stabilityai/stable-diffusion-2-base""" ) pipe.to(UpperCAmelCase__ ) pipe.set_progress_bar_config(disable=UpperCAmelCase__ ) _a : List[str] = self.get_inputs(UpperCAmelCase__ ) _a : Tuple = pipe(**UpperCAmelCase__ ).images _a : List[str] = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 512, 512, 3) _a : int = np.array([0.4_9_4_9_3, 0.4_7_8_9_6, 0.4_0_7_9_8, 0.5_4_2_1_4, 0.5_3_2_1_2, 0.4_8_2_0_2, 0.4_7_6_5_6, 0.4_6_3_2_9, 0.4_8_5_0_6] ) assert np.abs(image_slice - expected_slice ).max() < 7E-3
324
1
"""simple docstring""" import argparse from collections import defaultdict import yaml _snake_case = 'docs/source/en/_toctree.yml' def lowerCAmelCase__ ( UpperCamelCase__ ): '''simple docstring''' _a : Optional[int] = defaultdict(UpperCamelCase__ ) _a : Optional[Any] = [] _a : str = [] for doc in doc_list: if "local" in doc: counts[doc["local"]] += 1 if doc["title"].lower() == "overview": overview_doc.append({"""local""": doc["""local"""], """title""": doc["""title"""]} ) else: new_doc_list.append(UpperCamelCase__ ) _a : List[Any] = new_doc_list _a : Dict = [key for key, value in counts.items() if value > 1] _a : Any = [] for duplicate_key in duplicates: _a : Optional[int] = list({doc["""title"""] for doc in doc_list if doc["""local"""] == duplicate_key} ) if len(UpperCamelCase__ ) > 1: raise ValueError( F"""{duplicate_key} is present several times in the documentation table of content at """ """`docs/source/en/_toctree.yml` with different *Title* values. Choose one of those and remove the """ """others.""" ) # Only add this once new_doc.append({"""local""": duplicate_key, """title""": titles[0]} ) # Add none duplicate-keys new_doc.extend([doc for doc in doc_list if """local""" not in counts or counts[doc["""local"""]] == 1] ) _a : Optional[Any] = sorted(UpperCamelCase__ , key=lambda UpperCamelCase__ : s["title"].lower() ) # "overview" gets special treatment and is always first if len(UpperCamelCase__ ) > 1: raise ValueError("""{doc_list} has two 'overview' docs which is not allowed.""" ) overview_doc.extend(UpperCamelCase__ ) # Sort return overview_doc def lowerCAmelCase__ ( UpperCamelCase__=False ): '''simple docstring''' with open(UpperCamelCase__ , encoding="""utf-8""" ) as f: _a : Dict = yaml.safe_load(f.read() ) # Get to the API doc _a : Optional[Any] = 0 while content[api_idx]["title"] != "API": api_idx += 1 _a : Optional[Any] = content[api_idx]["""sections"""] # Then to the model doc _a : str = 0 while api_doc[scheduler_idx]["title"] != "Schedulers": scheduler_idx += 1 _a : List[Any] = api_doc[scheduler_idx]["""sections"""] _a : List[str] = clean_doc_toc(UpperCamelCase__ ) _a : Optional[int] = False if new_scheduler_doc != scheduler_doc: _a : List[str] = True if overwrite: _a : Tuple = new_scheduler_doc if diff: if overwrite: _a : Optional[int] = api_doc with open(UpperCamelCase__ , """w""" , encoding="""utf-8""" ) as f: f.write(yaml.dump(UpperCamelCase__ , allow_unicode=UpperCamelCase__ ) ) else: raise ValueError( """The model doc part of the table of content is not properly sorted, run `make style` to fix this.""" ) def lowerCAmelCase__ ( UpperCamelCase__=False ): '''simple docstring''' with open(UpperCamelCase__ , encoding="""utf-8""" ) as f: _a : Optional[int] = yaml.safe_load(f.read() ) # Get to the API doc _a : Union[str, Any] = 0 while content[api_idx]["title"] != "API": api_idx += 1 _a : Any = content[api_idx]["""sections"""] # Then to the model doc _a : Tuple = 0 while api_doc[pipeline_idx]["title"] != "Pipelines": pipeline_idx += 1 _a : Optional[int] = False _a : Dict = api_doc[pipeline_idx]["""sections"""] _a : List[str] = [] # sort sub pipeline docs for pipeline_doc in pipeline_docs: if "section" in pipeline_doc: _a : Any = pipeline_doc["""section"""] _a : Tuple = clean_doc_toc(UpperCamelCase__ ) if overwrite: _a : Optional[int] = new_sub_pipeline_doc new_pipeline_docs.append(UpperCamelCase__ ) # sort overall pipeline doc _a : Optional[Any] = clean_doc_toc(UpperCamelCase__ ) if new_pipeline_docs != pipeline_docs: _a : Optional[int] = True if overwrite: _a : Optional[Any] = new_pipeline_docs if diff: if overwrite: _a : Any = api_doc with open(UpperCamelCase__ , """w""" , encoding="""utf-8""" ) as f: f.write(yaml.dump(UpperCamelCase__ , allow_unicode=UpperCamelCase__ ) ) else: raise ValueError( """The model doc part of the table of content is not properly sorted, run `make style` to fix this.""" ) if __name__ == "__main__": _snake_case = argparse.ArgumentParser() parser.add_argument('--fix_and_overwrite', action='store_true', help='Whether to fix inconsistencies.') _snake_case = parser.parse_args() check_scheduler_doc(args.fix_and_overwrite) check_pipeline_doc(args.fix_and_overwrite)
324
"""simple docstring""" import argparse import json from dataclasses import dataclass, field from functools import partial from pathlib import Path from typing import List import timm import torch import torch.nn as nn from huggingface_hub import hf_hub_download from torch import Tensor from transformers import AutoImageProcessor, ResNetConfig, ResNetForImageClassification from transformers.utils import logging logging.set_verbosity_info() _snake_case = logging.get_logger() @dataclass class UpperCamelCase : UpperCamelCase : nn.Module UpperCamelCase : List[nn.Module] = field(default_factory=snake_case_ ) UpperCamelCase : list = field(default_factory=snake_case_ ) def _lowercase ( self : List[Any] , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : Tensor , UpperCAmelCase__ : Tensor ) -> Any: _a : int = len(list(m.modules() ) ) == 1 or isinstance(UpperCAmelCase__ , nn.Convad ) or isinstance(UpperCAmelCase__ , nn.BatchNormad ) if has_not_submodules: self.traced.append(UpperCAmelCase__ ) def __call__( self : Tuple , UpperCAmelCase__ : Tensor ) -> Tuple: for m in self.module.modules(): self.handles.append(m.register_forward_hook(self._forward_hook ) ) self.module(UpperCAmelCase__ ) [x.remove() for x in self.handles] return self @property def _lowercase ( self : Optional[int] ) -> int: # check the len of the state_dict keys to see if we have learnable params return list(filter(lambda UpperCAmelCase__ : len(list(x.state_dict().keys() ) ) > 0 , self.traced ) ) @dataclass class UpperCamelCase : UpperCamelCase : nn.Module UpperCamelCase : nn.Module UpperCamelCase : int = 0 UpperCamelCase : List = field(default_factory=snake_case_ ) UpperCamelCase : List = field(default_factory=snake_case_ ) def __call__( self : Optional[Any] , UpperCAmelCase__ : Tensor ) -> Tuple: _a : Union[str, Any] = Tracker(self.dest )(UpperCAmelCase__ ).parametrized _a : List[Any] = Tracker(self.src )(UpperCAmelCase__ ).parametrized _a : Tuple = list(filter(lambda UpperCAmelCase__ : type(UpperCAmelCase__ ) not in self.src_skip , UpperCAmelCase__ ) ) _a : Union[str, Any] = list(filter(lambda UpperCAmelCase__ : type(UpperCAmelCase__ ) not in self.dest_skip , UpperCAmelCase__ ) ) if len(UpperCAmelCase__ ) != len(UpperCAmelCase__ ): raise Exception( f"""Numbers of operations are different. Source module has {len(UpperCAmelCase__ )} operations while""" f""" destination module has {len(UpperCAmelCase__ )}.""" ) for dest_m, src_m in zip(UpperCAmelCase__ , UpperCAmelCase__ ): dest_m.load_state_dict(src_m.state_dict() ) if self.verbose == 1: print(f"""Transfered from={src_m} to={dest_m}""" ) def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = True ): '''simple docstring''' print(F"""Converting {name}...""" ) with torch.no_grad(): _a : List[str] = timm.create_model(UpperCamelCase__ , pretrained=UpperCamelCase__ ).eval() _a : str = ResNetForImageClassification(UpperCamelCase__ ).eval() _a : List[str] = ModuleTransfer(src=UpperCamelCase__ , dest=UpperCamelCase__ ) _a : List[str] = torch.randn((1, 3, 2_2_4, 2_2_4) ) module_transfer(UpperCamelCase__ ) assert torch.allclose(from_model(UpperCamelCase__ ) , our_model(UpperCamelCase__ ).logits ), "The model logits don't match the original one." _a : Dict = F"""resnet{'-'.join(name.split('resnet' ) )}""" print(UpperCamelCase__ ) if push_to_hub: our_model.push_to_hub( repo_path_or_name=save_directory / checkpoint_name , commit_message="""Add model""" , use_temp_dir=UpperCamelCase__ , ) # we can use the convnext one _a : Optional[Any] = AutoImageProcessor.from_pretrained("""facebook/convnext-base-224-22k-1k""" ) image_processor.push_to_hub( repo_path_or_name=save_directory / checkpoint_name , commit_message="""Add image processor""" , use_temp_dir=UpperCamelCase__ , ) print(F"""Pushed {checkpoint_name}""" ) def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ = None , UpperCamelCase__ = True ): '''simple docstring''' _a : Any = """imagenet-1k-id2label.json""" _a : Optional[int] = 1_0_0_0 _a : Any = (1, num_labels) _a : Union[str, Any] = """huggingface/label-files""" _a : Tuple = num_labels _a : Optional[int] = json.load(open(hf_hub_download(UpperCamelCase__ , UpperCamelCase__ , repo_type="""dataset""" ) , """r""" ) ) _a : Optional[Any] = {int(UpperCamelCase__ ): v for k, v in idalabel.items()} _a : Any = idalabel _a : Tuple = {v: k for k, v in idalabel.items()} _a : List[str] = partial(UpperCamelCase__ , num_labels=UpperCamelCase__ , idalabel=UpperCamelCase__ , labelaid=UpperCamelCase__ ) _a : Union[str, Any] = { """resnet18""": ImageNetPreTrainedConfig( depths=[2, 2, 2, 2] , hidden_sizes=[6_4, 1_2_8, 2_5_6, 5_1_2] , layer_type="""basic""" ), """resnet26""": ImageNetPreTrainedConfig( depths=[2, 2, 2, 2] , hidden_sizes=[2_5_6, 5_1_2, 1_0_2_4, 2_0_4_8] , layer_type="""bottleneck""" ), """resnet34""": ImageNetPreTrainedConfig( depths=[3, 4, 6, 3] , hidden_sizes=[6_4, 1_2_8, 2_5_6, 5_1_2] , layer_type="""basic""" ), """resnet50""": ImageNetPreTrainedConfig( depths=[3, 4, 6, 3] , hidden_sizes=[2_5_6, 5_1_2, 1_0_2_4, 2_0_4_8] , layer_type="""bottleneck""" ), """resnet101""": ImageNetPreTrainedConfig( depths=[3, 4, 2_3, 3] , hidden_sizes=[2_5_6, 5_1_2, 1_0_2_4, 2_0_4_8] , layer_type="""bottleneck""" ), """resnet152""": ImageNetPreTrainedConfig( depths=[3, 8, 3_6, 3] , hidden_sizes=[2_5_6, 5_1_2, 1_0_2_4, 2_0_4_8] , layer_type="""bottleneck""" ), } if model_name: convert_weight_and_push(UpperCamelCase__ , names_to_config[model_name] , UpperCamelCase__ , UpperCamelCase__ ) else: for model_name, config in names_to_config.items(): convert_weight_and_push(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) return config, expected_shape if __name__ == "__main__": _snake_case = argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default=None, type=str, help=( 'The name of the model you wish to convert, it must be one of the supported resnet* architecture,' ' currently: resnet18,26,34,50,101,152. If `None`, all of them will the converted.' ), ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=Path, required=True, help='Path to the output PyTorch model directory.', ) parser.add_argument( '--push_to_hub', default=True, type=bool, required=False, help='If True, push model and image processor to the hub.', ) _snake_case = parser.parse_args() _snake_case = args.pytorch_dump_folder_path pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True) convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)
324
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available _snake_case = { 'configuration_mask2former': [ 'MASK2FORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'Mask2FormerConfig', ], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _snake_case = ['Mask2FormerImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _snake_case = [ 'MASK2FORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'Mask2FormerForUniversalSegmentation', 'Mask2FormerModel', 'Mask2FormerPreTrainedModel', ] if TYPE_CHECKING: from .configuration_maskaformer import MASK2FORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, MaskaFormerConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_maskaformer import MaskaFormerImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_maskaformer import ( MASK2FORMER_PRETRAINED_MODEL_ARCHIVE_LIST, MaskaFormerForUniversalSegmentation, MaskaFormerModel, MaskaFormerPreTrainedModel, ) else: import sys _snake_case = _LazyModule(__name__, globals()['__file__'], _import_structure)
324
"""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, )
324
1
"""simple docstring""" from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_vision_available(): import PIL _snake_case = logging.get_logger(__name__) class UpperCamelCase ( snake_case_ ): UpperCamelCase : List[str] = ['''pixel_values'''] def __init__( self : Dict , UpperCAmelCase__ : bool = True , UpperCAmelCase__ : Dict[str, int] = None , UpperCAmelCase__ : int = 0.9 , UpperCAmelCase__ : PILImageResampling = PILImageResampling.BICUBIC , UpperCAmelCase__ : bool = True , UpperCAmelCase__ : Dict[str, int] = None , UpperCAmelCase__ : Union[int, float] = 1 / 255 , UpperCAmelCase__ : bool = True , UpperCAmelCase__ : bool = True , UpperCAmelCase__ : Optional[Union[float, List[float]]] = None , UpperCAmelCase__ : Optional[Union[float, List[float]]] = None , **UpperCAmelCase__ : str , ) -> None: super().__init__(**UpperCAmelCase__ ) _a : int = size if size is not None else {"""shortest_edge""": 224} _a : int = get_size_dict(UpperCAmelCase__ , default_to_square=UpperCAmelCase__ ) _a : str = crop_size if crop_size is not None else {"""height""": 224, """width""": 224} _a : int = get_size_dict(UpperCAmelCase__ , param_name="""crop_size""" ) _a : str = do_resize _a : Optional[int] = size _a : List[Any] = crop_pct _a : List[Any] = resample _a : Any = do_center_crop _a : List[str] = crop_size _a : Dict = do_rescale _a : Union[str, Any] = rescale_factor _a : List[str] = do_normalize _a : int = image_mean if image_mean is not None else IMAGENET_DEFAULT_MEAN _a : Optional[Any] = image_std if image_std is not None else IMAGENET_DEFAULT_STD def _lowercase ( self : List[Any] , UpperCAmelCase__ : np.ndarray , UpperCAmelCase__ : Dict[str, int] , UpperCAmelCase__ : Optional[float] = None , UpperCAmelCase__ : PILImageResampling = PILImageResampling.BICUBIC , UpperCAmelCase__ : Optional[Union[str, ChannelDimension]] = None , **UpperCAmelCase__ : List[Any] , ) -> np.ndarray: _a : int = get_size_dict(UpperCAmelCase__ , default_to_square=UpperCAmelCase__ ) if "shortest_edge" not in size and ("height" not in size or "width" not in size): raise ValueError(f"""size must contain 'height' and 'width' or 'shortest_edge' as keys. Got {size.keys()}""" ) if crop_pct is not None: if "shortest_edge" in size: _a : List[Any] = int(size["""shortest_edge"""] / crop_pct ) elif "height" in size and "width" in size: if size["height"] == size["width"]: _a : List[Any] = int(size["""height"""] / crop_pct ) else: _a : str = (int(size["""height"""] / crop_pct ), int(size["""width"""] / crop_pct )) else: raise ValueError("""Invalid size for resize: {}""".format(UpperCAmelCase__ ) ) _a : str = get_resize_output_image_size(UpperCAmelCase__ , size=UpperCAmelCase__ , default_to_square=UpperCAmelCase__ ) else: if "shortest_edge" in size: _a : str = get_resize_output_image_size(UpperCAmelCase__ , size=size["""shortest_edge"""] , default_to_square=UpperCAmelCase__ ) elif "height" in size and "width" in size: _a : Union[str, Any] = (size["""height"""], size["""width"""]) else: raise ValueError("""Invalid size for resize: {}""".format(UpperCAmelCase__ ) ) return resize(UpperCAmelCase__ , size=UpperCAmelCase__ , resample=UpperCAmelCase__ , data_format=UpperCAmelCase__ , **UpperCAmelCase__ ) def _lowercase ( self : Any , UpperCAmelCase__ : np.ndarray , UpperCAmelCase__ : Dict[str, int] , UpperCAmelCase__ : Optional[Union[str, ChannelDimension]] = None , **UpperCAmelCase__ : str , ) -> np.ndarray: _a : Optional[int] = get_size_dict(UpperCAmelCase__ ) if "height" not in size or "width" not in size: raise ValueError(f"""size must contain 'height' and 'width' as keys. Got {size.keys()}""" ) return center_crop(UpperCAmelCase__ , size=(size["""height"""], size["""width"""]) , data_format=UpperCAmelCase__ , **UpperCAmelCase__ ) def _lowercase ( self : Optional[int] , UpperCAmelCase__ : np.ndarray , UpperCAmelCase__ : Union[int, float] , UpperCAmelCase__ : Optional[Union[str, ChannelDimension]] = None , **UpperCAmelCase__ : Union[str, Any] , ) -> Union[str, Any]: return rescale(UpperCAmelCase__ , scale=UpperCAmelCase__ , data_format=UpperCAmelCase__ , **UpperCAmelCase__ ) def _lowercase ( self : Optional[int] , UpperCAmelCase__ : np.ndarray , UpperCAmelCase__ : Union[float, List[float]] , UpperCAmelCase__ : Union[float, List[float]] , UpperCAmelCase__ : Optional[Union[str, ChannelDimension]] = None , **UpperCAmelCase__ : Dict , ) -> np.ndarray: return normalize(UpperCAmelCase__ , mean=UpperCAmelCase__ , std=UpperCAmelCase__ , data_format=UpperCAmelCase__ , **UpperCAmelCase__ ) def _lowercase ( self : List[Any] , UpperCAmelCase__ : ImageInput , UpperCAmelCase__ : bool = None , UpperCAmelCase__ : Dict[str, int] = None , UpperCAmelCase__ : int = None , UpperCAmelCase__ : PILImageResampling = None , UpperCAmelCase__ : bool = None , UpperCAmelCase__ : Dict[str, int] = None , UpperCAmelCase__ : bool = None , UpperCAmelCase__ : float = None , UpperCAmelCase__ : bool = None , UpperCAmelCase__ : Optional[Union[float, List[float]]] = None , UpperCAmelCase__ : Optional[Union[float, List[float]]] = None , UpperCAmelCase__ : Optional[Union[str, TensorType]] = None , UpperCAmelCase__ : ChannelDimension = ChannelDimension.FIRST , **UpperCAmelCase__ : int , ) -> PIL.Image.Image: _a : int = do_resize if do_resize is not None else self.do_resize _a : Dict = crop_pct if crop_pct is not None else self.crop_pct _a : Any = resample if resample is not None else self.resample _a : Optional[Any] = do_center_crop if do_center_crop is not None else self.do_center_crop _a : Optional[int] = do_rescale if do_rescale is not None else self.do_rescale _a : List[Any] = rescale_factor if rescale_factor is not None else self.rescale_factor _a : Union[str, Any] = do_normalize if do_normalize is not None else self.do_normalize _a : Any = image_mean if image_mean is not None else self.image_mean _a : Tuple = image_std if image_std is not None else self.image_std _a : Optional[Any] = size if size is not None else self.size _a : Dict = get_size_dict(UpperCAmelCase__ , default_to_square=UpperCAmelCase__ ) _a : Any = crop_size if crop_size is not None else self.crop_size _a : List[Any] = get_size_dict(UpperCAmelCase__ , param_name="""crop_size""" ) _a : List[str] = make_list_of_images(UpperCAmelCase__ ) if not valid_images(UpperCAmelCase__ ): raise ValueError( """Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """ """torch.Tensor, tf.Tensor or jax.ndarray.""" ) if do_resize and size is None or resample is None: raise ValueError("""Size and resample must be specified if do_resize is True.""" ) if do_center_crop and crop_pct is None: raise ValueError("""Crop_pct must be specified if do_center_crop is True.""" ) if do_rescale and rescale_factor is None: raise ValueError("""Rescale factor must be specified if do_rescale is True.""" ) if do_normalize and (image_mean is None or image_std is None): raise ValueError("""Image mean and std must be specified if do_normalize is True.""" ) # All transformations expect numpy arrays. _a : Optional[Any] = [to_numpy_array(UpperCAmelCase__ ) for image in images] if do_resize: _a : int = [self.resize(image=UpperCAmelCase__ , size=UpperCAmelCase__ , crop_pct=UpperCAmelCase__ , resample=UpperCAmelCase__ ) for image in images] if do_center_crop: _a : List[Any] = [self.center_crop(image=UpperCAmelCase__ , size=UpperCAmelCase__ ) for image in images] if do_rescale: _a : Any = [self.rescale(image=UpperCAmelCase__ , scale=UpperCAmelCase__ ) for image in images] if do_normalize: _a : List[str] = [self.normalize(image=UpperCAmelCase__ , mean=UpperCAmelCase__ , std=UpperCAmelCase__ ) for image in images] _a : Union[str, Any] = [to_channel_dimension_format(UpperCAmelCase__ , UpperCAmelCase__ ) for image in images] _a : Union[str, Any] = {"""pixel_values""": images} return BatchFeature(data=UpperCAmelCase__ , tensor_type=UpperCAmelCase__ )
324
"""simple docstring""" _snake_case = 8.31_44_62 # Unit - J mol-1 K-1 def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' if moles < 0 or kelvin < 0 or volume < 0: raise ValueError("""Invalid inputs. Enter positive value.""" ) return moles * kelvin * UNIVERSAL_GAS_CONSTANT / volume def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' if moles < 0 or kelvin < 0 or pressure < 0: raise ValueError("""Invalid inputs. Enter positive value.""" ) return moles * kelvin * UNIVERSAL_GAS_CONSTANT / pressure if __name__ == "__main__": from doctest import testmod testmod()
324
1
"""simple docstring""" from __future__ import annotations import typing from collections.abc import Iterable import numpy as np _snake_case = typing.Union[Iterable[float], Iterable[int], np.ndarray] # noqa: UP007 _snake_case = typing.Union[np.floataa, int, float] # noqa: UP007 def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' return np.sqrt(np.sum((np.asarray(UpperCamelCase__ ) - np.asarray(UpperCamelCase__ )) ** 2 ) ) def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' return sum((va - va) ** 2 for va, va in zip(UpperCamelCase__ , UpperCamelCase__ ) ) ** (1 / 2) if __name__ == "__main__": def lowerCAmelCase__ ( ): '''simple docstring''' from timeit import timeit print("""Without Numpy""" ) print( timeit( """euclidean_distance_no_np([1, 2, 3], [4, 5, 6])""" , number=1_0_0_0_0 , globals=globals() , ) ) print("""With Numpy""" ) print( timeit( """euclidean_distance([1, 2, 3], [4, 5, 6])""" , number=1_0_0_0_0 , globals=globals() , ) ) benchmark()
324
"""simple docstring""" import argparse import dataclasses import json import logging import os import shutil from typing import List, Optional import datasets from accelerate import Accelerator from datasets import load_dataset from finetuning import finetune from tqdm.auto import tqdm import transformers from transformers import AutoConfig, set_seed from transformers.trainer_utils import IntervalStrategy _snake_case = logging.getLogger(__name__) _snake_case = 'pytorch_model.bin' @dataclasses.dataclass class UpperCamelCase : UpperCamelCase : str = dataclasses.field( metadata={'''help''': '''Path to pretrained model or model identifier from huggingface.co/models.'''} ) UpperCamelCase : Optional[str] = dataclasses.field( default=snake_case_ , metadata={'''help''': '''Where do you want to store the pretrained models downloaded from huggingface.co.'''} , ) @dataclasses.dataclass class UpperCamelCase : UpperCamelCase : str = dataclasses.field(metadata={'''help''': '''A csv or a json file containing the training data.'''} ) UpperCamelCase : str = dataclasses.field(metadata={'''help''': '''A csv or a json file containing the data to predict on.'''} ) UpperCamelCase : Optional[str] = dataclasses.field( default=snake_case_ , metadata={'''help''': '''A csv or a json file containing the validation data.'''} ) UpperCamelCase : Optional[str] = dataclasses.field( default=snake_case_ , metadata={'''help''': '''The name of the task to train on.'''} , ) UpperCamelCase : Optional[List[str]] = dataclasses.field( default=snake_case_ , metadata={'''help''': '''The list of labels for the task.'''} ) @dataclasses.dataclass class UpperCamelCase : UpperCamelCase : str = dataclasses.field( metadata={'''help''': '''The output directory where the model predictions and checkpoints will be written.'''} ) UpperCamelCase : Optional[str] = dataclasses.field( default='''accuracy''' , metadata={'''help''': '''The evaluation metric used for the task.'''} ) UpperCamelCase : Optional[str] = dataclasses.field( default='''no''' , metadata={ '''help''': '''The evaluation strategy to adopt during training. Possible values are: ["no", "step", "epoch]''' } , ) UpperCamelCase : Optional[int] = dataclasses.field( default=10 , metadata={'''help''': '''Number of evaluation calls with no improvement after which training will be stopped.'''} , ) UpperCamelCase : Optional[float] = dataclasses.field( default=0.0 , metadata={ '''help''': '''How much the specified evaluation metric must improve to satisfy early stopping conditions.''' } , ) UpperCamelCase : Optional[bool] = dataclasses.field( default=snake_case_ , metadata={'''help''': '''Whether to filter the pseudo-labeled data based on the confidence score.'''} , ) UpperCamelCase : Optional[bool] = dataclasses.field( default=snake_case_ , metadata={'''help''': '''Whether to filter the pseudo-labeled data based on the validation performance.'''} , ) UpperCamelCase : Optional[bool] = dataclasses.field( default=snake_case_ , metadata={'''help''': '''Whether to fine-tune on labeled data after pseudo training.'''} , ) UpperCamelCase : Optional[float] = dataclasses.field( default=0.0 , metadata={'''help''': '''Confidence threshold for pseudo-labeled data filtering.'''} , ) UpperCamelCase : Optional[int] = dataclasses.field( default=100 , metadata={'''help''': '''Number of evaluation calls with no improvement after which training will be stopped.'''} , ) UpperCamelCase : Optional[int] = dataclasses.field( default=snake_case_ , metadata={'''help''': '''Random seed for initialization.'''} , ) def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' _a : Optional[int] = datasets.concatenate_datasets([infer_input, infer_output] , axis=1 ) if args.do_filter_by_confidence: _a : Union[str, Any] = dataset.filter(lambda UpperCamelCase__ : example["probability"] > args.confidence_threshold ) if args.do_filter_by_val_performance: assert eval_result >= 0.0 and eval_result <= 1.0 _a : Any = int(eval_result * len(UpperCamelCase__ ) ) print(UpperCamelCase__ ) _a : str = dataset.sort("""probability""" , reverse=UpperCamelCase__ ) _a : Any = dataset.select(range(UpperCamelCase__ ) ) _a : Tuple = dataset.remove_columns(["""label""", """probability"""] ) _a : Optional[Any] = dataset.rename_column("""prediction""" , """label""" ) _a : Dict = dataset.map(lambda UpperCamelCase__ : {"label": idalabel[example["label"]]} ) _a : Union[str, Any] = dataset.shuffle(seed=args.seed ) _a : Optional[int] = os.path.join(UpperCamelCase__ , F"""train_pseudo.{args.data_file_extension}""" ) if args.data_file_extension == "csv": dataset.to_csv(UpperCamelCase__ , index=UpperCamelCase__ ) else: dataset.to_json(UpperCamelCase__ ) def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , **UpperCamelCase__ ): '''simple docstring''' _a : Optional[int] = Accelerator() # Make one log on every process with the configuration for debugging. logging.basicConfig( format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""" , datefmt="""%m/%d/%Y %H:%M:%S""" , level=logging.INFO , ) logger.info(accelerator.state ) # Setup logging, we only want one process per machine to log things on the # screen. accelerator.is_local_main_process is only True for one process per # machine. logger.setLevel(logging.INFO if accelerator.is_local_main_process else logging.ERROR ) if accelerator.is_local_main_process: datasets.utils.logging.set_verbosity_warning() transformers.utils.logging.set_verbosity_info() else: datasets.utils.logging.set_verbosity_error() transformers.utils.logging.set_verbosity_error() _a : Dict = STModelArguments(model_name_or_path=UpperCamelCase__ ) _a : Union[str, Any] = STDataArguments(train_file=UpperCamelCase__ , infer_file=UpperCamelCase__ ) _a : Any = STTrainingArguments(output_dir=UpperCamelCase__ ) _a : Any = argparse.Namespace() for arg_class in (model_args, data_args, training_args): for key, value in vars(UpperCamelCase__ ).items(): setattr(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) for key, value in kwargs.items(): if hasattr(UpperCamelCase__ , UpperCamelCase__ ): setattr(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) # Sanity checks _a : Union[str, Any] = {} _a : Tuple = None # You need to provide the training data and the data to predict on assert args.train_file is not None assert args.infer_file is not None _a : int = args.train_file _a : List[Any] = args.infer_file if args.evaluation_strategy != IntervalStrategy.NO.value: assert args.eval_file is not None _a : Union[str, Any] = args.eval_file for key in data_files: _a : Optional[Any] = data_files[key].split(""".""" )[-1] assert extension in ["csv", "json"], F"""`{key}_file` should be a csv or a json file.""" if args.data_file_extension is None: _a : str = extension else: assert extension == args.data_file_extension, F"""`{key}_file` should be a {args.data_file_extension} file`.""" assert ( args.eval_metric in datasets.list_metrics() ), F"""{args.eval_metric} not in the list of supported metrics {datasets.list_metrics()}.""" # If passed along, set the training seed now. if args.seed is not None: set_seed(args.seed ) logger.info("""Creating the initial data directory for self-training...""" ) _a : Tuple = F"""{args.output_dir}/self-train_iter-{{}}""".format _a : Dict = data_dir_format(0 ) if accelerator.is_main_process: if args.output_dir is not None: os.makedirs(args.output_dir , exist_ok=UpperCamelCase__ ) os.makedirs(UpperCamelCase__ , exist_ok=UpperCamelCase__ ) accelerator.wait_for_everyone() _a : str = None _a : int = None _a : str = 0 _a : List[Any] = False # Show the progress bar _a : List[Any] = tqdm(range(args.max_selftrain_iterations ) , disable=not accelerator.is_local_main_process ) # Self-train for iteration in range(0 , int(args.max_selftrain_iterations ) ): _a : Union[str, Any] = data_dir_format(UpperCamelCase__ ) assert os.path.exists(UpperCamelCase__ ) # Stage 1: initial fine-tuning for iteration = 0 or pseudo-training for # iteration > 0 _a : str = os.path.join(UpperCamelCase__ , """stage-1""" ) _a : Tuple = { """accelerator""": accelerator, """model_name_or_path""": args.model_name_or_path, """cache_dir""": args.cache_dir, """do_train""": True, """train_file""": data_files["""train"""] if iteration == 0 else data_files["""train_pseudo"""], """do_eval""": True if args.eval_file is not None else False, """eval_file""": data_files["""eval"""], """do_predict""": True, """infer_file""": data_files["""infer"""], """task_name""": args.task_name, """label_list""": args.label_list, """output_dir""": current_output_dir, """eval_metric""": args.eval_metric, """evaluation_strategy""": args.evaluation_strategy, """early_stopping_patience""": args.early_stopping_patience, """early_stopping_threshold""": args.early_stopping_threshold, """seed""": args.seed, } # Add additional training arguments for key, value in kwargs.items(): if key not in arguments_dict and not hasattr(UpperCamelCase__ , UpperCamelCase__ ): arguments_dict.update({key: value} ) _a : int = os.path.join(UpperCamelCase__ , """best-checkpoint""" , UpperCamelCase__ ) if os.path.exists(UpperCamelCase__ ): logger.info( """Found existing model checkpoint at %s. Skipping self-training: iteration: %d, stage: 1.""" , UpperCamelCase__ , UpperCamelCase__ , ) else: logger.info("""***** Running self-training: iteration: %d, stage: 1 *****""" , UpperCamelCase__ ) finetune(**UpperCamelCase__ ) accelerator.wait_for_everyone() assert os.path.exists(UpperCamelCase__ ) logger.info("""Self-training job completed: iteration: %d, stage: 1.""" , UpperCamelCase__ ) if iteration > 0 and args.finetune_on_labeled_data: # Stage 2 (optional): fine-tuning on the original labeled data _a : Dict = os.path.join(UpperCamelCase__ , """best-checkpoint""" ) _a : List[str] = os.path.join(UpperCamelCase__ , """stage-2""" ) # Update arguments_dict _a : int = model_path _a : Dict = data_files["""train"""] _a : int = current_output_dir _a : Any = os.path.join(UpperCamelCase__ , """best-checkpoint""" , UpperCamelCase__ ) if os.path.exists(UpperCamelCase__ ): logger.info( """Found existing model checkpoint at %s. Skipping self-training: iteration: %d, stage: 2.""" , UpperCamelCase__ , UpperCamelCase__ , ) else: logger.info("""***** Running self-training: iteration: %d, stage: 2 *****""" , UpperCamelCase__ ) finetune(**UpperCamelCase__ ) accelerator.wait_for_everyone() assert os.path.exists(UpperCamelCase__ ) logger.info("""Self-training job completed: iteration: %d, stage: 2.""" , UpperCamelCase__ ) _a : List[Any] = iteration _a : int = data_dir_format(iteration + 1 ) _a : Dict = AutoConfig.from_pretrained(os.path.join(UpperCamelCase__ , """best-checkpoint""" ) ) _a : Union[str, Any] = config.idalabel _a : Any = os.path.join(UpperCamelCase__ , """eval_results_best-checkpoint.json""" ) _a : Any = os.path.join(UpperCamelCase__ , """test_results_best-checkpoint.json""" ) assert os.path.exists(UpperCamelCase__ ) with open(UpperCamelCase__ , """r""" ) as f: _a : Tuple = float(json.load(UpperCamelCase__ )[args.eval_metric] ) _a : Dict = os.path.join(UpperCamelCase__ , """infer_output_best-checkpoint.csv""" ) assert os.path.exists(UpperCamelCase__ ) # Loading the dataset from local csv or json files. _a : List[Any] = load_dataset(args.data_file_extension , data_files={"""data""": data_files["""infer"""]} )["""data"""] _a : Any = load_dataset("""csv""" , data_files={"""data""": infer_output_file} )["""data"""] if accelerator.is_main_process: os.makedirs(UpperCamelCase__ , exist_ok=UpperCamelCase__ ) shutil.copy(UpperCamelCase__ , os.path.join(UpperCamelCase__ , F"""eval_results_iter-{iteration}.json""" ) ) if os.path.exists(UpperCamelCase__ ): shutil.copy(UpperCamelCase__ , os.path.join(UpperCamelCase__ , F"""test_results_iter-{iteration}.json""" ) ) create_pseudo_labeled_data(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) accelerator.wait_for_everyone() _a : List[str] = os.path.join(UpperCamelCase__ , F"""train_pseudo.{args.data_file_extension}""" ) if args.evaluation_strategy != IntervalStrategy.NO.value: _a : Any = eval_result if best_iteration is None: _a : Union[str, Any] = new_iteration _a : str = new_eval_result else: if new_eval_result - best_eval_result > args.early_stopping_threshold: _a : Union[str, Any] = new_iteration _a : List[str] = new_eval_result _a : Optional[Any] = 0 else: if new_eval_result == best_eval_result: _a : Tuple = new_iteration _a : List[Any] = new_eval_result early_stopping_patience_counter += 1 if early_stopping_patience_counter >= args.early_stopping_patience: _a : Union[str, Any] = True progress_bar.update(1 ) if should_training_stop: break if best_iteration is not None: # Save the best iteration logger.info("""Best iteration: %d""" , UpperCamelCase__ ) logger.info("""Best evaluation result: %s = %f""" , args.eval_metric , UpperCamelCase__ ) accelerator.wait_for_everyone() if accelerator.is_main_process: shutil.copy( os.path.join(UpperCamelCase__ , F"""eval_results_iter-{iteration}.json""" ) , os.path.join(UpperCamelCase__ , """eval_results_best-iteration.json""" ) , ) else: # Assume that the last iteration is the best logger.info("""Best iteration: %d""" , args.max_selftrain_iterations - 1 ) logger.info("""Best evaluation result: %s = %f""" , args.eval_metric , UpperCamelCase__ ) accelerator.wait_for_everyone() if accelerator.is_main_process: shutil.copy( os.path.join(UpperCamelCase__ , F"""eval_results_iter-{args.max_selftrain_iterations - 1}.json""" ) , os.path.join(UpperCamelCase__ , """eval_results_best-iteration.json""" ) , )
324
1
"""simple docstring""" from sklearn.metrics import matthews_corrcoef import datasets _snake_case = '\nCompute the Matthews correlation coefficient (MCC)\n\nThe Matthews correlation coefficient is used in machine learning as a\nmeasure of the quality of binary and multiclass classifications. It takes\ninto account true and false positives and negatives and is generally\nregarded as a balanced measure which can be used even if the classes are of\nvery different sizes. The MCC is in essence a correlation coefficient value\nbetween -1 and +1. A coefficient of +1 represents a perfect prediction, 0\nan average random prediction and -1 an inverse prediction. The statistic\nis also known as the phi coefficient. [source: Wikipedia]\n' _snake_case = '\nArgs:\n predictions (list of int): Predicted labels, as returned by a model.\n references (list of int): Ground truth labels.\n sample_weight (list of int, float, or bool): Sample weights. Defaults to `None`.\nReturns:\n matthews_correlation (dict containing float): Matthews correlation.\nExamples:\n Example 1, a basic example with only predictions and references as inputs:\n >>> matthews_metric = datasets.load_metric("matthews_correlation")\n >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2],\n ... predictions=[1, 2, 2, 0, 3, 3])\n >>> print(round(results[\'matthews_correlation\'], 2))\n 0.54\n\n Example 2, the same example as above, but also including sample weights:\n >>> matthews_metric = datasets.load_metric("matthews_correlation")\n >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2],\n ... predictions=[1, 2, 2, 0, 3, 3],\n ... sample_weight=[0.5, 3, 1, 1, 1, 2])\n >>> print(round(results[\'matthews_correlation\'], 2))\n 0.1\n\n Example 3, the same example as above, but with sample weights that cause a negative correlation:\n >>> matthews_metric = datasets.load_metric("matthews_correlation")\n >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2],\n ... predictions=[1, 2, 2, 0, 3, 3],\n ... sample_weight=[0.5, 1, 0, 0, 0, 1])\n >>> print(round(results[\'matthews_correlation\'], 2))\n -0.25\n' _snake_case = '\\n@article{scikit-learn,\n title={Scikit-learn: Machine Learning in {P}ython},\n author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V.\n and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P.\n and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and\n Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.},\n journal={Journal of Machine Learning Research},\n volume={12},\n pages={2825--2830},\n year={2011}\n}\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class UpperCamelCase ( datasets.Metric ): def _lowercase ( self : Tuple ) -> List[Any]: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": datasets.Value("""int32""" ), """references""": datasets.Value("""int32""" ), } ) , reference_urls=[ """https://scikit-learn.org/stable/modules/generated/sklearn.metrics.matthews_corrcoef.html""" ] , ) def _lowercase ( self : str , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : List[Any]=None ) -> Optional[int]: return { "matthews_correlation": float(matthews_corrcoef(UpperCAmelCase__ , UpperCAmelCase__ , sample_weight=UpperCAmelCase__ ) ), }
324
"""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_camembert import CamembertTokenizer else: _snake_case = None _snake_case = logging.get_logger(__name__) _snake_case = {'vocab_file': 'sentencepiece.bpe.model', 'tokenizer_file': 'tokenizer.json'} _snake_case = { 'vocab_file': { 'camembert-base': 'https://huggingface.co/camembert-base/resolve/main/sentencepiece.bpe.model', }, 'tokenizer_file': { 'camembert-base': 'https://huggingface.co/camembert-base/resolve/main/tokenizer.json', }, } _snake_case = { 'camembert-base': 512, } _snake_case = '▁' class UpperCamelCase ( snake_case_ ): UpperCamelCase : Any = VOCAB_FILES_NAMES UpperCamelCase : Union[str, Any] = PRETRAINED_VOCAB_FILES_MAP UpperCamelCase : Union[str, Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCamelCase : Dict = ['''input_ids''', '''attention_mask'''] UpperCamelCase : Optional[Any] = CamembertTokenizer def __init__( self : int , UpperCAmelCase__ : List[Any]=None , UpperCAmelCase__ : Optional[int]=None , UpperCAmelCase__ : Optional[Any]="<s>" , UpperCAmelCase__ : Optional[int]="</s>" , UpperCAmelCase__ : Tuple="</s>" , UpperCAmelCase__ : Tuple="<s>" , UpperCAmelCase__ : Tuple="<unk>" , UpperCAmelCase__ : Tuple="<pad>" , UpperCAmelCase__ : int="<mask>" , UpperCAmelCase__ : Optional[int]=["<s>NOTUSED", "</s>NOTUSED"] , **UpperCAmelCase__ : Optional[Any] , ) -> Union[str, Any]: # Mask token behave like a normal word, i.e. include the space before it _a : List[Any] = AddedToken(UpperCAmelCase__ , lstrip=UpperCAmelCase__ , rstrip=UpperCAmelCase__ ) if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ) else mask_token super().__init__( UpperCAmelCase__ , tokenizer_file=UpperCAmelCase__ , bos_token=UpperCAmelCase__ , eos_token=UpperCAmelCase__ , sep_token=UpperCAmelCase__ , cls_token=UpperCAmelCase__ , unk_token=UpperCAmelCase__ , pad_token=UpperCAmelCase__ , mask_token=UpperCAmelCase__ , additional_special_tokens=UpperCAmelCase__ , **UpperCAmelCase__ , ) _a : int = vocab_file _a : int = False if not self.vocab_file else True def _lowercase ( self : Union[str, Any] , 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] _a : List[Any] = [self.cls_token_id] _a : Dict = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def _lowercase ( self : Optional[int] , UpperCAmelCase__ : List[int] , UpperCAmelCase__ : Optional[List[int]] = None ) -> List[int]: _a : Union[str, Any] = [self.sep_token_id] _a : 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 _lowercase ( self : Optional[int] , UpperCAmelCase__ : str , UpperCAmelCase__ : Optional[str] = None ) -> Tuple[str]: 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(UpperCAmelCase__ ): logger.error(f"""Vocabulary path ({save_directory}) should be a directory""" ) return _a : List[str] = 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,)
324
1
"""simple docstring""" import argparse import logging import os import datasets import tensorflow as tf from transformers import AutoTokenizer _snake_case = logging.getLogger(__name__) def lowerCAmelCase__ ( ): '''simple docstring''' _a : int = argparse.ArgumentParser( description="""Prepare TFRecord shards from pre-tokenized samples of the wikitext dataset.""" ) parser.add_argument( """--dataset_name""" , type=UpperCamelCase__ , default="""wikitext""" , help="""Name of the training. Explore datasets at: hf.co/datasets.""" , ) parser.add_argument( """--dataset_config""" , type=UpperCamelCase__ , default="""wikitext-103-raw-v1""" , help="""Configuration name of the dataset.""" ) parser.add_argument( """--tokenizer_name_or_path""" , type=UpperCamelCase__ , default="""sayakpaul/unigram-tokenizer-wikitext""" , help="""Tokenizer identifier. Can be a local filepath or a Hub identifier.""" , ) parser.add_argument( """--shard_size""" , type=UpperCamelCase__ , default=1_0_0_0 , help="""Number of entries to go in a single shard.""" , ) parser.add_argument("""--split""" , type=UpperCamelCase__ , default="""train""" , choices=["""train""", """test""", """validation"""] ) parser.add_argument( """--limit""" , default=UpperCamelCase__ , type=UpperCamelCase__ , help="""Limit the number of shards (used for debugging).""" , ) parser.add_argument( """--max_length""" , type=UpperCamelCase__ , default=5_1_2 , help="""Maximum sequence length. For training on TPUs, it helps to have a maximum""" """ sequence length that is a multiple of 8.""" , ) parser.add_argument( """--output_dir""" , default="""tf-tpu""" , type=UpperCamelCase__ , help="""Output directory where the TFRecord shards will be saved. If the""" """ path is appended with `gs://` ('gs://tf-tpu', for example) then the TFRecord""" """ shards will be directly saved to a Google Cloud Storage bucket.""" , ) _a : List[str] = parser.parse_args() return args def lowerCAmelCase__ ( UpperCamelCase__ ): '''simple docstring''' def fn(UpperCamelCase__ ): return tokenizer(examples["""text"""] ) return fn def lowerCAmelCase__ ( UpperCamelCase__ ): '''simple docstring''' _a : str = [] for i in range(len(tokenized_data["""input_ids"""] ) ): _a : List[Any] = { """input_ids""": tf.train.Feature(intaa_list=tf.train.IntaaList(value=tokenized_data["""input_ids"""][i] ) ), """attention_mask""": tf.train.Feature( intaa_list=tf.train.IntaaList(value=tokenized_data["""attention_mask"""][i] ) ), } _a : str = tf.train.Features(feature=UpperCamelCase__ ) _a : List[Any] = tf.train.Example(features=UpperCamelCase__ ) _a : List[Any] = example.SerializeToString() records.append(UpperCamelCase__ ) return records def lowerCAmelCase__ ( UpperCamelCase__ ): '''simple docstring''' _a : Union[str, Any] = datasets.load_dataset(args.dataset_name , args.dataset_config , split=args.split ) if args.limit is not None: _a : List[str] = min(len(UpperCamelCase__ ) , args.limit ) _a : Optional[int] = dataset.select(range(UpperCamelCase__ ) ) print(F"""Limiting the dataset to {args.limit} entries.""" ) _a : Optional[Any] = AutoTokenizer.from_pretrained(args.tokenizer_name_or_path ) # Handle output directory creation. # For serializing into a Google Cloud Storage Bucket, one needs to first # create a bucket. if "gs" not in args.output_dir: if not os.path.exists(args.output_dir ): os.makedirs(args.output_dir ) _a : Optional[Any] = os.path.join(args.output_dir , args.split ) if not os.path.exists(UpperCamelCase__ ): os.makedirs(UpperCamelCase__ ) else: _a : Optional[int] = os.path.join(args.output_dir , args.split ) # Tokenize the whole dataset at once. _a : Optional[Any] = tokenize_function(UpperCamelCase__ ) _a : List[str] = dataset.map(UpperCamelCase__ , batched=UpperCamelCase__ , num_proc=4 , remove_columns=["""text"""] ) # We need to concatenate all our texts together, and then split the result # into chunks of a fixed size, which we will call block_size. To do this, we # will use the map method again, with the option batched=True. When we use batched=True, # the function we pass to map() will be passed multiple inputs at once, allowing us # to group them into more or fewer examples than we had in the input. # This allows us to create our new fixed-length samples. The advantage of this # method is that we don't lose a whole lot of content from the dataset compared to the # case where we simply tokenize with a pre-defined max_length. def group_texts(UpperCamelCase__ ): # Concatenate all texts. _a : Dict = {k: sum(examples[k] , [] ) for k in examples.keys()} _a : str = len(concatenated_examples[list(examples.keys() )[0]] ) # We drop the small remainder, though you could add padding instead if the model supports it # In this, as in all things, we advise you to follow your heart 🫀 _a : Dict = (total_length // args.max_length) * args.max_length # Split by chunks of max_len. _a : Optional[int] = { k: [t[i : i + args.max_length] for i in range(0 , UpperCamelCase__ , args.max_length )] for k, t in concatenated_examples.items() } return result _a : List[Any] = dataset_tokenized.map(UpperCamelCase__ , batched=UpperCamelCase__ , batch_size=1_0_0_0 , num_proc=4 ) _a : Any = 0 _a : Union[str, Any] = 0 for shard in range(0 , len(UpperCamelCase__ ) , args.shard_size ): _a : Optional[int] = grouped_dataset[shard : shard + args.shard_size] _a : int = len(dataset_snapshot["""input_ids"""] ) _a : Union[str, Any] = os.path.join(UpperCamelCase__ , F"""dataset-{shard_count}-{records_containing}.tfrecord""" ) _a : str = get_serialized_examples(UpperCamelCase__ ) with tf.io.TFRecordWriter(UpperCamelCase__ ) as out_file: for i in range(len(UpperCamelCase__ ) ): _a : Any = serialized_examples[i] out_file.write(UpperCamelCase__ ) print("""Wrote file {} containing {} records""".format(UpperCamelCase__ , UpperCamelCase__ ) ) shard_count += 1 total_records += records_containing with open(F"""split-{args.split}-records-count.txt""" , """w""" ) as f: print(F"""Total {args.split} records: {total_records}""" , file=UpperCamelCase__ ) if __name__ == "__main__": _snake_case = parse_args() main(args)
324
"""simple docstring""" from typing import List, Optional, Union import numpy as np import PIL.Image from ...image_processing_utils import BaseImageProcessor, BatchFeature from ...image_transforms import rescale, resize, to_channel_dimension_format from ...image_utils import ( ChannelDimension, PILImageResampling, get_image_size, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, logging _snake_case = logging.get_logger(__name__) class UpperCamelCase ( snake_case_ ): UpperCamelCase : Dict = ['''pixel_values'''] def __init__( self : Any , UpperCAmelCase__ : bool = True , UpperCAmelCase__ : int = 32 , UpperCAmelCase__ : Optional[Any]=PILImageResampling.BILINEAR , UpperCAmelCase__ : bool = True , **UpperCAmelCase__ : List[str] , ) -> None: _a : int = do_resize _a : Union[str, Any] = do_rescale _a : Any = size_divisor _a : Any = resample super().__init__(**UpperCAmelCase__ ) def _lowercase ( self : Tuple , UpperCAmelCase__ : np.ndarray , UpperCAmelCase__ : int , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Optional[ChannelDimension] = None , **UpperCAmelCase__ : Optional[Any] ) -> np.ndarray: _a , _a : Tuple = get_image_size(UpperCAmelCase__ ) # Rounds the height and width down to the closest multiple of size_divisor _a : Optional[Any] = height // size_divisor * size_divisor _a : Union[str, Any] = width // size_divisor * size_divisor _a : Any = resize(UpperCAmelCase__ , (new_h, new_w) , resample=UpperCAmelCase__ , data_format=UpperCAmelCase__ , **UpperCAmelCase__ ) return image def _lowercase ( self : Union[str, Any] , UpperCAmelCase__ : np.ndarray , UpperCAmelCase__ : float , UpperCAmelCase__ : Optional[ChannelDimension] = None , **UpperCAmelCase__ : Optional[int] ) -> np.ndarray: return rescale(image=UpperCAmelCase__ , scale=UpperCAmelCase__ , data_format=UpperCAmelCase__ , **UpperCAmelCase__ ) def _lowercase ( self : Optional[int] , UpperCAmelCase__ : Union["PIL.Image.Image", TensorType, List["PIL.Image.Image"], List[TensorType]] , UpperCAmelCase__ : Optional[bool] = None , UpperCAmelCase__ : Optional[int] = None , UpperCAmelCase__ : int=None , UpperCAmelCase__ : Optional[bool] = None , UpperCAmelCase__ : Optional[Union[TensorType, str]] = None , UpperCAmelCase__ : ChannelDimension = ChannelDimension.FIRST , **UpperCAmelCase__ : int , ) -> BatchFeature: _a : Dict = do_resize if do_resize is not None else self.do_resize _a : Optional[int] = do_rescale if do_rescale is not None else self.do_rescale _a : str = size_divisor if size_divisor is not None else self.size_divisor _a : Any = resample if resample is not None else self.resample if do_resize and size_divisor is None: raise ValueError("""size_divisor is required for resizing""" ) _a : List[str] = make_list_of_images(UpperCAmelCase__ ) if not valid_images(UpperCAmelCase__ ): raise ValueError("""Invalid image(s)""" ) # All transformations expect numpy arrays. _a : Tuple = [to_numpy_array(UpperCAmelCase__ ) for img in images] if do_resize: _a : Optional[int] = [self.resize(UpperCAmelCase__ , size_divisor=UpperCAmelCase__ , resample=UpperCAmelCase__ ) for image in images] if do_rescale: _a : str = [self.rescale(UpperCAmelCase__ , scale=1 / 255 ) for image in images] _a : Any = [to_channel_dimension_format(UpperCAmelCase__ , UpperCAmelCase__ ) for image in images] _a : Optional[int] = {"""pixel_values""": images} return BatchFeature(data=UpperCAmelCase__ , tensor_type=UpperCAmelCase__ )
324
1
"""simple docstring""" import os from huggingface_hub.constants import HUGGINGFACE_HUB_CACHE, hf_cache_home _snake_case = HUGGINGFACE_HUB_CACHE _snake_case = 'config.json' _snake_case = 'diffusion_pytorch_model.bin' _snake_case = 'diffusion_flax_model.msgpack' _snake_case = 'model.onnx' _snake_case = 'diffusion_pytorch_model.safetensors' _snake_case = 'weights.pb' _snake_case = 'https://huggingface.co' _snake_case = default_cache_path _snake_case = 'diffusers_modules' _snake_case = os.getenv('HF_MODULES_CACHE', os.path.join(hf_cache_home, 'modules')) _snake_case = ['fp16', 'non-ema'] _snake_case = '.self_attn'
324
"""simple docstring""" 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 ): @property def _lowercase ( self : Optional[int] ) -> Union[str, Any]: torch.manual_seed(0 ) _a : List[str] = 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 _lowercase ( self : Dict ) -> Dict: _a : str = self.dummy_uncond_unet _a : Optional[int] = KarrasVeScheduler() _a : List[str] = KarrasVePipeline(unet=UpperCAmelCase__ , scheduler=UpperCAmelCase__ ) pipe.to(UpperCAmelCase__ ) pipe.set_progress_bar_config(disable=UpperCAmelCase__ ) _a : int = torch.manual_seed(0 ) _a : List[Any] = pipe(num_inference_steps=2 , generator=UpperCAmelCase__ , output_type="""numpy""" ).images _a : Tuple = torch.manual_seed(0 ) _a : int = pipe(num_inference_steps=2 , generator=UpperCAmelCase__ , output_type="""numpy""" , return_dict=UpperCAmelCase__ )[0] _a : int = image[0, -3:, -3:, -1] _a : Optional[int] = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) _a : str = 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 ): def _lowercase ( self : Tuple ) -> List[str]: _a : Optional[Any] = """google/ncsnpp-celebahq-256""" _a : Any = UNetaDModel.from_pretrained(UpperCAmelCase__ ) _a : Dict = KarrasVeScheduler() _a : int = KarrasVePipeline(unet=UpperCAmelCase__ , scheduler=UpperCAmelCase__ ) pipe.to(UpperCAmelCase__ ) pipe.set_progress_bar_config(disable=UpperCAmelCase__ ) _a : Optional[int] = torch.manual_seed(0 ) _a : Tuple = pipe(num_inference_steps=20 , generator=UpperCAmelCase__ , output_type="""numpy""" ).images _a : List[str] = image[0, -3:, -3:, -1] assert image.shape == (1, 256, 256, 3) _a : Optional[int] = np.array([0.5_7_8, 0.5_8_1_1, 0.5_9_2_4, 0.5_8_0_9, 0.5_8_7, 0.5_8_8_6, 0.5_8_6_1, 0.5_8_0_2, 0.5_8_6] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
324
1
"""simple docstring""" from typing import Optional import numpy as np import torch from torch import nn from transformers import GPTaConfig, GPTaLMHeadModel from transformers.modeling_utils import ModuleUtilsMixin from ...configuration_utils import ConfigMixin, register_to_config from ...models import ModelMixin class UpperCamelCase ( snake_case_ , snake_case_ , snake_case_ ): UpperCamelCase : List[Any] = [R'''h\.\d+\.attn\.bias''', R'''h\.\d+\.attn\.masked_bias'''] @register_to_config def __init__( self : Tuple , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : Optional[int] = None , UpperCAmelCase__ : int = 50257 , UpperCAmelCase__ : int = 1024 , UpperCAmelCase__ : int = 768 , UpperCAmelCase__ : int = 12 , UpperCAmelCase__ : int = 12 , UpperCAmelCase__ : Optional[int] = None , UpperCAmelCase__ : str = "gelu_new" , UpperCAmelCase__ : float = 0.1 , UpperCAmelCase__ : float = 0.1 , UpperCAmelCase__ : float = 0.1 , UpperCAmelCase__ : float = 1E-5 , UpperCAmelCase__ : float = 0.0_2 , UpperCAmelCase__ : bool = True , UpperCAmelCase__ : bool = True , UpperCAmelCase__ : bool = False , UpperCAmelCase__ : bool = False , ) -> List[Any]: super().__init__() _a : Any = prefix_length if prefix_inner_dim != n_embd and prefix_hidden_dim is None: raise ValueError( f"""`prefix_hidden_dim` cannot be `None` when `prefix_inner_dim`: {prefix_hidden_dim} and""" f""" `n_embd`: {n_embd} are not equal.""" ) _a : str = prefix_inner_dim _a : int = prefix_hidden_dim _a : int = ( nn.Linear(self.prefix_inner_dim , self.prefix_hidden_dim ) if self.prefix_hidden_dim is not None else nn.Identity() ) _a : List[str] = ( nn.Linear(self.prefix_hidden_dim , UpperCAmelCase__ ) if self.prefix_hidden_dim is not None else nn.Identity() ) _a : Dict = GPTaConfig( vocab_size=UpperCAmelCase__ , n_positions=UpperCAmelCase__ , n_embd=UpperCAmelCase__ , n_layer=UpperCAmelCase__ , n_head=UpperCAmelCase__ , n_inner=UpperCAmelCase__ , activation_function=UpperCAmelCase__ , resid_pdrop=UpperCAmelCase__ , embd_pdrop=UpperCAmelCase__ , attn_pdrop=UpperCAmelCase__ , layer_norm_epsilon=UpperCAmelCase__ , initializer_range=UpperCAmelCase__ , scale_attn_weights=UpperCAmelCase__ , use_cache=UpperCAmelCase__ , scale_attn_by_inverse_layer_idx=UpperCAmelCase__ , reorder_and_upcast_attn=UpperCAmelCase__ , ) _a : Optional[Any] = GPTaLMHeadModel(UpperCAmelCase__ ) def _lowercase ( self : str , UpperCAmelCase__ : torch.Tensor , UpperCAmelCase__ : torch.Tensor , UpperCAmelCase__ : Optional[torch.Tensor] = None , UpperCAmelCase__ : Optional[torch.Tensor] = None , ) -> Tuple: _a : Union[str, Any] = self.transformer.transformer.wte(UpperCAmelCase__ ) _a : List[Any] = self.encode_prefix(UpperCAmelCase__ ) _a : Dict = self.decode_prefix(UpperCAmelCase__ ) _a : int = torch.cat((prefix_embeds, embedding_text) , dim=1 ) if labels is not None: _a : Optional[Any] = self.get_dummy_token(input_ids.shape[0] , input_ids.device ) _a : Any = torch.cat((dummy_token, input_ids) , dim=1 ) _a : Union[str, Any] = self.transformer(inputs_embeds=UpperCAmelCase__ , labels=UpperCAmelCase__ , attention_mask=UpperCAmelCase__ ) if self.prefix_hidden_dim is not None: return out, hidden else: return out def _lowercase ( self : Tuple , UpperCAmelCase__ : int , UpperCAmelCase__ : torch.device ) -> torch.Tensor: return torch.zeros(UpperCAmelCase__ , self.prefix_length , dtype=torch.intaa , device=UpperCAmelCase__ ) def _lowercase ( self : List[str] , UpperCAmelCase__ : List[str] ) -> Optional[Any]: return self.encode_prefix(UpperCAmelCase__ ) @torch.no_grad() def _lowercase ( self : Optional[Any] , UpperCAmelCase__ : str , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : Optional[Any] ) -> Dict: _a : Dict = torch.split(UpperCAmelCase__ , 1 , dim=0 ) _a : Dict = [] _a : Optional[int] = [] for feature in features: _a : List[str] = self.decode_prefix(feature.to(UpperCAmelCase__ ) ) # back to the clip feature # Only support beam search for now _a , _a : Optional[int] = self.generate_beam( input_embeds=UpperCAmelCase__ , device=UpperCAmelCase__ , eos_token_id=UpperCAmelCase__ ) generated_tokens.append(output_tokens[0] ) generated_seq_lengths.append(seq_lengths[0] ) _a : List[str] = torch.stack(UpperCAmelCase__ ) _a : int = torch.stack(UpperCAmelCase__ ) return generated_tokens, generated_seq_lengths @torch.no_grad() def _lowercase ( self : Any , UpperCAmelCase__ : Dict=None , UpperCAmelCase__ : Optional[int]=None , UpperCAmelCase__ : Tuple=None , UpperCAmelCase__ : int = 5 , UpperCAmelCase__ : int = 67 , UpperCAmelCase__ : float = 1.0 , UpperCAmelCase__ : Optional[int] = None , ) -> List[str]: _a : Dict = eos_token_id _a : Tuple = None _a : Tuple = None _a : str = torch.ones(UpperCAmelCase__ , device=UpperCAmelCase__ , dtype=torch.int ) _a : List[Any] = torch.zeros(UpperCAmelCase__ , device=UpperCAmelCase__ , dtype=torch.bool ) if input_embeds is not None: _a : List[Any] = input_embeds else: _a : List[str] = self.transformer.transformer.wte(UpperCAmelCase__ ) for i in range(UpperCAmelCase__ ): _a : Optional[Any] = self.transformer(inputs_embeds=UpperCAmelCase__ ) _a : Tuple = outputs.logits _a : List[Any] = logits[:, -1, :] / (temperature if temperature > 0 else 1.0) _a : Dict = logits.softmax(-1 ).log() if scores is None: _a , _a : Any = logits.topk(UpperCAmelCase__ , -1 ) _a : str = generated.expand(UpperCAmelCase__ , *generated.shape[1:] ) _a , _a : Union[str, Any] = next_tokens.permute(1 , 0 ), scores.squeeze(0 ) if tokens is None: _a : List[str] = next_tokens else: _a : Optional[Any] = tokens.expand(UpperCAmelCase__ , *tokens.shape[1:] ) _a : Optional[int] = torch.cat((tokens, next_tokens) , dim=1 ) else: _a : Optional[int] = -float(np.inf ) _a : List[Any] = 0 _a : List[str] = scores[:, None] + logits seq_lengths[~is_stopped] += 1 _a : Optional[Any] = scores_sum / seq_lengths[:, None] _a , _a : Optional[int] = scores_sum_average.view(-1 ).topk(UpperCAmelCase__ , -1 ) _a : Optional[int] = next_tokens // scores_sum.shape[1] _a : Tuple = seq_lengths[next_tokens_source] _a : Dict = next_tokens % scores_sum.shape[1] _a : int = next_tokens.unsqueeze(1 ) _a : Optional[Any] = tokens[next_tokens_source] _a : str = torch.cat((tokens, next_tokens) , dim=1 ) _a : int = generated[next_tokens_source] _a : List[str] = scores_sum_average * seq_lengths _a : Tuple = is_stopped[next_tokens_source] _a : Union[str, Any] = self.transformer.transformer.wte(next_tokens.squeeze() ).view(generated.shape[0] , 1 , -1 ) _a : Tuple = torch.cat((generated, next_token_embed) , dim=1 ) _a : Optional[int] = is_stopped + next_tokens.eq(UpperCAmelCase__ ).squeeze() if is_stopped.all(): break _a : Tuple = scores / seq_lengths _a : Any = scores.argsort(descending=UpperCAmelCase__ ) # tokens tensors are already padded to max_seq_length _a : Union[str, Any] = [tokens[i] for i in order] _a : int = torch.stack(UpperCAmelCase__ , dim=0 ) _a : Optional[Any] = torch.tensor([seq_lengths[i] for i in order] , dtype=seq_lengths.dtype ) return output_texts, seq_lengths
324
"""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 how to properly calculate the metrics on the # validation dataset when in a distributed system, 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 # ######################################################################## _snake_case = 16 _snake_case = 32 def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ = 1_6 ): '''simple docstring''' _a : str = AutoTokenizer.from_pretrained("""bert-base-cased""" ) _a : Dict = load_dataset("""glue""" , """mrpc""" ) def tokenize_function(UpperCamelCase__ ): # max_length=None => use the model max length (it's actually the default) _a : Optional[int] = 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(): _a : Tuple = 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 _a : List[Any] = tokenized_datasets.rename_column("""label""" , """labels""" ) def collate_fn(UpperCamelCase__ ): # On TPU it's best to pad everything to the same length or training will be very slow. _a : Union[str, Any] = 1_2_8 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": _a : int = 1_6 elif accelerator.mixed_precision != "no": _a : int = 8 else: _a : str = None return tokenizer.pad( UpperCamelCase__ , padding="""longest""" , max_length=UpperCamelCase__ , pad_to_multiple_of=UpperCamelCase__ , return_tensors="""pt""" , ) # Instantiate dataloaders. _a : int = DataLoader( tokenized_datasets["""train"""] , shuffle=UpperCamelCase__ , collate_fn=UpperCamelCase__ , batch_size=UpperCamelCase__ ) _a : List[str] = 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 _snake_case = mocked_dataloaders # noqa: F811 def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' # For testing only if os.environ.get("""TESTING_MOCKED_DATALOADERS""" , UpperCamelCase__ ) == "1": _a : str = 2 # Initialize accelerator _a : int = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs _a : Any = config["""lr"""] _a : Union[str, Any] = int(config["""num_epochs"""] ) _a : str = int(config["""seed"""] ) _a : List[Any] = int(config["""batch_size"""] ) _a : Tuple = evaluate.load("""glue""" , """mrpc""" ) # If the batch size is too big we use gradient accumulation _a : Optional[Any] = 1 if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU: _a : Optional[Any] = batch_size // MAX_GPU_BATCH_SIZE _a : str = MAX_GPU_BATCH_SIZE set_seed(UpperCamelCase__ ) _a , _a : Optional[int] = get_dataloaders(UpperCamelCase__ , UpperCamelCase__ ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) _a : int = 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). _a : List[str] = model.to(accelerator.device ) # Instantiate optimizer _a : List[str] = AdamW(params=model.parameters() , lr=UpperCamelCase__ ) # Instantiate scheduler _a : List[str] = get_linear_schedule_with_warmup( optimizer=UpperCamelCase__ , num_warmup_steps=1_0_0 , 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. _a , _a , _a , _a , _a : Optional[Any] = accelerator.prepare( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) # Now we train the model for epoch in range(UpperCamelCase__ ): model.train() for step, batch in enumerate(UpperCamelCase__ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) _a : Optional[Any] = model(**UpperCamelCase__ ) _a : str = outputs.loss _a : Optional[int] = loss / gradient_accumulation_steps accelerator.backward(UpperCamelCase__ ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() _a : Union[str, Any] = 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 ) with torch.no_grad(): _a : Dict = model(**UpperCamelCase__ ) _a : Optional[Any] = outputs.logits.argmax(dim=-1 ) _a , _a : int = accelerator.gather((predictions, batch["""labels"""]) ) # New Code # # First we check if it's a distributed system if accelerator.use_distributed: # Then see if we're on the last batch of our eval dataloader if step == len(UpperCamelCase__ ) - 1: # Last batch needs to be truncated on distributed systems as it contains additional samples _a : str = predictions[: len(eval_dataloader.dataset ) - samples_seen] _a : int = references[: len(eval_dataloader.dataset ) - samples_seen] else: # Otherwise we add the number of samples seen samples_seen += references.shape[0] # All of this can be avoided if you use `Accelerator.gather_for_metrics` instead of `Accelerator.gather`: # accelerator.gather_for_metrics((predictions, batch["labels"])) metric.add_batch( predictions=UpperCamelCase__ , references=UpperCamelCase__ , ) _a : int = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F"""epoch {epoch}:""" , UpperCamelCase__ ) def lowerCAmelCase__ ( ): '''simple docstring''' _a : Tuple = 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.""" ) _a : Optional[Any] = parser.parse_args() _a : Tuple = {"""lr""": 2e-5, """num_epochs""": 3, """seed""": 4_2, """batch_size""": 1_6} training_function(UpperCamelCase__ , UpperCamelCase__ ) if __name__ == "__main__": main()
324
1
"""simple docstring""" from torch import nn class UpperCamelCase ( nn.Module ): def __init__( self : Optional[int] , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : Dict ) -> int: super().__init__() _a : List[str] = class_size _a : Union[str, Any] = embed_size # self.mlp1 = nn.Linear(embed_size, embed_size) # self.mlp2 = (nn.Linear(embed_size, class_size)) _a : Dict = nn.Linear(UpperCAmelCase__ , UpperCAmelCase__ ) def _lowercase ( self : List[str] , UpperCAmelCase__ : str ) -> Optional[Any]: # hidden_state = nn.functional.relu(self.mlp1(hidden_state)) # hidden_state = self.mlp2(hidden_state) _a : Optional[int] = self.mlp(UpperCAmelCase__ ) return logits
324
"""simple docstring""" import numpy as np def lowerCAmelCase__ ( UpperCamelCase__ ): '''simple docstring''' return 1 / (1 + np.exp(-vector )) def lowerCAmelCase__ ( UpperCamelCase__ ): '''simple docstring''' return vector * sigmoid(1.702 * vector ) if __name__ == "__main__": import doctest doctest.testmod()
324
1
"""simple docstring""" from cva import destroyAllWindows, imread, imshow, waitKey def lowerCAmelCase__ ( UpperCamelCase__ ): '''simple docstring''' # getting number of pixels in the image _a , _a : Tuple = img.shape[0], img.shape[1] # converting each pixel's color to its negative for i in range(UpperCamelCase__ ): for j in range(UpperCamelCase__ ): _a : int = [2_5_5, 2_5_5, 2_5_5] - img[i][j] return img if __name__ == "__main__": # read original image _snake_case = imread('image_data/lena.jpg', 1) # convert to its negative _snake_case = convert_to_negative(img) # show result image imshow('negative of original image', img) waitKey(0) destroyAllWindows()
324
"""simple docstring""" import unittest from transformers import CamembertTokenizer, CamembertTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.utils import is_torch_available from ...test_tokenization_common import TokenizerTesterMixin _snake_case = get_tests_dir('fixtures/test_sentencepiece.model') _snake_case = get_tests_dir('fixtures/test_sentencepiece_bpe.model') _snake_case = 'pt' if is_torch_available() else 'tf' @require_sentencepiece @require_tokenizers class UpperCamelCase ( snake_case_ , unittest.TestCase ): UpperCamelCase : str = CamembertTokenizer UpperCamelCase : List[Any] = CamembertTokenizerFast UpperCamelCase : Optional[int] = True UpperCamelCase : Union[str, Any] = True def _lowercase ( self : List[Any] ) -> Union[str, Any]: super().setUp() # We have a SentencePiece fixture for testing _a : List[Any] = CamembertTokenizer(UpperCAmelCase__ ) tokenizer.save_pretrained(self.tmpdirname ) def _lowercase ( self : List[str] ) -> Tuple: _a : Optional[Any] = """<pad>""" _a : Tuple = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(UpperCAmelCase__ ) , UpperCAmelCase__ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(UpperCAmelCase__ ) , UpperCAmelCase__ ) def _lowercase ( self : Union[str, Any] ) -> str: _a : List[str] = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , """<s>NOTUSED""" ) self.assertEqual(vocab_keys[1] , """<pad>""" ) self.assertEqual(vocab_keys[-1] , """<mask>""" ) self.assertEqual(len(UpperCAmelCase__ ) , 1004 ) def _lowercase ( self : List[str] ) -> List[Any]: self.assertEqual(self.get_tokenizer().vocab_size , 1005 ) def _lowercase ( self : Union[str, Any] ) -> str: _a : Tuple = CamembertTokenizer(UpperCAmelCase__ ) tokenizer.save_pretrained(self.tmpdirname ) _a : List[Any] = CamembertTokenizerFast.from_pretrained(self.tmpdirname ) _a : Any = """I was born in 92000, and this is falsé.""" _a : Union[str, Any] = tokenizer.encode(UpperCAmelCase__ ) _a : Dict = rust_tokenizer.encode(UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) _a : Tuple = tokenizer.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) _a : List[Any] = rust_tokenizer.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) # <unk> tokens are not the same for `rust` than for `slow`. # Because spm gives back raw token instead of `unk` in EncodeAsPieces # tokens = tokenizer.tokenize(sequence) _a : List[str] = tokenizer.convert_ids_to_tokens(UpperCAmelCase__ ) _a : int = rust_tokenizer.tokenize(UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) def _lowercase ( self : Dict ) -> List[str]: if not self.test_rust_tokenizer: return _a : Optional[int] = self.get_tokenizer() _a : Tuple = self.get_rust_tokenizer() _a : List[Any] = """I was born in 92000, and this is falsé.""" _a : List[str] = tokenizer.tokenize(UpperCAmelCase__ ) _a : Union[str, Any] = rust_tokenizer.tokenize(UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) _a : int = tokenizer.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) _a : Optional[int] = rust_tokenizer.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) _a : int = self.get_rust_tokenizer() _a : Optional[Any] = tokenizer.encode(UpperCAmelCase__ ) _a : Dict = rust_tokenizer.encode(UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) @slow def _lowercase ( self : Tuple ) -> List[Any]: # fmt: off _a : Dict = {"""input_ids""": [[5, 54, 7196, 297, 30, 23, 776, 18, 11, 3215, 3705, 8252, 22, 3164, 1181, 2116, 29, 16, 813, 25, 791, 3314, 20, 3446, 38, 27575, 120, 6, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [5, 468, 17, 11, 9088, 20, 1517, 8, 22804, 18818, 10, 38, 629, 607, 607, 142, 19, 7196, 867, 56, 10326, 24, 2267, 20, 416, 5072, 15612, 233, 734, 7, 2399, 27, 16, 3015, 1649, 7, 24, 20, 4338, 2399, 27, 13, 3400, 14, 13, 6189, 8, 930, 9, 6]], """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, 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, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]} # noqa: E501 # fmt: on # camembert is a french model. So we also use french texts. _a : Union[str, Any] = [ """Le transformeur est un modèle d'apprentissage profond introduit en 2017, """ """utilisé principalement dans le domaine du traitement automatique des langues (TAL).""", """À l'instar des réseaux de neurones récurrents (RNN), les transformeurs sont conçus """ """pour gérer des données séquentielles, telles que le langage naturel, pour des tâches """ """telles que la traduction et la synthèse de texte.""", ] self.tokenizer_integration_test_util( expected_encoding=UpperCAmelCase__ , model_name="""camembert-base""" , revision="""3a0641d9a1aeb7e848a74299e7e4c4bca216b4cf""" , sequences=UpperCAmelCase__ , )
324
1
"""simple docstring""" from argparse import ArgumentParser from .env import EnvironmentCommand def lowerCAmelCase__ ( ): '''simple docstring''' _a : Tuple = ArgumentParser("""Diffusers CLI tool""" , usage="""diffusers-cli <command> [<args>]""" ) _a : Optional[Any] = parser.add_subparsers(help="""diffusers-cli command helpers""" ) # Register commands EnvironmentCommand.register_subcommand(UpperCamelCase__ ) # Let's go _a : int = parser.parse_args() if not hasattr(UpperCamelCase__ , """func""" ): parser.print_help() exit(1 ) # Run _a : Dict = args.func(UpperCamelCase__ ) service.run() if __name__ == "__main__": main()
324
"""simple docstring""" import argparse import collections import os import re import tempfile import pandas as pd from datasets import Dataset from huggingface_hub import hf_hub_download, upload_folder from transformers.utils import direct_transformers_import # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/update_metadata.py _snake_case = 'src/transformers' # This is to make sure the transformers module imported is the one in the repo. _snake_case = direct_transformers_import(TRANSFORMERS_PATH) # Regexes that match TF/Flax/PT model names. _snake_case = re.compile(r'TF(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)') _snake_case = re.compile(r'Flax(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)') # Will match any TF or Flax model too so need to be in an else branch afterthe two previous regexes. _snake_case = re.compile(r'(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)') # Fill this with tuples (pipeline_tag, model_mapping, auto_model) _snake_case = [ ('pretraining', 'MODEL_FOR_PRETRAINING_MAPPING_NAMES', 'AutoModelForPreTraining'), ('feature-extraction', 'MODEL_MAPPING_NAMES', 'AutoModel'), ('audio-classification', 'MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES', 'AutoModelForAudioClassification'), ('text-generation', 'MODEL_FOR_CAUSAL_LM_MAPPING_NAMES', 'AutoModelForCausalLM'), ('automatic-speech-recognition', 'MODEL_FOR_CTC_MAPPING_NAMES', 'AutoModelForCTC'), ('image-classification', 'MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES', 'AutoModelForImageClassification'), ('image-segmentation', 'MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES', 'AutoModelForImageSegmentation'), ('fill-mask', 'MODEL_FOR_MASKED_LM_MAPPING_NAMES', 'AutoModelForMaskedLM'), ('object-detection', 'MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES', 'AutoModelForObjectDetection'), ( 'zero-shot-object-detection', 'MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES', 'AutoModelForZeroShotObjectDetection', ), ('question-answering', 'MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES', 'AutoModelForQuestionAnswering'), ('text2text-generation', 'MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES', 'AutoModelForSeq2SeqLM'), ('text-classification', 'MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES', 'AutoModelForSequenceClassification'), ('automatic-speech-recognition', 'MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES', 'AutoModelForSpeechSeq2Seq'), ( 'table-question-answering', 'MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING_NAMES', 'AutoModelForTableQuestionAnswering', ), ('token-classification', 'MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES', 'AutoModelForTokenClassification'), ('multiple-choice', 'MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES', 'AutoModelForMultipleChoice'), ( 'next-sentence-prediction', 'MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING_NAMES', 'AutoModelForNextSentencePrediction', ), ( 'audio-frame-classification', 'MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES', 'AutoModelForAudioFrameClassification', ), ('audio-xvector', 'MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES', 'AutoModelForAudioXVector'), ( 'document-question-answering', 'MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES', 'AutoModelForDocumentQuestionAnswering', ), ( 'visual-question-answering', 'MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING_NAMES', 'AutoModelForVisualQuestionAnswering', ), ('image-to-text', 'MODEL_FOR_FOR_VISION_2_SEQ_MAPPING_NAMES', 'AutoModelForVision2Seq'), ( 'zero-shot-image-classification', 'MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING_NAMES', 'AutoModelForZeroShotImageClassification', ), ('depth-estimation', 'MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES', 'AutoModelForDepthEstimation'), ('video-classification', 'MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING_NAMES', 'AutoModelForVideoClassification'), ('mask-generation', 'MODEL_FOR_MASK_GENERATION_MAPPING_NAMES', 'AutoModelForMaskGeneration'), ] def lowerCAmelCase__ ( UpperCamelCase__ ): '''simple docstring''' _a : Dict = re.finditer(""".+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)""" , UpperCamelCase__ ) return [m.group(0 ) for m in matches] def lowerCAmelCase__ ( ): '''simple docstring''' _a : Tuple = transformers_module.models.auto.configuration_auto.CONFIG_MAPPING_NAMES _a : Optional[int] = { config.replace("""Config""" , """""" ): model_type for model_type, config in config_maping_names.items() } # Dictionaries flagging if each model prefix has a backend in PT/TF/Flax. _a : List[Any] = collections.defaultdict(UpperCamelCase__ ) _a : List[str] = collections.defaultdict(UpperCamelCase__ ) _a : Tuple = collections.defaultdict(UpperCamelCase__ ) # Let's lookup through all transformers object (once) and find if models are supported by a given backend. for attr_name in dir(UpperCamelCase__ ): _a : str = None if _re_tf_models.match(UpperCamelCase__ ) is not None: _a : List[Any] = tf_models _a : int = _re_tf_models.match(UpperCamelCase__ ).groups()[0] elif _re_flax_models.match(UpperCamelCase__ ) is not None: _a : Any = flax_models _a : Any = _re_flax_models.match(UpperCamelCase__ ).groups()[0] elif _re_pt_models.match(UpperCamelCase__ ) is not None: _a : int = pt_models _a : int = _re_pt_models.match(UpperCamelCase__ ).groups()[0] if lookup_dict is not None: while len(UpperCamelCase__ ) > 0: if attr_name in model_prefix_to_model_type: _a : Optional[int] = True break # Try again after removing the last word in the name _a : List[Any] = """""".join(camel_case_split(UpperCamelCase__ )[:-1] ) _a : Optional[int] = set(list(pt_models.keys() ) + list(tf_models.keys() ) + list(flax_models.keys() ) ) _a : Dict = list(UpperCamelCase__ ) all_models.sort() _a : str = {"""model_type""": all_models} _a : List[Any] = [pt_models[t] for t in all_models] _a : str = [tf_models[t] for t in all_models] _a : Optional[int] = [flax_models[t] for t in all_models] # Now let's use the auto-mapping names to make sure _a : str = {} for t in all_models: if t in transformers_module.models.auto.processing_auto.PROCESSOR_MAPPING_NAMES: _a : List[str] = """AutoProcessor""" elif t in transformers_module.models.auto.tokenization_auto.TOKENIZER_MAPPING_NAMES: _a : str = """AutoTokenizer""" elif t in transformers_module.models.auto.feature_extraction_auto.FEATURE_EXTRACTOR_MAPPING_NAMES: _a : int = """AutoFeatureExtractor""" else: # Default to AutoTokenizer if a model has nothing, for backward compatibility. _a : int = """AutoTokenizer""" _a : Any = [processors[t] for t in all_models] return pd.DataFrame(UpperCamelCase__ ) def lowerCAmelCase__ ( UpperCamelCase__ ): '''simple docstring''' _a : List[Any] = [ transformers_module.models.auto.modeling_auto, transformers_module.models.auto.modeling_tf_auto, transformers_module.models.auto.modeling_flax_auto, ] for pipeline_tag, model_mapping, auto_class in PIPELINE_TAGS_AND_AUTO_MODELS: _a : List[Any] = [model_mapping, F"""TF_{model_mapping}""", F"""FLAX_{model_mapping}"""] _a : Union[str, Any] = [auto_class, F"""TF_{auto_class}""", F"""Flax_{auto_class}"""] # Loop through all three frameworks for module, cls, mapping in zip(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): # The type of pipeline may not exist in this framework if not hasattr(UpperCamelCase__ , UpperCamelCase__ ): continue # First extract all model_names _a : str = [] for name in getattr(UpperCamelCase__ , UpperCamelCase__ ).values(): if isinstance(UpperCamelCase__ , UpperCamelCase__ ): model_names.append(UpperCamelCase__ ) else: model_names.extend(list(UpperCamelCase__ ) ) # Add pipeline tag and auto model class for those models table.update({model_name: (pipeline_tag, cls) for model_name in model_names} ) return table def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' _a : Dict = get_frameworks_table() _a : Optional[Any] = Dataset.from_pandas(UpperCamelCase__ ) _a : Any = hf_hub_download( """huggingface/transformers-metadata""" , """pipeline_tags.json""" , repo_type="""dataset""" , token=UpperCamelCase__ ) _a : List[Any] = Dataset.from_json(UpperCamelCase__ ) _a : List[str] = { tags_dataset[i]["""model_class"""]: (tags_dataset[i]["""pipeline_tag"""], tags_dataset[i]["""auto_class"""]) for i in range(len(UpperCamelCase__ ) ) } _a : str = update_pipeline_and_auto_class_table(UpperCamelCase__ ) # Sort the model classes to avoid some nondeterministic updates to create false update commits. _a : int = sorted(table.keys() ) _a : Union[str, Any] = pd.DataFrame( { """model_class""": model_classes, """pipeline_tag""": [table[m][0] for m in model_classes], """auto_class""": [table[m][1] for m in model_classes], } ) _a : Dict = Dataset.from_pandas(UpperCamelCase__ ) with tempfile.TemporaryDirectory() as tmp_dir: frameworks_dataset.to_json(os.path.join(UpperCamelCase__ , """frameworks.json""" ) ) tags_dataset.to_json(os.path.join(UpperCamelCase__ , """pipeline_tags.json""" ) ) if commit_sha is not None: _a : List[str] = ( F"""Update with commit {commit_sha}\n\nSee: """ F"""https://github.com/huggingface/transformers/commit/{commit_sha}""" ) else: _a : Optional[Any] = """Update""" upload_folder( repo_id="""huggingface/transformers-metadata""" , folder_path=UpperCamelCase__ , repo_type="""dataset""" , token=UpperCamelCase__ , commit_message=UpperCamelCase__ , ) def lowerCAmelCase__ ( ): '''simple docstring''' _a : List[str] = {tag: cls for tag, _, cls in PIPELINE_TAGS_AND_AUTO_MODELS} _a : Any = transformers_module.pipelines.SUPPORTED_TASKS _a : List[str] = [] for key in pipeline_tasks: if key not in in_table: _a : Tuple = pipeline_tasks[key]["""pt"""] if isinstance(UpperCamelCase__ , (list, tuple) ): _a : Dict = model[0] _a : List[str] = model.__name__ if model not in in_table.values(): missing.append(UpperCamelCase__ ) if len(UpperCamelCase__ ) > 0: _a : Union[str, Any] = """, """.join(UpperCamelCase__ ) raise ValueError( """The following pipeline tags are not present in the `PIPELINE_TAGS_AND_AUTO_MODELS` constant inside """ F"""`utils/update_metadata.py`: {msg}. Please add them!""" ) if __name__ == "__main__": _snake_case = argparse.ArgumentParser() parser.add_argument('--token', type=str, help='The token to use to push to the transformers-metadata dataset.') parser.add_argument('--commit_sha', type=str, help='The sha of the commit going with this update.') parser.add_argument('--check-only', action='store_true', help='Activate to just check all pipelines are present.') _snake_case = parser.parse_args() if args.check_only: check_pipeline_tags() else: update_metadata(args.token, args.commit_sha)
324
1
"""simple docstring""" import unittest from transformers import SPIECE_UNDERLINE, ReformerTokenizer, ReformerTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, require_torch, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin _snake_case = get_tests_dir('fixtures/test_sentencepiece.model') @require_sentencepiece @require_tokenizers class UpperCamelCase ( snake_case_ , unittest.TestCase ): UpperCamelCase : Dict = ReformerTokenizer UpperCamelCase : int = ReformerTokenizerFast UpperCamelCase : Dict = True UpperCamelCase : Dict = False UpperCamelCase : str = True def _lowercase ( self : Any ) -> str: super().setUp() _a : int = ReformerTokenizer(UpperCAmelCase__ , keep_accents=UpperCAmelCase__ ) tokenizer.save_pretrained(self.tmpdirname ) def _lowercase ( self : Optional[int] ) -> List[Any]: _a : Any = """<s>""" _a : List[str] = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(UpperCAmelCase__ ) , UpperCAmelCase__ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(UpperCAmelCase__ ) , UpperCAmelCase__ ) def _lowercase ( self : Optional[Any] ) -> Optional[int]: _a : List[Any] = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , """<unk>""" ) self.assertEqual(vocab_keys[1] , """<s>""" ) self.assertEqual(vocab_keys[-1] , """j""" ) self.assertEqual(len(UpperCAmelCase__ ) , 1000 ) def _lowercase ( self : List[str] ) -> str: self.assertEqual(self.get_tokenizer().vocab_size , 1000 ) def _lowercase ( self : Dict ) -> str: if not self.test_rust_tokenizer: return _a : Dict = self.get_tokenizer() _a : Tuple = self.get_rust_tokenizer() _a : Dict = """I was born in 92000, and this is falsé.""" _a : Dict = tokenizer.tokenize(UpperCAmelCase__ ) _a : Dict = rust_tokenizer.tokenize(UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) _a : str = tokenizer.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) _a : Dict = rust_tokenizer.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) _a : Any = self.get_rust_tokenizer() _a : Optional[Any] = tokenizer.encode(UpperCAmelCase__ ) _a : Optional[int] = rust_tokenizer.encode(UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) def _lowercase ( self : Optional[Any] , UpperCAmelCase__ : Optional[int]=15 ) -> Union[str, Any]: for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): _a : Any = self.rust_tokenizer_class.from_pretrained(UpperCAmelCase__ , **UpperCAmelCase__ ) # Simple input _a : Optional[Any] = """This is a simple input""" _a : List[str] = ["""This is a simple input 1""", """This is a simple input 2"""] _a : Union[str, Any] = ("""This is a simple input""", """This is a pair""") _a : List[Any] = [ ("""This is a simple input 1""", """This is a simple input 2"""), ("""This is a simple pair 1""", """This is a simple pair 2"""), ] # Simple input tests self.assertRaises(UpperCAmelCase__ , tokenizer_r.encode , UpperCAmelCase__ , max_length=UpperCAmelCase__ , padding="""max_length""" ) # Simple input self.assertRaises(UpperCAmelCase__ , tokenizer_r.encode_plus , UpperCAmelCase__ , max_length=UpperCAmelCase__ , padding="""max_length""" ) # Simple input self.assertRaises( UpperCAmelCase__ , tokenizer_r.batch_encode_plus , UpperCAmelCase__ , max_length=UpperCAmelCase__ , padding="""max_length""" , ) # Pair input self.assertRaises(UpperCAmelCase__ , tokenizer_r.encode , UpperCAmelCase__ , max_length=UpperCAmelCase__ , padding="""max_length""" ) # Pair input self.assertRaises(UpperCAmelCase__ , tokenizer_r.encode_plus , UpperCAmelCase__ , max_length=UpperCAmelCase__ , padding="""max_length""" ) # Pair input self.assertRaises( UpperCAmelCase__ , tokenizer_r.batch_encode_plus , UpperCAmelCase__ , max_length=UpperCAmelCase__ , padding="""max_length""" , ) def _lowercase ( self : Any ) -> List[Any]: pass def _lowercase ( self : str ) -> str: _a : List[Any] = ReformerTokenizer(UpperCAmelCase__ , keep_accents=UpperCAmelCase__ ) _a : List[str] = tokenizer.tokenize("""This is a test""" ) self.assertListEqual(UpperCAmelCase__ , ["""▁This""", """▁is""", """▁a""", """▁t""", """est"""] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(UpperCAmelCase__ ) , [285, 46, 10, 170, 382] , ) _a : int = tokenizer.tokenize("""I was born in 92000, and this is falsé.""" ) self.assertListEqual( UpperCAmelCase__ , [ SPIECE_UNDERLINE + """I""", SPIECE_UNDERLINE + """was""", SPIECE_UNDERLINE + """b""", """or""", """n""", SPIECE_UNDERLINE + """in""", SPIECE_UNDERLINE + """""", """9""", """2""", """0""", """0""", """0""", """,""", SPIECE_UNDERLINE + """and""", SPIECE_UNDERLINE + """this""", SPIECE_UNDERLINE + """is""", SPIECE_UNDERLINE + """f""", """al""", """s""", """é""", """.""", ] , ) _a : str = tokenizer.convert_tokens_to_ids(UpperCAmelCase__ ) self.assertListEqual( UpperCAmelCase__ , [8, 21, 84, 55, 24, 19, 7, 0, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 0, 4] , ) _a : List[str] = tokenizer.convert_ids_to_tokens(UpperCAmelCase__ ) self.assertListEqual( UpperCAmelCase__ , [ SPIECE_UNDERLINE + """I""", SPIECE_UNDERLINE + """was""", SPIECE_UNDERLINE + """b""", """or""", """n""", SPIECE_UNDERLINE + """in""", SPIECE_UNDERLINE + """""", """<unk>""", """2""", """0""", """0""", """0""", """,""", SPIECE_UNDERLINE + """and""", SPIECE_UNDERLINE + """this""", SPIECE_UNDERLINE + """is""", SPIECE_UNDERLINE + """f""", """al""", """s""", """<unk>""", """.""", ] , ) @cached_property def _lowercase ( self : str ) -> Dict: return ReformerTokenizer.from_pretrained("""google/reformer-crime-and-punishment""" ) @slow def _lowercase ( self : List[str] ) -> List[Any]: _a : int = """Hello World!""" _a : Optional[int] = [126, 32, 262, 152, 38, 72, 287] self.assertListEqual(UpperCAmelCase__ , self.big_tokenizer.encode(UpperCAmelCase__ ) ) @slow def _lowercase ( self : Optional[int] ) -> Union[str, Any]: _a : int = ( """This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) \" [ ] ! : - . Also we will""" """ add words that should not exsist and be tokenized to <unk>, such as saoneuhaoesuth""" ) _a : Tuple = [ 108, 265, 24, 111, 4, 258, 156, 35, 28, 275, 3, 259, 297, 260, 84, 4, 35, 110, 44, 8, 259, 91, 268, 21, 11, 209, 274, 109, 266, 277, 117, 86, 93, 315, 258, 278, 258, 277, 258, 0, 258, 288, 258, 319, 258, 0, 258, 0, 258, 0, 258, 0, 258, 287, 258, 315, 258, 289, 258, 278, 99, 269, 266, 262, 8, 259, 241, 4, 217, 230, 268, 266, 55, 168, 106, 75, 193, 266, 223, 27, 49, 26, 282, 25, 264, 299, 19, 26, 0, 258, 277, 117, 86, 93, 176, 183, 270, 11, 262, 42, 61, 265, ] self.assertListEqual(UpperCAmelCase__ , self.big_tokenizer.encode(UpperCAmelCase__ ) ) @require_torch @slow def _lowercase ( self : int ) -> Dict: import torch from transformers import ReformerConfig, ReformerModel # Build sequence _a : int = list(self.big_tokenizer.get_vocab().keys() )[:10] _a : Any = """ """.join(UpperCAmelCase__ ) _a : Tuple = self.big_tokenizer.encode_plus(UpperCAmelCase__ , return_tensors="""pt""" ) _a : List[str] = self.big_tokenizer.batch_encode_plus([sequence, sequence] , return_tensors="""pt""" ) _a : int = ReformerConfig() # The input gets padded during training so adjust the axial position encodings from the pretrained model value of (512, 1024) _a : int = encoded_sequence["""input_ids"""].shape _a : int = ReformerModel(UpperCAmelCase__ ) # Reformer has config.vocab_size == tokenizer.vocab_size == len(tokenizer) - 1 = 320; len(tokenizer) is 321 (including a pad token with id 320) assert model.get_input_embeddings().weight.shape[0] >= self.big_tokenizer.vocab_size with torch.no_grad(): model(**UpperCAmelCase__ ) model(**UpperCAmelCase__ ) @slow def _lowercase ( self : str ) -> int: # fmt: off _a : List[Any] = {"""input_ids""": [[108, 265, 24, 111, 4, 258, 156, 7, 51, 279, 58, 7, 76, 25, 69, 278], [140, 243, 264, 134, 17, 267, 77, 263, 22, 262, 297, 258, 304, 177, 279, 266, 14, 89, 13, 35, 261, 299, 272, 137, 275, 278]], """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]]} # noqa: E501 # fmt: on # This tokenizer does not know some characters like ")". # That is the reason why we use very simple texts here. # Also see https://github.com/huggingface/transformers/pull/11737#issuecomment-850769064 _a : str = [ """This is a very simple sentence.""", """The quick brown fox jumps over the lazy dog.""", ] self.tokenizer_integration_test_util( expected_encoding=UpperCAmelCase__ , model_name="""google/reformer-crime-and-punishment""" , revision="""0e6c3decb8211d49bf881013425dc8b0448b3f5a""" , padding=UpperCAmelCase__ , sequences=UpperCAmelCase__ , )
324
"""simple docstring""" import os import pytest import yaml from datasets.features.features import Features, Value from datasets.info import DatasetInfo, DatasetInfosDict @pytest.mark.parametrize( """files""" , [ ["""full:README.md""", """dataset_infos.json"""], ["""empty:README.md""", """dataset_infos.json"""], ["""dataset_infos.json"""], ["""full:README.md"""], ] , ) def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' _a : Dict = tmp_path_factory.mktemp("""dset_infos_dir""" ) if "full:README.md" in files: with open(dataset_infos_dir / """README.md""" , """w""" ) as f: f.write("""---\ndataset_info:\n dataset_size: 42\n---""" ) if "empty:README.md" in files: with open(dataset_infos_dir / """README.md""" , """w""" ) as f: f.write("""""" ) # we want to support dataset_infos.json for backward compatibility if "dataset_infos.json" in files: with open(dataset_infos_dir / """dataset_infos.json""" , """w""" ) as f: f.write("""{\"default\": {\"dataset_size\": 42}}""" ) _a : Dict = DatasetInfosDict.from_directory(UpperCamelCase__ ) assert dataset_infos assert dataset_infos["default"].dataset_size == 4_2 @pytest.mark.parametrize( """dataset_info""" , [ DatasetInfo(), DatasetInfo( description="""foo""" , features=Features({"""a""": Value("""int32""" )} ) , builder_name="""builder""" , config_name="""config""" , version="""1.0.0""" , splits=[{"""name""": """train"""}] , download_size=4_2 , ), ] , ) def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' _a : Optional[int] = str(UpperCamelCase__ ) dataset_info.write_to_directory(UpperCamelCase__ ) _a : Any = DatasetInfo.from_directory(UpperCamelCase__ ) assert dataset_info == reloaded assert os.path.exists(os.path.join(UpperCamelCase__ , """dataset_info.json""" ) ) def lowerCAmelCase__ ( ): '''simple docstring''' _a : Dict = DatasetInfo( description="""foo""" , citation="""bar""" , homepage="""https://foo.bar""" , license="""CC0""" , features=Features({"""a""": Value("""int32""" )} ) , post_processed={} , supervised_keys=() , task_templates=[] , builder_name="""builder""" , config_name="""config""" , version="""1.0.0""" , splits=[{"""name""": """train""", """num_examples""": 4_2}] , download_checksums={} , download_size=1_3_3_7 , post_processing_size=4_4_2 , dataset_size=1_2_3_4 , size_in_bytes=1_3_3_7 + 4_4_2 + 1_2_3_4 , ) _a : int = dataset_info._to_yaml_dict() assert sorted(UpperCamelCase__ ) == sorted(DatasetInfo._INCLUDED_INFO_IN_YAML ) for key in DatasetInfo._INCLUDED_INFO_IN_YAML: assert key in dataset_info_yaml_dict assert isinstance(dataset_info_yaml_dict[key] , (list, dict, int, str) ) _a : List[str] = yaml.safe_dump(UpperCamelCase__ ) _a : Optional[int] = yaml.safe_load(UpperCamelCase__ ) assert dataset_info_yaml_dict == reloaded def lowerCAmelCase__ ( ): '''simple docstring''' _a : List[Any] = DatasetInfo() _a : Any = dataset_info._to_yaml_dict() assert dataset_info_yaml_dict == {} @pytest.mark.parametrize( """dataset_infos_dict""" , [ DatasetInfosDict(), DatasetInfosDict({"""default""": DatasetInfo()} ), DatasetInfosDict({"""my_config_name""": DatasetInfo()} ), DatasetInfosDict( { """default""": DatasetInfo( description="""foo""" , features=Features({"""a""": Value("""int32""" )} ) , builder_name="""builder""" , config_name="""config""" , version="""1.0.0""" , splits=[{"""name""": """train"""}] , download_size=4_2 , ) } ), DatasetInfosDict( { """v1""": DatasetInfo(dataset_size=4_2 ), """v2""": DatasetInfo(dataset_size=1_3_3_7 ), } ), ] , ) def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' _a : List[Any] = str(UpperCamelCase__ ) dataset_infos_dict.write_to_directory(UpperCamelCase__ ) _a : List[Any] = DatasetInfosDict.from_directory(UpperCamelCase__ ) # the config_name of the dataset_infos_dict take over the attribute for config_name, dataset_info in dataset_infos_dict.items(): _a : str = config_name # the yaml representation doesn't include fields like description or citation # so we just test that we can recover what we can from the yaml _a : Dict = DatasetInfo._from_yaml_dict(dataset_info._to_yaml_dict() ) assert dataset_infos_dict == reloaded if dataset_infos_dict: assert os.path.exists(os.path.join(UpperCamelCase__ , """README.md""" ) )
324
1
"""simple docstring""" from argparse import ArgumentParser from ..pipelines import Pipeline, PipelineDataFormat, get_supported_tasks, pipeline from ..utils import logging from . import BaseTransformersCLICommand _snake_case = logging.get_logger(__name__) # pylint: disable=invalid-name def lowerCAmelCase__ ( UpperCamelCase__ ): '''simple docstring''' if not path: return "pipe" for ext in PipelineDataFormat.SUPPORTED_FORMATS: if path.endswith(UpperCamelCase__ ): return ext raise Exception( F"""Unable to determine file format from file extension {path}. """ F"""Please provide the format through --format {PipelineDataFormat.SUPPORTED_FORMATS}""" ) def lowerCAmelCase__ ( UpperCamelCase__ ): '''simple docstring''' _a : List[str] = pipeline( task=args.task , model=args.model if args.model else None , config=args.config , tokenizer=args.tokenizer , device=args.device , ) _a : Optional[Any] = try_infer_format_from_ext(args.input ) if args.format == """infer""" else args.format _a : List[Any] = PipelineDataFormat.from_str( format=UpperCamelCase__ , output_path=args.output , input_path=args.input , column=args.column if args.column else nlp.default_input_names , overwrite=args.overwrite , ) return RunCommand(UpperCamelCase__ , UpperCamelCase__ ) class UpperCamelCase ( snake_case_ ): def __init__( self : Union[str, Any] , UpperCAmelCase__ : Pipeline , UpperCAmelCase__ : PipelineDataFormat ) -> List[Any]: _a : Any = nlp _a : List[str] = reader @staticmethod def _lowercase ( UpperCAmelCase__ : ArgumentParser ) -> Optional[Any]: _a : Any = parser.add_parser("""run""" , help="""Run a pipeline through the CLI""" ) run_parser.add_argument("""--task""" , choices=get_supported_tasks() , help="""Task to run""" ) run_parser.add_argument("""--input""" , type=UpperCAmelCase__ , help="""Path to the file to use for inference""" ) run_parser.add_argument("""--output""" , type=UpperCAmelCase__ , help="""Path to the file that will be used post to write results.""" ) run_parser.add_argument("""--model""" , type=UpperCAmelCase__ , help="""Name or path to the model to instantiate.""" ) run_parser.add_argument("""--config""" , type=UpperCAmelCase__ , help="""Name or path to the model's config to instantiate.""" ) run_parser.add_argument( """--tokenizer""" , type=UpperCAmelCase__ , help="""Name of the tokenizer to use. (default: same as the model name)""" ) run_parser.add_argument( """--column""" , type=UpperCAmelCase__ , help="""Name of the column to use as input. (For multi columns input as QA use column1,columns2)""" , ) run_parser.add_argument( """--format""" , type=UpperCAmelCase__ , default="""infer""" , choices=PipelineDataFormat.SUPPORTED_FORMATS , help="""Input format to read from""" , ) run_parser.add_argument( """--device""" , type=UpperCAmelCase__ , default=-1 , help="""Indicate the device to run onto, -1 indicates CPU, >= 0 indicates GPU (default: -1)""" , ) run_parser.add_argument("""--overwrite""" , action="""store_true""" , help="""Allow overwriting the output file.""" ) run_parser.set_defaults(func=UpperCAmelCase__ ) def _lowercase ( self : str ) -> Tuple: _a , _a : int = self._nlp, [] for entry in self._reader: _a : Optional[int] = nlp(**UpperCAmelCase__ ) if self._reader.is_multi_columns else nlp(UpperCAmelCase__ ) if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): outputs.append(UpperCAmelCase__ ) else: outputs += output # Saving data if self._nlp.binary_output: _a : List[str] = self._reader.save_binary(UpperCAmelCase__ ) logger.warning(f"""Current pipeline requires output to be in binary format, saving at {binary_path}""" ) else: self._reader.save(UpperCAmelCase__ )
324
"""simple docstring""" 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 , snake_case_ ): def _lowercase ( self : int ) -> int: _a : Optional[Any] = load_tool("""text-to-speech""" ) self.tool.setup() def _lowercase ( self : List[str] ) -> Union[str, Any]: # SpeechT5 isn't deterministic torch.manual_seed(0 ) _a : str = self.tool("""hey""" ) _a : List[str] = result.to_raw() self.assertTrue( torch.allclose( resulting_tensor[:3] , torch.tensor([-0.0_0_0_5_9_6_6_6_6_8_8_3_2_1_1_5_8_2_9, -0.0_0_0_3_6_5_7_6_4_0_1_9_0_7_9_5_0_6_4, -0.0_0_0_1_3_4_3_9_5_0_2_7_9_9_8_8_3_4_8_5] ) , ) ) def _lowercase ( self : Optional[int] ) -> Optional[Any]: # SpeechT5 isn't deterministic torch.manual_seed(0 ) _a : int = self.tool("""hey""" ) _a : str = result.to_raw() self.assertTrue( torch.allclose( resulting_tensor[:3] , torch.tensor([-0.0_0_0_5_9_6_6_6_6_8_8_3_2_1_1_5_8_2_9, -0.0_0_0_3_6_5_7_6_4_0_1_9_0_7_9_5_0_6_4, -0.0_0_0_1_3_4_3_9_5_0_2_7_9_9_8_8_3_4_8_5] ) , ) )
324
1
"""simple docstring""" from PIL import Image def lowerCAmelCase__ ( UpperCamelCase__ ): '''simple docstring''' _a , _a : Dict = image.size _a : List[str] = 0 _a : Union[str, Any] = image.load() for i in range(UpperCamelCase__ ): for j in range(UpperCamelCase__ ): _a : Any = pixels[j, i] mean += pixel mean //= width * height for j in range(UpperCamelCase__ ): for i in range(UpperCamelCase__ ): _a : Dict = 2_5_5 if pixels[i, j] > mean else 0 return image if __name__ == "__main__": _snake_case = mean_threshold(Image.open('path_to_image').convert('L')) image.save('output_image_path')
324
"""simple docstring""" import copy import json import os import tempfile from transformers import is_torch_available from .test_configuration_utils import config_common_kwargs class UpperCamelCase ( snake_case_ ): def __init__( self : Union[str, Any] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : int=None , UpperCAmelCase__ : Optional[Any]=True , UpperCAmelCase__ : List[str]=None , **UpperCAmelCase__ : str ) -> int: _a : str = parent _a : Union[str, Any] = config_class _a : List[Any] = has_text_modality _a : List[Any] = kwargs _a : List[Any] = common_properties def _lowercase ( self : int ) -> Tuple: _a : List[str] = self.config_class(**self.inputs_dict ) _a : Dict = ( ["""hidden_size""", """num_attention_heads""", """num_hidden_layers"""] if self.common_properties is None else self.common_properties ) # Add common fields for text models if self.has_text_modality: common_properties.extend(["""vocab_size"""] ) # Test that config has the common properties as getters for prop in common_properties: self.parent.assertTrue(hasattr(UpperCAmelCase__ , UpperCAmelCase__ ) , msg=f"""`{prop}` does not exist""" ) # Test that config has the common properties as setter for idx, name in enumerate(UpperCAmelCase__ ): try: setattr(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) self.parent.assertEqual( getattr(UpperCAmelCase__ , UpperCAmelCase__ ) , UpperCAmelCase__ , msg=f"""`{name} value {idx} expected, but was {getattr(UpperCAmelCase__ , UpperCAmelCase__ )}""" ) except NotImplementedError: # Some models might not be able to implement setters for common_properties # In that case, a NotImplementedError is raised pass # Test if config class can be called with Config(prop_name=..) for idx, name in enumerate(UpperCAmelCase__ ): try: _a : Optional[int] = self.config_class(**{name: idx} ) self.parent.assertEqual( getattr(UpperCAmelCase__ , UpperCAmelCase__ ) , UpperCAmelCase__ , msg=f"""`{name} value {idx} expected, but was {getattr(UpperCAmelCase__ , UpperCAmelCase__ )}""" ) except NotImplementedError: # Some models might not be able to implement setters for common_properties # In that case, a NotImplementedError is raised pass def _lowercase ( self : Optional[int] ) -> Optional[Any]: _a : Optional[Any] = self.config_class(**self.inputs_dict ) _a : List[str] = json.loads(config.to_json_string() ) for key, value in self.inputs_dict.items(): self.parent.assertEqual(obj[key] , UpperCAmelCase__ ) def _lowercase ( self : int ) -> List[str]: _a : Optional[Any] = self.config_class(**self.inputs_dict ) with tempfile.TemporaryDirectory() as tmpdirname: _a : Tuple = os.path.join(UpperCAmelCase__ , """config.json""" ) config_first.to_json_file(UpperCAmelCase__ ) _a : List[str] = self.config_class.from_json_file(UpperCAmelCase__ ) self.parent.assertEqual(config_second.to_dict() , config_first.to_dict() ) def _lowercase ( self : Union[str, Any] ) -> Dict: _a : Dict = self.config_class(**self.inputs_dict ) with tempfile.TemporaryDirectory() as tmpdirname: config_first.save_pretrained(UpperCAmelCase__ ) _a : Dict = self.config_class.from_pretrained(UpperCAmelCase__ ) self.parent.assertEqual(config_second.to_dict() , config_first.to_dict() ) def _lowercase ( self : Dict ) -> Tuple: _a : List[Any] = self.config_class(**self.inputs_dict ) _a : Any = """test""" with tempfile.TemporaryDirectory() as tmpdirname: _a : List[Any] = os.path.join(UpperCAmelCase__ , UpperCAmelCase__ ) config_first.save_pretrained(UpperCAmelCase__ ) _a : List[Any] = self.config_class.from_pretrained(UpperCAmelCase__ , subfolder=UpperCAmelCase__ ) self.parent.assertEqual(config_second.to_dict() , config_first.to_dict() ) def _lowercase ( self : List[str] ) -> Union[str, Any]: _a : Tuple = self.config_class(**self.inputs_dict , num_labels=5 ) self.parent.assertEqual(len(config.idalabel ) , 5 ) self.parent.assertEqual(len(config.labelaid ) , 5 ) _a : Union[str, Any] = 3 self.parent.assertEqual(len(config.idalabel ) , 3 ) self.parent.assertEqual(len(config.labelaid ) , 3 ) def _lowercase ( self : Tuple ) -> List[str]: if self.config_class.is_composition: return _a : str = self.config_class() self.parent.assertIsNotNone(UpperCAmelCase__ ) def _lowercase ( self : List[Any] ) -> Optional[Any]: _a : Dict = copy.deepcopy(UpperCAmelCase__ ) _a : Any = self.config_class(**UpperCAmelCase__ ) _a : str = [] for key, value in config_common_kwargs.items(): if key == "torch_dtype": if not is_torch_available(): continue else: import torch if config.torch_dtype != torch.floataa: wrong_values.append(("""torch_dtype""", config.torch_dtype, torch.floataa) ) elif getattr(UpperCAmelCase__ , UpperCAmelCase__ ) != value: wrong_values.append((key, getattr(UpperCAmelCase__ , UpperCAmelCase__ ), value) ) if len(UpperCAmelCase__ ) > 0: _a : List[Any] = """\n""".join([f"""- {v[0]}: got {v[1]} instead of {v[2]}""" for v in wrong_values] ) raise ValueError(f"""The following keys were not properly set in the config:\n{errors}""" ) def _lowercase ( self : int ) -> Union[str, Any]: self.create_and_test_config_common_properties() self.create_and_test_config_to_json_string() self.create_and_test_config_to_json_file() self.create_and_test_config_from_and_save_pretrained() self.create_and_test_config_from_and_save_pretrained_subfolder() self.create_and_test_config_with_num_labels() self.check_config_can_be_init_without_params() self.check_config_arguments_init()
324
1
"""simple docstring""" import argparse import os from pathlib import Path from typing import Dict import tensorflow as tf import torch from tqdm import tqdm from transformers import PegasusConfig, PegasusForConditionalGeneration, PegasusTokenizer from transformers.models.pegasus.configuration_pegasus import DEFAULTS, task_specific_params _snake_case = [ # replace left string with right string to get the relevant state_dict key (identical state dict to bart) ['memory_attention', 'encoder_attn'], ['attention', 'attn'], ['/', '.'], ['.LayerNorm.gamma', '_layer_norm.weight'], ['.LayerNorm.beta', '_layer_norm.bias'], ['r.layer_', 'r.layers.'], ['output_proj', 'out_proj'], ['ffn.dense_1.', 'fc2.'], ['ffn.dense.', 'fc1.'], ['ffn_layer_norm', 'final_layer_norm'], ['kernel', 'weight'], ['encoder_layer_norm.', 'encoder.layer_norm.'], ['decoder_layer_norm.', 'decoder.layer_norm.'], ['embeddings.weights', 'shared.weight'], ] def lowerCAmelCase__ ( UpperCamelCase__ ): '''simple docstring''' for pegasus_name, hf_name in PATTERNS: _a : Optional[Any] = k.replace(UpperCamelCase__ , UpperCamelCase__ ) return k def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' _a : Union[str, Any] = DEFAULTS.copy() cfg_kwargs.update(UpperCamelCase__ ) _a : Optional[Any] = PegasusConfig(**UpperCamelCase__ ) _a : Tuple = PegasusForConditionalGeneration(UpperCamelCase__ ) _a : str = torch_model.model.state_dict() _a : Union[str, Any] = {} for k, v in tf_weights.items(): _a : Any = rename_state_dict_key(UpperCamelCase__ ) if new_k not in sd: raise ValueError(F"""could not find new key {new_k} in state dict. (converted from {k})""" ) if "dense" in k or "proj" in new_k: _a : str = v.T _a : int = torch.tensor(UpperCamelCase__ , dtype=sd[new_k].dtype ) assert v.shape == sd[new_k].shape, F"""{new_k}, {k}, {v.shape}, {sd[new_k].shape}""" # make sure embedding.padding_idx is respected _a : Union[str, Any] = torch.zeros_like(mapping["""shared.weight"""][cfg.pad_token_id + 1] ) _a : str = mapping["""shared.weight"""] _a : Union[str, Any] = mapping["""shared.weight"""] _a : Optional[Any] = {k: torch.zeros_like(UpperCamelCase__ ) for k, v in sd.items() if k.endswith("""bias""" ) and k not in mapping} mapping.update(**UpperCamelCase__ ) _a , _a : int = torch_model.model.load_state_dict(UpperCamelCase__ , strict=UpperCamelCase__ ) _a : Optional[Any] = [ k for k in missing if k not in ["""encoder.embed_positions.weight""", """decoder.embed_positions.weight"""] ] assert unexpected_missing == [], F"""no matches found for the following torch keys {unexpected_missing}""" assert extra == [], F"""no matches found for the following tf keys {extra}""" return torch_model def lowerCAmelCase__ ( UpperCamelCase__="./ckpt/aeslc/model.ckpt-32000" ): '''simple docstring''' _a : List[Any] = tf.train.list_variables(UpperCamelCase__ ) _a : Optional[int] = {} _a : Dict = ["""Adafactor""", """global_step"""] for name, shape in tqdm(UpperCamelCase__ , desc="""converting tf checkpoint to dict""" ): _a : Optional[Any] = any(pat in name for pat in ignore_name ) if skip_key: continue _a : str = tf.train.load_variable(UpperCamelCase__ , UpperCamelCase__ ) _a : int = array return tf_weights def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' # save tokenizer first _a : Dict = Path(UpperCamelCase__ ).parent.name _a : Optional[Any] = task_specific_params[F"""summarization_{dataset}"""]["""max_position_embeddings"""] _a : Tuple = PegasusTokenizer.from_pretrained("""sshleifer/pegasus""" , model_max_length=UpperCamelCase__ ) assert tok.model_max_length == desired_max_model_length tok.save_pretrained(UpperCamelCase__ ) # convert model _a : List[Any] = get_tf_weights_as_numpy(UpperCamelCase__ ) _a : Dict = task_specific_params[F"""summarization_{dataset}"""] if dataset == "large": _a : Tuple = task_specific_params _a : Optional[int] = convert_pegasus(UpperCamelCase__ , UpperCamelCase__ ) torch_model.save_pretrained(UpperCamelCase__ ) _a : Dict = torch_model.state_dict() sd.pop("""model.decoder.embed_positions.weight""" ) sd.pop("""model.encoder.embed_positions.weight""" ) torch.save(UpperCamelCase__ , Path(UpperCamelCase__ ) / """pytorch_model.bin""" ) if __name__ == "__main__": _snake_case = argparse.ArgumentParser() # Required parameters parser.add_argument('tf_ckpt_path', type=str, help='passed to tf.train.list_variables') parser.add_argument('save_dir', default=None, type=str, help='Path to the output PyTorch model.') _snake_case = parser.parse_args() if args.save_dir is None: _snake_case = Path(args.tf_ckpt_path).parent.name _snake_case = os.path.join('pegasus', dataset) convert_pegasus_ckpt_to_pytorch(args.tf_ckpt_path, args.save_dir)
324
"""simple docstring""" import os from huggingface_hub.constants import HUGGINGFACE_HUB_CACHE, hf_cache_home _snake_case = HUGGINGFACE_HUB_CACHE _snake_case = 'config.json' _snake_case = 'diffusion_pytorch_model.bin' _snake_case = 'diffusion_flax_model.msgpack' _snake_case = 'model.onnx' _snake_case = 'diffusion_pytorch_model.safetensors' _snake_case = 'weights.pb' _snake_case = 'https://huggingface.co' _snake_case = default_cache_path _snake_case = 'diffusers_modules' _snake_case = os.getenv('HF_MODULES_CACHE', os.path.join(hf_cache_home, 'modules')) _snake_case = ['fp16', 'non-ema'] _snake_case = '.self_attn'
324
1
"""simple docstring""" import gc import unittest from diffusers import FlaxStableDiffusionInpaintPipeline from diffusers.utils import is_flax_available, load_image, slow from diffusers.utils.testing_utils import require_flax if is_flax_available(): import jax import jax.numpy as jnp from flax.jax_utils import replicate from flax.training.common_utils import shard @slow @require_flax class UpperCamelCase ( unittest.TestCase ): def _lowercase ( self : Optional[Any] ) -> Union[str, Any]: # clean up the VRAM after each test super().tearDown() gc.collect() def _lowercase ( self : Union[str, Any] ) -> Union[str, Any]: _a : Any = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) _a : int = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) _a : List[Any] = """xvjiarui/stable-diffusion-2-inpainting""" _a , _a : Tuple = FlaxStableDiffusionInpaintPipeline.from_pretrained(UpperCAmelCase__ , safety_checker=UpperCAmelCase__ ) _a : str = """Face of a yellow cat, high resolution, sitting on a park bench""" _a : List[Any] = jax.random.PRNGKey(0 ) _a : Any = 50 _a : Dict = jax.device_count() _a : Optional[int] = num_samples * [prompt] _a : int = num_samples * [init_image] _a : Dict = num_samples * [mask_image] _a , _a , _a : str = pipeline.prepare_inputs(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) # shard inputs and rng _a : Any = replicate(UpperCAmelCase__ ) _a : Optional[Any] = jax.random.split(UpperCAmelCase__ , jax.device_count() ) _a : Tuple = shard(UpperCAmelCase__ ) _a : List[str] = shard(UpperCAmelCase__ ) _a : Any = shard(UpperCAmelCase__ ) _a : List[str] = pipeline( UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , jit=UpperCAmelCase__ ) _a : List[Any] = output.images.reshape(UpperCAmelCase__ , 512 , 512 , 3 ) _a : Union[str, Any] = images[0, 253:256, 253:256, -1] _a : Union[str, Any] = jnp.asarray(jax.device_get(image_slice.flatten() ) ) _a : Union[str, Any] = jnp.array( [0.3_6_1_1_3_0_7, 0.3_7_6_4_9_7_3_6, 0.3_7_5_7_4_0_8, 0.3_8_2_1_3_9_5_3, 0.3_9_2_9_5_1_6_7, 0.3_8_4_1_6_3_1, 0.4_1_5_5_4_9_7_8, 0.4_1_3_7_4_7_5, 0.4_2_1_7_0_8_4] ) print(f"""output_slice: {output_slice}""" ) assert jnp.abs(output_slice - expected_slice ).max() < 1E-2
324
"""simple docstring""" from math import factorial def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' if successes > trials: raise ValueError("""successes must be lower or equal to trials""" ) if trials < 0 or successes < 0: raise ValueError("""the function is defined for non-negative integers""" ) if not isinstance(UpperCamelCase__ , UpperCamelCase__ ) or not isinstance(UpperCamelCase__ , UpperCamelCase__ ): raise ValueError("""the function is defined for non-negative integers""" ) if not 0 < prob < 1: raise ValueError("""prob has to be in range of 1 - 0""" ) _a : Optional[int] = (prob**successes) * ((1 - prob) ** (trials - successes)) # Calculate the binomial coefficient: n! / k!(n-k)! _a : Optional[int] = float(factorial(UpperCamelCase__ ) ) coefficient /= factorial(UpperCamelCase__ ) * factorial(trials - successes ) return probability * coefficient if __name__ == "__main__": from doctest import testmod testmod() print('Probability of 2 successes out of 4 trails') print('with probability of 0.75 is:', end=' ') print(binomial_distribution(2, 4, 0.75))
324
1
"""simple docstring""" from typing import List, Optional, Union import numpy as np import PIL.Image from ...image_processing_utils import BaseImageProcessor, BatchFeature from ...image_transforms import rescale, resize, to_channel_dimension_format from ...image_utils import ( ChannelDimension, PILImageResampling, get_image_size, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, logging _snake_case = logging.get_logger(__name__) class UpperCamelCase ( snake_case_ ): UpperCamelCase : Dict = ['''pixel_values'''] def __init__( self : Any , UpperCAmelCase__ : bool = True , UpperCAmelCase__ : int = 32 , UpperCAmelCase__ : Optional[Any]=PILImageResampling.BILINEAR , UpperCAmelCase__ : bool = True , **UpperCAmelCase__ : List[str] , ) -> None: _a : int = do_resize _a : Union[str, Any] = do_rescale _a : Any = size_divisor _a : Any = resample super().__init__(**UpperCAmelCase__ ) def _lowercase ( self : Tuple , UpperCAmelCase__ : np.ndarray , UpperCAmelCase__ : int , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Optional[ChannelDimension] = None , **UpperCAmelCase__ : Optional[Any] ) -> np.ndarray: _a , _a : Tuple = get_image_size(UpperCAmelCase__ ) # Rounds the height and width down to the closest multiple of size_divisor _a : Optional[Any] = height // size_divisor * size_divisor _a : Union[str, Any] = width // size_divisor * size_divisor _a : Any = resize(UpperCAmelCase__ , (new_h, new_w) , resample=UpperCAmelCase__ , data_format=UpperCAmelCase__ , **UpperCAmelCase__ ) return image def _lowercase ( self : Union[str, Any] , UpperCAmelCase__ : np.ndarray , UpperCAmelCase__ : float , UpperCAmelCase__ : Optional[ChannelDimension] = None , **UpperCAmelCase__ : Optional[int] ) -> np.ndarray: return rescale(image=UpperCAmelCase__ , scale=UpperCAmelCase__ , data_format=UpperCAmelCase__ , **UpperCAmelCase__ ) def _lowercase ( self : Optional[int] , UpperCAmelCase__ : Union["PIL.Image.Image", TensorType, List["PIL.Image.Image"], List[TensorType]] , UpperCAmelCase__ : Optional[bool] = None , UpperCAmelCase__ : Optional[int] = None , UpperCAmelCase__ : int=None , UpperCAmelCase__ : Optional[bool] = None , UpperCAmelCase__ : Optional[Union[TensorType, str]] = None , UpperCAmelCase__ : ChannelDimension = ChannelDimension.FIRST , **UpperCAmelCase__ : int , ) -> BatchFeature: _a : Dict = do_resize if do_resize is not None else self.do_resize _a : Optional[int] = do_rescale if do_rescale is not None else self.do_rescale _a : str = size_divisor if size_divisor is not None else self.size_divisor _a : Any = resample if resample is not None else self.resample if do_resize and size_divisor is None: raise ValueError("""size_divisor is required for resizing""" ) _a : List[str] = make_list_of_images(UpperCAmelCase__ ) if not valid_images(UpperCAmelCase__ ): raise ValueError("""Invalid image(s)""" ) # All transformations expect numpy arrays. _a : Tuple = [to_numpy_array(UpperCAmelCase__ ) for img in images] if do_resize: _a : Optional[int] = [self.resize(UpperCAmelCase__ , size_divisor=UpperCAmelCase__ , resample=UpperCAmelCase__ ) for image in images] if do_rescale: _a : str = [self.rescale(UpperCAmelCase__ , scale=1 / 255 ) for image in images] _a : Any = [to_channel_dimension_format(UpperCAmelCase__ , UpperCAmelCase__ ) for image in images] _a : Optional[int] = {"""pixel_values""": images} return BatchFeature(data=UpperCAmelCase__ , tensor_type=UpperCAmelCase__ )
324
"""simple docstring""" def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' _a , _a : Dict = len(UpperCamelCase__ ), len(grid[0] ) if ( min(UpperCamelCase__ , UpperCamelCase__ ) < 0 or row == row_length or col == col_length or (row, col) in visit or grid[row][col] == 1 ): return 0 if row == row_length - 1 and col == col_length - 1: return 1 visit.add((row, col) ) _a : Any = 0 count += depth_first_search(UpperCamelCase__ , row + 1 , UpperCamelCase__ , UpperCamelCase__ ) count += depth_first_search(UpperCamelCase__ , row - 1 , UpperCamelCase__ , UpperCamelCase__ ) count += depth_first_search(UpperCamelCase__ , UpperCamelCase__ , col + 1 , UpperCamelCase__ ) count += depth_first_search(UpperCamelCase__ , UpperCamelCase__ , col - 1 , UpperCamelCase__ ) visit.remove((row, col) ) return count if __name__ == "__main__": import doctest doctest.testmod()
324
1
"""simple docstring""" import argparse import os from pathlib import Path import torch from bark.generation import _load_model as _bark_load_model from huggingface_hub import hf_hub_download from transformers import EncodecConfig, EncodecModel, set_seed from transformers.models.bark.configuration_bark import ( BarkCoarseConfig, BarkConfig, BarkFineConfig, BarkSemanticConfig, ) from transformers.models.bark.generation_configuration_bark import ( BarkCoarseGenerationConfig, BarkFineGenerationConfig, BarkGenerationConfig, BarkSemanticGenerationConfig, ) from transformers.models.bark.modeling_bark import BarkCoarseModel, BarkFineModel, BarkModel, BarkSemanticModel from transformers.utils import logging logging.set_verbosity_info() _snake_case = logging.get_logger(__name__) set_seed(770) _snake_case = { 'c_attn': 'att_proj', 'c_proj': 'out_proj', 'c_fc': 'in_proj', 'transformer.': '', 'h.': 'layers.', 'ln_1': 'layernorm_1', 'ln_2': 'layernorm_2', 'ln_f': 'layernorm_final', 'wpe': 'position_embeds_layer', 'wte': 'input_embeds_layer', } _snake_case = { 'text_small': { 'repo_id': 'suno/bark', 'file_name': 'text.pt', }, 'coarse_small': { 'repo_id': 'suno/bark', 'file_name': 'coarse.pt', }, 'fine_small': { 'repo_id': 'suno/bark', 'file_name': 'fine.pt', }, 'text': { 'repo_id': 'suno/bark', 'file_name': 'text_2.pt', }, 'coarse': { 'repo_id': 'suno/bark', 'file_name': 'coarse_2.pt', }, 'fine': { 'repo_id': 'suno/bark', 'file_name': 'fine_2.pt', }, } _snake_case = os.path.dirname(os.path.abspath(__file__)) _snake_case = os.path.join(os.path.expanduser('~'), '.cache') _snake_case = os.path.join(os.getenv('XDG_CACHE_HOME', default_cache_dir), 'suno', 'bark_v0') def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__=False ): '''simple docstring''' _a : Tuple = model_type if use_small: key += "_small" return os.path.join(UpperCamelCase__ , REMOTE_MODEL_PATHS[key]["""file_name"""] ) def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' os.makedirs(UpperCamelCase__ , exist_ok=UpperCamelCase__ ) hf_hub_download(repo_id=UpperCamelCase__ , filename=UpperCamelCase__ , local_dir=UpperCamelCase__ ) def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__=False , UpperCamelCase__="text" ): '''simple docstring''' if model_type == "text": _a : Optional[Any] = BarkSemanticModel _a : Union[str, Any] = BarkSemanticConfig _a : Dict = BarkSemanticGenerationConfig elif model_type == "coarse": _a : int = BarkCoarseModel _a : Union[str, Any] = BarkCoarseConfig _a : str = BarkCoarseGenerationConfig elif model_type == "fine": _a : Dict = BarkFineModel _a : List[Any] = BarkFineConfig _a : str = BarkFineGenerationConfig else: raise NotImplementedError() _a : int = F"""{model_type}_small""" if use_small else model_type _a : Optional[int] = REMOTE_MODEL_PATHS[model_key] if not os.path.exists(UpperCamelCase__ ): logger.info(F"""{model_type} model not found, downloading into `{CACHE_DIR}`.""" ) _download(model_info["""repo_id"""] , model_info["""file_name"""] ) _a : List[Any] = torch.load(UpperCamelCase__ , map_location=UpperCamelCase__ ) # this is a hack _a : Union[str, Any] = checkpoint["""model_args"""] if "input_vocab_size" not in model_args: _a : Any = model_args["""vocab_size"""] _a : Optional[int] = model_args["""vocab_size"""] del model_args["vocab_size"] # convert Bark model arguments to HF Bark model arguments _a : Dict = model_args.pop("""n_head""" ) _a : str = model_args.pop("""n_embd""" ) _a : int = model_args.pop("""n_layer""" ) _a : Any = ConfigClass(**checkpoint["""model_args"""] ) _a : Optional[Any] = ModelClass(config=UpperCamelCase__ ) _a : List[str] = GenerationConfigClass() _a : Union[str, Any] = model_generation_config _a : Tuple = checkpoint["""model"""] # fixup checkpoint _a : str = """_orig_mod.""" for k, v in list(state_dict.items() ): if k.startswith(UpperCamelCase__ ): # replace part of the key with corresponding layer name in HF implementation _a : List[Any] = k[len(UpperCamelCase__ ) :] for old_layer_name in new_layer_name_dict: _a : Dict = new_k.replace(UpperCamelCase__ , new_layer_name_dict[old_layer_name] ) _a : Optional[Any] = state_dict.pop(UpperCamelCase__ ) _a : Dict = set(state_dict.keys() ) - set(model.state_dict().keys() ) _a : Tuple = {k for k in extra_keys if not k.endswith(""".attn.bias""" )} _a : List[Any] = set(model.state_dict().keys() ) - set(state_dict.keys() ) _a : int = {k for k in missing_keys if not k.endswith(""".attn.bias""" )} if len(UpperCamelCase__ ) != 0: raise ValueError(F"""extra keys found: {extra_keys}""" ) if len(UpperCamelCase__ ) != 0: raise ValueError(F"""missing keys: {missing_keys}""" ) model.load_state_dict(UpperCamelCase__ , strict=UpperCamelCase__ ) _a : int = model.num_parameters(exclude_embeddings=UpperCamelCase__ ) _a : Union[str, Any] = checkpoint["""best_val_loss"""].item() logger.info(F"""model loaded: {round(n_params/1e6 , 1 )}M params, {round(UpperCamelCase__ , 3 )} loss""" ) model.eval() model.to(UpperCamelCase__ ) del checkpoint, state_dict return model def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__=False , UpperCamelCase__="text" ): '''simple docstring''' if model_type not in ("text", "coarse", "fine"): raise NotImplementedError() _a : Any = """cpu""" # do conversion on cpu _a : Union[str, Any] = _get_ckpt_path(UpperCamelCase__ , use_small=UpperCamelCase__ ) _a : Any = _load_model(UpperCamelCase__ , UpperCamelCase__ , model_type=UpperCamelCase__ , use_small=UpperCamelCase__ ) # load bark initial model _a : List[str] = _bark_load_model(UpperCamelCase__ , """cpu""" , model_type=UpperCamelCase__ , use_small=UpperCamelCase__ ) if model_type == "text": _a : Any = bark_model["""model"""] if model.num_parameters(exclude_embeddings=UpperCamelCase__ ) != bark_model.get_num_params(): raise ValueError("""initial and new models don't have the same number of parameters""" ) # check if same output as the bark model _a : Dict = 5 _a : List[str] = 1_0 if model_type in ["text", "coarse"]: _a : List[Any] = torch.randint(2_5_6 , (batch_size, sequence_length) , dtype=torch.int ) _a : Dict = bark_model(UpperCamelCase__ )[0] _a : Any = model(UpperCamelCase__ ) # take last logits _a : List[Any] = output_new_model_total.logits[:, [-1], :] else: _a : Optional[Any] = 3 _a : int = 8 _a : List[str] = torch.randint(2_5_6 , (batch_size, sequence_length, n_codes_total) , dtype=torch.int ) _a : Union[str, Any] = model(UpperCamelCase__ , UpperCamelCase__ ) _a : Any = bark_model(UpperCamelCase__ , UpperCamelCase__ ) _a : List[Any] = output_new_model_total.logits # output difference should come from the difference of self-attention implementation design if output_new_model.shape != output_old_model.shape: raise ValueError("""initial and new outputs don't have the same shape""" ) if (output_new_model - output_old_model).abs().max().item() > 1e-3: raise ValueError("""initial and new outputs are not equal""" ) Path(UpperCamelCase__ ).mkdir(exist_ok=UpperCamelCase__ ) model.save_pretrained(UpperCamelCase__ ) def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , ): '''simple docstring''' _a : List[str] = os.path.join(UpperCamelCase__ , UpperCamelCase__ ) _a : List[Any] = BarkSemanticConfig.from_pretrained(os.path.join(UpperCamelCase__ , """config.json""" ) ) _a : Optional[int] = BarkCoarseConfig.from_pretrained(os.path.join(UpperCamelCase__ , """config.json""" ) ) _a : int = BarkFineConfig.from_pretrained(os.path.join(UpperCamelCase__ , """config.json""" ) ) _a : Optional[Any] = EncodecConfig.from_pretrained("""facebook/encodec_24khz""" ) _a : Any = BarkSemanticModel.from_pretrained(UpperCamelCase__ ) _a : Any = BarkCoarseModel.from_pretrained(UpperCamelCase__ ) _a : List[str] = BarkFineModel.from_pretrained(UpperCamelCase__ ) _a : List[Any] = EncodecModel.from_pretrained("""facebook/encodec_24khz""" ) _a : Union[str, Any] = BarkConfig.from_sub_model_configs( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) _a : List[Any] = BarkGenerationConfig.from_sub_model_configs( semantic.generation_config , coarseAcoustic.generation_config , fineAcoustic.generation_config ) _a : List[str] = BarkModel(UpperCamelCase__ ) _a : int = semantic _a : Dict = coarseAcoustic _a : Union[str, Any] = fineAcoustic _a : str = codec _a : Optional[Any] = bark_generation_config Path(UpperCamelCase__ ).mkdir(exist_ok=UpperCamelCase__ ) bark.save_pretrained(UpperCamelCase__ , repo_id=UpperCamelCase__ , push_to_hub=UpperCamelCase__ ) if __name__ == "__main__": _snake_case = argparse.ArgumentParser() # Required parameters parser.add_argument('model_type', type=str, help='text, coarse or fine.') parser.add_argument('pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') parser.add_argument('--is_small', action='store_true', help='convert the small version instead of the large.') _snake_case = parser.parse_args() load_model(args.pytorch_dump_folder_path, model_type=args.model_type, use_small=args.is_small)
324
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) _snake_case = { 'configuration_vision_encoder_decoder': ['VisionEncoderDecoderConfig', 'VisionEncoderDecoderOnnxConfig'] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _snake_case = ['VisionEncoderDecoderModel'] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _snake_case = ['TFVisionEncoderDecoderModel'] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _snake_case = ['FlaxVisionEncoderDecoderModel'] if TYPE_CHECKING: from .configuration_vision_encoder_decoder import VisionEncoderDecoderConfig, VisionEncoderDecoderOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_vision_encoder_decoder import VisionEncoderDecoderModel try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_vision_encoder_decoder import TFVisionEncoderDecoderModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_vision_encoder_decoder import FlaxVisionEncoderDecoderModel else: import sys _snake_case = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
324
1
"""simple docstring""" _snake_case = [ (1000, 'M'), (900, 'CM'), (500, 'D'), (400, 'CD'), (100, 'C'), (90, 'XC'), (50, 'L'), (40, 'XL'), (10, 'X'), (9, 'IX'), (5, 'V'), (4, 'IV'), (1, 'I'), ] def lowerCAmelCase__ ( UpperCamelCase__ ): '''simple docstring''' _a : int = {"""I""": 1, """V""": 5, """X""": 1_0, """L""": 5_0, """C""": 1_0_0, """D""": 5_0_0, """M""": 1_0_0_0} _a : Optional[Any] = 0 _a : Optional[Any] = 0 while place < len(UpperCamelCase__ ): if (place + 1 < len(UpperCamelCase__ )) and (vals[roman[place]] < vals[roman[place + 1]]): total += vals[roman[place + 1]] - vals[roman[place]] place += 2 else: total += vals[roman[place]] place += 1 return total def lowerCAmelCase__ ( UpperCamelCase__ ): '''simple docstring''' _a : Tuple = [] for arabic, roman in ROMAN: ((_a) , (_a)) : Dict = divmod(UpperCamelCase__ , UpperCamelCase__ ) result.append(roman * factor ) if number == 0: break return "".join(UpperCamelCase__ ) if __name__ == "__main__": import doctest doctest.testmod()
324
"""simple docstring""" from __future__ import annotations import time _snake_case = list[tuple[int, int]] _snake_case = [ [0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles [0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0], [1, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0], ] _snake_case = [[-1, 0], [0, -1], [1, 0], [0, 1]] # up, left, down, right class UpperCamelCase : def __init__( self : Optional[int] , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : Node | None ) -> List[str]: _a : int = pos_x _a : Union[str, Any] = pos_y _a : Tuple = (pos_y, pos_x) _a : Tuple = goal_x _a : int = goal_y _a : str = parent class UpperCamelCase : def __init__( self : List[Any] , UpperCAmelCase__ : tuple[int, int] , UpperCAmelCase__ : tuple[int, int] ) -> List[str]: _a : List[Any] = Node(start[1] , start[0] , goal[1] , goal[0] , UpperCAmelCase__ ) _a : List[str] = Node(goal[1] , goal[0] , goal[1] , goal[0] , UpperCAmelCase__ ) _a : Optional[int] = [self.start] _a : Tuple = False def _lowercase ( self : str ) -> Path | None: while self.node_queue: _a : Tuple = self.node_queue.pop(0 ) if current_node.pos == self.target.pos: _a : Dict = True return self.retrace_path(UpperCAmelCase__ ) _a : Tuple = self.get_successors(UpperCAmelCase__ ) for node in successors: self.node_queue.append(UpperCAmelCase__ ) if not self.reached: return [self.start.pos] return None def _lowercase ( self : Optional[int] , UpperCAmelCase__ : Node ) -> list[Node]: _a : Optional[Any] = [] for action in delta: _a : str = parent.pos_x + action[1] _a : List[Any] = parent.pos_y + action[0] if not (0 <= pos_x <= len(grid[0] ) - 1 and 0 <= pos_y <= len(UpperCAmelCase__ ) - 1): continue if grid[pos_y][pos_x] != 0: continue successors.append( Node(UpperCAmelCase__ , UpperCAmelCase__ , self.target.pos_y , self.target.pos_x , UpperCAmelCase__ ) ) return successors def _lowercase ( self : List[Any] , UpperCAmelCase__ : Node | None ) -> Path: _a : Dict = node _a : List[str] = [] while current_node is not None: path.append((current_node.pos_y, current_node.pos_x) ) _a : Any = current_node.parent path.reverse() return path class UpperCamelCase : def __init__( self : List[str] , UpperCAmelCase__ : int , UpperCAmelCase__ : List[Any] ) -> Any: _a : Dict = BreadthFirstSearch(UpperCAmelCase__ , UpperCAmelCase__ ) _a : Optional[int] = BreadthFirstSearch(UpperCAmelCase__ , UpperCAmelCase__ ) _a : Dict = False def _lowercase ( self : Any ) -> Path | None: while self.fwd_bfs.node_queue or self.bwd_bfs.node_queue: _a : List[Any] = self.fwd_bfs.node_queue.pop(0 ) _a : Union[str, Any] = self.bwd_bfs.node_queue.pop(0 ) if current_bwd_node.pos == current_fwd_node.pos: _a : Optional[int] = True return self.retrace_bidirectional_path( UpperCAmelCase__ , UpperCAmelCase__ ) _a : List[str] = current_bwd_node _a : int = current_fwd_node _a : Optional[Any] = { self.fwd_bfs: self.fwd_bfs.get_successors(UpperCAmelCase__ ), self.bwd_bfs: self.bwd_bfs.get_successors(UpperCAmelCase__ ), } for bfs in [self.fwd_bfs, self.bwd_bfs]: for node in successors[bfs]: bfs.node_queue.append(UpperCAmelCase__ ) if not self.reached: return [self.fwd_bfs.start.pos] return None def _lowercase ( self : Optional[int] , UpperCAmelCase__ : Node , UpperCAmelCase__ : Node ) -> Path: _a : str = self.fwd_bfs.retrace_path(UpperCAmelCase__ ) _a : List[Any] = self.bwd_bfs.retrace_path(UpperCAmelCase__ ) bwd_path.pop() bwd_path.reverse() _a : Tuple = fwd_path + bwd_path return path if __name__ == "__main__": # all coordinates are given in format [y,x] import doctest doctest.testmod() _snake_case = (0, 0) _snake_case = (len(grid) - 1, len(grid[0]) - 1) for elem in grid: print(elem) _snake_case = time.time() _snake_case = BreadthFirstSearch(init, goal) _snake_case = bfs.search() _snake_case = time.time() - start_bfs_time print('Unidirectional BFS computation time : ', bfs_time) _snake_case = time.time() _snake_case = BidirectionalBreadthFirstSearch(init, goal) _snake_case = bd_bfs.search() _snake_case = time.time() - start_bd_bfs_time print('Bidirectional BFS computation time : ', bd_bfs_time)
324
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available _snake_case = { 'configuration_altclip': [ 'ALTCLIP_PRETRAINED_CONFIG_ARCHIVE_MAP', 'AltCLIPConfig', 'AltCLIPTextConfig', 'AltCLIPVisionConfig', ], 'processing_altclip': ['AltCLIPProcessor'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _snake_case = [ 'ALTCLIP_PRETRAINED_MODEL_ARCHIVE_LIST', 'AltCLIPPreTrainedModel', 'AltCLIPModel', 'AltCLIPTextModel', 'AltCLIPVisionModel', ] if TYPE_CHECKING: from .configuration_altclip import ( ALTCLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, AltCLIPConfig, AltCLIPTextConfig, AltCLIPVisionConfig, ) from .processing_altclip import AltCLIPProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_altclip import ( ALTCLIP_PRETRAINED_MODEL_ARCHIVE_LIST, AltCLIPModel, AltCLIPPreTrainedModel, AltCLIPTextModel, AltCLIPVisionModel, ) else: import sys _snake_case = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
324
"""simple docstring""" import logging import math import os from dataclasses import dataclass, field from glob import glob from typing import Optional from torch.utils.data import ConcatDataset import transformers from transformers import ( CONFIG_MAPPING, MODEL_WITH_LM_HEAD_MAPPING, AutoConfig, AutoModelWithLMHead, AutoTokenizer, DataCollatorForLanguageModeling, DataCollatorForPermutationLanguageModeling, DataCollatorForWholeWordMask, HfArgumentParser, LineByLineTextDataset, LineByLineWithRefDataset, PreTrainedTokenizer, TextDataset, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import is_main_process _snake_case = logging.getLogger(__name__) _snake_case = list(MODEL_WITH_LM_HEAD_MAPPING.keys()) _snake_case = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES) @dataclass class UpperCamelCase : UpperCamelCase : Optional[str] = field( default=snake_case_ , metadata={ '''help''': ( '''The model checkpoint for weights initialization. Leave None if you want to train a model from''' ''' scratch.''' ) } , ) UpperCamelCase : Optional[str] = field( default=snake_case_ , metadata={'''help''': '''If training from scratch, pass a model type from the list: ''' + ''', '''.join(snake_case_ )} , ) UpperCamelCase : Optional[str] = field( default=snake_case_ , metadata={'''help''': '''Pretrained config name or path if not the same as model_name'''} ) UpperCamelCase : Optional[str] = field( default=snake_case_ , metadata={'''help''': '''Pretrained tokenizer name or path if not the same as model_name'''} ) UpperCamelCase : Optional[str] = field( default=snake_case_ , metadata={'''help''': '''Where do you want to store the pretrained models downloaded from huggingface.co'''} , ) @dataclass class UpperCamelCase : UpperCamelCase : Optional[str] = field( default=snake_case_ , metadata={'''help''': '''The input training data file (a text file).'''} ) UpperCamelCase : Optional[str] = field( default=snake_case_ , metadata={ '''help''': ( '''The input training data files (multiple files in glob format). ''' '''Very often splitting large files to smaller files can prevent tokenizer going out of memory''' ) } , ) UpperCamelCase : Optional[str] = field( default=snake_case_ , metadata={'''help''': '''An optional input evaluation data file to evaluate the perplexity on (a text file).'''} , ) UpperCamelCase : Optional[str] = field( default=snake_case_ , metadata={'''help''': '''An optional input train ref data file for whole word mask in Chinese.'''} , ) UpperCamelCase : Optional[str] = field( default=snake_case_ , metadata={'''help''': '''An optional input eval ref data file for whole word mask in Chinese.'''} , ) UpperCamelCase : bool = field( default=snake_case_ , metadata={'''help''': '''Whether distinct lines of text in the dataset are to be handled as distinct sequences.'''} , ) UpperCamelCase : bool = field( default=snake_case_ , metadata={'''help''': '''Train with masked-language modeling loss instead of language modeling.'''} ) UpperCamelCase : bool = field(default=snake_case_ , metadata={'''help''': '''Whether ot not to use whole word mask.'''} ) UpperCamelCase : float = field( default=0.1_5 , metadata={'''help''': '''Ratio of tokens to mask for masked language modeling loss'''} ) UpperCamelCase : float = field( default=1 / 6 , metadata={ '''help''': ( '''Ratio of length of a span of masked tokens to surrounding context length for permutation language''' ''' modeling.''' ) } , ) UpperCamelCase : int = field( default=5 , metadata={'''help''': '''Maximum length of a span of masked tokens for permutation language modeling.'''} ) UpperCamelCase : int = field( default=-1 , metadata={ '''help''': ( '''Optional input sequence length after tokenization.''' '''The training dataset will be truncated in block of this size for training.''' '''Default to the model max input length for single sentence inputs (take into account special tokens).''' ) } , ) UpperCamelCase : bool = field( default=snake_case_ , metadata={'''help''': '''Overwrite the cached training and evaluation sets'''} ) def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = False , UpperCamelCase__ = None , ): '''simple docstring''' def _dataset(UpperCamelCase__ , UpperCamelCase__=None ): if args.line_by_line: if ref_path is not None: if not args.whole_word_mask or not args.mlm: raise ValueError("""You need to set world whole masking and mlm to True for Chinese Whole Word Mask""" ) return LineByLineWithRefDataset( tokenizer=UpperCamelCase__ , file_path=UpperCamelCase__ , block_size=args.block_size , ref_path=UpperCamelCase__ , ) return LineByLineTextDataset(tokenizer=UpperCamelCase__ , file_path=UpperCamelCase__ , block_size=args.block_size ) else: return TextDataset( tokenizer=UpperCamelCase__ , file_path=UpperCamelCase__ , block_size=args.block_size , overwrite_cache=args.overwrite_cache , cache_dir=UpperCamelCase__ , ) if evaluate: return _dataset(args.eval_data_file , args.eval_ref_file ) elif args.train_data_files: return ConcatDataset([_dataset(UpperCamelCase__ ) for f in glob(args.train_data_files )] ) else: return _dataset(args.train_data_file , args.train_ref_file ) def lowerCAmelCase__ ( ): '''simple docstring''' # See all possible arguments in src/transformers/training_args.py # or by passing the --help flag to this script. # We now keep distinct sets of args, for a cleaner separation of concerns. _a : Any = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) _a , _a , _a : List[str] = parser.parse_args_into_dataclasses() if data_args.eval_data_file is None and training_args.do_eval: raise ValueError( """Cannot do evaluation without an evaluation data file. Either supply a file to --eval_data_file """ """or remove the --do_eval argument.""" ) if ( os.path.exists(training_args.output_dir ) and os.listdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir ): raise ValueError( F"""Output directory ({training_args.output_dir}) already exists and is not empty. Use""" """ --overwrite_output_dir to overcome.""" ) # Setup logging logging.basicConfig( format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""" , datefmt="""%m/%d/%Y %H:%M:%S""" , level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN , ) logger.warning( """Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s""" , training_args.local_rank , training_args.device , training_args.n_gpu , bool(training_args.local_rank != -1 ) , training_args.fpaa , ) # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank ): transformers.utils.logging.set_verbosity_info() transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() logger.info("""Training/evaluation parameters %s""" , UpperCamelCase__ ) # Set seed set_seed(training_args.seed ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. if model_args.config_name: _a : str = AutoConfig.from_pretrained(model_args.config_name , cache_dir=model_args.cache_dir ) elif model_args.model_name_or_path: _a : Union[str, Any] = AutoConfig.from_pretrained(model_args.model_name_or_path , cache_dir=model_args.cache_dir ) else: _a : str = CONFIG_MAPPING[model_args.model_type]() logger.warning("""You are instantiating a new config instance from scratch.""" ) if model_args.tokenizer_name: _a : List[str] = AutoTokenizer.from_pretrained(model_args.tokenizer_name , cache_dir=model_args.cache_dir ) elif model_args.model_name_or_path: _a : Union[str, Any] = AutoTokenizer.from_pretrained(model_args.model_name_or_path , cache_dir=model_args.cache_dir ) else: raise ValueError( """You are instantiating a new tokenizer from scratch. This is not supported, but you can do it from another""" """ script, save it,and load it from here, using --tokenizer_name""" ) if model_args.model_name_or_path: _a : Optional[Any] = AutoModelWithLMHead.from_pretrained( model_args.model_name_or_path , from_tf=bool(""".ckpt""" in model_args.model_name_or_path ) , config=UpperCamelCase__ , cache_dir=model_args.cache_dir , ) else: logger.info("""Training new model from scratch""" ) _a : List[Any] = AutoModelWithLMHead.from_config(UpperCamelCase__ ) model.resize_token_embeddings(len(UpperCamelCase__ ) ) if config.model_type in ["bert", "roberta", "distilbert", "camembert"] and not data_args.mlm: raise ValueError( """BERT and RoBERTa-like models do not have LM heads but masked LM heads. They must be run using the""" """--mlm flag (masked language modeling).""" ) if data_args.block_size <= 0: _a : int = tokenizer.max_len # Our input block size will be the max possible for the model else: _a : Optional[Any] = min(data_args.block_size , tokenizer.max_len ) # Get datasets _a : Optional[Any] = ( get_dataset(UpperCamelCase__ , tokenizer=UpperCamelCase__ , cache_dir=model_args.cache_dir ) if training_args.do_train else None ) _a : Optional[int] = ( get_dataset(UpperCamelCase__ , tokenizer=UpperCamelCase__ , evaluate=UpperCamelCase__ , cache_dir=model_args.cache_dir ) if training_args.do_eval else None ) if config.model_type == "xlnet": _a : Any = DataCollatorForPermutationLanguageModeling( tokenizer=UpperCamelCase__ , plm_probability=data_args.plm_probability , max_span_length=data_args.max_span_length , ) else: if data_args.mlm and data_args.whole_word_mask: _a : Union[str, Any] = DataCollatorForWholeWordMask( tokenizer=UpperCamelCase__ , mlm_probability=data_args.mlm_probability ) else: _a : str = DataCollatorForLanguageModeling( tokenizer=UpperCamelCase__ , mlm=data_args.mlm , mlm_probability=data_args.mlm_probability ) # Initialize our Trainer _a : Union[str, Any] = Trainer( model=UpperCamelCase__ , args=UpperCamelCase__ , data_collator=UpperCamelCase__ , train_dataset=UpperCamelCase__ , eval_dataset=UpperCamelCase__ , prediction_loss_only=UpperCamelCase__ , ) # Training if training_args.do_train: _a : Optional[Any] = ( model_args.model_name_or_path if model_args.model_name_or_path is not None and os.path.isdir(model_args.model_name_or_path ) else None ) trainer.train(model_path=UpperCamelCase__ ) trainer.save_model() # For convenience, we also re-save the tokenizer to the same directory, # so that you can share your model easily on huggingface.co/models =) if trainer.is_world_master(): tokenizer.save_pretrained(training_args.output_dir ) # Evaluation _a : Union[str, Any] = {} if training_args.do_eval: logger.info("""*** Evaluate ***""" ) _a : int = trainer.evaluate() _a : Dict = math.exp(eval_output["""eval_loss"""] ) _a : Union[str, Any] = {"""perplexity""": perplexity} _a : Optional[Any] = os.path.join(training_args.output_dir , """eval_results_lm.txt""" ) if trainer.is_world_master(): with open(UpperCamelCase__ , """w""" ) as writer: logger.info("""***** Eval results *****""" ) for key in sorted(result.keys() ): logger.info(""" %s = %s""" , UpperCamelCase__ , str(result[key] ) ) writer.write("""%s = %s\n""" % (key, str(result[key] )) ) results.update(UpperCamelCase__ ) return results def lowerCAmelCase__ ( UpperCamelCase__ ): '''simple docstring''' # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
324
1
"""simple docstring""" import doctest import glob import importlib import inspect import os import re from contextlib import contextmanager from functools import wraps from unittest.mock import patch import numpy as np import pytest from absl.testing import parameterized import datasets from datasets import load_metric from .utils import for_all_test_methods, local, slow # mark all tests as integration _snake_case = pytest.mark.integration _snake_case = {'comet'} _snake_case = importlib.util.find_spec('fairseq') is not None _snake_case = {'code_eval'} _snake_case = os.name == 'nt' _snake_case = {'bertscore', 'frugalscore', 'perplexity'} _snake_case = importlib.util.find_spec('transformers') is not None def lowerCAmelCase__ ( UpperCamelCase__ ): '''simple docstring''' @wraps(UpperCamelCase__ ) def wrapper(self , UpperCamelCase__ ): if not _has_fairseq and metric_name in REQUIRE_FAIRSEQ: self.skipTest("""\"test requires Fairseq\"""" ) else: test_case(self , UpperCamelCase__ ) return wrapper def lowerCAmelCase__ ( UpperCamelCase__ ): '''simple docstring''' @wraps(UpperCamelCase__ ) def wrapper(self , UpperCamelCase__ ): if not _has_transformers and metric_name in REQUIRE_TRANSFORMERS: self.skipTest("""\"test requires transformers\"""" ) else: test_case(self , UpperCamelCase__ ) return wrapper def lowerCAmelCase__ ( UpperCamelCase__ ): '''simple docstring''' @wraps(UpperCamelCase__ ) def wrapper(self , UpperCamelCase__ ): if _on_windows and metric_name in UNSUPPORTED_ON_WINDOWS: self.skipTest("""\"test not supported on Windows\"""" ) else: test_case(self , UpperCamelCase__ ) return wrapper def lowerCAmelCase__ ( ): '''simple docstring''' _a : Any = [metric_dir.split(os.sep )[-2] for metric_dir in glob.glob("""./metrics/*/""" )] return [{"testcase_name": x, "metric_name": x} for x in metrics if x != "gleu"] # gleu is unfinished @parameterized.named_parameters(get_local_metric_names() ) @for_all_test_methods( snake_case_ , snake_case_ , snake_case_ ) @local class UpperCamelCase ( parameterized.TestCase ): UpperCamelCase : Optional[Any] = {} UpperCamelCase : Optional[Any] = None @pytest.mark.filterwarnings("""ignore:metric_module_factory is deprecated:FutureWarning""" ) @pytest.mark.filterwarnings("""ignore:load_metric is deprecated:FutureWarning""" ) def _lowercase ( self : List[Any] , UpperCAmelCase__ : str ) -> Union[str, Any]: _a : List[str] = """[...]""" _a : Optional[int] = importlib.import_module( datasets.load.metric_module_factory(os.path.join("""metrics""" , UpperCAmelCase__ ) ).module_path ) _a : int = datasets.load.import_main_class(metric_module.__name__ , dataset=UpperCAmelCase__ ) # check parameters _a : Any = inspect.signature(metric._compute ).parameters self.assertTrue(all(p.kind != p.VAR_KEYWORD for p in parameters.values() ) ) # no **kwargs # run doctest with self.patch_intensive_calls(UpperCAmelCase__ , metric_module.__name__ ): with self.use_local_metrics(): try: _a : int = doctest.testmod(UpperCAmelCase__ , verbose=UpperCAmelCase__ , raise_on_error=UpperCAmelCase__ ) except doctest.UnexpectedException as e: raise e.exc_info[1] # raise the exception that doctest caught self.assertEqual(results.failed , 0 ) self.assertGreater(results.attempted , 1 ) @slow def _lowercase ( self : Tuple , UpperCAmelCase__ : Optional[Any] ) -> int: _a : Union[str, Any] = """[...]""" _a : int = importlib.import_module( datasets.load.metric_module_factory(os.path.join("""metrics""" , UpperCAmelCase__ ) ).module_path ) # run doctest with self.use_local_metrics(): _a : List[str] = doctest.testmod(UpperCAmelCase__ , verbose=UpperCAmelCase__ , raise_on_error=UpperCAmelCase__ ) self.assertEqual(results.failed , 0 ) self.assertGreater(results.attempted , 1 ) @contextmanager def _lowercase ( self : Tuple , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : List[str] ) -> Optional[int]: if metric_name in self.INTENSIVE_CALLS_PATCHER: with self.INTENSIVE_CALLS_PATCHER[metric_name](UpperCAmelCase__ ): yield else: yield @contextmanager def _lowercase ( self : Optional[int] ) -> str: def load_local_metric(UpperCAmelCase__ : List[Any] , *UpperCAmelCase__ : Any , **UpperCAmelCase__ : List[Any] ): return load_metric(os.path.join("""metrics""" , UpperCAmelCase__ ) , *UpperCAmelCase__ , **UpperCAmelCase__ ) with patch("""datasets.load_metric""" ) as mock_load_metric: _a : List[str] = load_local_metric yield @classmethod def _lowercase ( cls : Tuple , UpperCAmelCase__ : List[str] ) -> int: def wrapper(UpperCAmelCase__ : int ): _a : Union[str, Any] = contextmanager(UpperCAmelCase__ ) _a : Dict = patcher return patcher return wrapper @LocalMetricTest.register_intensive_calls_patcher("""bleurt""" ) def lowerCAmelCase__ ( UpperCamelCase__ ): '''simple docstring''' import tensorflow.compat.va as tf from bleurt.score import Predictor tf.flags.DEFINE_string("""sv""" , """""" , """""" ) # handle pytest cli flags class UpperCamelCase ( snake_case_ ): def _lowercase ( self : int , UpperCAmelCase__ : Optional[int] ) -> Union[str, Any]: assert len(input_dict["""input_ids"""] ) == 2 return np.array([1.0_3, 1.0_4] ) # mock predict_fn which is supposed to do a forward pass with a bleurt model with patch("""bleurt.score._create_predictor""" ) as mock_create_predictor: _a : int = MockedPredictor() yield @LocalMetricTest.register_intensive_calls_patcher("""bertscore""" ) def lowerCAmelCase__ ( UpperCamelCase__ ): '''simple docstring''' import torch def bert_cos_score_idf(UpperCamelCase__ , UpperCamelCase__ , *UpperCamelCase__ , **UpperCamelCase__ ): return torch.tensor([[1.0, 1.0, 1.0]] * len(UpperCamelCase__ ) ) # mock get_model which is supposed to do download a bert model # mock bert_cos_score_idf which is supposed to do a forward pass with a bert model with patch("""bert_score.scorer.get_model""" ), patch( """bert_score.scorer.bert_cos_score_idf""" ) as mock_bert_cos_score_idf: _a : List[Any] = bert_cos_score_idf yield @LocalMetricTest.register_intensive_calls_patcher("""comet""" ) def lowerCAmelCase__ ( UpperCamelCase__ ): '''simple docstring''' def load_from_checkpoint(UpperCamelCase__ ): class UpperCamelCase : def _lowercase ( self : Optional[Any] , UpperCAmelCase__ : Dict , *UpperCAmelCase__ : List[str] , **UpperCAmelCase__ : List[str] ) -> Tuple: assert len(UpperCAmelCase__ ) == 2 _a : Optional[Any] = [0.1_9, 0.9_2] return scores, sum(UpperCAmelCase__ ) / len(UpperCAmelCase__ ) return Model() # mock load_from_checkpoint which is supposed to do download a bert model # mock load_from_checkpoint which is supposed to do download a bert model with patch("""comet.download_model""" ) as mock_download_model: _a : Optional[int] = None with patch("""comet.load_from_checkpoint""" ) as mock_load_from_checkpoint: _a : Union[str, Any] = load_from_checkpoint yield def lowerCAmelCase__ ( ): '''simple docstring''' _a : Dict = load_metric(os.path.join("""metrics""" , """seqeval""" ) ) _a : Tuple = """ERROR""" _a : Tuple = F"""Scheme should be one of [IOB1, IOB2, IOE1, IOE2, IOBES, BILOU], got {wrong_scheme}""" with pytest.raises(UpperCamelCase__ , match=re.escape(UpperCamelCase__ ) ): metric.compute(predictions=[] , references=[] , scheme=UpperCamelCase__ )
324
"""simple docstring""" import argparse import os from pathlib import Path from typing import Dict import tensorflow as tf import torch from tqdm import tqdm from transformers import PegasusConfig, PegasusForConditionalGeneration, PegasusTokenizer from transformers.models.pegasus.configuration_pegasus import DEFAULTS, task_specific_params _snake_case = [ # replace left string with right string to get the relevant state_dict key (identical state dict to bart) ['memory_attention', 'encoder_attn'], ['attention', 'attn'], ['/', '.'], ['.LayerNorm.gamma', '_layer_norm.weight'], ['.LayerNorm.beta', '_layer_norm.bias'], ['r.layer_', 'r.layers.'], ['output_proj', 'out_proj'], ['ffn.dense_1.', 'fc2.'], ['ffn.dense.', 'fc1.'], ['ffn_layer_norm', 'final_layer_norm'], ['kernel', 'weight'], ['encoder_layer_norm.', 'encoder.layer_norm.'], ['decoder_layer_norm.', 'decoder.layer_norm.'], ['embeddings.weights', 'shared.weight'], ] def lowerCAmelCase__ ( UpperCamelCase__ ): '''simple docstring''' for pegasus_name, hf_name in PATTERNS: _a : Optional[Any] = k.replace(UpperCamelCase__ , UpperCamelCase__ ) return k def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' _a : Union[str, Any] = DEFAULTS.copy() cfg_kwargs.update(UpperCamelCase__ ) _a : Optional[Any] = PegasusConfig(**UpperCamelCase__ ) _a : Tuple = PegasusForConditionalGeneration(UpperCamelCase__ ) _a : str = torch_model.model.state_dict() _a : Union[str, Any] = {} for k, v in tf_weights.items(): _a : Any = rename_state_dict_key(UpperCamelCase__ ) if new_k not in sd: raise ValueError(F"""could not find new key {new_k} in state dict. (converted from {k})""" ) if "dense" in k or "proj" in new_k: _a : str = v.T _a : int = torch.tensor(UpperCamelCase__ , dtype=sd[new_k].dtype ) assert v.shape == sd[new_k].shape, F"""{new_k}, {k}, {v.shape}, {sd[new_k].shape}""" # make sure embedding.padding_idx is respected _a : Union[str, Any] = torch.zeros_like(mapping["""shared.weight"""][cfg.pad_token_id + 1] ) _a : str = mapping["""shared.weight"""] _a : Union[str, Any] = mapping["""shared.weight"""] _a : Optional[Any] = {k: torch.zeros_like(UpperCamelCase__ ) for k, v in sd.items() if k.endswith("""bias""" ) and k not in mapping} mapping.update(**UpperCamelCase__ ) _a , _a : int = torch_model.model.load_state_dict(UpperCamelCase__ , strict=UpperCamelCase__ ) _a : Optional[Any] = [ k for k in missing if k not in ["""encoder.embed_positions.weight""", """decoder.embed_positions.weight"""] ] assert unexpected_missing == [], F"""no matches found for the following torch keys {unexpected_missing}""" assert extra == [], F"""no matches found for the following tf keys {extra}""" return torch_model def lowerCAmelCase__ ( UpperCamelCase__="./ckpt/aeslc/model.ckpt-32000" ): '''simple docstring''' _a : List[Any] = tf.train.list_variables(UpperCamelCase__ ) _a : Optional[int] = {} _a : Dict = ["""Adafactor""", """global_step"""] for name, shape in tqdm(UpperCamelCase__ , desc="""converting tf checkpoint to dict""" ): _a : Optional[Any] = any(pat in name for pat in ignore_name ) if skip_key: continue _a : str = tf.train.load_variable(UpperCamelCase__ , UpperCamelCase__ ) _a : int = array return tf_weights def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' # save tokenizer first _a : Dict = Path(UpperCamelCase__ ).parent.name _a : Optional[Any] = task_specific_params[F"""summarization_{dataset}"""]["""max_position_embeddings"""] _a : Tuple = PegasusTokenizer.from_pretrained("""sshleifer/pegasus""" , model_max_length=UpperCamelCase__ ) assert tok.model_max_length == desired_max_model_length tok.save_pretrained(UpperCamelCase__ ) # convert model _a : List[Any] = get_tf_weights_as_numpy(UpperCamelCase__ ) _a : Dict = task_specific_params[F"""summarization_{dataset}"""] if dataset == "large": _a : Tuple = task_specific_params _a : Optional[int] = convert_pegasus(UpperCamelCase__ , UpperCamelCase__ ) torch_model.save_pretrained(UpperCamelCase__ ) _a : Dict = torch_model.state_dict() sd.pop("""model.decoder.embed_positions.weight""" ) sd.pop("""model.encoder.embed_positions.weight""" ) torch.save(UpperCamelCase__ , Path(UpperCamelCase__ ) / """pytorch_model.bin""" ) if __name__ == "__main__": _snake_case = argparse.ArgumentParser() # Required parameters parser.add_argument('tf_ckpt_path', type=str, help='passed to tf.train.list_variables') parser.add_argument('save_dir', default=None, type=str, help='Path to the output PyTorch model.') _snake_case = parser.parse_args() if args.save_dir is None: _snake_case = Path(args.tf_ckpt_path).parent.name _snake_case = os.path.join('pegasus', dataset) convert_pegasus_ckpt_to_pytorch(args.tf_ckpt_path, args.save_dir)
324
1
"""simple docstring""" from typing import Dict, List, Optional, Tuple, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_torch_available, is_torch_tensor, logging if is_torch_available(): import torch _snake_case = logging.get_logger(__name__) class UpperCamelCase ( snake_case_ ): UpperCamelCase : int = ['''pixel_values'''] def __init__( self : List[Any] , UpperCAmelCase__ : bool = True , UpperCAmelCase__ : Optional[Dict[str, int]] = None , UpperCAmelCase__ : PILImageResampling = PILImageResampling.BILINEAR , UpperCAmelCase__ : bool = True , UpperCAmelCase__ : Dict[str, int] = None , UpperCAmelCase__ : bool = True , UpperCAmelCase__ : Union[int, float] = 1 / 255 , UpperCAmelCase__ : bool = True , UpperCAmelCase__ : Optional[Union[float, List[float]]] = None , UpperCAmelCase__ : Optional[Union[float, List[float]]] = None , **UpperCAmelCase__ : int , ) -> None: super().__init__(**UpperCAmelCase__ ) _a : Any = size if size is not None else {"""shortest_edge""": 256} _a : List[str] = get_size_dict(UpperCAmelCase__ , default_to_square=UpperCAmelCase__ ) _a : List[Any] = crop_size if crop_size is not None else {"""height""": 224, """width""": 224} _a : int = get_size_dict(UpperCAmelCase__ , param_name="""crop_size""" ) _a : Any = do_resize _a : Any = size _a : Union[str, Any] = resample _a : int = do_center_crop _a : Optional[Any] = crop_size _a : Optional[int] = do_rescale _a : List[str] = rescale_factor _a : Any = do_normalize _a : Dict = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN _a : List[Any] = image_std if image_std is not None else IMAGENET_STANDARD_STD def _lowercase ( self : Tuple , UpperCAmelCase__ : np.ndarray , UpperCAmelCase__ : Dict[str, int] , UpperCAmelCase__ : PILImageResampling = PILImageResampling.BICUBIC , UpperCAmelCase__ : Optional[Union[str, ChannelDimension]] = None , **UpperCAmelCase__ : Any , ) -> np.ndarray: _a : Optional[Any] = get_size_dict(UpperCAmelCase__ , default_to_square=UpperCAmelCase__ ) if "shortest_edge" not in size: raise ValueError(f"""The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}""" ) _a : Union[str, Any] = get_resize_output_image_size(UpperCAmelCase__ , size=size["""shortest_edge"""] , default_to_square=UpperCAmelCase__ ) return resize(UpperCAmelCase__ , size=UpperCAmelCase__ , resample=UpperCAmelCase__ , data_format=UpperCAmelCase__ , **UpperCAmelCase__ ) def _lowercase ( self : Dict , UpperCAmelCase__ : np.ndarray , UpperCAmelCase__ : Dict[str, int] , UpperCAmelCase__ : Optional[Union[str, ChannelDimension]] = None , **UpperCAmelCase__ : int , ) -> np.ndarray: _a : List[Any] = get_size_dict(UpperCAmelCase__ ) if "height" not in size or "width" not in size: raise ValueError(f"""The `size` parameter must contain the keys `height` and `width`. Got {size.keys()}""" ) return center_crop(UpperCAmelCase__ , size=(size["""height"""], size["""width"""]) , data_format=UpperCAmelCase__ , **UpperCAmelCase__ ) def _lowercase ( self : Tuple , UpperCAmelCase__ : np.ndarray , UpperCAmelCase__ : float , UpperCAmelCase__ : Optional[Union[str, ChannelDimension]] = None , **UpperCAmelCase__ : Tuple ) -> np.ndarray: return rescale(UpperCAmelCase__ , scale=UpperCAmelCase__ , data_format=UpperCAmelCase__ , **UpperCAmelCase__ ) def _lowercase ( self : List[Any] , UpperCAmelCase__ : np.ndarray , UpperCAmelCase__ : Union[float, List[float]] , UpperCAmelCase__ : Union[float, List[float]] , UpperCAmelCase__ : Optional[Union[str, ChannelDimension]] = None , **UpperCAmelCase__ : Tuple , ) -> np.ndarray: return normalize(UpperCAmelCase__ , mean=UpperCAmelCase__ , std=UpperCAmelCase__ , data_format=UpperCAmelCase__ , **UpperCAmelCase__ ) def _lowercase ( self : Optional[Any] , UpperCAmelCase__ : ImageInput , UpperCAmelCase__ : Optional[bool] = None , UpperCAmelCase__ : Dict[str, int] = None , UpperCAmelCase__ : PILImageResampling = None , UpperCAmelCase__ : bool = None , UpperCAmelCase__ : Dict[str, int] = None , UpperCAmelCase__ : Optional[bool] = None , UpperCAmelCase__ : Optional[float] = None , UpperCAmelCase__ : Optional[bool] = None , UpperCAmelCase__ : Optional[Union[float, List[float]]] = None , UpperCAmelCase__ : Optional[Union[float, List[float]]] = None , UpperCAmelCase__ : Optional[Union[str, TensorType]] = None , UpperCAmelCase__ : Union[str, ChannelDimension] = ChannelDimension.FIRST , **UpperCAmelCase__ : Optional[Any] , ) -> int: _a : Tuple = do_resize if do_resize is not None else self.do_resize _a : Any = size if size is not None else self.size _a : int = get_size_dict(UpperCAmelCase__ , default_to_square=UpperCAmelCase__ ) _a : int = resample if resample is not None else self.resample _a : Union[str, Any] = do_center_crop if do_center_crop is not None else self.do_center_crop _a : Union[str, Any] = crop_size if crop_size is not None else self.crop_size _a : Union[str, Any] = get_size_dict(UpperCAmelCase__ , param_name="""crop_size""" ) _a : Any = do_rescale if do_rescale is not None else self.do_rescale _a : Any = rescale_factor if rescale_factor is not None else self.rescale_factor _a : Any = do_normalize if do_normalize is not None else self.do_normalize _a : Any = image_mean if image_mean is not None else self.image_mean _a : Optional[int] = image_std if image_std is not None else self.image_std _a : Dict = make_list_of_images(UpperCAmelCase__ ) if not valid_images(UpperCAmelCase__ ): raise ValueError( """Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """ """torch.Tensor, tf.Tensor or jax.ndarray.""" ) if do_resize and size is None: raise ValueError("""Size must be specified if do_resize is True.""" ) if do_center_crop and crop_size is None: raise ValueError("""Crop size must be specified if do_center_crop is True.""" ) if do_rescale and rescale_factor is None: raise ValueError("""Rescale factor must be specified if do_rescale is True.""" ) if do_normalize and (image_mean is None or image_std is None): raise ValueError("""Image mean and std must be specified if do_normalize is True.""" ) # All transformations expect numpy arrays. _a : Dict = [to_numpy_array(UpperCAmelCase__ ) for image in images] if do_resize: _a : Dict = [self.resize(image=UpperCAmelCase__ , size=UpperCAmelCase__ , resample=UpperCAmelCase__ ) for image in images] if do_center_crop: _a : Optional[Any] = [self.center_crop(image=UpperCAmelCase__ , size=UpperCAmelCase__ ) for image in images] if do_rescale: _a : Any = [self.rescale(image=UpperCAmelCase__ , scale=UpperCAmelCase__ ) for image in images] if do_normalize: _a : Any = [self.normalize(image=UpperCAmelCase__ , mean=UpperCAmelCase__ , std=UpperCAmelCase__ ) for image in images] _a : int = [to_channel_dimension_format(UpperCAmelCase__ , UpperCAmelCase__ ) for image in images] _a : Tuple = {"""pixel_values""": images} return BatchFeature(data=UpperCAmelCase__ , tensor_type=UpperCAmelCase__ ) def _lowercase ( self : Tuple , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : List[Tuple] = None ) -> int: _a : List[Any] = outputs.logits # Resize logits and compute semantic segmentation maps if target_sizes is not None: if len(UpperCAmelCase__ ) != len(UpperCAmelCase__ ): raise ValueError( """Make sure that you pass in as many target sizes as the batch dimension of the logits""" ) if is_torch_tensor(UpperCAmelCase__ ): _a : Optional[int] = target_sizes.numpy() _a : Optional[Any] = [] for idx in range(len(UpperCAmelCase__ ) ): _a : List[Any] = torch.nn.functional.interpolate( logits[idx].unsqueeze(dim=0 ) , size=target_sizes[idx] , mode="""bilinear""" , align_corners=UpperCAmelCase__ ) _a : Dict = resized_logits[0].argmax(dim=0 ) semantic_segmentation.append(UpperCAmelCase__ ) else: _a : List[str] = logits.argmax(dim=1 ) _a : Tuple = [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0] )] return semantic_segmentation
324
"""simple docstring""" import gc import random import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTextModelWithProjection, CLIPTokenizer from diffusers import ( AutoencoderKL, DiffusionPipeline, EulerDiscreteScheduler, StableDiffusionXLImgaImgPipeline, UNetaDConditionModel, ) from diffusers.utils import floats_tensor, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import ( IMAGE_TO_IMAGE_IMAGE_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class UpperCamelCase ( snake_case_ , snake_case_ , unittest.TestCase ): UpperCamelCase : Union[str, Any] = StableDiffusionXLImgaImgPipeline UpperCamelCase : Any = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'''height''', '''width'''} UpperCamelCase : Tuple = PipelineTesterMixin.required_optional_params - {'''latents'''} UpperCamelCase : int = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS UpperCamelCase : Optional[Any] = IMAGE_TO_IMAGE_IMAGE_PARAMS UpperCamelCase : Optional[Any] = IMAGE_TO_IMAGE_IMAGE_PARAMS def _lowercase ( self : Any ) -> List[Any]: torch.manual_seed(0 ) _a : str = 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""") , attention_head_dim=(2, 4) , use_linear_projection=UpperCAmelCase__ , addition_embed_type="""text_time""" , addition_time_embed_dim=8 , transformer_layers_per_block=(1, 2) , projection_class_embeddings_input_dim=80 , cross_attention_dim=64 , ) _a : Union[str, Any] = EulerDiscreteScheduler( beta_start=0.0_0_0_8_5 , beta_end=0.0_1_2 , steps_offset=1 , beta_schedule="""scaled_linear""" , timestep_spacing="""leading""" , ) torch.manual_seed(0 ) _a : List[str] = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , sample_size=128 , ) torch.manual_seed(0 ) _a : int = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , hidden_act="""gelu""" , projection_dim=32 , ) _a : Tuple = CLIPTextModel(UpperCAmelCase__ ) _a : str = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" , local_files_only=UpperCAmelCase__ ) _a : Dict = CLIPTextModelWithProjection(UpperCAmelCase__ ) _a : Dict = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" , local_files_only=UpperCAmelCase__ ) _a : Any = { """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """text_encoder_2""": text_encoder_a, """tokenizer_2""": tokenizer_a, # "safety_checker": None, # "feature_extractor": None, } return components def _lowercase ( self : List[Any] , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : int=0 ) -> int: _a : Dict = floats_tensor((1, 3, 32, 32) , rng=random.Random(UpperCAmelCase__ ) ).to(UpperCAmelCase__ ) _a : Any = image / 2 + 0.5 if str(UpperCAmelCase__ ).startswith("""mps""" ): _a : Any = torch.manual_seed(UpperCAmelCase__ ) else: _a : Tuple = torch.Generator(device=UpperCAmelCase__ ).manual_seed(UpperCAmelCase__ ) _a : Optional[Any] = { """prompt""": """A painting of a squirrel eating a burger""", """image""": image, """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 5.0, """output_type""": """numpy""", """strength""": 0.7_5, } return inputs def _lowercase ( self : Any ) -> List[Any]: _a : Union[str, Any] = """cpu""" # ensure determinism for the device-dependent torch.Generator _a : Dict = self.get_dummy_components() _a : List[Any] = StableDiffusionXLImgaImgPipeline(**UpperCAmelCase__ ) _a : Union[str, Any] = sd_pipe.to(UpperCAmelCase__ ) sd_pipe.set_progress_bar_config(disable=UpperCAmelCase__ ) _a : List[str] = self.get_dummy_inputs(UpperCAmelCase__ ) _a : List[str] = sd_pipe(**UpperCAmelCase__ ).images _a : Union[str, Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) _a : List[str] = np.array([0.4_6_5_6, 0.4_8_4_0, 0.4_4_3_9, 0.6_6_9_8, 0.5_5_7_4, 0.4_5_2_4, 0.5_7_9_9, 0.5_9_4_3, 0.5_1_6_5] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def _lowercase ( self : Any ) -> Any: super().test_attention_slicing_forward_pass(expected_max_diff=3E-3 ) def _lowercase ( self : List[Any] ) -> Optional[Any]: super().test_inference_batch_single_identical(expected_max_diff=3E-3 ) def _lowercase ( self : Any ) -> Any: pass def _lowercase ( self : Tuple ) -> Union[str, Any]: _a : int = self.get_dummy_components() _a : Any = StableDiffusionXLImgaImgPipeline(**UpperCAmelCase__ ) _a : Dict = sd_pipe.to(UpperCAmelCase__ ) _a : List[str] = sd_pipe.to(UpperCAmelCase__ ) sd_pipe.set_progress_bar_config(disable=UpperCAmelCase__ ) # forward without prompt embeds _a : int = self.get_dummy_inputs(UpperCAmelCase__ ) _a : List[str] = 3 * ["""this is a negative prompt"""] _a : Dict = negative_prompt _a : Dict = 3 * [inputs["""prompt"""]] _a : Optional[Any] = sd_pipe(**UpperCAmelCase__ ) _a : Tuple = output.images[0, -3:, -3:, -1] # forward with prompt embeds _a : int = self.get_dummy_inputs(UpperCAmelCase__ ) _a : Union[str, Any] = 3 * ["""this is a negative prompt"""] _a : int = 3 * [inputs.pop("""prompt""" )] ( ( _a ) , ( _a ) , ( _a ) , ( _a ) , ) : List[str] = sd_pipe.encode_prompt(UpperCAmelCase__ , negative_prompt=UpperCAmelCase__ ) _a : Tuple = sd_pipe( **UpperCAmelCase__ , prompt_embeds=UpperCAmelCase__ , negative_prompt_embeds=UpperCAmelCase__ , pooled_prompt_embeds=UpperCAmelCase__ , negative_pooled_prompt_embeds=UpperCAmelCase__ , ) _a : Dict = output.images[0, -3:, -3:, -1] # make sure that it's equal assert np.abs(image_slice_a.flatten() - image_slice_a.flatten() ).max() < 1E-4 @slow @require_torch_gpu class UpperCamelCase ( unittest.TestCase ): def _lowercase ( self : List[str] ) -> Union[str, Any]: super().tearDown() gc.collect() torch.cuda.empty_cache() def _lowercase ( self : List[str] , UpperCAmelCase__ : str , UpperCAmelCase__ : str="cpu" , UpperCAmelCase__ : str=torch.floataa , UpperCAmelCase__ : List[Any]=0 ) -> List[str]: _a : List[str] = torch.Generator(device=UpperCAmelCase__ ).manual_seed(UpperCAmelCase__ ) _a : Union[str, Any] = np.random.RandomState(UpperCAmelCase__ ).standard_normal((1, 4, 64, 64) ) _a : List[Any] = torch.from_numpy(UpperCAmelCase__ ).to(device=UpperCAmelCase__ , dtype=UpperCAmelCase__ ) _a : Any = { """prompt""": """a photograph of an astronaut riding a horse""", """latents""": latents, """generator""": generator, """num_inference_steps""": 3, """guidance_scale""": 7.5, """output_type""": """numpy""", } return inputs def _lowercase ( self : int ) -> Union[str, Any]: _a : Union[str, Any] = DiffusionPipeline.from_pretrained("""stabilityai/stable-diffusion-2-base""" ) pipe.to(UpperCAmelCase__ ) pipe.set_progress_bar_config(disable=UpperCAmelCase__ ) _a : List[str] = self.get_inputs(UpperCAmelCase__ ) _a : Tuple = pipe(**UpperCAmelCase__ ).images _a : List[str] = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 512, 512, 3) _a : int = np.array([0.4_9_4_9_3, 0.4_7_8_9_6, 0.4_0_7_9_8, 0.5_4_2_1_4, 0.5_3_2_1_2, 0.4_8_2_0_2, 0.4_7_6_5_6, 0.4_6_3_2_9, 0.4_8_5_0_6] ) assert np.abs(image_slice - expected_slice ).max() < 7E-3
324
1
"""simple docstring""" from __future__ import annotations def lowerCAmelCase__ ( UpperCamelCase__ ): '''simple docstring''' _a : int = 2 _a : List[str] = [] while i * i <= n: if n % i: i += 1 else: n //= i factors.append(UpperCamelCase__ ) if n > 1: factors.append(UpperCamelCase__ ) return factors if __name__ == "__main__": import doctest doctest.testmod()
324
"""simple docstring""" import argparse import json from dataclasses import dataclass, field from functools import partial from pathlib import Path from typing import List import timm import torch import torch.nn as nn from huggingface_hub import hf_hub_download from torch import Tensor from transformers import AutoImageProcessor, ResNetConfig, ResNetForImageClassification from transformers.utils import logging logging.set_verbosity_info() _snake_case = logging.get_logger() @dataclass class UpperCamelCase : UpperCamelCase : nn.Module UpperCamelCase : List[nn.Module] = field(default_factory=snake_case_ ) UpperCamelCase : list = field(default_factory=snake_case_ ) def _lowercase ( self : List[Any] , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : Tensor , UpperCAmelCase__ : Tensor ) -> Any: _a : int = len(list(m.modules() ) ) == 1 or isinstance(UpperCAmelCase__ , nn.Convad ) or isinstance(UpperCAmelCase__ , nn.BatchNormad ) if has_not_submodules: self.traced.append(UpperCAmelCase__ ) def __call__( self : Tuple , UpperCAmelCase__ : Tensor ) -> Tuple: for m in self.module.modules(): self.handles.append(m.register_forward_hook(self._forward_hook ) ) self.module(UpperCAmelCase__ ) [x.remove() for x in self.handles] return self @property def _lowercase ( self : Optional[int] ) -> int: # check the len of the state_dict keys to see if we have learnable params return list(filter(lambda UpperCAmelCase__ : len(list(x.state_dict().keys() ) ) > 0 , self.traced ) ) @dataclass class UpperCamelCase : UpperCamelCase : nn.Module UpperCamelCase : nn.Module UpperCamelCase : int = 0 UpperCamelCase : List = field(default_factory=snake_case_ ) UpperCamelCase : List = field(default_factory=snake_case_ ) def __call__( self : Optional[Any] , UpperCAmelCase__ : Tensor ) -> Tuple: _a : Union[str, Any] = Tracker(self.dest )(UpperCAmelCase__ ).parametrized _a : List[Any] = Tracker(self.src )(UpperCAmelCase__ ).parametrized _a : Tuple = list(filter(lambda UpperCAmelCase__ : type(UpperCAmelCase__ ) not in self.src_skip , UpperCAmelCase__ ) ) _a : Union[str, Any] = list(filter(lambda UpperCAmelCase__ : type(UpperCAmelCase__ ) not in self.dest_skip , UpperCAmelCase__ ) ) if len(UpperCAmelCase__ ) != len(UpperCAmelCase__ ): raise Exception( f"""Numbers of operations are different. Source module has {len(UpperCAmelCase__ )} operations while""" f""" destination module has {len(UpperCAmelCase__ )}.""" ) for dest_m, src_m in zip(UpperCAmelCase__ , UpperCAmelCase__ ): dest_m.load_state_dict(src_m.state_dict() ) if self.verbose == 1: print(f"""Transfered from={src_m} to={dest_m}""" ) def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = True ): '''simple docstring''' print(F"""Converting {name}...""" ) with torch.no_grad(): _a : List[str] = timm.create_model(UpperCamelCase__ , pretrained=UpperCamelCase__ ).eval() _a : str = ResNetForImageClassification(UpperCamelCase__ ).eval() _a : List[str] = ModuleTransfer(src=UpperCamelCase__ , dest=UpperCamelCase__ ) _a : List[str] = torch.randn((1, 3, 2_2_4, 2_2_4) ) module_transfer(UpperCamelCase__ ) assert torch.allclose(from_model(UpperCamelCase__ ) , our_model(UpperCamelCase__ ).logits ), "The model logits don't match the original one." _a : Dict = F"""resnet{'-'.join(name.split('resnet' ) )}""" print(UpperCamelCase__ ) if push_to_hub: our_model.push_to_hub( repo_path_or_name=save_directory / checkpoint_name , commit_message="""Add model""" , use_temp_dir=UpperCamelCase__ , ) # we can use the convnext one _a : Optional[Any] = AutoImageProcessor.from_pretrained("""facebook/convnext-base-224-22k-1k""" ) image_processor.push_to_hub( repo_path_or_name=save_directory / checkpoint_name , commit_message="""Add image processor""" , use_temp_dir=UpperCamelCase__ , ) print(F"""Pushed {checkpoint_name}""" ) def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ = None , UpperCamelCase__ = True ): '''simple docstring''' _a : Any = """imagenet-1k-id2label.json""" _a : Optional[int] = 1_0_0_0 _a : Any = (1, num_labels) _a : Union[str, Any] = """huggingface/label-files""" _a : Tuple = num_labels _a : Optional[int] = json.load(open(hf_hub_download(UpperCamelCase__ , UpperCamelCase__ , repo_type="""dataset""" ) , """r""" ) ) _a : Optional[Any] = {int(UpperCamelCase__ ): v for k, v in idalabel.items()} _a : Any = idalabel _a : Tuple = {v: k for k, v in idalabel.items()} _a : List[str] = partial(UpperCamelCase__ , num_labels=UpperCamelCase__ , idalabel=UpperCamelCase__ , labelaid=UpperCamelCase__ ) _a : Union[str, Any] = { """resnet18""": ImageNetPreTrainedConfig( depths=[2, 2, 2, 2] , hidden_sizes=[6_4, 1_2_8, 2_5_6, 5_1_2] , layer_type="""basic""" ), """resnet26""": ImageNetPreTrainedConfig( depths=[2, 2, 2, 2] , hidden_sizes=[2_5_6, 5_1_2, 1_0_2_4, 2_0_4_8] , layer_type="""bottleneck""" ), """resnet34""": ImageNetPreTrainedConfig( depths=[3, 4, 6, 3] , hidden_sizes=[6_4, 1_2_8, 2_5_6, 5_1_2] , layer_type="""basic""" ), """resnet50""": ImageNetPreTrainedConfig( depths=[3, 4, 6, 3] , hidden_sizes=[2_5_6, 5_1_2, 1_0_2_4, 2_0_4_8] , layer_type="""bottleneck""" ), """resnet101""": ImageNetPreTrainedConfig( depths=[3, 4, 2_3, 3] , hidden_sizes=[2_5_6, 5_1_2, 1_0_2_4, 2_0_4_8] , layer_type="""bottleneck""" ), """resnet152""": ImageNetPreTrainedConfig( depths=[3, 8, 3_6, 3] , hidden_sizes=[2_5_6, 5_1_2, 1_0_2_4, 2_0_4_8] , layer_type="""bottleneck""" ), } if model_name: convert_weight_and_push(UpperCamelCase__ , names_to_config[model_name] , UpperCamelCase__ , UpperCamelCase__ ) else: for model_name, config in names_to_config.items(): convert_weight_and_push(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) return config, expected_shape if __name__ == "__main__": _snake_case = argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default=None, type=str, help=( 'The name of the model you wish to convert, it must be one of the supported resnet* architecture,' ' currently: resnet18,26,34,50,101,152. If `None`, all of them will the converted.' ), ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=Path, required=True, help='Path to the output PyTorch model directory.', ) parser.add_argument( '--push_to_hub', default=True, type=bool, required=False, help='If True, push model and image processor to the hub.', ) _snake_case = parser.parse_args() _snake_case = args.pytorch_dump_folder_path pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True) convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)
324
1
"""simple docstring""" import argparse import glob import importlib.util import os import re import black from doc_builder.style_doc import style_docstrings_in_code # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_copies.py _snake_case = 'src/diffusers' _snake_case = '.' # This is to make sure the diffusers module imported is the one in the repo. _snake_case = importlib.util.spec_from_file_location( 'diffusers', os.path.join(DIFFUSERS_PATH, '__init__.py'), submodule_search_locations=[DIFFUSERS_PATH], ) _snake_case = spec.loader.load_module() def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' return line.startswith(UpperCamelCase__ ) or len(UpperCamelCase__ ) <= 1 or re.search(R"""^\s*\)(\s*->.*:|:)\s*$""" , UpperCamelCase__ ) is not None def lowerCAmelCase__ ( UpperCamelCase__ ): '''simple docstring''' _a : List[Any] = object_name.split(""".""" ) _a : int = 0 # First let's find the module where our object lives. _a : List[str] = parts[i] while i < len(UpperCamelCase__ ) and not os.path.isfile(os.path.join(UpperCamelCase__ , F"""{module}.py""" ) ): i += 1 if i < len(UpperCamelCase__ ): _a : List[Any] = os.path.join(UpperCamelCase__ , parts[i] ) if i >= len(UpperCamelCase__ ): raise ValueError(F"""`object_name` should begin with the name of a module of diffusers but got {object_name}.""" ) with open(os.path.join(UpperCamelCase__ , F"""{module}.py""" ) , """r""" , encoding="""utf-8""" , newline="""\n""" ) as f: _a : str = f.readlines() # Now let's find the class / func in the code! _a : List[str] = """""" _a : int = 0 for name in parts[i + 1 :]: while ( line_index < len(UpperCamelCase__ ) and re.search(RF"""^{indent}(class|def)\s+{name}(\(|\:)""" , lines[line_index] ) is None ): line_index += 1 indent += " " line_index += 1 if line_index >= len(UpperCamelCase__ ): raise ValueError(F""" {object_name} does not match any function or class in {module}.""" ) # We found the beginning of the class / func, now let's find the end (when the indent diminishes). _a : Dict = line_index while line_index < len(UpperCamelCase__ ) and _should_continue(lines[line_index] , UpperCamelCase__ ): line_index += 1 # Clean up empty lines at the end (if any). while len(lines[line_index - 1] ) <= 1: line_index -= 1 _a : List[str] = lines[start_index:line_index] return "".join(UpperCamelCase__ ) _snake_case = re.compile(r'^(\s*)#\s*Copied from\s+diffusers\.(\S+\.\S+)\s*($|\S.*$)') _snake_case = re.compile(r'^\s*(\S+)->(\S+)(\s+.*|$)') _snake_case = re.compile(r'<FILL\s+[^>]*>') def lowerCAmelCase__ ( UpperCamelCase__ ): '''simple docstring''' _a : Optional[Any] = code.split("""\n""" ) _a : Optional[int] = 0 while idx < len(UpperCamelCase__ ) and len(lines[idx] ) == 0: idx += 1 if idx < len(UpperCamelCase__ ): return re.search(R"""^(\s*)\S""" , lines[idx] ).groups()[0] return "" def lowerCAmelCase__ ( UpperCamelCase__ ): '''simple docstring''' _a : Optional[Any] = len(get_indent(UpperCamelCase__ ) ) > 0 if has_indent: _a : str = F"""class Bla:\n{code}""" _a : Optional[Any] = black.Mode(target_versions={black.TargetVersion.PYaa} , line_length=1_1_9 , preview=UpperCamelCase__ ) _a : Optional[int] = black.format_str(UpperCamelCase__ , mode=UpperCamelCase__ ) _a , _a : Optional[Any] = style_docstrings_in_code(UpperCamelCase__ ) return result[len("""class Bla:\n""" ) :] if has_indent else result def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__=False ): '''simple docstring''' with open(UpperCamelCase__ , """r""" , encoding="""utf-8""" , newline="""\n""" ) as f: _a : str = f.readlines() _a : List[str] = [] _a : Optional[int] = 0 # Not a for loop cause `lines` is going to change (if `overwrite=True`). while line_index < len(UpperCamelCase__ ): _a : int = _re_copy_warning.search(lines[line_index] ) if search is None: line_index += 1 continue # There is some copied code here, let's retrieve the original. _a , _a , _a : Union[str, Any] = search.groups() _a : Optional[int] = find_code_in_diffusers(UpperCamelCase__ ) _a : Tuple = get_indent(UpperCamelCase__ ) _a : Any = line_index + 1 if indent == theoretical_indent else line_index + 2 _a : Optional[int] = theoretical_indent _a : Any = start_index # Loop to check the observed code, stop when indentation diminishes or if we see a End copy comment. _a : Optional[Any] = True while line_index < len(UpperCamelCase__ ) and should_continue: line_index += 1 if line_index >= len(UpperCamelCase__ ): break _a : Dict = lines[line_index] _a : Dict = _should_continue(UpperCamelCase__ , UpperCamelCase__ ) and re.search(F"""^{indent}# End copy""" , UpperCamelCase__ ) is None # Clean up empty lines at the end (if any). while len(lines[line_index - 1] ) <= 1: line_index -= 1 _a : Dict = lines[start_index:line_index] _a : Tuple = """""".join(UpperCamelCase__ ) # Remove any nested `Copied from` comments to avoid circular copies _a : Union[str, Any] = [line for line in theoretical_code.split("""\n""" ) if _re_copy_warning.search(UpperCamelCase__ ) is None] _a : str = """\n""".join(UpperCamelCase__ ) # Before comparing, use the `replace_pattern` on the original code. if len(UpperCamelCase__ ) > 0: _a : str = replace_pattern.replace("""with""" , """""" ).split(""",""" ) _a : Tuple = [_re_replace_pattern.search(UpperCamelCase__ ) for p in patterns] for pattern in patterns: if pattern is None: continue _a , _a , _a : List[str] = pattern.groups() _a : Tuple = re.sub(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) if option.strip() == "all-casing": _a : str = re.sub(obja.lower() , obja.lower() , UpperCamelCase__ ) _a : Optional[int] = re.sub(obja.upper() , obja.upper() , UpperCamelCase__ ) # Blackify after replacement. To be able to do that, we need the header (class or function definition) # from the previous line _a : Union[str, Any] = blackify(lines[start_index - 1] + theoretical_code ) _a : str = theoretical_code[len(lines[start_index - 1] ) :] # Test for a diff and act accordingly. if observed_code != theoretical_code: diffs.append([object_name, start_index] ) if overwrite: _a : Union[str, Any] = lines[:start_index] + [theoretical_code] + lines[line_index:] _a : Tuple = start_index + 1 if overwrite and len(UpperCamelCase__ ) > 0: # Warn the user a file has been modified. print(F"""Detected changes, rewriting {filename}.""" ) with open(UpperCamelCase__ , """w""" , encoding="""utf-8""" , newline="""\n""" ) as f: f.writelines(UpperCamelCase__ ) return diffs def lowerCAmelCase__ ( UpperCamelCase__ = False ): '''simple docstring''' _a : List[Any] = glob.glob(os.path.join(UpperCamelCase__ , """**/*.py""" ) , recursive=UpperCamelCase__ ) _a : List[str] = [] for filename in all_files: _a : Any = is_copy_consistent(UpperCamelCase__ , UpperCamelCase__ ) diffs += [F"""- {filename}: copy does not match {d[0]} at line {d[1]}""" for d in new_diffs] if not overwrite and len(UpperCamelCase__ ) > 0: _a : List[str] = """\n""".join(UpperCamelCase__ ) raise Exception( """Found the following copy inconsistencies:\n""" + diff + """\nRun `make fix-copies` or `python utils/check_copies.py --fix_and_overwrite` to fix them.""" ) if __name__ == "__main__": _snake_case = argparse.ArgumentParser() parser.add_argument('--fix_and_overwrite', action='store_true', help='Whether to fix inconsistencies.') _snake_case = parser.parse_args() check_copies(args.fix_and_overwrite)
324
"""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, )
324
1
"""simple docstring""" import logging import os import sys from dataclasses import dataclass, field from typing import Optional import torch from datasets import load_dataset from torchvision.transforms import Compose, Lambda, Normalize, RandomHorizontalFlip, RandomResizedCrop, ToTensor from torchvision.transforms.functional import InterpolationMode import transformers from transformers import ( HfArgumentParser, Trainer, TrainingArguments, ViTImageProcessor, ViTMAEConfig, ViTMAEForPreTraining, ) 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 _snake_case = 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.8.0', 'To fix: pip install -r examples/pytorch/image-pretraining/requirements.txt') @dataclass class UpperCamelCase : UpperCamelCase : Optional[str] = field( default='''cifar10''' , metadata={'''help''': '''Name of a dataset from the datasets package'''} ) UpperCamelCase : Optional[str] = field( default=snake_case_ , metadata={'''help''': '''The configuration name of the dataset to use (via the datasets library).'''} ) UpperCamelCase : Optional[str] = field( default=snake_case_ , metadata={'''help''': '''The column name of the images in the files.'''} ) UpperCamelCase : Optional[str] = field(default=snake_case_ , metadata={'''help''': '''A folder containing the training data.'''} ) UpperCamelCase : Optional[str] = field(default=snake_case_ , metadata={'''help''': '''A folder containing the validation data.'''} ) UpperCamelCase : Optional[float] = field( default=0.1_5 , metadata={'''help''': '''Percent to split off of train for validation.'''} ) UpperCamelCase : Optional[int] = field( default=snake_case_ , metadata={ '''help''': ( '''For debugging purposes or quicker training, truncate the number of training examples to this ''' '''value if set.''' ) } , ) UpperCamelCase : Optional[int] = field( default=snake_case_ , metadata={ '''help''': ( '''For debugging purposes or quicker training, truncate the number of evaluation examples to this ''' '''value if set.''' ) } , ) def _lowercase ( self : Optional[int] ) -> int: _a : int = {} if self.train_dir is not None: _a : str = self.train_dir if self.validation_dir is not None: _a : List[str] = self.validation_dir _a : List[Any] = data_files if data_files else None @dataclass class UpperCamelCase : UpperCamelCase : str = field( default=snake_case_ , metadata={ '''help''': ( '''The model checkpoint for weights initialization.Don\'t set if you want to train a model from scratch.''' ) } , ) UpperCamelCase : Optional[str] = field( default=snake_case_ , metadata={'''help''': '''Pretrained config name or path if not the same as model_name_or_path'''} ) UpperCamelCase : Optional[str] = field( default=snake_case_ , metadata={ '''help''': ( '''Override some existing default config settings when a model is trained from scratch. Example: ''' '''n_embd=10,resid_pdrop=0.2,scale_attn_weights=false,summary_type=cls_index''' ) } , ) UpperCamelCase : Optional[str] = field( default=snake_case_ , metadata={'''help''': '''Where do you want to store the pretrained models downloaded from s3'''} ) UpperCamelCase : str = field( default='''main''' , metadata={'''help''': '''The specific model version to use (can be a branch name, tag name or commit id).'''} , ) UpperCamelCase : str = field(default=snake_case_ , metadata={'''help''': '''Name or path of preprocessor config.'''} ) UpperCamelCase : bool = field( default=snake_case_ , metadata={ '''help''': ( '''Will use the token generated when running `huggingface-cli login` (necessary to use this script ''' '''with private models).''' ) } , ) UpperCamelCase : float = field( default=0.7_5 , metadata={'''help''': '''The ratio of the number of masked tokens in the input sequence.'''} ) UpperCamelCase : bool = field( default=snake_case_ , metadata={'''help''': '''Whether or not to train with normalized pixel values as target.'''} ) @dataclass class UpperCamelCase ( snake_case_ ): UpperCamelCase : float = field( default=1E-3 , metadata={'''help''': '''Base learning rate: absolute_lr = base_lr * total_batch_size / 256.'''} ) def lowerCAmelCase__ ( UpperCamelCase__ ): '''simple docstring''' _a : Any = torch.stack([example["""pixel_values"""] for example in examples] ) return {"pixel_values": pixel_values} def lowerCAmelCase__ ( ): '''simple docstring''' # See all possible arguments in src/transformers/training_args.py # or by passing the --help flag to this script. # We now keep distinct sets of args, for a cleaner separation of concerns. _a : Dict = HfArgumentParser((ModelArguments, DataTrainingArguments, CustomTrainingArguments) ) 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 : List[str] = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: _a , _a , _a : str = 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_mae""" , UpperCamelCase__ , UpperCamelCase__ ) # 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() _a : Tuple = training_args.get_process_log_level() logger.setLevel(UpperCamelCase__ ) transformers.utils.logging.set_verbosity(UpperCamelCase__ ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Log on each process the small summary: logger.warning( F"""Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}""" + F"""distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}""" ) logger.info(F"""Training/evaluation parameters {training_args}""" ) # Detecting last checkpoint. _a : Tuple = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: _a : Dict = get_last_checkpoint(training_args.output_dir ) if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0: raise ValueError( F"""Output directory ({training_args.output_dir}) already exists and is not empty. """ """Use --overwrite_output_dir to overcome.""" ) elif last_checkpoint is not None and training_args.resume_from_checkpoint is None: logger.info( F"""Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change """ """the `--output_dir` or add `--overwrite_output_dir` to train from scratch.""" ) # Initialize our dataset. _a : str = load_dataset( data_args.dataset_name , data_args.dataset_config_name , data_files=data_args.data_files , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , ) # If we don't have a validation split, split off a percentage of train as validation. _a : Optional[int] = None if """validation""" in ds.keys() else data_args.train_val_split if isinstance(data_args.train_val_split , UpperCamelCase__ ) and data_args.train_val_split > 0.0: _a : Any = ds["""train"""].train_test_split(data_args.train_val_split ) _a : Any = split["""train"""] _a : List[str] = split["""test"""] # Load pretrained model and image processor # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. _a : List[str] = { """cache_dir""": model_args.cache_dir, """revision""": model_args.model_revision, """use_auth_token""": True if model_args.use_auth_token else None, } if model_args.config_name: _a : Union[str, Any] = ViTMAEConfig.from_pretrained(model_args.config_name , **UpperCamelCase__ ) elif model_args.model_name_or_path: _a : List[str] = ViTMAEConfig.from_pretrained(model_args.model_name_or_path , **UpperCamelCase__ ) else: _a : Dict = ViTMAEConfig() logger.warning("""You are instantiating a new config instance from scratch.""" ) if model_args.config_overrides is not None: logger.info(F"""Overriding config: {model_args.config_overrides}""" ) config.update_from_string(model_args.config_overrides ) logger.info(F"""New config: {config}""" ) # adapt config config.update( { """mask_ratio""": model_args.mask_ratio, """norm_pix_loss""": model_args.norm_pix_loss, } ) # create image processor if model_args.image_processor_name: _a : Union[str, Any] = ViTImageProcessor.from_pretrained(model_args.image_processor_name , **UpperCamelCase__ ) elif model_args.model_name_or_path: _a : Dict = ViTImageProcessor.from_pretrained(model_args.model_name_or_path , **UpperCamelCase__ ) else: _a : List[Any] = ViTImageProcessor() # create model if model_args.model_name_or_path: _a : Optional[int] = ViTMAEForPreTraining.from_pretrained( model_args.model_name_or_path , from_tf=bool(""".ckpt""" in model_args.model_name_or_path ) , config=UpperCamelCase__ , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) else: logger.info("""Training new model from scratch""" ) _a : int = ViTMAEForPreTraining(UpperCamelCase__ ) if training_args.do_train: _a : Optional[Any] = ds["""train"""].column_names else: _a : int = ds["""validation"""].column_names if data_args.image_column_name is not None: _a : Tuple = data_args.image_column_name elif "image" in column_names: _a : str = """image""" elif "img" in column_names: _a : Any = """img""" else: _a : Any = column_names[0] # transformations as done in original MAE paper # source: https://github.com/facebookresearch/mae/blob/main/main_pretrain.py if "shortest_edge" in image_processor.size: _a : str = image_processor.size["""shortest_edge"""] else: _a : str = (image_processor.size["""height"""], image_processor.size["""width"""]) _a : Tuple = Compose( [ Lambda(lambda UpperCamelCase__ : img.convert("""RGB""" ) if img.mode != "RGB" else img ), RandomResizedCrop(UpperCamelCase__ , scale=(0.2, 1.0) , interpolation=InterpolationMode.BICUBIC ), RandomHorizontalFlip(), ToTensor(), Normalize(mean=image_processor.image_mean , std=image_processor.image_std ), ] ) def preprocess_images(UpperCamelCase__ ): _a : int = [transforms(UpperCamelCase__ ) for image in examples[image_column_name]] return examples if training_args.do_train: if "train" not in ds: raise ValueError("""--do_train requires a train dataset""" ) if data_args.max_train_samples is not None: _a : str = ds["""train"""].shuffle(seed=training_args.seed ).select(range(data_args.max_train_samples ) ) # Set the training transforms ds["train"].set_transform(UpperCamelCase__ ) if training_args.do_eval: if "validation" not in ds: raise ValueError("""--do_eval requires a validation dataset""" ) if data_args.max_eval_samples is not None: _a : int = ( ds["""validation"""].shuffle(seed=training_args.seed ).select(range(data_args.max_eval_samples ) ) ) # Set the validation transforms ds["validation"].set_transform(UpperCamelCase__ ) # Compute absolute learning rate _a : Optional[int] = ( training_args.train_batch_size * training_args.gradient_accumulation_steps * training_args.world_size ) if training_args.base_learning_rate is not None: _a : Dict = training_args.base_learning_rate * total_train_batch_size / 2_5_6 # Initialize our trainer _a : Union[str, Any] = Trainer( model=UpperCamelCase__ , args=UpperCamelCase__ , train_dataset=ds["""train"""] if training_args.do_train else None , eval_dataset=ds["""validation"""] if training_args.do_eval else None , tokenizer=UpperCamelCase__ , data_collator=UpperCamelCase__ , ) # Training if training_args.do_train: _a : Optional[Any] = None if training_args.resume_from_checkpoint is not None: _a : int = training_args.resume_from_checkpoint elif last_checkpoint is not None: _a : int = last_checkpoint _a : int = trainer.train(resume_from_checkpoint=UpperCamelCase__ ) 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: _a : int = trainer.evaluate() trainer.log_metrics("""eval""" , UpperCamelCase__ ) trainer.save_metrics("""eval""" , UpperCamelCase__ ) # Write model card and (optionally) push to hub _a : str = { """tasks""": """masked-auto-encoding""", """dataset""": data_args.dataset_name, """tags""": ["""masked-auto-encoding"""], } if training_args.push_to_hub: trainer.push_to_hub(**UpperCamelCase__ ) else: trainer.create_model_card(**UpperCamelCase__ ) def lowerCAmelCase__ ( UpperCamelCase__ ): '''simple docstring''' # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
324
"""simple docstring""" _snake_case = 8.31_44_62 # Unit - J mol-1 K-1 def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' if moles < 0 or kelvin < 0 or volume < 0: raise ValueError("""Invalid inputs. Enter positive value.""" ) return moles * kelvin * UNIVERSAL_GAS_CONSTANT / volume def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' if moles < 0 or kelvin < 0 or pressure < 0: raise ValueError("""Invalid inputs. Enter positive value.""" ) return moles * kelvin * UNIVERSAL_GAS_CONSTANT / pressure if __name__ == "__main__": from doctest import testmod testmod()
324
1
"""simple docstring""" import gc import random import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTextModelWithProjection, CLIPTokenizer from diffusers import ( AutoencoderKL, DiffusionPipeline, EulerDiscreteScheduler, StableDiffusionXLImgaImgPipeline, UNetaDConditionModel, ) from diffusers.utils import floats_tensor, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import ( IMAGE_TO_IMAGE_IMAGE_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class UpperCamelCase ( snake_case_ , snake_case_ , unittest.TestCase ): UpperCamelCase : Union[str, Any] = StableDiffusionXLImgaImgPipeline UpperCamelCase : Any = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'''height''', '''width'''} UpperCamelCase : Tuple = PipelineTesterMixin.required_optional_params - {'''latents'''} UpperCamelCase : int = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS UpperCamelCase : Optional[Any] = IMAGE_TO_IMAGE_IMAGE_PARAMS UpperCamelCase : Optional[Any] = IMAGE_TO_IMAGE_IMAGE_PARAMS def _lowercase ( self : Any ) -> List[Any]: torch.manual_seed(0 ) _a : str = 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""") , attention_head_dim=(2, 4) , use_linear_projection=UpperCAmelCase__ , addition_embed_type="""text_time""" , addition_time_embed_dim=8 , transformer_layers_per_block=(1, 2) , projection_class_embeddings_input_dim=80 , cross_attention_dim=64 , ) _a : Union[str, Any] = EulerDiscreteScheduler( beta_start=0.0_0_0_8_5 , beta_end=0.0_1_2 , steps_offset=1 , beta_schedule="""scaled_linear""" , timestep_spacing="""leading""" , ) torch.manual_seed(0 ) _a : List[str] = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , sample_size=128 , ) torch.manual_seed(0 ) _a : int = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , hidden_act="""gelu""" , projection_dim=32 , ) _a : Tuple = CLIPTextModel(UpperCAmelCase__ ) _a : str = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" , local_files_only=UpperCAmelCase__ ) _a : Dict = CLIPTextModelWithProjection(UpperCAmelCase__ ) _a : Dict = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" , local_files_only=UpperCAmelCase__ ) _a : Any = { """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """text_encoder_2""": text_encoder_a, """tokenizer_2""": tokenizer_a, # "safety_checker": None, # "feature_extractor": None, } return components def _lowercase ( self : List[Any] , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : int=0 ) -> int: _a : Dict = floats_tensor((1, 3, 32, 32) , rng=random.Random(UpperCAmelCase__ ) ).to(UpperCAmelCase__ ) _a : Any = image / 2 + 0.5 if str(UpperCAmelCase__ ).startswith("""mps""" ): _a : Any = torch.manual_seed(UpperCAmelCase__ ) else: _a : Tuple = torch.Generator(device=UpperCAmelCase__ ).manual_seed(UpperCAmelCase__ ) _a : Optional[Any] = { """prompt""": """A painting of a squirrel eating a burger""", """image""": image, """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 5.0, """output_type""": """numpy""", """strength""": 0.7_5, } return inputs def _lowercase ( self : Any ) -> List[Any]: _a : Union[str, Any] = """cpu""" # ensure determinism for the device-dependent torch.Generator _a : Dict = self.get_dummy_components() _a : List[Any] = StableDiffusionXLImgaImgPipeline(**UpperCAmelCase__ ) _a : Union[str, Any] = sd_pipe.to(UpperCAmelCase__ ) sd_pipe.set_progress_bar_config(disable=UpperCAmelCase__ ) _a : List[str] = self.get_dummy_inputs(UpperCAmelCase__ ) _a : List[str] = sd_pipe(**UpperCAmelCase__ ).images _a : Union[str, Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) _a : List[str] = np.array([0.4_6_5_6, 0.4_8_4_0, 0.4_4_3_9, 0.6_6_9_8, 0.5_5_7_4, 0.4_5_2_4, 0.5_7_9_9, 0.5_9_4_3, 0.5_1_6_5] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def _lowercase ( self : Any ) -> Any: super().test_attention_slicing_forward_pass(expected_max_diff=3E-3 ) def _lowercase ( self : List[Any] ) -> Optional[Any]: super().test_inference_batch_single_identical(expected_max_diff=3E-3 ) def _lowercase ( self : Any ) -> Any: pass def _lowercase ( self : Tuple ) -> Union[str, Any]: _a : int = self.get_dummy_components() _a : Any = StableDiffusionXLImgaImgPipeline(**UpperCAmelCase__ ) _a : Dict = sd_pipe.to(UpperCAmelCase__ ) _a : List[str] = sd_pipe.to(UpperCAmelCase__ ) sd_pipe.set_progress_bar_config(disable=UpperCAmelCase__ ) # forward without prompt embeds _a : int = self.get_dummy_inputs(UpperCAmelCase__ ) _a : List[str] = 3 * ["""this is a negative prompt"""] _a : Dict = negative_prompt _a : Dict = 3 * [inputs["""prompt"""]] _a : Optional[Any] = sd_pipe(**UpperCAmelCase__ ) _a : Tuple = output.images[0, -3:, -3:, -1] # forward with prompt embeds _a : int = self.get_dummy_inputs(UpperCAmelCase__ ) _a : Union[str, Any] = 3 * ["""this is a negative prompt"""] _a : int = 3 * [inputs.pop("""prompt""" )] ( ( _a ) , ( _a ) , ( _a ) , ( _a ) , ) : List[str] = sd_pipe.encode_prompt(UpperCAmelCase__ , negative_prompt=UpperCAmelCase__ ) _a : Tuple = sd_pipe( **UpperCAmelCase__ , prompt_embeds=UpperCAmelCase__ , negative_prompt_embeds=UpperCAmelCase__ , pooled_prompt_embeds=UpperCAmelCase__ , negative_pooled_prompt_embeds=UpperCAmelCase__ , ) _a : Dict = output.images[0, -3:, -3:, -1] # make sure that it's equal assert np.abs(image_slice_a.flatten() - image_slice_a.flatten() ).max() < 1E-4 @slow @require_torch_gpu class UpperCamelCase ( unittest.TestCase ): def _lowercase ( self : List[str] ) -> Union[str, Any]: super().tearDown() gc.collect() torch.cuda.empty_cache() def _lowercase ( self : List[str] , UpperCAmelCase__ : str , UpperCAmelCase__ : str="cpu" , UpperCAmelCase__ : str=torch.floataa , UpperCAmelCase__ : List[Any]=0 ) -> List[str]: _a : List[str] = torch.Generator(device=UpperCAmelCase__ ).manual_seed(UpperCAmelCase__ ) _a : Union[str, Any] = np.random.RandomState(UpperCAmelCase__ ).standard_normal((1, 4, 64, 64) ) _a : List[Any] = torch.from_numpy(UpperCAmelCase__ ).to(device=UpperCAmelCase__ , dtype=UpperCAmelCase__ ) _a : Any = { """prompt""": """a photograph of an astronaut riding a horse""", """latents""": latents, """generator""": generator, """num_inference_steps""": 3, """guidance_scale""": 7.5, """output_type""": """numpy""", } return inputs def _lowercase ( self : int ) -> Union[str, Any]: _a : Union[str, Any] = DiffusionPipeline.from_pretrained("""stabilityai/stable-diffusion-2-base""" ) pipe.to(UpperCAmelCase__ ) pipe.set_progress_bar_config(disable=UpperCAmelCase__ ) _a : List[str] = self.get_inputs(UpperCAmelCase__ ) _a : Tuple = pipe(**UpperCAmelCase__ ).images _a : List[str] = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 512, 512, 3) _a : int = np.array([0.4_9_4_9_3, 0.4_7_8_9_6, 0.4_0_7_9_8, 0.5_4_2_1_4, 0.5_3_2_1_2, 0.4_8_2_0_2, 0.4_7_6_5_6, 0.4_6_3_2_9, 0.4_8_5_0_6] ) assert np.abs(image_slice - expected_slice ).max() < 7E-3
324
"""simple docstring""" import argparse import dataclasses import json import logging import os import shutil from typing import List, Optional import datasets from accelerate import Accelerator from datasets import load_dataset from finetuning import finetune from tqdm.auto import tqdm import transformers from transformers import AutoConfig, set_seed from transformers.trainer_utils import IntervalStrategy _snake_case = logging.getLogger(__name__) _snake_case = 'pytorch_model.bin' @dataclasses.dataclass class UpperCamelCase : UpperCamelCase : str = dataclasses.field( metadata={'''help''': '''Path to pretrained model or model identifier from huggingface.co/models.'''} ) UpperCamelCase : Optional[str] = dataclasses.field( default=snake_case_ , metadata={'''help''': '''Where do you want to store the pretrained models downloaded from huggingface.co.'''} , ) @dataclasses.dataclass class UpperCamelCase : UpperCamelCase : str = dataclasses.field(metadata={'''help''': '''A csv or a json file containing the training data.'''} ) UpperCamelCase : str = dataclasses.field(metadata={'''help''': '''A csv or a json file containing the data to predict on.'''} ) UpperCamelCase : Optional[str] = dataclasses.field( default=snake_case_ , metadata={'''help''': '''A csv or a json file containing the validation data.'''} ) UpperCamelCase : Optional[str] = dataclasses.field( default=snake_case_ , metadata={'''help''': '''The name of the task to train on.'''} , ) UpperCamelCase : Optional[List[str]] = dataclasses.field( default=snake_case_ , metadata={'''help''': '''The list of labels for the task.'''} ) @dataclasses.dataclass class UpperCamelCase : UpperCamelCase : str = dataclasses.field( metadata={'''help''': '''The output directory where the model predictions and checkpoints will be written.'''} ) UpperCamelCase : Optional[str] = dataclasses.field( default='''accuracy''' , metadata={'''help''': '''The evaluation metric used for the task.'''} ) UpperCamelCase : Optional[str] = dataclasses.field( default='''no''' , metadata={ '''help''': '''The evaluation strategy to adopt during training. Possible values are: ["no", "step", "epoch]''' } , ) UpperCamelCase : Optional[int] = dataclasses.field( default=10 , metadata={'''help''': '''Number of evaluation calls with no improvement after which training will be stopped.'''} , ) UpperCamelCase : Optional[float] = dataclasses.field( default=0.0 , metadata={ '''help''': '''How much the specified evaluation metric must improve to satisfy early stopping conditions.''' } , ) UpperCamelCase : Optional[bool] = dataclasses.field( default=snake_case_ , metadata={'''help''': '''Whether to filter the pseudo-labeled data based on the confidence score.'''} , ) UpperCamelCase : Optional[bool] = dataclasses.field( default=snake_case_ , metadata={'''help''': '''Whether to filter the pseudo-labeled data based on the validation performance.'''} , ) UpperCamelCase : Optional[bool] = dataclasses.field( default=snake_case_ , metadata={'''help''': '''Whether to fine-tune on labeled data after pseudo training.'''} , ) UpperCamelCase : Optional[float] = dataclasses.field( default=0.0 , metadata={'''help''': '''Confidence threshold for pseudo-labeled data filtering.'''} , ) UpperCamelCase : Optional[int] = dataclasses.field( default=100 , metadata={'''help''': '''Number of evaluation calls with no improvement after which training will be stopped.'''} , ) UpperCamelCase : Optional[int] = dataclasses.field( default=snake_case_ , metadata={'''help''': '''Random seed for initialization.'''} , ) def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' _a : Optional[int] = datasets.concatenate_datasets([infer_input, infer_output] , axis=1 ) if args.do_filter_by_confidence: _a : Union[str, Any] = dataset.filter(lambda UpperCamelCase__ : example["probability"] > args.confidence_threshold ) if args.do_filter_by_val_performance: assert eval_result >= 0.0 and eval_result <= 1.0 _a : Any = int(eval_result * len(UpperCamelCase__ ) ) print(UpperCamelCase__ ) _a : str = dataset.sort("""probability""" , reverse=UpperCamelCase__ ) _a : Any = dataset.select(range(UpperCamelCase__ ) ) _a : Tuple = dataset.remove_columns(["""label""", """probability"""] ) _a : Optional[Any] = dataset.rename_column("""prediction""" , """label""" ) _a : Dict = dataset.map(lambda UpperCamelCase__ : {"label": idalabel[example["label"]]} ) _a : Union[str, Any] = dataset.shuffle(seed=args.seed ) _a : Optional[int] = os.path.join(UpperCamelCase__ , F"""train_pseudo.{args.data_file_extension}""" ) if args.data_file_extension == "csv": dataset.to_csv(UpperCamelCase__ , index=UpperCamelCase__ ) else: dataset.to_json(UpperCamelCase__ ) def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , **UpperCamelCase__ ): '''simple docstring''' _a : Optional[int] = Accelerator() # Make one log on every process with the configuration for debugging. logging.basicConfig( format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""" , datefmt="""%m/%d/%Y %H:%M:%S""" , level=logging.INFO , ) logger.info(accelerator.state ) # Setup logging, we only want one process per machine to log things on the # screen. accelerator.is_local_main_process is only True for one process per # machine. logger.setLevel(logging.INFO if accelerator.is_local_main_process else logging.ERROR ) if accelerator.is_local_main_process: datasets.utils.logging.set_verbosity_warning() transformers.utils.logging.set_verbosity_info() else: datasets.utils.logging.set_verbosity_error() transformers.utils.logging.set_verbosity_error() _a : Dict = STModelArguments(model_name_or_path=UpperCamelCase__ ) _a : Union[str, Any] = STDataArguments(train_file=UpperCamelCase__ , infer_file=UpperCamelCase__ ) _a : Any = STTrainingArguments(output_dir=UpperCamelCase__ ) _a : Any = argparse.Namespace() for arg_class in (model_args, data_args, training_args): for key, value in vars(UpperCamelCase__ ).items(): setattr(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) for key, value in kwargs.items(): if hasattr(UpperCamelCase__ , UpperCamelCase__ ): setattr(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) # Sanity checks _a : Union[str, Any] = {} _a : Tuple = None # You need to provide the training data and the data to predict on assert args.train_file is not None assert args.infer_file is not None _a : int = args.train_file _a : List[Any] = args.infer_file if args.evaluation_strategy != IntervalStrategy.NO.value: assert args.eval_file is not None _a : Union[str, Any] = args.eval_file for key in data_files: _a : Optional[Any] = data_files[key].split(""".""" )[-1] assert extension in ["csv", "json"], F"""`{key}_file` should be a csv or a json file.""" if args.data_file_extension is None: _a : str = extension else: assert extension == args.data_file_extension, F"""`{key}_file` should be a {args.data_file_extension} file`.""" assert ( args.eval_metric in datasets.list_metrics() ), F"""{args.eval_metric} not in the list of supported metrics {datasets.list_metrics()}.""" # If passed along, set the training seed now. if args.seed is not None: set_seed(args.seed ) logger.info("""Creating the initial data directory for self-training...""" ) _a : Tuple = F"""{args.output_dir}/self-train_iter-{{}}""".format _a : Dict = data_dir_format(0 ) if accelerator.is_main_process: if args.output_dir is not None: os.makedirs(args.output_dir , exist_ok=UpperCamelCase__ ) os.makedirs(UpperCamelCase__ , exist_ok=UpperCamelCase__ ) accelerator.wait_for_everyone() _a : str = None _a : int = None _a : str = 0 _a : List[Any] = False # Show the progress bar _a : List[Any] = tqdm(range(args.max_selftrain_iterations ) , disable=not accelerator.is_local_main_process ) # Self-train for iteration in range(0 , int(args.max_selftrain_iterations ) ): _a : Union[str, Any] = data_dir_format(UpperCamelCase__ ) assert os.path.exists(UpperCamelCase__ ) # Stage 1: initial fine-tuning for iteration = 0 or pseudo-training for # iteration > 0 _a : str = os.path.join(UpperCamelCase__ , """stage-1""" ) _a : Tuple = { """accelerator""": accelerator, """model_name_or_path""": args.model_name_or_path, """cache_dir""": args.cache_dir, """do_train""": True, """train_file""": data_files["""train"""] if iteration == 0 else data_files["""train_pseudo"""], """do_eval""": True if args.eval_file is not None else False, """eval_file""": data_files["""eval"""], """do_predict""": True, """infer_file""": data_files["""infer"""], """task_name""": args.task_name, """label_list""": args.label_list, """output_dir""": current_output_dir, """eval_metric""": args.eval_metric, """evaluation_strategy""": args.evaluation_strategy, """early_stopping_patience""": args.early_stopping_patience, """early_stopping_threshold""": args.early_stopping_threshold, """seed""": args.seed, } # Add additional training arguments for key, value in kwargs.items(): if key not in arguments_dict and not hasattr(UpperCamelCase__ , UpperCamelCase__ ): arguments_dict.update({key: value} ) _a : int = os.path.join(UpperCamelCase__ , """best-checkpoint""" , UpperCamelCase__ ) if os.path.exists(UpperCamelCase__ ): logger.info( """Found existing model checkpoint at %s. Skipping self-training: iteration: %d, stage: 1.""" , UpperCamelCase__ , UpperCamelCase__ , ) else: logger.info("""***** Running self-training: iteration: %d, stage: 1 *****""" , UpperCamelCase__ ) finetune(**UpperCamelCase__ ) accelerator.wait_for_everyone() assert os.path.exists(UpperCamelCase__ ) logger.info("""Self-training job completed: iteration: %d, stage: 1.""" , UpperCamelCase__ ) if iteration > 0 and args.finetune_on_labeled_data: # Stage 2 (optional): fine-tuning on the original labeled data _a : Dict = os.path.join(UpperCamelCase__ , """best-checkpoint""" ) _a : List[str] = os.path.join(UpperCamelCase__ , """stage-2""" ) # Update arguments_dict _a : int = model_path _a : Dict = data_files["""train"""] _a : int = current_output_dir _a : Any = os.path.join(UpperCamelCase__ , """best-checkpoint""" , UpperCamelCase__ ) if os.path.exists(UpperCamelCase__ ): logger.info( """Found existing model checkpoint at %s. Skipping self-training: iteration: %d, stage: 2.""" , UpperCamelCase__ , UpperCamelCase__ , ) else: logger.info("""***** Running self-training: iteration: %d, stage: 2 *****""" , UpperCamelCase__ ) finetune(**UpperCamelCase__ ) accelerator.wait_for_everyone() assert os.path.exists(UpperCamelCase__ ) logger.info("""Self-training job completed: iteration: %d, stage: 2.""" , UpperCamelCase__ ) _a : List[Any] = iteration _a : int = data_dir_format(iteration + 1 ) _a : Dict = AutoConfig.from_pretrained(os.path.join(UpperCamelCase__ , """best-checkpoint""" ) ) _a : Union[str, Any] = config.idalabel _a : Any = os.path.join(UpperCamelCase__ , """eval_results_best-checkpoint.json""" ) _a : Any = os.path.join(UpperCamelCase__ , """test_results_best-checkpoint.json""" ) assert os.path.exists(UpperCamelCase__ ) with open(UpperCamelCase__ , """r""" ) as f: _a : Tuple = float(json.load(UpperCamelCase__ )[args.eval_metric] ) _a : Dict = os.path.join(UpperCamelCase__ , """infer_output_best-checkpoint.csv""" ) assert os.path.exists(UpperCamelCase__ ) # Loading the dataset from local csv or json files. _a : List[Any] = load_dataset(args.data_file_extension , data_files={"""data""": data_files["""infer"""]} )["""data"""] _a : Any = load_dataset("""csv""" , data_files={"""data""": infer_output_file} )["""data"""] if accelerator.is_main_process: os.makedirs(UpperCamelCase__ , exist_ok=UpperCamelCase__ ) shutil.copy(UpperCamelCase__ , os.path.join(UpperCamelCase__ , F"""eval_results_iter-{iteration}.json""" ) ) if os.path.exists(UpperCamelCase__ ): shutil.copy(UpperCamelCase__ , os.path.join(UpperCamelCase__ , F"""test_results_iter-{iteration}.json""" ) ) create_pseudo_labeled_data(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) accelerator.wait_for_everyone() _a : List[str] = os.path.join(UpperCamelCase__ , F"""train_pseudo.{args.data_file_extension}""" ) if args.evaluation_strategy != IntervalStrategy.NO.value: _a : Any = eval_result if best_iteration is None: _a : Union[str, Any] = new_iteration _a : str = new_eval_result else: if new_eval_result - best_eval_result > args.early_stopping_threshold: _a : Union[str, Any] = new_iteration _a : List[str] = new_eval_result _a : Optional[Any] = 0 else: if new_eval_result == best_eval_result: _a : Tuple = new_iteration _a : List[Any] = new_eval_result early_stopping_patience_counter += 1 if early_stopping_patience_counter >= args.early_stopping_patience: _a : Union[str, Any] = True progress_bar.update(1 ) if should_training_stop: break if best_iteration is not None: # Save the best iteration logger.info("""Best iteration: %d""" , UpperCamelCase__ ) logger.info("""Best evaluation result: %s = %f""" , args.eval_metric , UpperCamelCase__ ) accelerator.wait_for_everyone() if accelerator.is_main_process: shutil.copy( os.path.join(UpperCamelCase__ , F"""eval_results_iter-{iteration}.json""" ) , os.path.join(UpperCamelCase__ , """eval_results_best-iteration.json""" ) , ) else: # Assume that the last iteration is the best logger.info("""Best iteration: %d""" , args.max_selftrain_iterations - 1 ) logger.info("""Best evaluation result: %s = %f""" , args.eval_metric , UpperCamelCase__ ) accelerator.wait_for_everyone() if accelerator.is_main_process: shutil.copy( os.path.join(UpperCamelCase__ , F"""eval_results_iter-{args.max_selftrain_iterations - 1}.json""" ) , os.path.join(UpperCamelCase__ , """eval_results_best-iteration.json""" ) , )
324
1
"""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 UpperCamelCase : def __init__( self : Optional[Any] , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : Tuple=3 , UpperCAmelCase__ : Any=7 , UpperCAmelCase__ : Tuple=True , UpperCAmelCase__ : List[Any]=True , UpperCAmelCase__ : Dict=False , UpperCAmelCase__ : Union[str, Any]=True , UpperCAmelCase__ : Union[str, Any]=99 , UpperCAmelCase__ : List[Any]=32 , UpperCAmelCase__ : List[str]=5 , UpperCAmelCase__ : Dict=4 , UpperCAmelCase__ : Any=37 , UpperCAmelCase__ : Dict="gelu" , UpperCAmelCase__ : List[str]=0.1 , UpperCAmelCase__ : Any=0.1 , UpperCAmelCase__ : int=512 , UpperCAmelCase__ : Dict=16 , UpperCAmelCase__ : Optional[Any]=2 , UpperCAmelCase__ : int=0.0_2 , UpperCAmelCase__ : Tuple=3 , UpperCAmelCase__ : Dict=4 , UpperCAmelCase__ : Optional[int]=None , ) -> Any: _a : Optional[Any] = parent _a : List[str] = batch_size _a : Union[str, Any] = seq_length _a : Optional[int] = is_training _a : List[Any] = use_input_mask _a : List[Any] = use_token_type_ids _a : List[Any] = use_labels _a : Optional[int] = vocab_size _a : str = hidden_size _a : Any = num_hidden_layers _a : List[Any] = num_attention_heads _a : List[str] = intermediate_size _a : str = hidden_act _a : Union[str, Any] = hidden_dropout_prob _a : Dict = attention_probs_dropout_prob _a : Optional[int] = max_position_embeddings _a : Union[str, Any] = type_vocab_size _a : List[Any] = type_sequence_label_size _a : Union[str, Any] = initializer_range _a : Dict = num_labels _a : Dict = num_choices _a : int = scope def _lowercase ( self : Tuple ) -> List[Any]: _a : Dict = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _a : Tuple = None if self.use_input_mask: _a : List[str] = random_attention_mask([self.batch_size, self.seq_length] ) _a : List[str] = None _a : Any = None _a : Optional[int] = None _a : Tuple = None if self.use_labels: _a : List[str] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) _a : Any = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) _a : List[str] = ids_tensor([self.batch_size] , self.num_choices ) _a : str = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def _lowercase ( self : Union[str, Any] ) -> Tuple: 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=UpperCAmelCase__ , initializer_range=self.initializer_range , pad_token_id=1 , new_decoder_architecture=UpperCAmelCase__ , ) def _lowercase ( self : int , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Any , UpperCAmelCase__ : Any , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Optional[int] ) -> Union[str, Any]: _a : Optional[Any] = FalconModel(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() _a : Tuple = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ ) _a : Optional[int] = model(UpperCAmelCase__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _lowercase ( self : Optional[int] , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Any , UpperCAmelCase__ : str , UpperCAmelCase__ : str , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Dict , ) -> Union[str, Any]: _a : List[str] = True _a : Dict = FalconModel(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() _a : int = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , encoder_hidden_states=UpperCAmelCase__ , encoder_attention_mask=UpperCAmelCase__ , ) _a : Optional[Any] = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , encoder_hidden_states=UpperCAmelCase__ , ) _a : str = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _lowercase ( self : Tuple , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : int , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Dict , ) -> Tuple: _a : List[Any] = FalconForCausalLM(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() _a : int = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def _lowercase ( self : Any , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : str , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Any , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : int , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : str , ) -> int: _a : Dict = True _a : List[Any] = True _a : int = FalconForCausalLM(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() # first forward pass _a : Tuple = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , encoder_hidden_states=UpperCAmelCase__ , encoder_attention_mask=UpperCAmelCase__ , use_cache=UpperCAmelCase__ , ) _a : List[Any] = outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids _a : Optional[int] = ids_tensor((self.batch_size, 3) , config.vocab_size ) _a : List[str] = ids_tensor((self.batch_size, 3) , vocab_size=2 ) # append to next input_ids and _a : str = torch.cat([input_ids, next_tokens] , dim=-1 ) _a : Dict = torch.cat([input_mask, next_mask] , dim=-1 ) _a : List[Any] = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , encoder_hidden_states=UpperCAmelCase__ , encoder_attention_mask=UpperCAmelCase__ , output_hidden_states=UpperCAmelCase__ , )["""hidden_states"""][0] _a : int = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , encoder_hidden_states=UpperCAmelCase__ , encoder_attention_mask=UpperCAmelCase__ , past_key_values=UpperCAmelCase__ , output_hidden_states=UpperCAmelCase__ , )["""hidden_states"""][0] # select random slice _a : Optional[Any] = ids_tensor((1,) , output_from_past.shape[-1] ).item() _a : str = output_from_no_past[:, -3:, random_slice_idx].detach() _a : List[Any] = 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(UpperCAmelCase__ , UpperCAmelCase__ , atol=1E-3 ) ) def _lowercase ( self : str ) -> int: _a : List[str] = self.prepare_config_and_inputs() ( ( _a ) , ( _a ) , ( _a ) , ( _a ) , ( _a ) , ( _a ) , ( _a ) , ) : Optional[Any] = config_and_inputs _a : Tuple = {"""input_ids""": input_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class UpperCamelCase ( snake_case_ , snake_case_ , snake_case_ , unittest.TestCase ): UpperCamelCase : Any = ( ( FalconModel, FalconForCausalLM, FalconForSequenceClassification, FalconForTokenClassification, FalconForQuestionAnswering, ) if is_torch_available() else () ) UpperCamelCase : Optional[int] = (FalconForCausalLM,) if is_torch_available() else () UpperCamelCase : Dict = ( { '''feature-extraction''': FalconModel, '''text-classification''': FalconForSequenceClassification, '''text-generation''': FalconForCausalLM, '''question-answering''': FalconForQuestionAnswering, '''token-classification''': FalconForTokenClassification, '''zero-shot''': FalconForSequenceClassification, } if is_torch_available() else {} ) UpperCamelCase : List[Any] = False UpperCamelCase : str = False def _lowercase ( self : str ) -> Dict: _a : Optional[int] = FalconModelTester(self ) _a : Tuple = ConfigTester(self , config_class=UpperCAmelCase__ , hidden_size=37 ) def _lowercase ( self : Optional[Any] ) -> Tuple: self.config_tester.run_common_tests() def _lowercase ( self : Union[str, Any] ) -> Any: _a : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCAmelCase__ ) def _lowercase ( self : int ) -> Tuple: _a , *_a : int = self.model_tester.prepare_config_and_inputs() for alibi in [True, False]: _a : Optional[Any] = alibi self.model_tester.create_and_check_model(UpperCAmelCase__ , *UpperCAmelCase__ ) def _lowercase ( self : Any ) -> Any: _a , _a : Tuple = self.model_tester.prepare_config_and_inputs_for_common() _a : str = 3 _a : List[str] = input_dict["""input_ids"""] _a : Union[str, Any] = input_ids.ne(1 ).to(UpperCAmelCase__ ) _a : Union[str, Any] = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) _a : Any = FalconForSequenceClassification(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() _a : int = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def _lowercase ( self : List[Any] ) -> str: _a , _a : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() _a : Any = 3 _a : str = """single_label_classification""" _a : Union[str, Any] = input_dict["""input_ids"""] _a : List[Any] = input_ids.ne(1 ).to(UpperCAmelCase__ ) _a : Union[str, Any] = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) _a : Tuple = FalconForSequenceClassification(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() _a : int = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def _lowercase ( self : Optional[Any] ) -> List[Any]: _a , _a : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() _a : List[Any] = input_dict["""input_ids"""] _a : Union[str, Any] = FalconForCausalLM(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() _a : List[str] = model(UpperCAmelCase__ , use_cache=UpperCAmelCase__ ) _a : Optional[Any] = input_ids.shape[0] _a : Any = model._convert_to_rw_cache(result.past_key_values ) _a : Dict = model._convert_cache_to_standard_format(UpperCAmelCase__ , UpperCAmelCase__ ) for layer in range(len(UpperCAmelCase__ ) ): 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 _lowercase ( self : Union[str, Any] ) -> int: _a , _a : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() _a : List[Any] = 3 _a : Any = """multi_label_classification""" _a : int = input_dict["""input_ids"""] _a : List[str] = input_ids.ne(1 ).to(UpperCAmelCase__ ) _a : str = ids_tensor( [self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size ).to(torch.float ) _a : Union[str, Any] = FalconForSequenceClassification(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() _a : Any = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def _lowercase ( self : Optional[int] ) -> Any: # Falcon can have different numbers of KV-heads than the number of query heads, so we need # to override this test to use the right head counts. for model_class in self.all_generative_model_classes: _a , _a : Tuple = self.model_tester.prepare_config_and_inputs_for_common() # If it doesn't support cache, pass the test if not hasattr(UpperCAmelCase__ , """use_cache""" ): return _a : Optional[Any] = model_class(UpperCAmelCase__ ).to(UpperCAmelCase__ ) if "use_cache" not in inputs: _a : Tuple = True _a : str = model(**UpperCAmelCase__ ) # 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 _a : Tuple = ( getattr(UpperCAmelCase__ , """decoder_layers""" , UpperCAmelCase__ ) or getattr(UpperCAmelCase__ , """num_decoder_layers""" , UpperCAmelCase__ ) or config.num_hidden_layers ) _a : Union[str, Any] = getattr(UpperCAmelCase__ , """num_kv_heads""" , config.num_attention_heads ) _a : Optional[Any] = getattr(UpperCAmelCase__ , """d_model""" , config.hidden_size ) _a : Optional[int] = embed_dim // num_attention_heads _a : Dict = outputs["""past_key_values"""] self.assertEqual(len(UpperCAmelCase__ ) , UpperCAmelCase__ ) _a , _a : Union[str, Any] = inputs["""input_ids"""].shape for i in range(UpperCAmelCase__ ): if config.new_decoder_architecture: _a : Optional[Any] = config.num_attention_heads elif config.multi_query: _a : 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 UpperCamelCase ( unittest.TestCase ): @slow def _lowercase ( self : Any ) -> Tuple: _a : Any = AutoTokenizer.from_pretrained("""Rocketknight1/falcon-rw-1b""" ) _a : List[Any] = FalconForCausalLM.from_pretrained("""Rocketknight1/falcon-rw-1b""" ) model.eval() model.to(UpperCAmelCase__ ) _a : str = tokenizer("""My favorite food is""" , return_tensors="""pt""" ).to(UpperCAmelCase__ ) _a : Optional[int] = ( """My favorite food is pizza. I love it so much that I have a pizza party every year for my birthday.""" ) _a : Optional[Any] = model.generate(**UpperCAmelCase__ , do_sample=UpperCAmelCase__ , max_new_tokens=19 ) _a : Dict = tokenizer.batch_decode(UpperCAmelCase__ )[0] self.assertEqual(UpperCAmelCase__ , UpperCAmelCase__ ) @slow def _lowercase ( self : str ) -> Dict: # The big models are way too big for the CI, so we use tiny random models that resemble their # architectures but with much smaller and fewer layers for repo in ["Rocketknight1/tiny-random-falcon-7b", "Rocketknight1/tiny-random-falcon-40b"]: _a : Optional[int] = AutoTokenizer.from_pretrained(UpperCAmelCase__ ) _a : int = FalconForCausalLM.from_pretrained(UpperCAmelCase__ ) model.eval() model.to(UpperCAmelCase__ ) _a : Any = tokenizer("""My favorite food is""" , return_tensors="""pt""" ).to(UpperCAmelCase__ ) # We just test that these run without errors - the models are randomly initialized # and so the actual text outputs will be garbage model.generate(**UpperCAmelCase__ , do_sample=UpperCAmelCase__ , max_new_tokens=4 ) model.generate(**UpperCAmelCase__ , do_sample=UpperCAmelCase__ , max_new_tokens=4 ) model.generate(**UpperCAmelCase__ , num_beams=2 , max_new_tokens=4 ) @slow def _lowercase ( self : Union[str, Any] ) -> List[str]: # The big models are way too big for the CI, so we use tiny random models that resemble their # architectures but with much smaller and fewer layers with torch.no_grad(): for repo in [ "Rocketknight1/falcon-rw-1b", "Rocketknight1/tiny-random-falcon-7b", "Rocketknight1/tiny-random-falcon-40b", ]: _a : Union[str, Any] = AutoTokenizer.from_pretrained(UpperCAmelCase__ ) _a : Tuple = FalconForCausalLM.from_pretrained(UpperCAmelCase__ ) model.eval() model.to(device=UpperCAmelCase__ ) _a : Optional[int] = tokenizer("""My favorite food is""" , return_tensors="""pt""" ).to(UpperCAmelCase__ ) # Test results are the same with and without cache _a : str = model.generate(**UpperCAmelCase__ , do_sample=UpperCAmelCase__ , max_new_tokens=20 , use_cache=UpperCAmelCase__ ) _a : Union[str, Any] = model.generate(**UpperCAmelCase__ , do_sample=UpperCAmelCase__ , max_new_tokens=20 , use_cache=UpperCAmelCase__ ) self.assertTrue((outputs_cache - outputs_no_cache).sum().item() == 0 )
324
"""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_camembert import CamembertTokenizer else: _snake_case = None _snake_case = logging.get_logger(__name__) _snake_case = {'vocab_file': 'sentencepiece.bpe.model', 'tokenizer_file': 'tokenizer.json'} _snake_case = { 'vocab_file': { 'camembert-base': 'https://huggingface.co/camembert-base/resolve/main/sentencepiece.bpe.model', }, 'tokenizer_file': { 'camembert-base': 'https://huggingface.co/camembert-base/resolve/main/tokenizer.json', }, } _snake_case = { 'camembert-base': 512, } _snake_case = '▁' class UpperCamelCase ( snake_case_ ): UpperCamelCase : Any = VOCAB_FILES_NAMES UpperCamelCase : Union[str, Any] = PRETRAINED_VOCAB_FILES_MAP UpperCamelCase : Union[str, Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCamelCase : Dict = ['''input_ids''', '''attention_mask'''] UpperCamelCase : Optional[Any] = CamembertTokenizer def __init__( self : int , UpperCAmelCase__ : List[Any]=None , UpperCAmelCase__ : Optional[int]=None , UpperCAmelCase__ : Optional[Any]="<s>" , UpperCAmelCase__ : Optional[int]="</s>" , UpperCAmelCase__ : Tuple="</s>" , UpperCAmelCase__ : Tuple="<s>" , UpperCAmelCase__ : Tuple="<unk>" , UpperCAmelCase__ : Tuple="<pad>" , UpperCAmelCase__ : int="<mask>" , UpperCAmelCase__ : Optional[int]=["<s>NOTUSED", "</s>NOTUSED"] , **UpperCAmelCase__ : Optional[Any] , ) -> Union[str, Any]: # Mask token behave like a normal word, i.e. include the space before it _a : List[Any] = AddedToken(UpperCAmelCase__ , lstrip=UpperCAmelCase__ , rstrip=UpperCAmelCase__ ) if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ) else mask_token super().__init__( UpperCAmelCase__ , tokenizer_file=UpperCAmelCase__ , bos_token=UpperCAmelCase__ , eos_token=UpperCAmelCase__ , sep_token=UpperCAmelCase__ , cls_token=UpperCAmelCase__ , unk_token=UpperCAmelCase__ , pad_token=UpperCAmelCase__ , mask_token=UpperCAmelCase__ , additional_special_tokens=UpperCAmelCase__ , **UpperCAmelCase__ , ) _a : int = vocab_file _a : int = False if not self.vocab_file else True def _lowercase ( self : Union[str, Any] , 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] _a : List[Any] = [self.cls_token_id] _a : Dict = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def _lowercase ( self : Optional[int] , UpperCAmelCase__ : List[int] , UpperCAmelCase__ : Optional[List[int]] = None ) -> List[int]: _a : Union[str, Any] = [self.sep_token_id] _a : 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 _lowercase ( self : Optional[int] , UpperCAmelCase__ : str , UpperCAmelCase__ : Optional[str] = None ) -> Tuple[str]: 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(UpperCAmelCase__ ): logger.error(f"""Vocabulary path ({save_directory}) should be a directory""" ) return _a : List[str] = 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,)
324
1
"""simple docstring""" import os import unicodedata from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import SPIECE_UNDERLINE, logging _snake_case = logging.get_logger(__name__) _snake_case = {'vocab_file': 'spiece.model'} _snake_case = { 'vocab_file': { 'TsinghuaAI/CPM-Generate': 'https://huggingface.co/TsinghuaAI/CPM-Generate/resolve/main/spiece.model', } } class UpperCamelCase ( snake_case_ ): def __init__( self : str , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Union[str, Any]=False , UpperCAmelCase__ : List[str]=True , UpperCAmelCase__ : int=False , UpperCAmelCase__ : Any="<s>" , UpperCAmelCase__ : int="</s>" , UpperCAmelCase__ : Union[str, Any]="<unk>" , UpperCAmelCase__ : str="<sep>" , UpperCAmelCase__ : str="<pad>" , UpperCAmelCase__ : Optional[int]="<cls>" , UpperCAmelCase__ : Tuple="<mask>" , UpperCAmelCase__ : Dict=["<eop>", "<eod>"] , UpperCAmelCase__ : Optional[Dict[str, Any]] = None , **UpperCAmelCase__ : Optional[Any] , ) -> None: _a : Dict = AddedToken(UpperCAmelCase__ , lstrip=UpperCAmelCase__ , rstrip=UpperCAmelCase__ ) if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ) else mask_token _a : int = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( 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__ , additional_special_tokens=UpperCAmelCase__ , sp_model_kwargs=self.sp_model_kwargs , **UpperCAmelCase__ , ) _a : Union[str, Any] = 3 _a : Dict = do_lower_case _a : int = remove_space _a : Union[str, Any] = keep_accents _a : Any = vocab_file _a : Any = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(UpperCAmelCase__ ) try: import jieba except ModuleNotFoundError as error: raise error.__class__( """You need to install jieba to use CpmTokenizer or CpmTokenizerFast. """ """See https://pypi.org/project/jieba/ for installation.""" ) _a : List[str] = jieba _a : int = str.maketrans(""" \n""" , """\u2582\u2583""" ) @property # Copied from transformers.models.xlnet.tokenization_xlnet.XLNetTokenizer.vocab_size def _lowercase ( self : Dict ) -> str: return len(self.sp_model ) def _lowercase ( self : Tuple ) -> str: _a : Optional[int] = {self.convert_ids_to_tokens(UpperCAmelCase__ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self : List[Any] ) -> List[Any]: _a : Tuple = self.__dict__.copy() _a : Optional[Any] = None return state def __setstate__( self : Union[str, Any] , UpperCAmelCase__ : str ) -> List[Any]: _a : int = d # for backward compatibility if not hasattr(self , """sp_model_kwargs""" ): _a : List[str] = {} _a : str = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def _lowercase ( self : List[Any] , UpperCAmelCase__ : int ) -> Optional[Any]: if self.remove_space: _a : Any = """ """.join(inputs.strip().split() ) else: _a : Union[str, Any] = inputs _a : Optional[int] = outputs.replace("""``""" , """\"""" ).replace("""''""" , """\"""" ) if not self.keep_accents: _a : List[Any] = unicodedata.normalize("""NFKD""" , UpperCAmelCase__ ) _a : Union[str, Any] = """""".join([c for c in outputs if not unicodedata.combining(UpperCAmelCase__ )] ) if self.do_lower_case: _a : Optional[int] = outputs.lower() return outputs def _lowercase ( self : Dict , UpperCAmelCase__ : str ) -> List[str]: _a : Union[str, Any] = self.preprocess_text(UpperCAmelCase__ ) _a : Optional[int] = self.sp_model.encode(UpperCAmelCase__ , out_type=UpperCAmelCase__ ) _a : Optional[int] = [] for piece in pieces: if len(UpperCAmelCase__ ) > 1 and piece[-1] == str(""",""" ) and piece[-2].isdigit(): _a : Any = self.sp_model.EncodeAsPieces(piece[:-1].replace(UpperCAmelCase__ , """""" ) ) if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE: if len(cur_pieces[0] ) == 1: _a : Tuple = cur_pieces[1:] else: _a : int = cur_pieces[0][1:] cur_pieces.append(piece[-1] ) new_pieces.extend(UpperCAmelCase__ ) else: new_pieces.append(UpperCAmelCase__ ) return new_pieces def _lowercase ( self : Dict , UpperCAmelCase__ : List[str] ) -> Dict: return self.sp_model.PieceToId(UpperCAmelCase__ ) def _lowercase ( self : Optional[int] , UpperCAmelCase__ : Tuple ) -> Dict: return self.sp_model.IdToPiece(UpperCAmelCase__ ) def _lowercase ( self : List[Any] , UpperCAmelCase__ : Optional[int] ) -> Dict: _a : Any = """""".join(UpperCAmelCase__ ).replace(UpperCAmelCase__ , """ """ ).strip() return out_string def _lowercase ( self : Tuple , UpperCAmelCase__ : List[int] , UpperCAmelCase__ : Optional[List[int]] = None ) -> List[int]: _a : str = [self.sep_token_id] _a : Union[str, Any] = [self.cls_token_id] if token_ids_a is None: return token_ids_a + sep + cls return token_ids_a + sep + token_ids_a + sep + cls def _lowercase ( self : Optional[int] , 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 not None: return ([0] * len(UpperCAmelCase__ )) + [1] + ([0] * len(UpperCAmelCase__ )) + [1, 1] return ([0] * len(UpperCAmelCase__ )) + [1, 1] def _lowercase ( self : List[str] , UpperCAmelCase__ : List[int] , UpperCAmelCase__ : Optional[List[int]] = None ) -> List[int]: _a : Any = [self.sep_token_id] _a : Optional[int] = [2] if token_ids_a is None: return len(token_ids_a + sep ) * [0] + cls_segment_id return len(token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] + cls_segment_id def _lowercase ( self : Any , 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 _a : Tuple = 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: _a : Any = self.sp_model.serialized_model_proto() fi.write(UpperCAmelCase__ ) return (out_vocab_file,) def _lowercase ( self : List[Any] , *UpperCAmelCase__ : Any , **UpperCAmelCase__ : str ) -> Union[str, Any]: _a : List[str] = super()._decode(*UpperCAmelCase__ , **UpperCAmelCase__ ) _a : List[Any] = text.replace(""" """ , """""" ).replace("""\u2582""" , """ """ ).replace("""\u2583""" , """\n""" ) return text
324
"""simple docstring""" from typing import List, Optional, Union import numpy as np import PIL.Image from ...image_processing_utils import BaseImageProcessor, BatchFeature from ...image_transforms import rescale, resize, to_channel_dimension_format from ...image_utils import ( ChannelDimension, PILImageResampling, get_image_size, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, logging _snake_case = logging.get_logger(__name__) class UpperCamelCase ( snake_case_ ): UpperCamelCase : Dict = ['''pixel_values'''] def __init__( self : Any , UpperCAmelCase__ : bool = True , UpperCAmelCase__ : int = 32 , UpperCAmelCase__ : Optional[Any]=PILImageResampling.BILINEAR , UpperCAmelCase__ : bool = True , **UpperCAmelCase__ : List[str] , ) -> None: _a : int = do_resize _a : Union[str, Any] = do_rescale _a : Any = size_divisor _a : Any = resample super().__init__(**UpperCAmelCase__ ) def _lowercase ( self : Tuple , UpperCAmelCase__ : np.ndarray , UpperCAmelCase__ : int , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Optional[ChannelDimension] = None , **UpperCAmelCase__ : Optional[Any] ) -> np.ndarray: _a , _a : Tuple = get_image_size(UpperCAmelCase__ ) # Rounds the height and width down to the closest multiple of size_divisor _a : Optional[Any] = height // size_divisor * size_divisor _a : Union[str, Any] = width // size_divisor * size_divisor _a : Any = resize(UpperCAmelCase__ , (new_h, new_w) , resample=UpperCAmelCase__ , data_format=UpperCAmelCase__ , **UpperCAmelCase__ ) return image def _lowercase ( self : Union[str, Any] , UpperCAmelCase__ : np.ndarray , UpperCAmelCase__ : float , UpperCAmelCase__ : Optional[ChannelDimension] = None , **UpperCAmelCase__ : Optional[int] ) -> np.ndarray: return rescale(image=UpperCAmelCase__ , scale=UpperCAmelCase__ , data_format=UpperCAmelCase__ , **UpperCAmelCase__ ) def _lowercase ( self : Optional[int] , UpperCAmelCase__ : Union["PIL.Image.Image", TensorType, List["PIL.Image.Image"], List[TensorType]] , UpperCAmelCase__ : Optional[bool] = None , UpperCAmelCase__ : Optional[int] = None , UpperCAmelCase__ : int=None , UpperCAmelCase__ : Optional[bool] = None , UpperCAmelCase__ : Optional[Union[TensorType, str]] = None , UpperCAmelCase__ : ChannelDimension = ChannelDimension.FIRST , **UpperCAmelCase__ : int , ) -> BatchFeature: _a : Dict = do_resize if do_resize is not None else self.do_resize _a : Optional[int] = do_rescale if do_rescale is not None else self.do_rescale _a : str = size_divisor if size_divisor is not None else self.size_divisor _a : Any = resample if resample is not None else self.resample if do_resize and size_divisor is None: raise ValueError("""size_divisor is required for resizing""" ) _a : List[str] = make_list_of_images(UpperCAmelCase__ ) if not valid_images(UpperCAmelCase__ ): raise ValueError("""Invalid image(s)""" ) # All transformations expect numpy arrays. _a : Tuple = [to_numpy_array(UpperCAmelCase__ ) for img in images] if do_resize: _a : Optional[int] = [self.resize(UpperCAmelCase__ , size_divisor=UpperCAmelCase__ , resample=UpperCAmelCase__ ) for image in images] if do_rescale: _a : str = [self.rescale(UpperCAmelCase__ , scale=1 / 255 ) for image in images] _a : Any = [to_channel_dimension_format(UpperCAmelCase__ , UpperCAmelCase__ ) for image in images] _a : Optional[int] = {"""pixel_values""": images} return BatchFeature(data=UpperCAmelCase__ , tensor_type=UpperCAmelCase__ )
324
1
"""simple docstring""" import math def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ = 0 , UpperCamelCase__ = 0 ): '''simple docstring''' _a : List[Any] = end or len(UpperCamelCase__ ) for i in range(UpperCamelCase__ , UpperCamelCase__ ): _a : int = i _a : Tuple = array[i] while temp_index != start and temp_index_value < array[temp_index - 1]: _a : Any = array[temp_index - 1] temp_index -= 1 _a : List[Any] = temp_index_value return array def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): # Max Heap '''simple docstring''' _a : Union[str, Any] = index _a : Union[str, Any] = 2 * index + 1 # Left Node _a : Union[str, Any] = 2 * index + 2 # Right Node if left_index < heap_size and array[largest] < array[left_index]: _a : Dict = left_index if right_index < heap_size and array[largest] < array[right_index]: _a : Dict = right_index if largest != index: _a , _a : Optional[int] = array[largest], array[index] heapify(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) def lowerCAmelCase__ ( UpperCamelCase__ ): '''simple docstring''' _a : Optional[int] = len(UpperCamelCase__ ) for i in range(n // 2 , -1 , -1 ): heapify(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) for i in range(n - 1 , 0 , -1 ): _a , _a : List[Any] = array[0], array[i] heapify(UpperCamelCase__ , 0 , UpperCamelCase__ ) return array def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' if (array[first_index] > array[middle_index]) != ( array[first_index] > array[last_index] ): return array[first_index] elif (array[middle_index] > array[first_index]) != ( array[middle_index] > array[last_index] ): return array[middle_index] else: return array[last_index] def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' _a : str = low _a : List[Any] = high while True: while array[i] < pivot: i += 1 j -= 1 while pivot < array[j]: j -= 1 if i >= j: return i _a , _a : int = array[j], array[i] i += 1 def lowerCAmelCase__ ( UpperCamelCase__ ): '''simple docstring''' if len(UpperCamelCase__ ) == 0: return array _a : str = 2 * math.ceil(math.loga(len(UpperCamelCase__ ) ) ) _a : Any = 1_6 return intro_sort(UpperCamelCase__ , 0 , len(UpperCamelCase__ ) , UpperCamelCase__ , UpperCamelCase__ ) def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' while end - start > size_threshold: if max_depth == 0: return heap_sort(UpperCamelCase__ ) max_depth -= 1 _a : Dict = median_of_a(UpperCamelCase__ , UpperCamelCase__ , start + ((end - start) // 2) + 1 , end - 1 ) _a : Optional[Any] = partition(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) intro_sort(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) _a : List[str] = p return insertion_sort(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) if __name__ == "__main__": import doctest doctest.testmod() _snake_case = input('Enter numbers separated by a comma : ').strip() _snake_case = [float(item) for item in user_input.split(',')] print(sort(unsorted))
324
"""simple docstring""" 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 ): @property def _lowercase ( self : Optional[int] ) -> Union[str, Any]: torch.manual_seed(0 ) _a : List[str] = 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 _lowercase ( self : Dict ) -> Dict: _a : str = self.dummy_uncond_unet _a : Optional[int] = KarrasVeScheduler() _a : List[str] = KarrasVePipeline(unet=UpperCAmelCase__ , scheduler=UpperCAmelCase__ ) pipe.to(UpperCAmelCase__ ) pipe.set_progress_bar_config(disable=UpperCAmelCase__ ) _a : int = torch.manual_seed(0 ) _a : List[Any] = pipe(num_inference_steps=2 , generator=UpperCAmelCase__ , output_type="""numpy""" ).images _a : Tuple = torch.manual_seed(0 ) _a : int = pipe(num_inference_steps=2 , generator=UpperCAmelCase__ , output_type="""numpy""" , return_dict=UpperCAmelCase__ )[0] _a : int = image[0, -3:, -3:, -1] _a : Optional[int] = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) _a : str = 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 ): def _lowercase ( self : Tuple ) -> List[str]: _a : Optional[Any] = """google/ncsnpp-celebahq-256""" _a : Any = UNetaDModel.from_pretrained(UpperCAmelCase__ ) _a : Dict = KarrasVeScheduler() _a : int = KarrasVePipeline(unet=UpperCAmelCase__ , scheduler=UpperCAmelCase__ ) pipe.to(UpperCAmelCase__ ) pipe.set_progress_bar_config(disable=UpperCAmelCase__ ) _a : Optional[int] = torch.manual_seed(0 ) _a : Tuple = pipe(num_inference_steps=20 , generator=UpperCAmelCase__ , output_type="""numpy""" ).images _a : List[str] = image[0, -3:, -3:, -1] assert image.shape == (1, 256, 256, 3) _a : Optional[int] = np.array([0.5_7_8, 0.5_8_1_1, 0.5_9_2_4, 0.5_8_0_9, 0.5_8_7, 0.5_8_8_6, 0.5_8_6_1, 0.5_8_0_2, 0.5_8_6] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
324
1
"""simple docstring""" from __future__ import annotations _snake_case = tuple[int, int, int] _snake_case = tuple[str, str, str] # used alphabet -------------------------- # from string.ascii_uppercase _snake_case = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' # -------------------------- default selection -------------------------- # rotors -------------------------- _snake_case = 'EGZWVONAHDCLFQMSIPJBYUKXTR' _snake_case = 'FOBHMDKEXQNRAULPGSJVTYICZW' _snake_case = 'ZJXESIUQLHAVRMDOYGTNFWPBKC' # reflector -------------------------- _snake_case = { 'A': 'N', 'N': 'A', 'B': 'O', 'O': 'B', 'C': 'P', 'P': 'C', 'D': 'Q', 'Q': 'D', 'E': 'R', 'R': 'E', 'F': 'S', 'S': 'F', 'G': 'T', 'T': 'G', 'H': 'U', 'U': 'H', 'I': 'V', 'V': 'I', 'J': 'W', 'W': 'J', 'K': 'X', 'X': 'K', 'L': 'Y', 'Y': 'L', 'M': 'Z', 'Z': 'M', } # -------------------------- extra rotors -------------------------- _snake_case = 'RMDJXFUWGISLHVTCQNKYPBEZOA' _snake_case = 'SGLCPQWZHKXAREONTFBVIYJUDM' _snake_case = 'HVSICLTYKQUBXDWAJZOMFGPREN' _snake_case = 'RZWQHFMVDBKICJLNTUXAGYPSOE' _snake_case = 'LFKIJODBEGAMQPXVUHYSTCZRWN' _snake_case = 'KOAEGVDHXPQZMLFTYWJNBRCIUS' def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' # Checks if there are 3 unique rotors if (unique_rotsel := len(set(UpperCamelCase__ ) )) < 3: _a : Tuple = F"""Please use 3 unique rotors (not {unique_rotsel})""" raise Exception(UpperCamelCase__ ) # Checks if rotor positions are valid _a , _a , _a : int = rotpos if not 0 < rotorposa <= len(UpperCamelCase__ ): _a : List[str] = F"""First rotor position is not within range of 1..26 ({rotorposa}""" raise ValueError(UpperCamelCase__ ) if not 0 < rotorposa <= len(UpperCamelCase__ ): _a : Optional[Any] = F"""Second rotor position is not within range of 1..26 ({rotorposa})""" raise ValueError(UpperCamelCase__ ) if not 0 < rotorposa <= len(UpperCamelCase__ ): _a : Optional[Any] = F"""Third rotor position is not within range of 1..26 ({rotorposa})""" raise ValueError(UpperCamelCase__ ) # Validates string and returns dict _a : Union[str, Any] = _plugboard(UpperCamelCase__ ) return rotpos, rotsel, pbdict def lowerCAmelCase__ ( UpperCamelCase__ ): '''simple docstring''' # tests the input string if it # a) is type string # b) has even length (so pairs can be made) if not isinstance(UpperCamelCase__ , UpperCamelCase__ ): _a : Dict = F"""Plugboard setting isn't type string ({type(UpperCamelCase__ )})""" raise TypeError(UpperCamelCase__ ) elif len(UpperCamelCase__ ) % 2 != 0: _a : Any = F"""Odd number of symbols ({len(UpperCamelCase__ )})""" raise Exception(UpperCamelCase__ ) elif pbstring == "": return {} pbstring.replace(""" """ , """""" ) # Checks if all characters are unique _a : int = set() for i in pbstring: if i not in abc: _a : Optional[Any] = F"""'{i}' not in list of symbols""" raise Exception(UpperCamelCase__ ) elif i in tmppbl: _a : List[str] = F"""Duplicate symbol ({i})""" raise Exception(UpperCamelCase__ ) else: tmppbl.add(UpperCamelCase__ ) del tmppbl # Created the dictionary _a : int = {} for j in range(0 , len(UpperCamelCase__ ) - 1 , 2 ): _a : Any = pbstring[j + 1] _a : Optional[Any] = pbstring[j] return pb def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = (rotora, rotora, rotora) , UpperCamelCase__ = "" , ): '''simple docstring''' _a : List[Any] = text.upper() _a , _a , _a : Optional[Any] = _validator( UpperCamelCase__ , UpperCamelCase__ , plugb.upper() ) _a , _a , _a : Tuple = rotor_position _a , _a , _a : Optional[int] = rotor_selection rotorposa -= 1 rotorposa -= 1 rotorposa -= 1 _a : Any = [] # encryption/decryption process -------------------------- for symbol in text: if symbol in abc: # 1st plugboard -------------------------- if symbol in plugboard: _a : Union[str, Any] = plugboard[symbol] # rotor ra -------------------------- _a : Optional[Any] = abc.index(UpperCamelCase__ ) + rotorposa _a : List[Any] = rotora[index % len(UpperCamelCase__ )] # rotor rb -------------------------- _a : Tuple = abc.index(UpperCamelCase__ ) + rotorposa _a : Union[str, Any] = rotora[index % len(UpperCamelCase__ )] # rotor rc -------------------------- _a : str = abc.index(UpperCamelCase__ ) + rotorposa _a : str = rotora[index % len(UpperCamelCase__ )] # reflector -------------------------- # this is the reason you don't need another machine to decipher _a : Tuple = reflector[symbol] # 2nd rotors _a : Optional[int] = abc[rotora.index(UpperCamelCase__ ) - rotorposa] _a : Tuple = abc[rotora.index(UpperCamelCase__ ) - rotorposa] _a : str = abc[rotora.index(UpperCamelCase__ ) - rotorposa] # 2nd plugboard if symbol in plugboard: _a : int = plugboard[symbol] # moves/resets rotor positions rotorposa += 1 if rotorposa >= len(UpperCamelCase__ ): _a : Tuple = 0 rotorposa += 1 if rotorposa >= len(UpperCamelCase__ ): _a : int = 0 rotorposa += 1 if rotorposa >= len(UpperCamelCase__ ): _a : Union[str, Any] = 0 # else: # pass # Error could be also raised # raise ValueError( # 'Invalid symbol('+repr(symbol)+')') result.append(UpperCamelCase__ ) return "".join(UpperCamelCase__ ) if __name__ == "__main__": _snake_case = 'This is my Python script that emulates the Enigma machine from WWII.' _snake_case = (1, 1, 1) _snake_case = 'pictures' _snake_case = (rotora, rotora, rotora) _snake_case = enigma(message, rotor_pos, rotor_sel, pb) print('Encrypted message:', en) print('Decrypted message:', enigma(en, rotor_pos, rotor_sel, pb))
324
"""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 how to properly calculate the metrics on the # validation dataset when in a distributed system, 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 # ######################################################################## _snake_case = 16 _snake_case = 32 def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ = 1_6 ): '''simple docstring''' _a : str = AutoTokenizer.from_pretrained("""bert-base-cased""" ) _a : Dict = load_dataset("""glue""" , """mrpc""" ) def tokenize_function(UpperCamelCase__ ): # max_length=None => use the model max length (it's actually the default) _a : Optional[int] = 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(): _a : Tuple = 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 _a : List[Any] = tokenized_datasets.rename_column("""label""" , """labels""" ) def collate_fn(UpperCamelCase__ ): # On TPU it's best to pad everything to the same length or training will be very slow. _a : Union[str, Any] = 1_2_8 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": _a : int = 1_6 elif accelerator.mixed_precision != "no": _a : int = 8 else: _a : str = None return tokenizer.pad( UpperCamelCase__ , padding="""longest""" , max_length=UpperCamelCase__ , pad_to_multiple_of=UpperCamelCase__ , return_tensors="""pt""" , ) # Instantiate dataloaders. _a : int = DataLoader( tokenized_datasets["""train"""] , shuffle=UpperCamelCase__ , collate_fn=UpperCamelCase__ , batch_size=UpperCamelCase__ ) _a : List[str] = 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 _snake_case = mocked_dataloaders # noqa: F811 def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' # For testing only if os.environ.get("""TESTING_MOCKED_DATALOADERS""" , UpperCamelCase__ ) == "1": _a : str = 2 # Initialize accelerator _a : int = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs _a : Any = config["""lr"""] _a : Union[str, Any] = int(config["""num_epochs"""] ) _a : str = int(config["""seed"""] ) _a : List[Any] = int(config["""batch_size"""] ) _a : Tuple = evaluate.load("""glue""" , """mrpc""" ) # If the batch size is too big we use gradient accumulation _a : Optional[Any] = 1 if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU: _a : Optional[Any] = batch_size // MAX_GPU_BATCH_SIZE _a : str = MAX_GPU_BATCH_SIZE set_seed(UpperCamelCase__ ) _a , _a : Optional[int] = get_dataloaders(UpperCamelCase__ , UpperCamelCase__ ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) _a : int = 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). _a : List[str] = model.to(accelerator.device ) # Instantiate optimizer _a : List[str] = AdamW(params=model.parameters() , lr=UpperCamelCase__ ) # Instantiate scheduler _a : List[str] = get_linear_schedule_with_warmup( optimizer=UpperCamelCase__ , num_warmup_steps=1_0_0 , 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. _a , _a , _a , _a , _a : Optional[Any] = accelerator.prepare( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) # Now we train the model for epoch in range(UpperCamelCase__ ): model.train() for step, batch in enumerate(UpperCamelCase__ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) _a : Optional[Any] = model(**UpperCamelCase__ ) _a : str = outputs.loss _a : Optional[int] = loss / gradient_accumulation_steps accelerator.backward(UpperCamelCase__ ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() _a : Union[str, Any] = 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 ) with torch.no_grad(): _a : Dict = model(**UpperCamelCase__ ) _a : Optional[Any] = outputs.logits.argmax(dim=-1 ) _a , _a : int = accelerator.gather((predictions, batch["""labels"""]) ) # New Code # # First we check if it's a distributed system if accelerator.use_distributed: # Then see if we're on the last batch of our eval dataloader if step == len(UpperCamelCase__ ) - 1: # Last batch needs to be truncated on distributed systems as it contains additional samples _a : str = predictions[: len(eval_dataloader.dataset ) - samples_seen] _a : int = references[: len(eval_dataloader.dataset ) - samples_seen] else: # Otherwise we add the number of samples seen samples_seen += references.shape[0] # All of this can be avoided if you use `Accelerator.gather_for_metrics` instead of `Accelerator.gather`: # accelerator.gather_for_metrics((predictions, batch["labels"])) metric.add_batch( predictions=UpperCamelCase__ , references=UpperCamelCase__ , ) _a : int = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F"""epoch {epoch}:""" , UpperCamelCase__ ) def lowerCAmelCase__ ( ): '''simple docstring''' _a : Tuple = 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.""" ) _a : Optional[Any] = parser.parse_args() _a : Tuple = {"""lr""": 2e-5, """num_epochs""": 3, """seed""": 4_2, """batch_size""": 1_6} training_function(UpperCamelCase__ , UpperCamelCase__ ) if __name__ == "__main__": main()
324
1
"""simple docstring""" import argparse import collections import json import os import re import string import sys import numpy as np _snake_case = re.compile(r'\b(a|an|the)\b', re.UNICODE) _snake_case = None def lowerCAmelCase__ ( ): '''simple docstring''' _a : int = argparse.ArgumentParser("""Official evaluation script for SQuAD version 2.0.""" ) parser.add_argument("""data_file""" , metavar="""data.json""" , help="""Input data JSON file.""" ) parser.add_argument("""pred_file""" , metavar="""pred.json""" , help="""Model predictions.""" ) parser.add_argument( """--out-file""" , """-o""" , metavar="""eval.json""" , help="""Write accuracy metrics to file (default is stdout).""" ) parser.add_argument( """--na-prob-file""" , """-n""" , metavar="""na_prob.json""" , help="""Model estimates of probability of no answer.""" ) parser.add_argument( """--na-prob-thresh""" , """-t""" , type=UpperCamelCase__ , default=1.0 , help="""Predict \"\" if no-answer probability exceeds this (default = 1.0).""" , ) parser.add_argument( """--out-image-dir""" , """-p""" , metavar="""out_images""" , default=UpperCamelCase__ , help="""Save precision-recall curves to directory.""" ) parser.add_argument("""--verbose""" , """-v""" , action="""store_true""" ) if len(sys.argv ) == 1: parser.print_help() sys.exit(1 ) return parser.parse_args() def lowerCAmelCase__ ( UpperCamelCase__ ): '''simple docstring''' _a : List[str] = {} for article in dataset: for p in article["paragraphs"]: for qa in p["qas"]: _a : List[str] = bool(qa["""answers"""]["""text"""] ) return qid_to_has_ans def lowerCAmelCase__ ( UpperCamelCase__ ): '''simple docstring''' def remove_articles(UpperCamelCase__ ): return ARTICLES_REGEX.sub(""" """ , UpperCamelCase__ ) def white_space_fix(UpperCamelCase__ ): return " ".join(text.split() ) def remove_punc(UpperCamelCase__ ): _a : List[Any] = set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(UpperCamelCase__ ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(UpperCamelCase__ ) ) ) ) def lowerCAmelCase__ ( UpperCamelCase__ ): '''simple docstring''' if not s: return [] return normalize_answer(UpperCamelCase__ ).split() def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' return int(normalize_answer(UpperCamelCase__ ) == normalize_answer(UpperCamelCase__ ) ) def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' _a : List[Any] = get_tokens(UpperCamelCase__ ) _a : str = get_tokens(UpperCamelCase__ ) _a : Optional[Any] = collections.Counter(UpperCamelCase__ ) & collections.Counter(UpperCamelCase__ ) _a : Optional[Any] = sum(common.values() ) if len(UpperCamelCase__ ) == 0 or len(UpperCamelCase__ ) == 0: # If either is no-answer, then F1 is 1 if they agree, 0 otherwise return int(gold_toks == pred_toks ) if num_same == 0: return 0 _a : Dict = 1.0 * num_same / len(UpperCamelCase__ ) _a : Optional[Any] = 1.0 * num_same / len(UpperCamelCase__ ) _a : str = (2 * precision * recall) / (precision + recall) return fa def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' _a : int = {} _a : Tuple = {} for article in dataset: for p in article["paragraphs"]: for qa in p["qas"]: _a : Union[str, Any] = qa["""id"""] _a : Tuple = [t for t in qa["""answers"""]["""text"""] if normalize_answer(UpperCamelCase__ )] if not gold_answers: # For unanswerable questions, only correct answer is empty string _a : int = [""""""] if qid not in preds: print(F"""Missing prediction for {qid}""" ) continue _a : Optional[Any] = preds[qid] # Take max over all gold answers _a : int = max(compute_exact(UpperCamelCase__ , UpperCamelCase__ ) for a in gold_answers ) _a : Dict = max(compute_fa(UpperCamelCase__ , UpperCamelCase__ ) for a in gold_answers ) return exact_scores, fa_scores def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' _a : Union[str, Any] = {} for qid, s in scores.items(): _a : str = na_probs[qid] > na_prob_thresh if pred_na: _a : Dict = float(not qid_to_has_ans[qid] ) else: _a : List[str] = s return new_scores def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__=None ): '''simple docstring''' if not qid_list: _a : Optional[int] = len(UpperCamelCase__ ) return collections.OrderedDict( [ ("""exact""", 100.0 * sum(exact_scores.values() ) / total), ("""f1""", 100.0 * sum(fa_scores.values() ) / total), ("""total""", total), ] ) else: _a : Dict = len(UpperCamelCase__ ) return collections.OrderedDict( [ ("""exact""", 100.0 * sum(exact_scores[k] for k in qid_list ) / total), ("""f1""", 100.0 * sum(fa_scores[k] for k in qid_list ) / total), ("""total""", total), ] ) def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' for k in new_eval: _a : Optional[Any] = new_eval[k] def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' plt.step(UpperCamelCase__ , UpperCamelCase__ , color="""b""" , alpha=0.2 , where="""post""" ) plt.fill_between(UpperCamelCase__ , UpperCamelCase__ , step="""post""" , alpha=0.2 , color="""b""" ) plt.xlabel("""Recall""" ) plt.ylabel("""Precision""" ) plt.xlim([0.0, 1.05] ) plt.ylim([0.0, 1.05] ) plt.title(UpperCamelCase__ ) plt.savefig(UpperCamelCase__ ) plt.clf() def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__=None , UpperCamelCase__=None ): '''simple docstring''' _a : List[Any] = sorted(UpperCamelCase__ , key=lambda UpperCamelCase__ : na_probs[k] ) _a : Dict = 0.0 _a : Dict = 1.0 _a : Any = 0.0 _a : Union[str, Any] = [1.0] _a : str = [0.0] _a : Union[str, Any] = 0.0 for i, qid in enumerate(UpperCamelCase__ ): if qid_to_has_ans[qid]: true_pos += scores[qid] _a : Any = true_pos / float(i + 1 ) _a : Optional[int] = true_pos / float(UpperCamelCase__ ) if i == len(UpperCamelCase__ ) - 1 or na_probs[qid] != na_probs[qid_list[i + 1]]: # i.e., if we can put a threshold after this point avg_prec += cur_p * (cur_r - recalls[-1]) precisions.append(UpperCamelCase__ ) recalls.append(UpperCamelCase__ ) if out_image: plot_pr_curve(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) return {"ap": 100.0 * avg_prec} def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' if out_image_dir and not os.path.exists(UpperCamelCase__ ): os.makedirs(UpperCamelCase__ ) _a : Any = sum(1 for v in qid_to_has_ans.values() if v ) if num_true_pos == 0: return _a : List[str] = make_precision_recall_eval( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , out_image=os.path.join(UpperCamelCase__ , """pr_exact.png""" ) , title="""Precision-Recall curve for Exact Match score""" , ) _a : Union[str, Any] = make_precision_recall_eval( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , out_image=os.path.join(UpperCamelCase__ , """pr_f1.png""" ) , title="""Precision-Recall curve for F1 score""" , ) _a : List[Any] = {k: float(UpperCamelCase__ ) for k, v in qid_to_has_ans.items()} _a : List[Any] = make_precision_recall_eval( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , out_image=os.path.join(UpperCamelCase__ , """pr_oracle.png""" ) , title="""Oracle Precision-Recall curve (binary task of HasAns vs. NoAns)""" , ) merge_eval(UpperCamelCase__ , UpperCamelCase__ , """pr_exact""" ) merge_eval(UpperCamelCase__ , UpperCamelCase__ , """pr_f1""" ) merge_eval(UpperCamelCase__ , UpperCamelCase__ , """pr_oracle""" ) def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' if not qid_list: return _a : Union[str, Any] = [na_probs[k] for k in qid_list] _a : int = np.ones_like(UpperCamelCase__ ) / float(len(UpperCamelCase__ ) ) plt.hist(UpperCamelCase__ , weights=UpperCamelCase__ , bins=2_0 , range=(0.0, 1.0) ) plt.xlabel("""Model probability of no-answer""" ) plt.ylabel("""Proportion of dataset""" ) plt.title(F"""Histogram of no-answer probability: {name}""" ) plt.savefig(os.path.join(UpperCamelCase__ , F"""na_prob_hist_{name}.png""" ) ) plt.clf() def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' _a : List[Any] = sum(1 for k in qid_to_has_ans if not qid_to_has_ans[k] ) _a : Tuple = num_no_ans _a : int = cur_score _a : str = 0.0 _a : Dict = sorted(UpperCamelCase__ , key=lambda UpperCamelCase__ : na_probs[k] ) for i, qid in enumerate(UpperCamelCase__ ): if qid not in scores: continue if qid_to_has_ans[qid]: _a : List[Any] = scores[qid] else: if preds[qid]: _a : Optional[Any] = -1 else: _a : Optional[Any] = 0 cur_score += diff if cur_score > best_score: _a : List[str] = cur_score _a : Dict = na_probs[qid] return 100.0 * best_score / len(UpperCamelCase__ ), best_thresh def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' _a , _a : Optional[int] = find_best_thresh(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) _a , _a : List[str] = find_best_thresh(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) _a : Dict = best_exact _a : str = exact_thresh _a : Dict = best_fa _a : str = fa_thresh def lowerCAmelCase__ ( ): '''simple docstring''' with open(OPTS.data_file ) as f: _a : str = json.load(UpperCamelCase__ ) _a : Tuple = dataset_json["""data"""] with open(OPTS.pred_file ) as f: _a : Union[str, Any] = json.load(UpperCamelCase__ ) if OPTS.na_prob_file: with open(OPTS.na_prob_file ) as f: _a : Optional[int] = json.load(UpperCamelCase__ ) else: _a : int = {k: 0.0 for k in preds} _a : str = make_qid_to_has_ans(UpperCamelCase__ ) # maps qid to True/False _a : Dict = [k for k, v in qid_to_has_ans.items() if v] _a : List[str] = [k for k, v in qid_to_has_ans.items() if not v] _a , _a : int = get_raw_scores(UpperCamelCase__ , UpperCamelCase__ ) _a : List[str] = apply_no_ans_threshold(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , OPTS.na_prob_thresh ) _a : List[str] = apply_no_ans_threshold(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , OPTS.na_prob_thresh ) _a : str = make_eval_dict(UpperCamelCase__ , UpperCamelCase__ ) if has_ans_qids: _a : Dict = make_eval_dict(UpperCamelCase__ , UpperCamelCase__ , qid_list=UpperCamelCase__ ) merge_eval(UpperCamelCase__ , UpperCamelCase__ , """HasAns""" ) if no_ans_qids: _a : Any = make_eval_dict(UpperCamelCase__ , UpperCamelCase__ , qid_list=UpperCamelCase__ ) merge_eval(UpperCamelCase__ , UpperCamelCase__ , """NoAns""" ) if OPTS.na_prob_file: find_all_best_thresh(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) if OPTS.na_prob_file and OPTS.out_image_dir: run_precision_recall_analysis(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , OPTS.out_image_dir ) histogram_na_prob(UpperCamelCase__ , UpperCamelCase__ , OPTS.out_image_dir , """hasAns""" ) histogram_na_prob(UpperCamelCase__ , UpperCamelCase__ , OPTS.out_image_dir , """noAns""" ) if OPTS.out_file: with open(OPTS.out_file , """w""" ) as f: json.dump(UpperCamelCase__ , UpperCamelCase__ ) else: print(json.dumps(UpperCamelCase__ , indent=2 ) ) if __name__ == "__main__": _snake_case = parse_args() if OPTS.out_image_dir: import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt main()
324
"""simple docstring""" import numpy as np def lowerCAmelCase__ ( UpperCamelCase__ ): '''simple docstring''' return 1 / (1 + np.exp(-vector )) def lowerCAmelCase__ ( UpperCamelCase__ ): '''simple docstring''' return vector * sigmoid(1.702 * vector ) if __name__ == "__main__": import doctest doctest.testmod()
324
1
"""simple docstring""" def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' # 1. Validate that path exists between current and next vertices if graph[path[curr_ind - 1]][next_ver] == 0: return False # 2. Validate that next vertex is not already in path return not any(vertex == next_ver for vertex in path ) def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' # Base Case if curr_ind == len(UpperCamelCase__ ): # return whether path exists between current and starting vertices return graph[path[curr_ind - 1]][path[0]] == 1 # Recursive Step for next_ver in range(0 , len(UpperCamelCase__ ) ): if valid_connection(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): # Insert current vertex into path as next transition _a : int = next_ver # Validate created path if util_hamilton_cycle(UpperCamelCase__ , UpperCamelCase__ , curr_ind + 1 ): return True # Backtrack _a : Tuple = -1 return False def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ = 0 ): '''simple docstring''' _a : int = [-1] * (len(UpperCamelCase__ ) + 1) # initialize start and end of path with starting index _a : str = start_index # evaluate and if we find answer return path either return empty array return path if util_hamilton_cycle(UpperCamelCase__ , UpperCamelCase__ , 1 ) else []
324
"""simple docstring""" import unittest from transformers import CamembertTokenizer, CamembertTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.utils import is_torch_available from ...test_tokenization_common import TokenizerTesterMixin _snake_case = get_tests_dir('fixtures/test_sentencepiece.model') _snake_case = get_tests_dir('fixtures/test_sentencepiece_bpe.model') _snake_case = 'pt' if is_torch_available() else 'tf' @require_sentencepiece @require_tokenizers class UpperCamelCase ( snake_case_ , unittest.TestCase ): UpperCamelCase : str = CamembertTokenizer UpperCamelCase : List[Any] = CamembertTokenizerFast UpperCamelCase : Optional[int] = True UpperCamelCase : Union[str, Any] = True def _lowercase ( self : List[Any] ) -> Union[str, Any]: super().setUp() # We have a SentencePiece fixture for testing _a : List[Any] = CamembertTokenizer(UpperCAmelCase__ ) tokenizer.save_pretrained(self.tmpdirname ) def _lowercase ( self : List[str] ) -> Tuple: _a : Optional[Any] = """<pad>""" _a : Tuple = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(UpperCAmelCase__ ) , UpperCAmelCase__ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(UpperCAmelCase__ ) , UpperCAmelCase__ ) def _lowercase ( self : Union[str, Any] ) -> str: _a : List[str] = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , """<s>NOTUSED""" ) self.assertEqual(vocab_keys[1] , """<pad>""" ) self.assertEqual(vocab_keys[-1] , """<mask>""" ) self.assertEqual(len(UpperCAmelCase__ ) , 1004 ) def _lowercase ( self : List[str] ) -> List[Any]: self.assertEqual(self.get_tokenizer().vocab_size , 1005 ) def _lowercase ( self : Union[str, Any] ) -> str: _a : Tuple = CamembertTokenizer(UpperCAmelCase__ ) tokenizer.save_pretrained(self.tmpdirname ) _a : List[Any] = CamembertTokenizerFast.from_pretrained(self.tmpdirname ) _a : Any = """I was born in 92000, and this is falsé.""" _a : Union[str, Any] = tokenizer.encode(UpperCAmelCase__ ) _a : Dict = rust_tokenizer.encode(UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) _a : Tuple = tokenizer.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) _a : List[Any] = rust_tokenizer.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) # <unk> tokens are not the same for `rust` than for `slow`. # Because spm gives back raw token instead of `unk` in EncodeAsPieces # tokens = tokenizer.tokenize(sequence) _a : List[str] = tokenizer.convert_ids_to_tokens(UpperCAmelCase__ ) _a : int = rust_tokenizer.tokenize(UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) def _lowercase ( self : Dict ) -> List[str]: if not self.test_rust_tokenizer: return _a : Optional[int] = self.get_tokenizer() _a : Tuple = self.get_rust_tokenizer() _a : List[Any] = """I was born in 92000, and this is falsé.""" _a : List[str] = tokenizer.tokenize(UpperCAmelCase__ ) _a : Union[str, Any] = rust_tokenizer.tokenize(UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) _a : int = tokenizer.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) _a : Optional[int] = rust_tokenizer.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) _a : int = self.get_rust_tokenizer() _a : Optional[Any] = tokenizer.encode(UpperCAmelCase__ ) _a : Dict = rust_tokenizer.encode(UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) @slow def _lowercase ( self : Tuple ) -> List[Any]: # fmt: off _a : Dict = {"""input_ids""": [[5, 54, 7196, 297, 30, 23, 776, 18, 11, 3215, 3705, 8252, 22, 3164, 1181, 2116, 29, 16, 813, 25, 791, 3314, 20, 3446, 38, 27575, 120, 6, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [5, 468, 17, 11, 9088, 20, 1517, 8, 22804, 18818, 10, 38, 629, 607, 607, 142, 19, 7196, 867, 56, 10326, 24, 2267, 20, 416, 5072, 15612, 233, 734, 7, 2399, 27, 16, 3015, 1649, 7, 24, 20, 4338, 2399, 27, 13, 3400, 14, 13, 6189, 8, 930, 9, 6]], """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, 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, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]} # noqa: E501 # fmt: on # camembert is a french model. So we also use french texts. _a : Union[str, Any] = [ """Le transformeur est un modèle d'apprentissage profond introduit en 2017, """ """utilisé principalement dans le domaine du traitement automatique des langues (TAL).""", """À l'instar des réseaux de neurones récurrents (RNN), les transformeurs sont conçus """ """pour gérer des données séquentielles, telles que le langage naturel, pour des tâches """ """telles que la traduction et la synthèse de texte.""", ] self.tokenizer_integration_test_util( expected_encoding=UpperCAmelCase__ , model_name="""camembert-base""" , revision="""3a0641d9a1aeb7e848a74299e7e4c4bca216b4cf""" , sequences=UpperCAmelCase__ , )
324
1
"""simple docstring""" import numpy as np from PIL import Image def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' _a : Optional[int] = np.array(UpperCamelCase__ ) if arr.shape[0] != arr.shape[1]: raise ValueError("""The input array is not a square matrix""" ) _a : Tuple = 0 _a : Tuple = 0 _a : Dict = 0 _a : int = 0 # compute the shape of the output matrix _a : Dict = (arr.shape[0] - size) // stride + 1 # initialize the output matrix with zeros of shape maxpool_shape _a : Any = np.zeros((maxpool_shape, maxpool_shape) ) while i < arr.shape[0]: if i + size > arr.shape[0]: # if the end of the matrix is reached, break break while j < arr.shape[1]: # if the end of the matrix is reached, break if j + size > arr.shape[1]: break # compute the maximum of the pooling matrix _a : Optional[Any] = np.max(arr[i : i + size, j : j + size] ) # shift the pooling matrix by stride of column pixels j += stride mat_j += 1 # shift the pooling matrix by stride of row pixels i += stride mat_i += 1 # reset the column index to 0 _a : Optional[int] = 0 _a : Dict = 0 return updated_arr def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' _a : Dict = np.array(UpperCamelCase__ ) if arr.shape[0] != arr.shape[1]: raise ValueError("""The input array is not a square matrix""" ) _a : int = 0 _a : Dict = 0 _a : Dict = 0 _a : Any = 0 # compute the shape of the output matrix _a : Optional[Any] = (arr.shape[0] - size) // stride + 1 # initialize the output matrix with zeros of shape avgpool_shape _a : Optional[Any] = np.zeros((avgpool_shape, avgpool_shape) ) while i < arr.shape[0]: # if the end of the matrix is reached, break if i + size > arr.shape[0]: break while j < arr.shape[1]: # if the end of the matrix is reached, break if j + size > arr.shape[1]: break # compute the average of the pooling matrix _a : Optional[int] = int(np.average(arr[i : i + size, j : j + size] ) ) # shift the pooling matrix by stride of column pixels j += stride mat_j += 1 # shift the pooling matrix by stride of row pixels i += stride mat_i += 1 # reset the column index to 0 _a : int = 0 _a : Union[str, Any] = 0 return updated_arr # Main Function if __name__ == "__main__": from doctest import testmod testmod(name='avgpooling', verbose=True) # Loading the image _snake_case = Image.open('path_to_image') # Converting the image to numpy array and maxpooling, displaying the result # Ensure that the image is a square matrix Image.fromarray(maxpooling(np.array(image), size=3, stride=2)).show() # Converting the image to numpy array and averagepooling, displaying the result # Ensure that the image is a square matrix Image.fromarray(avgpooling(np.array(image), size=3, stride=2)).show()
324
"""simple docstring""" import argparse import collections import os import re import tempfile import pandas as pd from datasets import Dataset from huggingface_hub import hf_hub_download, upload_folder from transformers.utils import direct_transformers_import # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/update_metadata.py _snake_case = 'src/transformers' # This is to make sure the transformers module imported is the one in the repo. _snake_case = direct_transformers_import(TRANSFORMERS_PATH) # Regexes that match TF/Flax/PT model names. _snake_case = re.compile(r'TF(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)') _snake_case = re.compile(r'Flax(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)') # Will match any TF or Flax model too so need to be in an else branch afterthe two previous regexes. _snake_case = re.compile(r'(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)') # Fill this with tuples (pipeline_tag, model_mapping, auto_model) _snake_case = [ ('pretraining', 'MODEL_FOR_PRETRAINING_MAPPING_NAMES', 'AutoModelForPreTraining'), ('feature-extraction', 'MODEL_MAPPING_NAMES', 'AutoModel'), ('audio-classification', 'MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES', 'AutoModelForAudioClassification'), ('text-generation', 'MODEL_FOR_CAUSAL_LM_MAPPING_NAMES', 'AutoModelForCausalLM'), ('automatic-speech-recognition', 'MODEL_FOR_CTC_MAPPING_NAMES', 'AutoModelForCTC'), ('image-classification', 'MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES', 'AutoModelForImageClassification'), ('image-segmentation', 'MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES', 'AutoModelForImageSegmentation'), ('fill-mask', 'MODEL_FOR_MASKED_LM_MAPPING_NAMES', 'AutoModelForMaskedLM'), ('object-detection', 'MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES', 'AutoModelForObjectDetection'), ( 'zero-shot-object-detection', 'MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES', 'AutoModelForZeroShotObjectDetection', ), ('question-answering', 'MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES', 'AutoModelForQuestionAnswering'), ('text2text-generation', 'MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES', 'AutoModelForSeq2SeqLM'), ('text-classification', 'MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES', 'AutoModelForSequenceClassification'), ('automatic-speech-recognition', 'MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES', 'AutoModelForSpeechSeq2Seq'), ( 'table-question-answering', 'MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING_NAMES', 'AutoModelForTableQuestionAnswering', ), ('token-classification', 'MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES', 'AutoModelForTokenClassification'), ('multiple-choice', 'MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES', 'AutoModelForMultipleChoice'), ( 'next-sentence-prediction', 'MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING_NAMES', 'AutoModelForNextSentencePrediction', ), ( 'audio-frame-classification', 'MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES', 'AutoModelForAudioFrameClassification', ), ('audio-xvector', 'MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES', 'AutoModelForAudioXVector'), ( 'document-question-answering', 'MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES', 'AutoModelForDocumentQuestionAnswering', ), ( 'visual-question-answering', 'MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING_NAMES', 'AutoModelForVisualQuestionAnswering', ), ('image-to-text', 'MODEL_FOR_FOR_VISION_2_SEQ_MAPPING_NAMES', 'AutoModelForVision2Seq'), ( 'zero-shot-image-classification', 'MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING_NAMES', 'AutoModelForZeroShotImageClassification', ), ('depth-estimation', 'MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES', 'AutoModelForDepthEstimation'), ('video-classification', 'MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING_NAMES', 'AutoModelForVideoClassification'), ('mask-generation', 'MODEL_FOR_MASK_GENERATION_MAPPING_NAMES', 'AutoModelForMaskGeneration'), ] def lowerCAmelCase__ ( UpperCamelCase__ ): '''simple docstring''' _a : Dict = re.finditer(""".+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)""" , UpperCamelCase__ ) return [m.group(0 ) for m in matches] def lowerCAmelCase__ ( ): '''simple docstring''' _a : Tuple = transformers_module.models.auto.configuration_auto.CONFIG_MAPPING_NAMES _a : Optional[int] = { config.replace("""Config""" , """""" ): model_type for model_type, config in config_maping_names.items() } # Dictionaries flagging if each model prefix has a backend in PT/TF/Flax. _a : List[Any] = collections.defaultdict(UpperCamelCase__ ) _a : List[str] = collections.defaultdict(UpperCamelCase__ ) _a : Tuple = collections.defaultdict(UpperCamelCase__ ) # Let's lookup through all transformers object (once) and find if models are supported by a given backend. for attr_name in dir(UpperCamelCase__ ): _a : str = None if _re_tf_models.match(UpperCamelCase__ ) is not None: _a : List[Any] = tf_models _a : int = _re_tf_models.match(UpperCamelCase__ ).groups()[0] elif _re_flax_models.match(UpperCamelCase__ ) is not None: _a : Any = flax_models _a : Any = _re_flax_models.match(UpperCamelCase__ ).groups()[0] elif _re_pt_models.match(UpperCamelCase__ ) is not None: _a : int = pt_models _a : int = _re_pt_models.match(UpperCamelCase__ ).groups()[0] if lookup_dict is not None: while len(UpperCamelCase__ ) > 0: if attr_name in model_prefix_to_model_type: _a : Optional[int] = True break # Try again after removing the last word in the name _a : List[Any] = """""".join(camel_case_split(UpperCamelCase__ )[:-1] ) _a : Optional[int] = set(list(pt_models.keys() ) + list(tf_models.keys() ) + list(flax_models.keys() ) ) _a : Dict = list(UpperCamelCase__ ) all_models.sort() _a : str = {"""model_type""": all_models} _a : List[Any] = [pt_models[t] for t in all_models] _a : str = [tf_models[t] for t in all_models] _a : Optional[int] = [flax_models[t] for t in all_models] # Now let's use the auto-mapping names to make sure _a : str = {} for t in all_models: if t in transformers_module.models.auto.processing_auto.PROCESSOR_MAPPING_NAMES: _a : List[str] = """AutoProcessor""" elif t in transformers_module.models.auto.tokenization_auto.TOKENIZER_MAPPING_NAMES: _a : str = """AutoTokenizer""" elif t in transformers_module.models.auto.feature_extraction_auto.FEATURE_EXTRACTOR_MAPPING_NAMES: _a : int = """AutoFeatureExtractor""" else: # Default to AutoTokenizer if a model has nothing, for backward compatibility. _a : int = """AutoTokenizer""" _a : Any = [processors[t] for t in all_models] return pd.DataFrame(UpperCamelCase__ ) def lowerCAmelCase__ ( UpperCamelCase__ ): '''simple docstring''' _a : List[Any] = [ transformers_module.models.auto.modeling_auto, transformers_module.models.auto.modeling_tf_auto, transformers_module.models.auto.modeling_flax_auto, ] for pipeline_tag, model_mapping, auto_class in PIPELINE_TAGS_AND_AUTO_MODELS: _a : List[Any] = [model_mapping, F"""TF_{model_mapping}""", F"""FLAX_{model_mapping}"""] _a : Union[str, Any] = [auto_class, F"""TF_{auto_class}""", F"""Flax_{auto_class}"""] # Loop through all three frameworks for module, cls, mapping in zip(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): # The type of pipeline may not exist in this framework if not hasattr(UpperCamelCase__ , UpperCamelCase__ ): continue # First extract all model_names _a : str = [] for name in getattr(UpperCamelCase__ , UpperCamelCase__ ).values(): if isinstance(UpperCamelCase__ , UpperCamelCase__ ): model_names.append(UpperCamelCase__ ) else: model_names.extend(list(UpperCamelCase__ ) ) # Add pipeline tag and auto model class for those models table.update({model_name: (pipeline_tag, cls) for model_name in model_names} ) return table def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' _a : Dict = get_frameworks_table() _a : Optional[Any] = Dataset.from_pandas(UpperCamelCase__ ) _a : Any = hf_hub_download( """huggingface/transformers-metadata""" , """pipeline_tags.json""" , repo_type="""dataset""" , token=UpperCamelCase__ ) _a : List[Any] = Dataset.from_json(UpperCamelCase__ ) _a : List[str] = { tags_dataset[i]["""model_class"""]: (tags_dataset[i]["""pipeline_tag"""], tags_dataset[i]["""auto_class"""]) for i in range(len(UpperCamelCase__ ) ) } _a : str = update_pipeline_and_auto_class_table(UpperCamelCase__ ) # Sort the model classes to avoid some nondeterministic updates to create false update commits. _a : int = sorted(table.keys() ) _a : Union[str, Any] = pd.DataFrame( { """model_class""": model_classes, """pipeline_tag""": [table[m][0] for m in model_classes], """auto_class""": [table[m][1] for m in model_classes], } ) _a : Dict = Dataset.from_pandas(UpperCamelCase__ ) with tempfile.TemporaryDirectory() as tmp_dir: frameworks_dataset.to_json(os.path.join(UpperCamelCase__ , """frameworks.json""" ) ) tags_dataset.to_json(os.path.join(UpperCamelCase__ , """pipeline_tags.json""" ) ) if commit_sha is not None: _a : List[str] = ( F"""Update with commit {commit_sha}\n\nSee: """ F"""https://github.com/huggingface/transformers/commit/{commit_sha}""" ) else: _a : Optional[Any] = """Update""" upload_folder( repo_id="""huggingface/transformers-metadata""" , folder_path=UpperCamelCase__ , repo_type="""dataset""" , token=UpperCamelCase__ , commit_message=UpperCamelCase__ , ) def lowerCAmelCase__ ( ): '''simple docstring''' _a : List[str] = {tag: cls for tag, _, cls in PIPELINE_TAGS_AND_AUTO_MODELS} _a : Any = transformers_module.pipelines.SUPPORTED_TASKS _a : List[str] = [] for key in pipeline_tasks: if key not in in_table: _a : Tuple = pipeline_tasks[key]["""pt"""] if isinstance(UpperCamelCase__ , (list, tuple) ): _a : Dict = model[0] _a : List[str] = model.__name__ if model not in in_table.values(): missing.append(UpperCamelCase__ ) if len(UpperCamelCase__ ) > 0: _a : Union[str, Any] = """, """.join(UpperCamelCase__ ) raise ValueError( """The following pipeline tags are not present in the `PIPELINE_TAGS_AND_AUTO_MODELS` constant inside """ F"""`utils/update_metadata.py`: {msg}. Please add them!""" ) if __name__ == "__main__": _snake_case = argparse.ArgumentParser() parser.add_argument('--token', type=str, help='The token to use to push to the transformers-metadata dataset.') parser.add_argument('--commit_sha', type=str, help='The sha of the commit going with this update.') parser.add_argument('--check-only', action='store_true', help='Activate to just check all pipelines are present.') _snake_case = parser.parse_args() if args.check_only: check_pipeline_tags() else: update_metadata(args.token, args.commit_sha)
324
1
"""simple docstring""" from copy import deepcopy class UpperCamelCase : def __init__( self : int , UpperCAmelCase__ : list[int] | None = None , UpperCAmelCase__ : int | None = None ) -> None: if arr is None and size is not None: _a : Dict = size _a : Tuple = [0] * size elif arr is not None: self.init(UpperCAmelCase__ ) else: raise ValueError("""Either arr or size must be specified""" ) def _lowercase ( self : Tuple , UpperCAmelCase__ : list[int] ) -> None: _a : Optional[int] = len(UpperCAmelCase__ ) _a : int = deepcopy(UpperCAmelCase__ ) for i in range(1 , self.size ): _a : str = self.next_(UpperCAmelCase__ ) if j < self.size: self.tree[j] += self.tree[i] def _lowercase ( self : Optional[Any] ) -> list[int]: _a : int = self.tree[:] for i in range(self.size - 1 , 0 , -1 ): _a : Optional[int] = self.next_(UpperCAmelCase__ ) if j < self.size: arr[j] -= arr[i] return arr @staticmethod def _lowercase ( UpperCAmelCase__ : int ) -> int: return index + (index & (-index)) @staticmethod def _lowercase ( UpperCAmelCase__ : int ) -> int: return index - (index & (-index)) def _lowercase ( self : Tuple , UpperCAmelCase__ : int , UpperCAmelCase__ : int ) -> None: if index == 0: self.tree[0] += value return while index < self.size: self.tree[index] += value _a : List[str] = self.next_(UpperCAmelCase__ ) def _lowercase ( self : Any , UpperCAmelCase__ : int , UpperCAmelCase__ : int ) -> None: self.add(UpperCAmelCase__ , value - self.get(UpperCAmelCase__ ) ) def _lowercase ( self : List[Any] , UpperCAmelCase__ : int ) -> int: if right == 0: return 0 _a : int = self.tree[0] right -= 1 # make right inclusive while right > 0: result += self.tree[right] _a : Union[str, Any] = self.prev(UpperCAmelCase__ ) return result def _lowercase ( self : Union[str, Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : int ) -> int: return self.prefix(UpperCAmelCase__ ) - self.prefix(UpperCAmelCase__ ) def _lowercase ( self : int , UpperCAmelCase__ : int ) -> int: return self.query(UpperCAmelCase__ , index + 1 ) def _lowercase ( self : Tuple , UpperCAmelCase__ : int ) -> int: value -= self.tree[0] if value < 0: return -1 _a : Any = 1 # Largest power of 2 <= size while j * 2 < self.size: j *= 2 _a : str = 0 while j > 0: if i + j < self.size and self.tree[i + j] <= value: value -= self.tree[i + j] i += j j //= 2 return i if __name__ == "__main__": import doctest doctest.testmod()
324
"""simple docstring""" import os import pytest import yaml from datasets.features.features import Features, Value from datasets.info import DatasetInfo, DatasetInfosDict @pytest.mark.parametrize( """files""" , [ ["""full:README.md""", """dataset_infos.json"""], ["""empty:README.md""", """dataset_infos.json"""], ["""dataset_infos.json"""], ["""full:README.md"""], ] , ) def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' _a : Dict = tmp_path_factory.mktemp("""dset_infos_dir""" ) if "full:README.md" in files: with open(dataset_infos_dir / """README.md""" , """w""" ) as f: f.write("""---\ndataset_info:\n dataset_size: 42\n---""" ) if "empty:README.md" in files: with open(dataset_infos_dir / """README.md""" , """w""" ) as f: f.write("""""" ) # we want to support dataset_infos.json for backward compatibility if "dataset_infos.json" in files: with open(dataset_infos_dir / """dataset_infos.json""" , """w""" ) as f: f.write("""{\"default\": {\"dataset_size\": 42}}""" ) _a : Dict = DatasetInfosDict.from_directory(UpperCamelCase__ ) assert dataset_infos assert dataset_infos["default"].dataset_size == 4_2 @pytest.mark.parametrize( """dataset_info""" , [ DatasetInfo(), DatasetInfo( description="""foo""" , features=Features({"""a""": Value("""int32""" )} ) , builder_name="""builder""" , config_name="""config""" , version="""1.0.0""" , splits=[{"""name""": """train"""}] , download_size=4_2 , ), ] , ) def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' _a : Optional[int] = str(UpperCamelCase__ ) dataset_info.write_to_directory(UpperCamelCase__ ) _a : Any = DatasetInfo.from_directory(UpperCamelCase__ ) assert dataset_info == reloaded assert os.path.exists(os.path.join(UpperCamelCase__ , """dataset_info.json""" ) ) def lowerCAmelCase__ ( ): '''simple docstring''' _a : Dict = DatasetInfo( description="""foo""" , citation="""bar""" , homepage="""https://foo.bar""" , license="""CC0""" , features=Features({"""a""": Value("""int32""" )} ) , post_processed={} , supervised_keys=() , task_templates=[] , builder_name="""builder""" , config_name="""config""" , version="""1.0.0""" , splits=[{"""name""": """train""", """num_examples""": 4_2}] , download_checksums={} , download_size=1_3_3_7 , post_processing_size=4_4_2 , dataset_size=1_2_3_4 , size_in_bytes=1_3_3_7 + 4_4_2 + 1_2_3_4 , ) _a : int = dataset_info._to_yaml_dict() assert sorted(UpperCamelCase__ ) == sorted(DatasetInfo._INCLUDED_INFO_IN_YAML ) for key in DatasetInfo._INCLUDED_INFO_IN_YAML: assert key in dataset_info_yaml_dict assert isinstance(dataset_info_yaml_dict[key] , (list, dict, int, str) ) _a : List[str] = yaml.safe_dump(UpperCamelCase__ ) _a : Optional[int] = yaml.safe_load(UpperCamelCase__ ) assert dataset_info_yaml_dict == reloaded def lowerCAmelCase__ ( ): '''simple docstring''' _a : List[Any] = DatasetInfo() _a : Any = dataset_info._to_yaml_dict() assert dataset_info_yaml_dict == {} @pytest.mark.parametrize( """dataset_infos_dict""" , [ DatasetInfosDict(), DatasetInfosDict({"""default""": DatasetInfo()} ), DatasetInfosDict({"""my_config_name""": DatasetInfo()} ), DatasetInfosDict( { """default""": DatasetInfo( description="""foo""" , features=Features({"""a""": Value("""int32""" )} ) , builder_name="""builder""" , config_name="""config""" , version="""1.0.0""" , splits=[{"""name""": """train"""}] , download_size=4_2 , ) } ), DatasetInfosDict( { """v1""": DatasetInfo(dataset_size=4_2 ), """v2""": DatasetInfo(dataset_size=1_3_3_7 ), } ), ] , ) def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' _a : List[Any] = str(UpperCamelCase__ ) dataset_infos_dict.write_to_directory(UpperCamelCase__ ) _a : List[Any] = DatasetInfosDict.from_directory(UpperCamelCase__ ) # the config_name of the dataset_infos_dict take over the attribute for config_name, dataset_info in dataset_infos_dict.items(): _a : str = config_name # the yaml representation doesn't include fields like description or citation # so we just test that we can recover what we can from the yaml _a : Dict = DatasetInfo._from_yaml_dict(dataset_info._to_yaml_dict() ) assert dataset_infos_dict == reloaded if dataset_infos_dict: assert os.path.exists(os.path.join(UpperCamelCase__ , """README.md""" ) )
324
1
"""simple docstring""" import numpy as np from sklearn.datasets import fetch_california_housing from sklearn.metrics import mean_absolute_error, mean_squared_error from sklearn.model_selection import train_test_split from xgboost import XGBRegressor def lowerCAmelCase__ ( UpperCamelCase__ ): '''simple docstring''' return (data["data"], data["target"]) def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' _a : Union[str, Any] = XGBRegressor(verbosity=0 , random_state=4_2 ) xgb.fit(UpperCamelCase__ , UpperCamelCase__ ) # Predict target for test data _a : Union[str, Any] = xgb.predict(UpperCamelCase__ ) _a : Optional[int] = predictions.reshape(len(UpperCamelCase__ ) , 1 ) return predictions def lowerCAmelCase__ ( ): '''simple docstring''' _a : Optional[Any] = fetch_california_housing() _a , _a : List[str] = data_handling(UpperCamelCase__ ) _a , _a , _a , _a : Optional[int] = train_test_split( UpperCamelCase__ , UpperCamelCase__ , test_size=0.25 , random_state=1 ) _a : str = xgboost(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) # Error printing print(F"""Mean Absolute Error : {mean_absolute_error(UpperCamelCase__ , UpperCamelCase__ )}""" ) print(F"""Mean Square Error : {mean_squared_error(UpperCamelCase__ , UpperCamelCase__ )}""" ) if __name__ == "__main__": import doctest doctest.testmod(verbose=True) main()
324
"""simple docstring""" 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 , snake_case_ ): def _lowercase ( self : int ) -> int: _a : Optional[Any] = load_tool("""text-to-speech""" ) self.tool.setup() def _lowercase ( self : List[str] ) -> Union[str, Any]: # SpeechT5 isn't deterministic torch.manual_seed(0 ) _a : str = self.tool("""hey""" ) _a : List[str] = result.to_raw() self.assertTrue( torch.allclose( resulting_tensor[:3] , torch.tensor([-0.0_0_0_5_9_6_6_6_6_8_8_3_2_1_1_5_8_2_9, -0.0_0_0_3_6_5_7_6_4_0_1_9_0_7_9_5_0_6_4, -0.0_0_0_1_3_4_3_9_5_0_2_7_9_9_8_8_3_4_8_5] ) , ) ) def _lowercase ( self : Optional[int] ) -> Optional[Any]: # SpeechT5 isn't deterministic torch.manual_seed(0 ) _a : int = self.tool("""hey""" ) _a : str = result.to_raw() self.assertTrue( torch.allclose( resulting_tensor[:3] , torch.tensor([-0.0_0_0_5_9_6_6_6_6_8_8_3_2_1_1_5_8_2_9, -0.0_0_0_3_6_5_7_6_4_0_1_9_0_7_9_5_0_6_4, -0.0_0_0_1_3_4_3_9_5_0_2_7_9_9_8_8_3_4_8_5] ) , ) )
324
1
"""simple docstring""" _snake_case = 8.31_44_62 # Unit - J mol-1 K-1 def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' if moles < 0 or kelvin < 0 or volume < 0: raise ValueError("""Invalid inputs. Enter positive value.""" ) return moles * kelvin * UNIVERSAL_GAS_CONSTANT / volume def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' if moles < 0 or kelvin < 0 or pressure < 0: raise ValueError("""Invalid inputs. Enter positive value.""" ) return moles * kelvin * UNIVERSAL_GAS_CONSTANT / pressure if __name__ == "__main__": from doctest import testmod testmod()
324
"""simple docstring""" import copy import json import os import tempfile from transformers import is_torch_available from .test_configuration_utils import config_common_kwargs class UpperCamelCase ( snake_case_ ): def __init__( self : Union[str, Any] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : int=None , UpperCAmelCase__ : Optional[Any]=True , UpperCAmelCase__ : List[str]=None , **UpperCAmelCase__ : str ) -> int: _a : str = parent _a : Union[str, Any] = config_class _a : List[Any] = has_text_modality _a : List[Any] = kwargs _a : List[Any] = common_properties def _lowercase ( self : int ) -> Tuple: _a : List[str] = self.config_class(**self.inputs_dict ) _a : Dict = ( ["""hidden_size""", """num_attention_heads""", """num_hidden_layers"""] if self.common_properties is None else self.common_properties ) # Add common fields for text models if self.has_text_modality: common_properties.extend(["""vocab_size"""] ) # Test that config has the common properties as getters for prop in common_properties: self.parent.assertTrue(hasattr(UpperCAmelCase__ , UpperCAmelCase__ ) , msg=f"""`{prop}` does not exist""" ) # Test that config has the common properties as setter for idx, name in enumerate(UpperCAmelCase__ ): try: setattr(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) self.parent.assertEqual( getattr(UpperCAmelCase__ , UpperCAmelCase__ ) , UpperCAmelCase__ , msg=f"""`{name} value {idx} expected, but was {getattr(UpperCAmelCase__ , UpperCAmelCase__ )}""" ) except NotImplementedError: # Some models might not be able to implement setters for common_properties # In that case, a NotImplementedError is raised pass # Test if config class can be called with Config(prop_name=..) for idx, name in enumerate(UpperCAmelCase__ ): try: _a : Optional[int] = self.config_class(**{name: idx} ) self.parent.assertEqual( getattr(UpperCAmelCase__ , UpperCAmelCase__ ) , UpperCAmelCase__ , msg=f"""`{name} value {idx} expected, but was {getattr(UpperCAmelCase__ , UpperCAmelCase__ )}""" ) except NotImplementedError: # Some models might not be able to implement setters for common_properties # In that case, a NotImplementedError is raised pass def _lowercase ( self : Optional[int] ) -> Optional[Any]: _a : Optional[Any] = self.config_class(**self.inputs_dict ) _a : List[str] = json.loads(config.to_json_string() ) for key, value in self.inputs_dict.items(): self.parent.assertEqual(obj[key] , UpperCAmelCase__ ) def _lowercase ( self : int ) -> List[str]: _a : Optional[Any] = self.config_class(**self.inputs_dict ) with tempfile.TemporaryDirectory() as tmpdirname: _a : Tuple = os.path.join(UpperCAmelCase__ , """config.json""" ) config_first.to_json_file(UpperCAmelCase__ ) _a : List[str] = self.config_class.from_json_file(UpperCAmelCase__ ) self.parent.assertEqual(config_second.to_dict() , config_first.to_dict() ) def _lowercase ( self : Union[str, Any] ) -> Dict: _a : Dict = self.config_class(**self.inputs_dict ) with tempfile.TemporaryDirectory() as tmpdirname: config_first.save_pretrained(UpperCAmelCase__ ) _a : Dict = self.config_class.from_pretrained(UpperCAmelCase__ ) self.parent.assertEqual(config_second.to_dict() , config_first.to_dict() ) def _lowercase ( self : Dict ) -> Tuple: _a : List[Any] = self.config_class(**self.inputs_dict ) _a : Any = """test""" with tempfile.TemporaryDirectory() as tmpdirname: _a : List[Any] = os.path.join(UpperCAmelCase__ , UpperCAmelCase__ ) config_first.save_pretrained(UpperCAmelCase__ ) _a : List[Any] = self.config_class.from_pretrained(UpperCAmelCase__ , subfolder=UpperCAmelCase__ ) self.parent.assertEqual(config_second.to_dict() , config_first.to_dict() ) def _lowercase ( self : List[str] ) -> Union[str, Any]: _a : Tuple = self.config_class(**self.inputs_dict , num_labels=5 ) self.parent.assertEqual(len(config.idalabel ) , 5 ) self.parent.assertEqual(len(config.labelaid ) , 5 ) _a : Union[str, Any] = 3 self.parent.assertEqual(len(config.idalabel ) , 3 ) self.parent.assertEqual(len(config.labelaid ) , 3 ) def _lowercase ( self : Tuple ) -> List[str]: if self.config_class.is_composition: return _a : str = self.config_class() self.parent.assertIsNotNone(UpperCAmelCase__ ) def _lowercase ( self : List[Any] ) -> Optional[Any]: _a : Dict = copy.deepcopy(UpperCAmelCase__ ) _a : Any = self.config_class(**UpperCAmelCase__ ) _a : str = [] for key, value in config_common_kwargs.items(): if key == "torch_dtype": if not is_torch_available(): continue else: import torch if config.torch_dtype != torch.floataa: wrong_values.append(("""torch_dtype""", config.torch_dtype, torch.floataa) ) elif getattr(UpperCAmelCase__ , UpperCAmelCase__ ) != value: wrong_values.append((key, getattr(UpperCAmelCase__ , UpperCAmelCase__ ), value) ) if len(UpperCAmelCase__ ) > 0: _a : List[Any] = """\n""".join([f"""- {v[0]}: got {v[1]} instead of {v[2]}""" for v in wrong_values] ) raise ValueError(f"""The following keys were not properly set in the config:\n{errors}""" ) def _lowercase ( self : int ) -> Union[str, Any]: self.create_and_test_config_common_properties() self.create_and_test_config_to_json_string() self.create_and_test_config_to_json_file() self.create_and_test_config_from_and_save_pretrained() self.create_and_test_config_from_and_save_pretrained_subfolder() self.create_and_test_config_with_num_labels() self.check_config_can_be_init_without_params() self.check_config_arguments_init()
324
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_fnet import FNetTokenizer else: _snake_case = None _snake_case = logging.get_logger(__name__) _snake_case = {'vocab_file': 'spiece.model', 'tokenizer_file': 'tokenizer.json'} _snake_case = { 'vocab_file': { 'google/fnet-base': 'https://huggingface.co/google/fnet-base/resolve/main/spiece.model', 'google/fnet-large': 'https://huggingface.co/google/fnet-large/resolve/main/spiece.model', }, 'tokenizer_file': { 'google/fnet-base': 'https://huggingface.co/google/fnet-base/resolve/main/tokenizer.json', 'google/fnet-large': 'https://huggingface.co/google/fnet-large/resolve/main/tokenizer.json', }, } _snake_case = { 'google/fnet-base': 512, 'google/fnet-large': 512, } _snake_case = '▁' class UpperCamelCase ( snake_case_ ): UpperCamelCase : Optional[Any] = VOCAB_FILES_NAMES UpperCamelCase : Optional[int] = PRETRAINED_VOCAB_FILES_MAP UpperCamelCase : Union[str, Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCamelCase : str = ['''input_ids''', '''token_type_ids'''] UpperCamelCase : List[str] = FNetTokenizer def __init__( self : Dict , UpperCAmelCase__ : Optional[Any]=None , UpperCAmelCase__ : Union[str, Any]=None , UpperCAmelCase__ : Optional[int]=False , UpperCAmelCase__ : int=True , UpperCAmelCase__ : List[Any]=True , UpperCAmelCase__ : List[Any]="<unk>" , UpperCAmelCase__ : Optional[Any]="[SEP]" , UpperCAmelCase__ : Optional[Any]="<pad>" , UpperCAmelCase__ : List[Any]="[CLS]" , UpperCAmelCase__ : List[Any]="[MASK]" , **UpperCAmelCase__ : Union[str, Any] , ) -> Optional[Any]: # Mask token behave like a normal word, i.e. include the space before it and # is included in the raw text, there should be a match in a non-normalized sentence. _a : List[Any] = ( AddedToken(UpperCAmelCase__ , lstrip=UpperCAmelCase__ , rstrip=UpperCAmelCase__ , normalized=UpperCAmelCase__ ) if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ) else mask_token ) super().__init__( UpperCAmelCase__ , tokenizer_file=UpperCAmelCase__ , do_lower_case=UpperCAmelCase__ , remove_space=UpperCAmelCase__ , keep_accents=UpperCAmelCase__ , unk_token=UpperCAmelCase__ , sep_token=UpperCAmelCase__ , pad_token=UpperCAmelCase__ , cls_token=UpperCAmelCase__ , mask_token=UpperCAmelCase__ , **UpperCAmelCase__ , ) _a : List[str] = do_lower_case _a : List[Any] = remove_space _a : List[str] = keep_accents _a : List[Any] = vocab_file _a : Optional[Any] = False if not self.vocab_file else True def _lowercase ( self : Any , UpperCAmelCase__ : List[int] , UpperCAmelCase__ : Optional[List[int]] = None ) -> List[int]: _a : int = [self.sep_token_id] _a : Any = [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 _lowercase ( self : Tuple , UpperCAmelCase__ : List[int] , UpperCAmelCase__ : Optional[List[int]] = None ) -> List[int]: _a : Any = [self.sep_token_id] _a : Any = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def _lowercase ( self : List[str] , 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 _a : Any = 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,)
324
"""simple docstring""" import os from huggingface_hub.constants import HUGGINGFACE_HUB_CACHE, hf_cache_home _snake_case = HUGGINGFACE_HUB_CACHE _snake_case = 'config.json' _snake_case = 'diffusion_pytorch_model.bin' _snake_case = 'diffusion_flax_model.msgpack' _snake_case = 'model.onnx' _snake_case = 'diffusion_pytorch_model.safetensors' _snake_case = 'weights.pb' _snake_case = 'https://huggingface.co' _snake_case = default_cache_path _snake_case = 'diffusers_modules' _snake_case = os.getenv('HF_MODULES_CACHE', os.path.join(hf_cache_home, 'modules')) _snake_case = ['fp16', 'non-ema'] _snake_case = '.self_attn'
324
1
"""simple docstring""" from .glue import glue_convert_examples_to_features, glue_output_modes, glue_processors, glue_tasks_num_labels from .squad import SquadExample, SquadFeatures, SquadVaProcessor, SquadVaProcessor, squad_convert_examples_to_features from .utils import DataProcessor, InputExample, InputFeatures, SingleSentenceClassificationProcessor from .xnli import xnli_output_modes, xnli_processors, xnli_tasks_num_labels
324
"""simple docstring""" from math import factorial def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' if successes > trials: raise ValueError("""successes must be lower or equal to trials""" ) if trials < 0 or successes < 0: raise ValueError("""the function is defined for non-negative integers""" ) if not isinstance(UpperCamelCase__ , UpperCamelCase__ ) or not isinstance(UpperCamelCase__ , UpperCamelCase__ ): raise ValueError("""the function is defined for non-negative integers""" ) if not 0 < prob < 1: raise ValueError("""prob has to be in range of 1 - 0""" ) _a : Optional[int] = (prob**successes) * ((1 - prob) ** (trials - successes)) # Calculate the binomial coefficient: n! / k!(n-k)! _a : Optional[int] = float(factorial(UpperCamelCase__ ) ) coefficient /= factorial(UpperCamelCase__ ) * factorial(trials - successes ) return probability * coefficient if __name__ == "__main__": from doctest import testmod testmod() print('Probability of 2 successes out of 4 trails') print('with probability of 0.75 is:', end=' ') print(binomial_distribution(2, 4, 0.75))
324
1
"""simple docstring""" import inspect import unittest from transformers import ViTConfig from transformers.testing_utils import ( require_accelerate, require_torch, require_torch_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, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ViTForImageClassification, ViTForMaskedImageModeling, ViTModel from transformers.models.vit.modeling_vit import VIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class UpperCamelCase : def __init__( self : Dict , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : List[Any]=13 , UpperCAmelCase__ : Dict=30 , UpperCAmelCase__ : List[str]=2 , UpperCAmelCase__ : Dict=3 , UpperCAmelCase__ : Dict=True , UpperCAmelCase__ : Dict=True , UpperCAmelCase__ : Dict=32 , UpperCAmelCase__ : str=5 , UpperCAmelCase__ : Tuple=4 , UpperCAmelCase__ : Tuple=37 , UpperCAmelCase__ : Tuple="gelu" , UpperCAmelCase__ : List[str]=0.1 , UpperCAmelCase__ : List[str]=0.1 , UpperCAmelCase__ : Dict=10 , UpperCAmelCase__ : Tuple=0.0_2 , UpperCAmelCase__ : List[str]=None , UpperCAmelCase__ : int=2 , ) -> Dict: _a : int = parent _a : Optional[Any] = batch_size _a : Tuple = image_size _a : List[str] = patch_size _a : Tuple = num_channels _a : List[str] = is_training _a : List[Any] = use_labels _a : List[Any] = hidden_size _a : int = num_hidden_layers _a : Optional[Any] = num_attention_heads _a : List[str] = intermediate_size _a : Optional[Any] = hidden_act _a : Tuple = hidden_dropout_prob _a : Optional[int] = attention_probs_dropout_prob _a : List[Any] = type_sequence_label_size _a : Dict = initializer_range _a : Optional[int] = scope _a : Dict = encoder_stride # in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) _a : List[Any] = (image_size // patch_size) ** 2 _a : List[Any] = num_patches + 1 def _lowercase ( self : int ) -> Optional[Any]: _a : Optional[Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) _a : Optional[int] = None if self.use_labels: _a : Optional[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) _a : Optional[Any] = self.get_config() return config, pixel_values, labels def _lowercase ( self : List[str] ) -> str: return ViTConfig( 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=UpperCAmelCase__ , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , ) def _lowercase ( self : Optional[int] , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : int , UpperCAmelCase__ : Dict ) -> str: _a : Dict = ViTModel(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() _a : Optional[int] = model(UpperCAmelCase__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _lowercase ( self : Dict , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : str ) -> Tuple: _a : Dict = ViTForMaskedImageModeling(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() _a : Optional[int] = model(UpperCAmelCase__ ) self.parent.assertEqual( result.reconstruction.shape , (self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images _a : List[str] = 1 _a : Optional[Any] = ViTForMaskedImageModeling(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() _a : List[Any] = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) _a : int = model(UpperCAmelCase__ ) self.parent.assertEqual(result.reconstruction.shape , (self.batch_size, 1, self.image_size, self.image_size) ) def _lowercase ( self : str , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Optional[Any] ) -> List[Any]: _a : Union[str, Any] = self.type_sequence_label_size _a : int = ViTForImageClassification(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() _a : int = model(UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images _a : Union[str, Any] = 1 _a : List[str] = ViTForImageClassification(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() _a : int = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) _a : Optional[int] = model(UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def _lowercase ( self : int ) -> Union[str, Any]: _a : Any = self.prepare_config_and_inputs() ( ( _a ) , ( _a ) , ( _a ) , ) : List[Any] = config_and_inputs _a : List[Any] = {"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class UpperCamelCase ( snake_case_ , snake_case_ , unittest.TestCase ): UpperCamelCase : Any = ( ( ViTModel, ViTForImageClassification, ViTForMaskedImageModeling, ) if is_torch_available() else () ) UpperCamelCase : List[str] = ( {'''feature-extraction''': ViTModel, '''image-classification''': ViTForImageClassification} if is_torch_available() else {} ) UpperCamelCase : Dict = True UpperCamelCase : Optional[Any] = False UpperCamelCase : Optional[int] = False UpperCamelCase : Optional[int] = False def _lowercase ( self : Union[str, Any] ) -> Optional[Any]: _a : Optional[Any] = ViTModelTester(self ) _a : int = ConfigTester(self , config_class=UpperCAmelCase__ , has_text_modality=UpperCAmelCase__ , hidden_size=37 ) def _lowercase ( self : Optional[int] ) -> List[str]: self.config_tester.run_common_tests() @unittest.skip(reason="""ViT does not use inputs_embeds""" ) def _lowercase ( self : Tuple ) -> Tuple: pass def _lowercase ( self : Dict ) -> int: _a , _a : List[str] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _a : Optional[Any] = model_class(UpperCAmelCase__ ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) _a : Optional[Any] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(UpperCAmelCase__ , nn.Linear ) ) def _lowercase ( self : Dict ) -> Tuple: _a , _a : Dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _a : List[Any] = model_class(UpperCAmelCase__ ) _a : Any = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic _a : Tuple = [*signature.parameters.keys()] _a : List[Any] = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , UpperCAmelCase__ ) def _lowercase ( self : List[Any] ) -> str: _a : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCAmelCase__ ) def _lowercase ( self : Optional[int] ) -> Dict: _a : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*UpperCAmelCase__ ) def _lowercase ( self : Optional[Any] ) -> List[Any]: _a : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*UpperCAmelCase__ ) @slow def _lowercase ( self : List[Any] ) -> Optional[Any]: for model_name in VIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _a : Optional[Any] = ViTModel.from_pretrained(UpperCAmelCase__ ) self.assertIsNotNone(UpperCAmelCase__ ) def lowerCAmelCase__ ( ): '''simple docstring''' _a : List[Any] = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch @require_vision class UpperCamelCase ( unittest.TestCase ): @cached_property def _lowercase ( self : Union[str, Any] ) -> Union[str, Any]: return ViTImageProcessor.from_pretrained("""google/vit-base-patch16-224""" ) if is_vision_available() else None @slow def _lowercase ( self : Dict ) -> Optional[int]: _a : Tuple = ViTForImageClassification.from_pretrained("""google/vit-base-patch16-224""" ).to(UpperCAmelCase__ ) _a : Union[str, Any] = self.default_image_processor _a : str = prepare_img() _a : Optional[Any] = image_processor(images=UpperCAmelCase__ , return_tensors="""pt""" ).to(UpperCAmelCase__ ) # forward pass with torch.no_grad(): _a : List[str] = model(**UpperCAmelCase__ ) # verify the logits _a : Optional[Any] = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , UpperCAmelCase__ ) _a : str = torch.tensor([-0.2_7_4_4, 0.8_2_1_5, -0.0_8_3_6] ).to(UpperCAmelCase__ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , UpperCAmelCase__ , atol=1E-4 ) ) @slow def _lowercase ( self : Dict ) -> int: # ViT models have an `interpolate_pos_encoding` argument in their forward method, # allowing to interpolate the pre-trained position embeddings in order to use # the model on higher resolutions. The DINO model by Facebook AI leverages this # to visualize self-attention on higher resolution images. _a : Any = ViTModel.from_pretrained("""facebook/dino-vits8""" ).to(UpperCAmelCase__ ) _a : Optional[int] = ViTImageProcessor.from_pretrained("""facebook/dino-vits8""" , size=480 ) _a : str = prepare_img() _a : Dict = image_processor(images=UpperCAmelCase__ , return_tensors="""pt""" ) _a : List[Any] = inputs.pixel_values.to(UpperCAmelCase__ ) # forward pass with torch.no_grad(): _a : Dict = model(UpperCAmelCase__ , interpolate_pos_encoding=UpperCAmelCase__ ) # verify the logits _a : Union[str, Any] = torch.Size((1, 3601, 384) ) self.assertEqual(outputs.last_hidden_state.shape , UpperCAmelCase__ ) _a : Optional[int] = torch.tensor( [[4.2_3_4_0, 4.3_9_0_6, -6.6_6_9_2], [4.5_4_6_3, 1.8_9_2_8, -6.7_2_5_7], [4.4_4_2_9, 0.8_4_9_6, -5.8_5_8_5]] ).to(UpperCAmelCase__ ) self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :3, :3] , UpperCAmelCase__ , atol=1E-4 ) ) @slow @require_accelerate @require_torch_gpu def _lowercase ( self : Dict ) -> Union[str, Any]: _a : List[str] = ViTModel.from_pretrained("""facebook/dino-vits8""" , torch_dtype=torch.floataa , device_map="""auto""" ) _a : str = self.default_image_processor _a : Any = prepare_img() _a : Any = image_processor(images=UpperCAmelCase__ , return_tensors="""pt""" ) _a : List[str] = inputs.pixel_values.to(UpperCAmelCase__ ) # forward pass to make sure inference works in fp16 with torch.no_grad(): _a : List[str] = model(UpperCAmelCase__ )
324
"""simple docstring""" def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' _a , _a : Dict = len(UpperCamelCase__ ), len(grid[0] ) if ( min(UpperCamelCase__ , UpperCamelCase__ ) < 0 or row == row_length or col == col_length or (row, col) in visit or grid[row][col] == 1 ): return 0 if row == row_length - 1 and col == col_length - 1: return 1 visit.add((row, col) ) _a : Any = 0 count += depth_first_search(UpperCamelCase__ , row + 1 , UpperCamelCase__ , UpperCamelCase__ ) count += depth_first_search(UpperCamelCase__ , row - 1 , UpperCamelCase__ , UpperCamelCase__ ) count += depth_first_search(UpperCamelCase__ , UpperCamelCase__ , col + 1 , UpperCamelCase__ ) count += depth_first_search(UpperCamelCase__ , UpperCamelCase__ , col - 1 , UpperCamelCase__ ) visit.remove((row, col) ) return count if __name__ == "__main__": import doctest doctest.testmod()
324
1
"""simple docstring""" def lowerCAmelCase__ ( UpperCamelCase__ ): '''simple docstring''' _a : Union[str, Any] = abs(UpperCamelCase__ ) _a : Tuple = 0 while n > 0: res += n % 1_0 n //= 1_0 return res def lowerCAmelCase__ ( UpperCamelCase__ ): '''simple docstring''' _a : Optional[int] = abs(UpperCamelCase__ ) return n if n < 1_0 else n % 1_0 + sum_of_digits(n // 1_0 ) def lowerCAmelCase__ ( UpperCamelCase__ ): '''simple docstring''' return sum(int(UpperCamelCase__ ) for c in str(abs(UpperCamelCase__ ) ) ) def lowerCAmelCase__ ( ): '''simple docstring''' from collections.abc import Callable from timeit import timeit def benchmark_a_function(UpperCamelCase__ , UpperCamelCase__ ) -> None: _a : Optional[int] = F"""{func.__name__}({value})""" _a : int = timeit(F"""__main__.{call}""" , setup="""import __main__""" ) print(F"""{call:56} = {func(UpperCamelCase__ )} -- {timing:.4f} seconds""" ) for value in (2_6_2_1_4_4, 1_1_2_5_8_9_9_9_0_6_8_4_2_6_2_4, 1_2_6_7_6_5_0_6_0_0_2_2_8_2_2_9_4_0_1_4_9_6_7_0_3_2_0_5_3_7_6): for func in (sum_of_digits, sum_of_digits_recursion, sum_of_digits_compact): benchmark_a_function(UpperCamelCase__ , UpperCamelCase__ ) print() if __name__ == "__main__": import doctest doctest.testmod() benchmark()
324
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) _snake_case = { 'configuration_vision_encoder_decoder': ['VisionEncoderDecoderConfig', 'VisionEncoderDecoderOnnxConfig'] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _snake_case = ['VisionEncoderDecoderModel'] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _snake_case = ['TFVisionEncoderDecoderModel'] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _snake_case = ['FlaxVisionEncoderDecoderModel'] if TYPE_CHECKING: from .configuration_vision_encoder_decoder import VisionEncoderDecoderConfig, VisionEncoderDecoderOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_vision_encoder_decoder import VisionEncoderDecoderModel try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_vision_encoder_decoder import TFVisionEncoderDecoderModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_vision_encoder_decoder import FlaxVisionEncoderDecoderModel else: import sys _snake_case = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
324
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available _snake_case = { 'configuration_conditional_detr': [ 'CONDITIONAL_DETR_PRETRAINED_CONFIG_ARCHIVE_MAP', 'ConditionalDetrConfig', 'ConditionalDetrOnnxConfig', ] } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _snake_case = ['ConditionalDetrFeatureExtractor'] _snake_case = ['ConditionalDetrImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _snake_case = [ 'CONDITIONAL_DETR_PRETRAINED_MODEL_ARCHIVE_LIST', 'ConditionalDetrForObjectDetection', 'ConditionalDetrForSegmentation', 'ConditionalDetrModel', 'ConditionalDetrPreTrainedModel', ] if TYPE_CHECKING: from .configuration_conditional_detr import ( CONDITIONAL_DETR_PRETRAINED_CONFIG_ARCHIVE_MAP, ConditionalDetrConfig, ConditionalDetrOnnxConfig, ) try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_conditional_detr import ConditionalDetrFeatureExtractor from .image_processing_conditional_detr import ConditionalDetrImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_conditional_detr import ( CONDITIONAL_DETR_PRETRAINED_MODEL_ARCHIVE_LIST, ConditionalDetrForObjectDetection, ConditionalDetrForSegmentation, ConditionalDetrModel, ConditionalDetrPreTrainedModel, ) else: import sys _snake_case = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
324
"""simple docstring""" from __future__ import annotations import time _snake_case = list[tuple[int, int]] _snake_case = [ [0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles [0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0], [1, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0], ] _snake_case = [[-1, 0], [0, -1], [1, 0], [0, 1]] # up, left, down, right class UpperCamelCase : def __init__( self : Optional[int] , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : Node | None ) -> List[str]: _a : int = pos_x _a : Union[str, Any] = pos_y _a : Tuple = (pos_y, pos_x) _a : Tuple = goal_x _a : int = goal_y _a : str = parent class UpperCamelCase : def __init__( self : List[Any] , UpperCAmelCase__ : tuple[int, int] , UpperCAmelCase__ : tuple[int, int] ) -> List[str]: _a : List[Any] = Node(start[1] , start[0] , goal[1] , goal[0] , UpperCAmelCase__ ) _a : List[str] = Node(goal[1] , goal[0] , goal[1] , goal[0] , UpperCAmelCase__ ) _a : Optional[int] = [self.start] _a : Tuple = False def _lowercase ( self : str ) -> Path | None: while self.node_queue: _a : Tuple = self.node_queue.pop(0 ) if current_node.pos == self.target.pos: _a : Dict = True return self.retrace_path(UpperCAmelCase__ ) _a : Tuple = self.get_successors(UpperCAmelCase__ ) for node in successors: self.node_queue.append(UpperCAmelCase__ ) if not self.reached: return [self.start.pos] return None def _lowercase ( self : Optional[int] , UpperCAmelCase__ : Node ) -> list[Node]: _a : Optional[Any] = [] for action in delta: _a : str = parent.pos_x + action[1] _a : List[Any] = parent.pos_y + action[0] if not (0 <= pos_x <= len(grid[0] ) - 1 and 0 <= pos_y <= len(UpperCAmelCase__ ) - 1): continue if grid[pos_y][pos_x] != 0: continue successors.append( Node(UpperCAmelCase__ , UpperCAmelCase__ , self.target.pos_y , self.target.pos_x , UpperCAmelCase__ ) ) return successors def _lowercase ( self : List[Any] , UpperCAmelCase__ : Node | None ) -> Path: _a : Dict = node _a : List[str] = [] while current_node is not None: path.append((current_node.pos_y, current_node.pos_x) ) _a : Any = current_node.parent path.reverse() return path class UpperCamelCase : def __init__( self : List[str] , UpperCAmelCase__ : int , UpperCAmelCase__ : List[Any] ) -> Any: _a : Dict = BreadthFirstSearch(UpperCAmelCase__ , UpperCAmelCase__ ) _a : Optional[int] = BreadthFirstSearch(UpperCAmelCase__ , UpperCAmelCase__ ) _a : Dict = False def _lowercase ( self : Any ) -> Path | None: while self.fwd_bfs.node_queue or self.bwd_bfs.node_queue: _a : List[Any] = self.fwd_bfs.node_queue.pop(0 ) _a : Union[str, Any] = self.bwd_bfs.node_queue.pop(0 ) if current_bwd_node.pos == current_fwd_node.pos: _a : Optional[int] = True return self.retrace_bidirectional_path( UpperCAmelCase__ , UpperCAmelCase__ ) _a : List[str] = current_bwd_node _a : int = current_fwd_node _a : Optional[Any] = { self.fwd_bfs: self.fwd_bfs.get_successors(UpperCAmelCase__ ), self.bwd_bfs: self.bwd_bfs.get_successors(UpperCAmelCase__ ), } for bfs in [self.fwd_bfs, self.bwd_bfs]: for node in successors[bfs]: bfs.node_queue.append(UpperCAmelCase__ ) if not self.reached: return [self.fwd_bfs.start.pos] return None def _lowercase ( self : Optional[int] , UpperCAmelCase__ : Node , UpperCAmelCase__ : Node ) -> Path: _a : str = self.fwd_bfs.retrace_path(UpperCAmelCase__ ) _a : List[Any] = self.bwd_bfs.retrace_path(UpperCAmelCase__ ) bwd_path.pop() bwd_path.reverse() _a : Tuple = fwd_path + bwd_path return path if __name__ == "__main__": # all coordinates are given in format [y,x] import doctest doctest.testmod() _snake_case = (0, 0) _snake_case = (len(grid) - 1, len(grid[0]) - 1) for elem in grid: print(elem) _snake_case = time.time() _snake_case = BreadthFirstSearch(init, goal) _snake_case = bfs.search() _snake_case = time.time() - start_bfs_time print('Unidirectional BFS computation time : ', bfs_time) _snake_case = time.time() _snake_case = BidirectionalBreadthFirstSearch(init, goal) _snake_case = bd_bfs.search() _snake_case = time.time() - start_bd_bfs_time print('Bidirectional BFS computation time : ', bd_bfs_time)
324
1