code
stringlengths
82
54.1k
code_codestyle
int64
0
699
style_context
stringlengths
111
35.6k
style_context_codestyle
int64
0
699
label
int64
0
1
import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import BertTokenizer, BertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import AlignProcessor, EfficientNetImageProcessor @require_vision class __lowerCAmelCase ( unittest.TestCase ): def lowerCamelCase (self ) -> Optional[int]: '''simple docstring''' snake_case_ : Tuple = tempfile.mkdtemp() snake_case_ : Union[str, Any] = [ '''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest''', ] snake_case_ : Union[str, Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) ) snake_case_ : List[str] = { '''do_resize''': True, '''size''': 20, '''do_center_crop''': True, '''crop_size''': 18, '''do_normalize''': True, '''image_mean''': [0.48_145_466, 0.4_578_275, 0.40_821_073], '''image_std''': [0.26_862_954, 0.26_130_258, 0.27_577_711], } snake_case_ : Union[str, Any] = os.path.join(self.tmpdirname , __magic_name__ ) with open(self.image_processor_file , '''w''' , encoding='''utf-8''' ) as fp: json.dump(__magic_name__ , __magic_name__ ) def lowerCamelCase (self , **__magic_name__ ) -> Any: '''simple docstring''' return BertTokenizer.from_pretrained(self.tmpdirname , **__magic_name__ ) def lowerCamelCase (self , **__magic_name__ ) -> int: '''simple docstring''' return BertTokenizerFast.from_pretrained(self.tmpdirname , **__magic_name__ ) def lowerCamelCase (self , **__magic_name__ ) -> Tuple: '''simple docstring''' return EfficientNetImageProcessor.from_pretrained(self.tmpdirname , **__magic_name__ ) def lowerCamelCase (self ) -> Any: '''simple docstring''' shutil.rmtree(self.tmpdirname ) def lowerCamelCase (self ) -> Optional[Any]: '''simple docstring''' snake_case_ : List[Any] = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] snake_case_ : Dict = [Image.fromarray(np.moveaxis(__magic_name__ , 0 , -1 ) ) for x in image_inputs] return image_inputs def lowerCamelCase (self ) -> List[str]: '''simple docstring''' snake_case_ : Dict = self.get_tokenizer() snake_case_ : int = self.get_rust_tokenizer() snake_case_ : Tuple = self.get_image_processor() snake_case_ : str = AlignProcessor(tokenizer=__magic_name__ , image_processor=__magic_name__ ) processor_slow.save_pretrained(self.tmpdirname ) snake_case_ : Optional[int] = AlignProcessor.from_pretrained(self.tmpdirname , use_fast=__magic_name__ ) snake_case_ : Optional[Any] = AlignProcessor(tokenizer=__magic_name__ , image_processor=__magic_name__ ) processor_fast.save_pretrained(self.tmpdirname ) snake_case_ : Tuple = AlignProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor_slow.tokenizer.get_vocab() , tokenizer_slow.get_vocab() ) self.assertEqual(processor_fast.tokenizer.get_vocab() , tokenizer_fast.get_vocab() ) self.assertEqual(tokenizer_slow.get_vocab() , tokenizer_fast.get_vocab() ) self.assertIsInstance(processor_slow.tokenizer , __magic_name__ ) self.assertIsInstance(processor_fast.tokenizer , __magic_name__ ) self.assertEqual(processor_slow.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertEqual(processor_fast.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor_slow.image_processor , __magic_name__ ) self.assertIsInstance(processor_fast.image_processor , __magic_name__ ) def lowerCamelCase (self ) -> int: '''simple docstring''' snake_case_ : Any = AlignProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) snake_case_ : int = self.get_tokenizer(bos_token='''(BOS)''' , eos_token='''(EOS)''' ) snake_case_ : List[str] = self.get_image_processor(do_normalize=__magic_name__ , padding_value=1.0 ) snake_case_ : Optional[Any] = AlignProcessor.from_pretrained( self.tmpdirname , bos_token='''(BOS)''' , eos_token='''(EOS)''' , do_normalize=__magic_name__ , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , __magic_name__ ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , __magic_name__ ) def lowerCamelCase (self ) -> Any: '''simple docstring''' snake_case_ : Any = self.get_image_processor() snake_case_ : List[str] = self.get_tokenizer() snake_case_ : Optional[int] = AlignProcessor(tokenizer=__magic_name__ , image_processor=__magic_name__ ) snake_case_ : str = self.prepare_image_inputs() snake_case_ : Optional[int] = image_processor(__magic_name__ , return_tensors='''np''' ) snake_case_ : List[str] = processor(images=__magic_name__ , return_tensors='''np''' ) for key in input_image_proc.keys(): self.assertAlmostEqual(input_image_proc[key].sum() , input_processor[key].sum() , delta=1e-2 ) def lowerCamelCase (self ) -> List[str]: '''simple docstring''' snake_case_ : Tuple = self.get_image_processor() snake_case_ : Optional[Any] = self.get_tokenizer() snake_case_ : Union[str, Any] = AlignProcessor(tokenizer=__magic_name__ , image_processor=__magic_name__ ) snake_case_ : Dict = '''lower newer''' snake_case_ : str = processor(text=__magic_name__ ) snake_case_ : List[str] = tokenizer(__magic_name__ , padding='''max_length''' , max_length=64 ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def lowerCamelCase (self ) -> Optional[int]: '''simple docstring''' snake_case_ : str = self.get_image_processor() snake_case_ : Optional[Any] = self.get_tokenizer() snake_case_ : Union[str, Any] = AlignProcessor(tokenizer=__magic_name__ , image_processor=__magic_name__ ) snake_case_ : List[str] = '''lower newer''' snake_case_ : Optional[int] = self.prepare_image_inputs() snake_case_ : List[Any] = processor(text=__magic_name__ , images=__magic_name__ ) self.assertListEqual(list(inputs.keys() ) , ['''input_ids''', '''token_type_ids''', '''attention_mask''', '''pixel_values'''] ) # test if it raises when no input is passed with pytest.raises(__magic_name__ ): processor() def lowerCamelCase (self ) -> List[str]: '''simple docstring''' snake_case_ : Optional[int] = self.get_image_processor() snake_case_ : Optional[int] = self.get_tokenizer() snake_case_ : Union[str, Any] = AlignProcessor(tokenizer=__magic_name__ , image_processor=__magic_name__ ) snake_case_ : List[Any] = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] snake_case_ : Dict = processor.batch_decode(__magic_name__ ) snake_case_ : Optional[int] = tokenizer.batch_decode(__magic_name__ ) self.assertListEqual(__magic_name__ , __magic_name__ ) def lowerCamelCase (self ) -> str: '''simple docstring''' snake_case_ : Any = self.get_image_processor() snake_case_ : Tuple = self.get_tokenizer() snake_case_ : Optional[Any] = AlignProcessor(tokenizer=__magic_name__ , image_processor=__magic_name__ ) snake_case_ : Optional[int] = '''lower newer''' snake_case_ : Optional[Any] = self.prepare_image_inputs() snake_case_ : List[str] = processor(text=__magic_name__ , images=__magic_name__ ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
60
"""simple docstring""" from collections import OrderedDict from ...utils import logging from .auto_factory import _BaseAutoModelClass, _LazyAutoMapping, auto_class_update from .configuration_auto import CONFIG_MAPPING_NAMES UpperCAmelCase = logging.get_logger(__name__) UpperCAmelCase = OrderedDict( [ # Base model mapping ("""albert""", """FlaxAlbertModel"""), ("""bart""", """FlaxBartModel"""), ("""beit""", """FlaxBeitModel"""), ("""bert""", """FlaxBertModel"""), ("""big_bird""", """FlaxBigBirdModel"""), ("""blenderbot""", """FlaxBlenderbotModel"""), ("""blenderbot-small""", """FlaxBlenderbotSmallModel"""), ("""clip""", """FlaxCLIPModel"""), ("""distilbert""", """FlaxDistilBertModel"""), ("""electra""", """FlaxElectraModel"""), ("""gpt-sw3""", """FlaxGPT2Model"""), ("""gpt2""", """FlaxGPT2Model"""), ("""gpt_neo""", """FlaxGPTNeoModel"""), ("""gptj""", """FlaxGPTJModel"""), ("""longt5""", """FlaxLongT5Model"""), ("""marian""", """FlaxMarianModel"""), ("""mbart""", """FlaxMBartModel"""), ("""mt5""", """FlaxMT5Model"""), ("""opt""", """FlaxOPTModel"""), ("""pegasus""", """FlaxPegasusModel"""), ("""regnet""", """FlaxRegNetModel"""), ("""resnet""", """FlaxResNetModel"""), ("""roberta""", """FlaxRobertaModel"""), ("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormModel"""), ("""roformer""", """FlaxRoFormerModel"""), ("""t5""", """FlaxT5Model"""), ("""vision-text-dual-encoder""", """FlaxVisionTextDualEncoderModel"""), ("""vit""", """FlaxViTModel"""), ("""wav2vec2""", """FlaxWav2Vec2Model"""), ("""whisper""", """FlaxWhisperModel"""), ("""xglm""", """FlaxXGLMModel"""), ("""xlm-roberta""", """FlaxXLMRobertaModel"""), ] ) UpperCAmelCase = OrderedDict( [ # Model for pre-training mapping ("""albert""", """FlaxAlbertForPreTraining"""), ("""bart""", """FlaxBartForConditionalGeneration"""), ("""bert""", """FlaxBertForPreTraining"""), ("""big_bird""", """FlaxBigBirdForPreTraining"""), ("""electra""", """FlaxElectraForPreTraining"""), ("""longt5""", """FlaxLongT5ForConditionalGeneration"""), ("""mbart""", """FlaxMBartForConditionalGeneration"""), ("""mt5""", """FlaxMT5ForConditionalGeneration"""), ("""roberta""", """FlaxRobertaForMaskedLM"""), ("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormForMaskedLM"""), ("""roformer""", """FlaxRoFormerForMaskedLM"""), ("""t5""", """FlaxT5ForConditionalGeneration"""), ("""wav2vec2""", """FlaxWav2Vec2ForPreTraining"""), ("""whisper""", """FlaxWhisperForConditionalGeneration"""), ("""xlm-roberta""", """FlaxXLMRobertaForMaskedLM"""), ] ) UpperCAmelCase = OrderedDict( [ # Model for Masked LM mapping ("""albert""", """FlaxAlbertForMaskedLM"""), ("""bart""", """FlaxBartForConditionalGeneration"""), ("""bert""", """FlaxBertForMaskedLM"""), ("""big_bird""", """FlaxBigBirdForMaskedLM"""), ("""distilbert""", """FlaxDistilBertForMaskedLM"""), ("""electra""", """FlaxElectraForMaskedLM"""), ("""mbart""", """FlaxMBartForConditionalGeneration"""), ("""roberta""", """FlaxRobertaForMaskedLM"""), ("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormForMaskedLM"""), ("""roformer""", """FlaxRoFormerForMaskedLM"""), ("""xlm-roberta""", """FlaxXLMRobertaForMaskedLM"""), ] ) UpperCAmelCase = OrderedDict( [ # Model for Seq2Seq Causal LM mapping ("""bart""", """FlaxBartForConditionalGeneration"""), ("""blenderbot""", """FlaxBlenderbotForConditionalGeneration"""), ("""blenderbot-small""", """FlaxBlenderbotSmallForConditionalGeneration"""), ("""encoder-decoder""", """FlaxEncoderDecoderModel"""), ("""longt5""", """FlaxLongT5ForConditionalGeneration"""), ("""marian""", """FlaxMarianMTModel"""), ("""mbart""", """FlaxMBartForConditionalGeneration"""), ("""mt5""", """FlaxMT5ForConditionalGeneration"""), ("""pegasus""", """FlaxPegasusForConditionalGeneration"""), ("""t5""", """FlaxT5ForConditionalGeneration"""), ] ) UpperCAmelCase = OrderedDict( [ # Model for Image-classsification ("""beit""", """FlaxBeitForImageClassification"""), ("""regnet""", """FlaxRegNetForImageClassification"""), ("""resnet""", """FlaxResNetForImageClassification"""), ("""vit""", """FlaxViTForImageClassification"""), ] ) UpperCAmelCase = OrderedDict( [ ("""vision-encoder-decoder""", """FlaxVisionEncoderDecoderModel"""), ] ) UpperCAmelCase = OrderedDict( [ # Model for Causal LM mapping ("""bart""", """FlaxBartForCausalLM"""), ("""bert""", """FlaxBertForCausalLM"""), ("""big_bird""", """FlaxBigBirdForCausalLM"""), ("""electra""", """FlaxElectraForCausalLM"""), ("""gpt-sw3""", """FlaxGPT2LMHeadModel"""), ("""gpt2""", """FlaxGPT2LMHeadModel"""), ("""gpt_neo""", """FlaxGPTNeoForCausalLM"""), ("""gptj""", """FlaxGPTJForCausalLM"""), ("""opt""", """FlaxOPTForCausalLM"""), ("""roberta""", """FlaxRobertaForCausalLM"""), ("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormForCausalLM"""), ("""xglm""", """FlaxXGLMForCausalLM"""), ("""xlm-roberta""", """FlaxXLMRobertaForCausalLM"""), ] ) UpperCAmelCase = OrderedDict( [ # Model for Sequence Classification mapping ("""albert""", """FlaxAlbertForSequenceClassification"""), ("""bart""", """FlaxBartForSequenceClassification"""), ("""bert""", """FlaxBertForSequenceClassification"""), ("""big_bird""", """FlaxBigBirdForSequenceClassification"""), ("""distilbert""", """FlaxDistilBertForSequenceClassification"""), ("""electra""", """FlaxElectraForSequenceClassification"""), ("""mbart""", """FlaxMBartForSequenceClassification"""), ("""roberta""", """FlaxRobertaForSequenceClassification"""), ("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormForSequenceClassification"""), ("""roformer""", """FlaxRoFormerForSequenceClassification"""), ("""xlm-roberta""", """FlaxXLMRobertaForSequenceClassification"""), ] ) UpperCAmelCase = OrderedDict( [ # Model for Question Answering mapping ("""albert""", """FlaxAlbertForQuestionAnswering"""), ("""bart""", """FlaxBartForQuestionAnswering"""), ("""bert""", """FlaxBertForQuestionAnswering"""), ("""big_bird""", """FlaxBigBirdForQuestionAnswering"""), ("""distilbert""", """FlaxDistilBertForQuestionAnswering"""), ("""electra""", """FlaxElectraForQuestionAnswering"""), ("""mbart""", """FlaxMBartForQuestionAnswering"""), ("""roberta""", """FlaxRobertaForQuestionAnswering"""), ("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormForQuestionAnswering"""), ("""roformer""", """FlaxRoFormerForQuestionAnswering"""), ("""xlm-roberta""", """FlaxXLMRobertaForQuestionAnswering"""), ] ) UpperCAmelCase = OrderedDict( [ # Model for Token Classification mapping ("""albert""", """FlaxAlbertForTokenClassification"""), ("""bert""", """FlaxBertForTokenClassification"""), ("""big_bird""", """FlaxBigBirdForTokenClassification"""), ("""distilbert""", """FlaxDistilBertForTokenClassification"""), ("""electra""", """FlaxElectraForTokenClassification"""), ("""roberta""", """FlaxRobertaForTokenClassification"""), ("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormForTokenClassification"""), ("""roformer""", """FlaxRoFormerForTokenClassification"""), ("""xlm-roberta""", """FlaxXLMRobertaForTokenClassification"""), ] ) UpperCAmelCase = OrderedDict( [ # Model for Multiple Choice mapping ("""albert""", """FlaxAlbertForMultipleChoice"""), ("""bert""", """FlaxBertForMultipleChoice"""), ("""big_bird""", """FlaxBigBirdForMultipleChoice"""), ("""distilbert""", """FlaxDistilBertForMultipleChoice"""), ("""electra""", """FlaxElectraForMultipleChoice"""), ("""roberta""", """FlaxRobertaForMultipleChoice"""), ("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormForMultipleChoice"""), ("""roformer""", """FlaxRoFormerForMultipleChoice"""), ("""xlm-roberta""", """FlaxXLMRobertaForMultipleChoice"""), ] ) UpperCAmelCase = OrderedDict( [ ("""bert""", """FlaxBertForNextSentencePrediction"""), ] ) UpperCAmelCase = OrderedDict( [ ("""speech-encoder-decoder""", """FlaxSpeechEncoderDecoderModel"""), ("""whisper""", """FlaxWhisperForConditionalGeneration"""), ] ) UpperCAmelCase = OrderedDict( [ ("""whisper""", """FlaxWhisperForAudioClassification"""), ] ) UpperCAmelCase = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_MAPPING_NAMES) UpperCAmelCase = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_PRETRAINING_MAPPING_NAMES) UpperCAmelCase = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MASKED_LM_MAPPING_NAMES) UpperCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES ) UpperCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES ) UpperCAmelCase = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES) UpperCAmelCase = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_CAUSAL_LM_MAPPING_NAMES) UpperCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES ) UpperCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES ) UpperCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES ) UpperCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES ) UpperCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING_NAMES ) UpperCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES ) UpperCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES ) class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_MAPPING UpperCAmelCase = auto_class_update(FlaxAutoModel) class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_PRETRAINING_MAPPING UpperCAmelCase = auto_class_update(FlaxAutoModelForPreTraining, head_doc="""pretraining""") class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_CAUSAL_LM_MAPPING UpperCAmelCase = auto_class_update(FlaxAutoModelForCausalLM, head_doc="""causal language modeling""") class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_MASKED_LM_MAPPING UpperCAmelCase = auto_class_update(FlaxAutoModelForMaskedLM, head_doc="""masked language modeling""") class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING UpperCAmelCase = auto_class_update( FlaxAutoModelForSeqaSeqLM, head_doc="""sequence-to-sequence language modeling""", checkpoint_for_example="""t5-base""" ) class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING UpperCAmelCase = auto_class_update( FlaxAutoModelForSequenceClassification, head_doc="""sequence classification""" ) class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING UpperCAmelCase = auto_class_update(FlaxAutoModelForQuestionAnswering, head_doc="""question answering""") class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING UpperCAmelCase = auto_class_update( FlaxAutoModelForTokenClassification, head_doc="""token classification""" ) class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING UpperCAmelCase = auto_class_update(FlaxAutoModelForMultipleChoice, head_doc="""multiple choice""") class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING UpperCAmelCase = auto_class_update( FlaxAutoModelForNextSentencePrediction, head_doc="""next sentence prediction""" ) class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING UpperCAmelCase = auto_class_update( FlaxAutoModelForImageClassification, head_doc="""image classification""" ) class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING UpperCAmelCase = auto_class_update(FlaxAutoModelForVisionaSeq, head_doc="""vision-to-text modeling""") class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING UpperCAmelCase = auto_class_update( FlaxAutoModelForSpeechSeqaSeq, head_doc="""sequence-to-sequence speech-to-text modeling""" )
88
0
import warnings from transformers import AutoTokenizer from transformers.utils import is_torch_available from transformers.utils.generic import ExplicitEnum from ...processing_utils import ProcessorMixin if is_torch_available(): import torch class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = "char" snake_case__ = "bpe" snake_case__ = "wp" UpperCamelCase = (DecodeType.CHARACTER, DecodeType.BPE, DecodeType.WORDPIECE) class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = ["image_processor", "char_tokenizer"] snake_case__ = "ViTImageProcessor" snake_case__ = "MgpstrTokenizer" def __init__( self : Any , SCREAMING_SNAKE_CASE__ : Dict=None , SCREAMING_SNAKE_CASE__ : int=None , **SCREAMING_SNAKE_CASE__ : str ) -> str: lowerCAmelCase__ = None if "feature_extractor" in kwargs: warnings.warn( "The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`" " instead." , SCREAMING_SNAKE_CASE__ , ) lowerCAmelCase__ = kwargs.pop("feature_extractor" ) lowerCAmelCase__ = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError("You need to specify an `image_processor`." ) if tokenizer is None: raise ValueError("You need to specify a `tokenizer`." ) lowerCAmelCase__ = tokenizer lowerCAmelCase__ = AutoTokenizer.from_pretrained("gpt2" ) lowerCAmelCase__ = AutoTokenizer.from_pretrained("bert-base-uncased" ) super().__init__(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def __call__( self : List[str] , SCREAMING_SNAKE_CASE__ : List[str]=None , SCREAMING_SNAKE_CASE__ : Any=None , SCREAMING_SNAKE_CASE__ : Union[str, Any]=None , **SCREAMING_SNAKE_CASE__ : Dict ) -> Dict: if images is None and text is None: raise ValueError("You need to specify either an `images` or `text` input to process." ) if images is not None: lowerCAmelCase__ = self.image_processor(SCREAMING_SNAKE_CASE__ , return_tensors=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) if text is not None: lowerCAmelCase__ = self.char_tokenizer(SCREAMING_SNAKE_CASE__ , return_tensors=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) if text is None: return inputs elif images is None: return encodings else: lowerCAmelCase__ = encodings["input_ids"] return inputs def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : List[str] ) -> Any: lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = sequences lowerCAmelCase__ = char_preds.size(0 ) lowerCAmelCase__ , lowerCAmelCase__ = self._decode_helper(SCREAMING_SNAKE_CASE__ , "char" ) lowerCAmelCase__ , lowerCAmelCase__ = self._decode_helper(SCREAMING_SNAKE_CASE__ , "bpe" ) lowerCAmelCase__ , lowerCAmelCase__ = self._decode_helper(SCREAMING_SNAKE_CASE__ , "wp" ) lowerCAmelCase__ = [] lowerCAmelCase__ = [] for i in range(SCREAMING_SNAKE_CASE__ ): lowerCAmelCase__ = [char_scores[i], bpe_scores[i], wp_scores[i]] lowerCAmelCase__ = [char_strs[i], bpe_strs[i], wp_strs[i]] lowerCAmelCase__ = scores.index(max(SCREAMING_SNAKE_CASE__ ) ) final_strs.append(strs[max_score_index] ) final_scores.append(scores[max_score_index] ) lowerCAmelCase__ = {} lowerCAmelCase__ = final_strs lowerCAmelCase__ = final_scores lowerCAmelCase__ = char_strs lowerCAmelCase__ = bpe_strs lowerCAmelCase__ = wp_strs return out def a ( self : List[Any] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Tuple ) -> str: if format == DecodeType.CHARACTER: lowerCAmelCase__ = self.char_decode lowerCAmelCase__ = 1 lowerCAmelCase__ = "[s]" elif format == DecodeType.BPE: lowerCAmelCase__ = self.bpe_decode lowerCAmelCase__ = 2 lowerCAmelCase__ = "#" elif format == DecodeType.WORDPIECE: lowerCAmelCase__ = self.wp_decode lowerCAmelCase__ = 102 lowerCAmelCase__ = "[SEP]" else: raise ValueError(f'Format {format} is not supported.' ) lowerCAmelCase__ , lowerCAmelCase__ = [], [] lowerCAmelCase__ = pred_logits.size(0 ) lowerCAmelCase__ = pred_logits.size(1 ) lowerCAmelCase__ , lowerCAmelCase__ = pred_logits.topk(1 , dim=-1 , largest=SCREAMING_SNAKE_CASE__ , sorted=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = preds_index.view(-1 , SCREAMING_SNAKE_CASE__ )[:, 1:] lowerCAmelCase__ = decoder(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ , lowerCAmelCase__ = torch.nn.functional.softmax(SCREAMING_SNAKE_CASE__ , dim=2 ).max(dim=2 ) lowerCAmelCase__ = preds_max_prob[:, 1:] for index in range(SCREAMING_SNAKE_CASE__ ): lowerCAmelCase__ = preds_str[index].find(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = preds_str[index][:pred_eos] lowerCAmelCase__ = preds_index[index].cpu().tolist() lowerCAmelCase__ = pred_index.index(SCREAMING_SNAKE_CASE__ ) if eos_token in pred_index else -1 lowerCAmelCase__ = preds_max_prob[index][: pred_eos_index + 1] lowerCAmelCase__ = pred_max_prob.cumprod(dim=0 )[-1] if pred_max_prob.nelement() != 0 else 0.0 dec_strs.append(SCREAMING_SNAKE_CASE__ ) conf_scores.append(SCREAMING_SNAKE_CASE__ ) return dec_strs, conf_scores def a ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Any ) -> Dict: lowerCAmelCase__ = [seq.replace(" " , "" ) for seq in self.char_tokenizer.batch_decode(SCREAMING_SNAKE_CASE__ )] return decode_strs def a ( self : Any , SCREAMING_SNAKE_CASE__ : int ) -> Optional[int]: return self.bpe_tokenizer.batch_decode(SCREAMING_SNAKE_CASE__ ) def a ( self : Tuple , SCREAMING_SNAKE_CASE__ : str ) -> List[Any]: lowerCAmelCase__ = [seq.replace(" " , "" ) for seq in self.wp_tokenizer.batch_decode(SCREAMING_SNAKE_CASE__ )] return decode_strs
61
"""simple docstring""" # limitations under the License. # NOTE: This file is deprecated and will be removed in a future version. # It only exists so that temporarely `from diffusers.pipelines import DiffusionPipeline` works from .pipelines import DiffusionPipeline, ImagePipelineOutput # noqa: F401 from .utils import deprecate deprecate( """pipelines_utils""", """0.22.0""", """Importing `DiffusionPipeline` or `ImagePipelineOutput` from diffusers.pipeline_utils is deprecated. Please import from diffusers.pipelines.pipeline_utils instead.""", standard_warn=False, stacklevel=3, )
88
0
import pyarrow.parquet as pq import pytest from datasets import Audio, Dataset, DatasetDict, Features, NamedSplit, Sequence, Value, config from datasets.features.image import Image from datasets.io.parquet import ParquetDatasetReader, ParquetDatasetWriter, get_writer_batch_size from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases def lowerCamelCase__ ( lowercase , lowercase ): """simple docstring""" assert isinstance(lowercase , lowercase ) assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize("keep_in_memory" , [False, True] ) def lowerCamelCase__ ( lowercase , lowercase , lowercase ): """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = tmp_path / "cache" SCREAMING_SNAKE_CASE : str = {"col_1": "string", "col_2": "int64", "col_3": "float64"} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): SCREAMING_SNAKE_CASE : int = ParquetDatasetReader(lowercase , cache_dir=lowercase , keep_in_memory=lowercase ).read() _check_parquet_dataset(lowercase , lowercase ) @pytest.mark.parametrize( "features" , [ None, {"col_1": "string", "col_2": "int64", "col_3": "float64"}, {"col_1": "string", "col_2": "string", "col_3": "string"}, {"col_1": "int32", "col_2": "int32", "col_3": "int32"}, {"col_1": "float32", "col_2": "float32", "col_3": "float32"}, ] , ) def lowerCamelCase__ ( lowercase , lowercase , lowercase ): """simple docstring""" SCREAMING_SNAKE_CASE : Optional[Any] = tmp_path / "cache" SCREAMING_SNAKE_CASE : int = {"col_1": "string", "col_2": "int64", "col_3": "float64"} SCREAMING_SNAKE_CASE : str = features.copy() if features else default_expected_features SCREAMING_SNAKE_CASE : str = ( Features({feature: Value(lowercase ) for feature, dtype in features.items()} ) if features is not None else None ) SCREAMING_SNAKE_CASE : List[Any] = ParquetDatasetReader(lowercase , features=lowercase , cache_dir=lowercase ).read() _check_parquet_dataset(lowercase , lowercase ) @pytest.mark.parametrize("split" , [None, NamedSplit("train" ), "train", "test"] ) def lowerCamelCase__ ( lowercase , lowercase , lowercase ): """simple docstring""" SCREAMING_SNAKE_CASE : Any = tmp_path / "cache" SCREAMING_SNAKE_CASE : Any = {"col_1": "string", "col_2": "int64", "col_3": "float64"} SCREAMING_SNAKE_CASE : str = ParquetDatasetReader(lowercase , cache_dir=lowercase , split=lowercase ).read() _check_parquet_dataset(lowercase , lowercase ) assert dataset.split == split if split else "train" @pytest.mark.parametrize("path_type" , [str, list] ) def lowerCamelCase__ ( lowercase , lowercase , lowercase ): """simple docstring""" if issubclass(lowercase , lowercase ): SCREAMING_SNAKE_CASE : Union[str, Any] = parquet_path elif issubclass(lowercase , lowercase ): SCREAMING_SNAKE_CASE : Any = [parquet_path] SCREAMING_SNAKE_CASE : str = tmp_path / "cache" SCREAMING_SNAKE_CASE : str = {"col_1": "string", "col_2": "int64", "col_3": "float64"} SCREAMING_SNAKE_CASE : str = ParquetDatasetReader(lowercase , cache_dir=lowercase ).read() _check_parquet_dataset(lowercase , lowercase ) def lowerCamelCase__ ( lowercase , lowercase , lowercase=("train",) ): """simple docstring""" assert isinstance(lowercase , lowercase ) for split in splits: SCREAMING_SNAKE_CASE : Union[str, Any] = dataset_dict[split] assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize("keep_in_memory" , [False, True] ) def lowerCamelCase__ ( lowercase , lowercase , lowercase ): """simple docstring""" SCREAMING_SNAKE_CASE : Optional[int] = tmp_path / "cache" SCREAMING_SNAKE_CASE : str = {"col_1": "string", "col_2": "int64", "col_3": "float64"} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): SCREAMING_SNAKE_CASE : List[Any] = ParquetDatasetReader( {"train": parquet_path} , cache_dir=lowercase , keep_in_memory=lowercase ).read() _check_parquet_datasetdict(lowercase , lowercase ) @pytest.mark.parametrize( "features" , [ None, {"col_1": "string", "col_2": "int64", "col_3": "float64"}, {"col_1": "string", "col_2": "string", "col_3": "string"}, {"col_1": "int32", "col_2": "int32", "col_3": "int32"}, {"col_1": "float32", "col_2": "float32", "col_3": "float32"}, ] , ) def lowerCamelCase__ ( lowercase , lowercase , lowercase ): """simple docstring""" SCREAMING_SNAKE_CASE : int = tmp_path / "cache" SCREAMING_SNAKE_CASE : int = {"col_1": "string", "col_2": "int64", "col_3": "float64"} SCREAMING_SNAKE_CASE : Optional[int] = features.copy() if features else default_expected_features SCREAMING_SNAKE_CASE : Dict = ( Features({feature: Value(lowercase ) for feature, dtype in features.items()} ) if features is not None else None ) SCREAMING_SNAKE_CASE : Tuple = ParquetDatasetReader({"train": parquet_path} , features=lowercase , cache_dir=lowercase ).read() _check_parquet_datasetdict(lowercase , lowercase ) @pytest.mark.parametrize("split" , [None, NamedSplit("train" ), "train", "test"] ) def lowerCamelCase__ ( lowercase , lowercase , lowercase ): """simple docstring""" if split: SCREAMING_SNAKE_CASE : Dict = {split: parquet_path} else: SCREAMING_SNAKE_CASE : Optional[Any] = "train" SCREAMING_SNAKE_CASE : Dict = {"train": parquet_path, "test": parquet_path} SCREAMING_SNAKE_CASE : str = tmp_path / "cache" SCREAMING_SNAKE_CASE : Union[str, Any] = {"col_1": "string", "col_2": "int64", "col_3": "float64"} SCREAMING_SNAKE_CASE : int = ParquetDatasetReader(lowercase , cache_dir=lowercase ).read() _check_parquet_datasetdict(lowercase , lowercase , splits=list(path.keys() ) ) assert all(dataset[split].split == split for split in path.keys() ) def lowerCamelCase__ ( lowercase , lowercase ): """simple docstring""" SCREAMING_SNAKE_CASE : Any = ParquetDatasetWriter(lowercase , tmp_path / "foo.parquet" ) assert writer.write() > 0 SCREAMING_SNAKE_CASE : Optional[int] = pq.ParquetFile(tmp_path / "foo.parquet" ) SCREAMING_SNAKE_CASE : Union[str, Any] = pf.read() assert dataset.data.table == output_table def lowerCamelCase__ ( lowercase , lowercase ): """simple docstring""" SCREAMING_SNAKE_CASE : List[str] = str(shared_datadir / "test_image_rgb.jpg" ) SCREAMING_SNAKE_CASE : Union[str, Any] = {"image": [image_path]} SCREAMING_SNAKE_CASE : Any = Features({"image": Image()} ) SCREAMING_SNAKE_CASE : List[Any] = Dataset.from_dict(lowercase , features=lowercase ) SCREAMING_SNAKE_CASE : Tuple = ParquetDatasetWriter(lowercase , tmp_path / "foo.parquet" ) assert writer.write() > 0 SCREAMING_SNAKE_CASE : Dict = Dataset.from_parquet(str(tmp_path / "foo.parquet" ) ) assert dataset.features == reloaded_dataset.features SCREAMING_SNAKE_CASE : Dict = ParquetDatasetReader(str(tmp_path / "foo.parquet" ) , streaming=lowercase ).read() assert dataset.features == reloaded_iterable_dataset.features @pytest.mark.parametrize( "feature, expected" , [ (Features({"foo": Value("int32" )} ), None), (Features({"image": Image(), "foo": Value("int32" )} ), config.PARQUET_ROW_GROUP_SIZE_FOR_IMAGE_DATASETS), (Features({"nested": Sequence(Audio() )} ), config.PARQUET_ROW_GROUP_SIZE_FOR_AUDIO_DATASETS), ] , ) def lowerCamelCase__ ( lowercase , lowercase ): """simple docstring""" assert get_writer_batch_size(lowercase ) == expected
62
"""simple docstring""" def _snake_case ( __snake_case : list[list[int]] , __snake_case : int , __snake_case : int , __snake_case : list[int] ): """simple docstring""" 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 _snake_case ( __snake_case : list[list[int]] , __snake_case : list[int] , __snake_case : int ): """simple docstring""" if curr_ind == len(__snake_case ): # 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(__snake_case ) ): if valid_connection(__snake_case , __snake_case , __snake_case , __snake_case ): # Insert current vertex into path as next transition _lowerCamelCase : List[str] = next_ver # Validate created path if util_hamilton_cycle(__snake_case , __snake_case , curr_ind + 1 ): return True # Backtrack _lowerCamelCase : Tuple = -1 return False def _snake_case ( __snake_case : list[list[int]] , __snake_case : int = 0 ): """simple docstring""" _lowerCamelCase : Any = [-1] * (len(__snake_case ) + 1) # initialize start and end of path with starting index _lowerCamelCase : Optional[int] = start_index # evaluate and if we find answer return path either return empty array return path if util_hamilton_cycle(__snake_case , __snake_case , 1 ) else []
88
0
from __future__ import annotations import unittest from transformers import is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow if is_tf_available(): import numpy as np import tensorflow as tf from transformers import TFXLMRobertaModel @require_tf @require_sentencepiece @require_tokenizers class a ( unittest.TestCase ): """simple docstring""" @slow def UpperCAmelCase ( self : Union[str, Any] ) -> Optional[int]: __UpperCAmelCase : Tuple = TFXLMRobertaModel.from_pretrained("""jplu/tf-xlm-roberta-base""" ) __UpperCAmelCase : Any = { """input_ids""": tf.convert_to_tensor([[0, 2646, 10269, 83, 99942, 2]] , dtype=tf.intaa ), # "My dog is cute" """attention_mask""": tf.convert_to_tensor([[1, 1, 1, 1, 1, 1]] , dtype=tf.intaa ), } __UpperCAmelCase : str = model(__lowercase )["""last_hidden_state"""] __UpperCAmelCase : int = tf.TensorShape((1, 6, 768) ) self.assertEqual(output.shape , __lowercase ) # compare the actual values for a slice. __UpperCAmelCase : str = tf.convert_to_tensor( [ [ [0.0_681_762, 0.10_894_451, 0.06_772_504], [-0.06_423_668, 0.02_366_615, 0.04_329_344], [-0.06_057_295, 0.09_974_135, -0.00_070_584], ] ] , dtype=tf.floataa , ) self.assertTrue(np.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1e-4 ) )
63
"""simple docstring""" import mpmath # for roots of unity import numpy as np class lowercase__ : def __init__( self , SCREAMING_SNAKE_CASE=None , SCREAMING_SNAKE_CASE=None) -> Tuple: # Input as list _lowerCamelCase : Any = list(poly_a or [0])[:] _lowerCamelCase : Optional[Any] = list(poly_b or [0])[:] # Remove leading zero coefficients while self.polyA[-1] == 0: self.polyA.pop() _lowerCamelCase : int = len(self.polyA) while self.polyB[-1] == 0: self.polyB.pop() _lowerCamelCase : Union[str, Any] = len(self.polyB) # Add 0 to make lengths equal a power of 2 _lowerCamelCase : List[Any] = int( 2 ** np.ceil(np.loga(len(self.polyA) + len(self.polyB) - 1))) while len(self.polyA) < self.c_max_length: self.polyA.append(0) while len(self.polyB) < self.c_max_length: self.polyB.append(0) # A complex root used for the fourier transform _lowerCamelCase : Optional[Any] = complex(mpmath.root(x=1 , n=self.c_max_length , k=1)) # The product _lowerCamelCase : int = self.__multiply() def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE) -> List[str]: _lowerCamelCase : Dict = [[x] for x in self.polyA] if which == """A""" else [[x] for x in self.polyB] # Corner case if len(SCREAMING_SNAKE_CASE) <= 1: return dft[0] # _lowerCamelCase : str = self.c_max_length // 2 while next_ncol > 0: _lowerCamelCase : Dict = [[] for i in range(SCREAMING_SNAKE_CASE)] _lowerCamelCase : Tuple = self.root**next_ncol # First half of next step _lowerCamelCase : int = 1 for j in range(self.c_max_length // (next_ncol * 2)): for i in range(SCREAMING_SNAKE_CASE): new_dft[i].append(dft[i][j] + current_root * dft[i + next_ncol][j]) current_root *= root # Second half of next step _lowerCamelCase : Optional[int] = 1 for j in range(self.c_max_length // (next_ncol * 2)): for i in range(SCREAMING_SNAKE_CASE): new_dft[i].append(dft[i][j] - current_root * dft[i + next_ncol][j]) current_root *= root # Update _lowerCamelCase : Union[str, Any] = new_dft _lowerCamelCase : List[str] = next_ncol // 2 return dft[0] def UpperCamelCase_ ( self) -> str: _lowerCamelCase : Optional[Any] = self.__dft("""A""") _lowerCamelCase : List[str] = self.__dft("""B""") _lowerCamelCase : List[Any] = [[dft_a[i] * dft_b[i] for i in range(self.c_max_length)]] del dft_a del dft_b # Corner Case if len(inverce_c[0]) <= 1: return inverce_c[0] # Inverse DFT _lowerCamelCase : List[str] = 2 while next_ncol <= self.c_max_length: _lowerCamelCase : Any = [[] for i in range(SCREAMING_SNAKE_CASE)] _lowerCamelCase : List[Any] = self.root ** (next_ncol // 2) _lowerCamelCase : str = 1 # First half of next step for j in range(self.c_max_length // next_ncol): for i in range(next_ncol // 2): # Even positions new_inverse_c[i].append( ( inverce_c[i][j] + inverce_c[i][j + self.c_max_length // next_ncol] ) / 2) # Odd positions new_inverse_c[i + next_ncol // 2].append( ( inverce_c[i][j] - inverce_c[i][j + self.c_max_length // next_ncol] ) / (2 * current_root)) current_root *= root # Update _lowerCamelCase : Any = new_inverse_c next_ncol *= 2 # Unpack _lowerCamelCase : Optional[Any] = [round(x[0].real , 8) + round(x[0].imag , 8) * 1j for x in inverce_c] # Remove leading 0's while inverce_c[-1] == 0: inverce_c.pop() return inverce_c def __str__( self) -> Any: _lowerCamelCase : Dict = """A = """ + """ + """.join( F'{coef}*x^{i}' for coef, i in enumerate(self.polyA[: self.len_A])) _lowerCamelCase : List[Any] = """B = """ + """ + """.join( F'{coef}*x^{i}' for coef, i in enumerate(self.polyB[: self.len_B])) _lowerCamelCase : int = """A*B = """ + """ + """.join( F'{coef}*x^{i}' for coef, i in enumerate(self.product)) return F'{a}\n{b}\n{c}' # Unit tests if __name__ == "__main__": import doctest doctest.testmod()
88
0
import pickle import shutil import tempfile import unittest from transformers import SPIECE_UNDERLINE, XGLMTokenizer, XGLMTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin lowercase_ : Dict = get_tests_dir('fixtures/test_sentencepiece.model') @require_sentencepiece @require_tokenizers class _lowerCamelCase ( UpperCamelCase_ , unittest.TestCase ): __a = XGLMTokenizer __a = XGLMTokenizerFast __a = True __a = True def UpperCamelCase_ ( self ) -> Dict: super().setUp() # We have a SentencePiece fixture for testing SCREAMING_SNAKE_CASE__: Union[str, Any]= XGLMTokenizer(lowerCAmelCase , keep_accents=lowerCAmelCase ) tokenizer.save_pretrained(self.tmpdirname ) def UpperCamelCase_ ( self ) -> Dict: SCREAMING_SNAKE_CASE__: Tuple= '''<pad>''' SCREAMING_SNAKE_CASE__: Union[str, Any]= 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(lowerCAmelCase ) , lowerCAmelCase ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(lowerCAmelCase ) , lowerCAmelCase ) def UpperCamelCase_ ( self ) -> Optional[Any]: SCREAMING_SNAKE_CASE__: List[Any]= list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '''<s>''' ) self.assertEqual(vocab_keys[1] , '''<pad>''' ) self.assertEqual(len(lowerCAmelCase ) , 1008 ) def UpperCamelCase_ ( self ) -> Dict: self.assertEqual(self.get_tokenizer().vocab_size , 1008 ) def UpperCamelCase_ ( self ) -> List[str]: SCREAMING_SNAKE_CASE__: Optional[int]= XGLMTokenizer(lowerCAmelCase , keep_accents=lowerCAmelCase ) SCREAMING_SNAKE_CASE__: Dict= tokenizer.tokenize('''This is a test''' ) self.assertListEqual(lowerCAmelCase , ['''▁This''', '''▁is''', '''▁a''', '''▁t''', '''est'''] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(lowerCAmelCase ) , [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]] , ) SCREAMING_SNAKE_CASE__: int= tokenizer.tokenize('''I was born in 92000, and this is falsé.''' ) self.assertListEqual( lowerCAmelCase , [ 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''', '''é''', '''.''', ] , ) SCREAMING_SNAKE_CASE__: str= tokenizer.convert_tokens_to_ids(lowerCAmelCase ) self.assertListEqual( lowerCAmelCase , [ 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] ] , ) SCREAMING_SNAKE_CASE__: Union[str, Any]= tokenizer.convert_ids_to_tokens(lowerCAmelCase ) self.assertListEqual( lowerCAmelCase , [ 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 UpperCamelCase_ ( self ) -> Union[str, Any]: return XGLMTokenizer.from_pretrained('''facebook/xglm-564M''' ) def UpperCamelCase_ ( self ) -> List[Any]: with tempfile.NamedTemporaryFile() as f: shutil.copyfile(lowerCAmelCase , f.name ) SCREAMING_SNAKE_CASE__: str= XGLMTokenizer(f.name , keep_accents=lowerCAmelCase ) SCREAMING_SNAKE_CASE__: Dict= pickle.dumps(lowerCAmelCase ) pickle.loads(lowerCAmelCase ) def UpperCamelCase_ ( self ) -> Optional[Any]: if not self.test_rust_tokenizer: return SCREAMING_SNAKE_CASE__: List[Any]= self.get_tokenizer() SCREAMING_SNAKE_CASE__: List[Any]= self.get_rust_tokenizer() SCREAMING_SNAKE_CASE__: List[str]= '''I was born in 92000, and this is falsé.''' SCREAMING_SNAKE_CASE__: Tuple= tokenizer.tokenize(lowerCAmelCase ) SCREAMING_SNAKE_CASE__: Tuple= rust_tokenizer.tokenize(lowerCAmelCase ) self.assertListEqual(lowerCAmelCase , lowerCAmelCase ) SCREAMING_SNAKE_CASE__: List[Any]= tokenizer.encode(lowerCAmelCase , add_special_tokens=lowerCAmelCase ) SCREAMING_SNAKE_CASE__: int= rust_tokenizer.encode(lowerCAmelCase , add_special_tokens=lowerCAmelCase ) self.assertListEqual(lowerCAmelCase , lowerCAmelCase ) SCREAMING_SNAKE_CASE__: str= self.get_rust_tokenizer() SCREAMING_SNAKE_CASE__: int= tokenizer.encode(lowerCAmelCase ) SCREAMING_SNAKE_CASE__: List[str]= rust_tokenizer.encode(lowerCAmelCase ) self.assertListEqual(lowerCAmelCase , lowerCAmelCase ) @slow def UpperCamelCase_ ( self ) -> Optional[Any]: SCREAMING_SNAKE_CASE__: Tuple= '''Hello World!''' SCREAMING_SNAKE_CASE__: Optional[int]= [2, 31227, 4447, 35] self.assertListEqual(lowerCAmelCase , self.big_tokenizer.encode(lowerCAmelCase ) ) @slow def UpperCamelCase_ ( self ) -> int: SCREAMING_SNAKE_CASE__: List[Any]= ( '''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''' ) # fmt: off SCREAMING_SNAKE_CASE__: Dict= [2, 1018, 67, 11, 1988, 2617, 5631, 278, 11, 3407, 48, 71630, 28085, 4, 3234, 157, 13, 6, 5, 6, 4, 3526, 768, 15, 659, 57, 298, 3983, 864, 129, 21, 6, 5, 13675, 377, 652, 7580, 10341, 155, 2817, 422, 1666, 7, 1674, 53, 113, 202277, 17892, 33, 60, 87, 4, 3234, 157, 61, 2667, 52376, 19, 88, 23, 735] # fmt: on self.assertListEqual(lowerCAmelCase , self.big_tokenizer.encode(lowerCAmelCase ) ) @slow def UpperCamelCase_ ( self ) -> str: # fmt: off SCREAMING_SNAKE_CASE__: Any= { '''input_ids''': [[2, 108825, 1163, 15, 88010, 473, 15898, 157, 13672, 1857, 312, 8, 238021, 1163, 53, 13672, 1857, 312, 8, 53283, 182396, 8, 18566, 16, 36733, 4101, 8, 230, 244017, 122553, 7, 15, 132597, 4, 293, 12511, 7610, 4, 3414, 132597, 9, 4, 32361, 362, 4, 734, 28512, 32569, 18, 4, 32361, 26096, 14982, 73, 18715, 21433, 235261, 15, 492, 12427, 16, 53, 18715, 21433, 65454, 15, 23659, 563, 16, 278, 597, 2843, 595, 7931, 182396, 64186, 22, 886, 595, 132981, 53, 25540, 3449, 43982, 39901, 5951, 878, 330, 4, 27694, 80269, 312, 53, 6517, 11780, 611, 20408, 5], [2, 6, 132597, 67, 42897, 33, 592, 8, 163729, 25540, 361, 136997, 109514, 173230, 7, 501, 60, 102913, 196, 5631, 235, 63243, 473, 6, 231757, 74, 5277, 7905, 53, 3095, 37317, 22, 454, 183874, 5], [2, 268, 31298, 46530, 6, 132935, 43831, 7, 597, 32, 24, 3688, 9865, 5]], '''attention_mask''': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] } # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=lowerCAmelCase , model_name='''facebook/xglm-564M''' , padding=lowerCAmelCase , )
64
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) UpperCAmelCase = { """configuration_vision_encoder_decoder""": ["""VisionEncoderDecoderConfig""", """VisionEncoderDecoderOnnxConfig"""] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase = ["""VisionEncoderDecoderModel"""] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase = ["""TFVisionEncoderDecoderModel"""] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase = ["""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 UpperCAmelCase = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
88
0
"""simple docstring""" import math class __lowercase : def __lowercase ( self : Any ,A : list[list[float]] ,A : list[int] ): '''simple docstring''' UpperCAmelCase__ : List[Any] = 0.0 UpperCAmelCase__ : Any = 0.0 for i in range(len(A ) ): da += math.pow((sample[i] - weights[0][i]) ,2 ) da += math.pow((sample[i] - weights[1][i]) ,2 ) return 0 if da > da else 1 return 0 def __lowercase ( self : Union[str, Any] ,A : list[list[int | float]] ,A : list[int] ,A : int ,A : float ): '''simple docstring''' for i in range(len(A ) ): weights[j][i] += alpha * (sample[i] - weights[j][i]) return weights def lowerCAmelCase ( ): '''simple docstring''' UpperCAmelCase__ : int = [[1, 1, 0, 0], [0, 0, 0, 1], [1, 0, 0, 0], [0, 0, 1, 1]] # weight initialization ( n, C ) UpperCAmelCase__ : Union[str, Any] = [[0.2, 0.6, 0.5, 0.9], [0.8, 0.4, 0.7, 0.3]] # training UpperCAmelCase__ : int = SelfOrganizingMap() UpperCAmelCase__ : Any = 3 UpperCAmelCase__ : Optional[int] = 0.5 for _ in range(__UpperCamelCase ): for j in range(len(__UpperCamelCase ) ): # training sample UpperCAmelCase__ : int = training_samples[j] # Compute the winning vector UpperCAmelCase__ : List[str] = self_organizing_map.get_winner(__UpperCamelCase , __UpperCamelCase ) # Update the winning vector UpperCAmelCase__ : Optional[Any] = self_organizing_map.update(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ) # classify test sample UpperCAmelCase__ : List[str] = [0, 0, 0, 1] UpperCAmelCase__ : Optional[int] = self_organizing_map.get_winner(__UpperCamelCase , __UpperCamelCase ) # results print(F"Clusters that the test sample belongs to : {winner}" ) print(F"Weights that have been trained : {weights}" ) # running the main() function if __name__ == "__main__": main()
65
"""simple docstring""" from datetime import datetime import matplotlib.pyplot as plt import torch def _snake_case ( __snake_case : List[str] ): """simple docstring""" for param in module.parameters(): _lowerCamelCase : Optional[Any] = False def _snake_case ( ): """simple docstring""" _lowerCamelCase : Any = """cuda""" if torch.cuda.is_available() else """cpu""" if torch.backends.mps.is_available() and torch.backends.mps.is_built(): _lowerCamelCase : Any = """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 _snake_case ( __snake_case : Union[str, Any] ): """simple docstring""" _lowerCamelCase : int = plt.imshow(__snake_case ) fig.axes.get_xaxis().set_visible(__snake_case ) fig.axes.get_yaxis().set_visible(__snake_case ) plt.show() def _snake_case ( ): """simple docstring""" _lowerCamelCase : Tuple = datetime.now() _lowerCamelCase : Optional[Any] = current_time.strftime("""%H:%M:%S""" ) return timestamp
88
0
from pathlib import PurePosixPath from typing import Optional import fsspec from fsspec import AbstractFileSystem from huggingface_hub.hf_api import DatasetInfo from ..utils.file_utils import get_authentication_headers_for_url from ..utils.hub import hf_hub_url class lowerCAmelCase_ ( __snake_case ): _UpperCamelCase : Union[str, Any] = "" _UpperCamelCase : List[str] = "hf-legacy" # "hf://"" is reserved for hffs def __init__( self , _lowerCAmelCase = None , _lowerCAmelCase = None , **_lowerCAmelCase , ): super().__init__(self , **_lowerCAmelCase ) _lowercase : Union[str, Any] = repo_info _lowercase : Tuple = token _lowercase : Optional[Any] = None def __a ( self ): if self.dir_cache is None: _lowercase : Dict = {} for hf_file in self.repo_info.siblings: # TODO(QL): add sizes _lowercase : str = { 'name': hf_file.rfilename, 'size': None, 'type': 'file', } self.dir_cache.update( { str(_lowerCAmelCase ): {'name': str(_lowerCAmelCase ), 'size': None, 'type': 'directory'} for d in list(PurePosixPath(hf_file.rfilename ).parents )[:-1] } ) def __a ( self , _lowerCAmelCase , _lowerCAmelCase = "rb" , **_lowerCAmelCase , ): if not isinstance(self.repo_info , _lowerCAmelCase ): raise NotImplementedError(F"""Open is only implemented for dataset repositories, but got {self.repo_info}""" ) _lowercase : Tuple = hf_hub_url(self.repo_info.id , _lowerCAmelCase , revision=self.repo_info.sha ) return fsspec.open( _lowerCAmelCase , mode=_lowerCAmelCase , headers=get_authentication_headers_for_url(_lowerCAmelCase , use_auth_token=self.token ) , client_kwargs={'trust_env': True} , ).open() def __a ( self , _lowerCAmelCase , **_lowerCAmelCase ): self._get_dirs() _lowercase : Union[str, Any] = self._strip_protocol(_lowerCAmelCase ) if path in self.dir_cache: return self.dir_cache[path] else: raise FileNotFoundError(_lowerCAmelCase ) def __a ( self , _lowerCAmelCase , _lowerCAmelCase=False , **_lowerCAmelCase ): self._get_dirs() _lowercase : List[Any] = PurePosixPath(path.strip('/' ) ) _lowercase : Optional[Any] = {} for p, f in self.dir_cache.items(): _lowercase : Any = PurePosixPath(p.strip('/' ) ) _lowercase : Tuple = p.parent if root == path: _lowercase : int = f _lowercase : Tuple = list(paths.values() ) if detail: return out else: return sorted(f['name'] for f in out )
66
"""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 UpperCAmelCase = 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 lowercase__ : __UpperCAmelCase = field( default='''cifar10''' ,metadata={'''help''': '''Name of a dataset from the datasets package'''} ) __UpperCAmelCase = field( default=A_ ,metadata={'''help''': '''The configuration name of the dataset to use (via the datasets library).'''} ) __UpperCAmelCase = field( default=A_ ,metadata={'''help''': '''The column name of the images in the files.'''} ) __UpperCAmelCase = field(default=A_ ,metadata={'''help''': '''A folder containing the training data.'''} ) __UpperCAmelCase = field(default=A_ ,metadata={'''help''': '''A folder containing the validation data.'''} ) __UpperCAmelCase = field( default=0.1_5 ,metadata={'''help''': '''Percent to split off of train for validation.'''} ) __UpperCAmelCase = field( default=A_ ,metadata={ '''help''': ( '''For debugging purposes or quicker training, truncate the number of training examples to this ''' '''value if set.''' ) } ,) __UpperCAmelCase = field( default=A_ ,metadata={ '''help''': ( '''For debugging purposes or quicker training, truncate the number of evaluation examples to this ''' '''value if set.''' ) } ,) def UpperCamelCase_ ( self) -> Any: _lowerCamelCase : Any = {} if self.train_dir is not None: _lowerCamelCase : int = self.train_dir if self.validation_dir is not None: _lowerCamelCase : Tuple = self.validation_dir _lowerCamelCase : Optional[int] = data_files if data_files else None @dataclass class lowercase__ : __UpperCAmelCase = field( default=A_ ,metadata={ '''help''': ( '''The model checkpoint for weights initialization.Don\'t set if you want to train a model from scratch.''' ) } ,) __UpperCAmelCase = field( default=A_ ,metadata={'''help''': '''Pretrained config name or path if not the same as model_name_or_path'''} ) __UpperCAmelCase = field( default=A_ ,metadata={ '''help''': ( '''Override some existing default config settings when a model is trained from scratch. Example: ''' '''n_embd=10,resid_pdrop=0.2,scale_attn_weights=false,summary_type=cls_index''' ) } ,) __UpperCAmelCase = field( default=A_ ,metadata={'''help''': '''Where do you want to store the pretrained models downloaded from s3'''} ) __UpperCAmelCase = field( default='''main''' ,metadata={'''help''': '''The specific model version to use (can be a branch name, tag name or commit id).'''} ,) __UpperCAmelCase = field(default=A_ ,metadata={'''help''': '''Name or path of preprocessor config.'''} ) __UpperCAmelCase = field( default=A_ ,metadata={ '''help''': ( '''Will use the token generated when running `huggingface-cli login` (necessary to use this script ''' '''with private models).''' ) } ,) __UpperCAmelCase = field( default=0.7_5 ,metadata={'''help''': '''The ratio of the number of masked tokens in the input sequence.'''} ) __UpperCAmelCase = field( default=A_ ,metadata={'''help''': '''Whether or not to train with normalized pixel values as target.'''} ) @dataclass class lowercase__ ( A_ ): __UpperCAmelCase = field( default=1e-3 ,metadata={'''help''': '''Base learning rate: absolute_lr = base_lr * total_batch_size / 256.'''} ) def _snake_case ( __snake_case : Optional[Any] ): """simple docstring""" _lowerCamelCase : int = torch.stack([example["""pixel_values"""] for example in examples] ) return {"pixel_values": pixel_values} def _snake_case ( ): """simple docstring""" _lowerCamelCase : Tuple = 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. _lowerCamelCase , _lowerCamelCase , _lowerCamelCase : Union[str, Any] = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: _lowerCamelCase , _lowerCamelCase , _lowerCamelCase : Dict = 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""" , __snake_case , __snake_case ) # Setup logging logging.basicConfig( format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""" , datefmt="""%m/%d/%Y %H:%M:%S""" , handlers=[logging.StreamHandler(sys.stdout )] , ) if training_args.should_log: # The default of training_args.log_level is passive, so we set log level at info here to have that default. transformers.utils.logging.set_verbosity_info() _lowerCamelCase : Union[str, Any] = training_args.get_process_log_level() logger.setLevel(__snake_case ) transformers.utils.logging.set_verbosity(__snake_case ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Log on each process the small summary: logger.warning( F'Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}' + F'distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}' ) logger.info(F'Training/evaluation parameters {training_args}' ) # Detecting last checkpoint. _lowerCamelCase : List[Any] = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: _lowerCamelCase : Optional[int] = 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. _lowerCamelCase : Optional[Any] = 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. _lowerCamelCase : Tuple = None if """validation""" in ds.keys() else data_args.train_val_split if isinstance(data_args.train_val_split , __snake_case ) and data_args.train_val_split > 0.0: _lowerCamelCase : List[str] = ds["""train"""].train_test_split(data_args.train_val_split ) _lowerCamelCase : Union[str, Any] = split["""train"""] _lowerCamelCase : Optional[int] = 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. _lowerCamelCase : 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: _lowerCamelCase : Dict = ViTMAEConfig.from_pretrained(model_args.config_name , **__snake_case ) elif model_args.model_name_or_path: _lowerCamelCase : Union[str, Any] = ViTMAEConfig.from_pretrained(model_args.model_name_or_path , **__snake_case ) else: _lowerCamelCase : Optional[Any] = 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: _lowerCamelCase : str = ViTImageProcessor.from_pretrained(model_args.image_processor_name , **__snake_case ) elif model_args.model_name_or_path: _lowerCamelCase : Dict = ViTImageProcessor.from_pretrained(model_args.model_name_or_path , **__snake_case ) else: _lowerCamelCase : Union[str, Any] = ViTImageProcessor() # create model if model_args.model_name_or_path: _lowerCamelCase : List[Any] = ViTMAEForPreTraining.from_pretrained( model_args.model_name_or_path , from_tf=bool(""".ckpt""" in model_args.model_name_or_path ) , config=__snake_case , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) else: logger.info("""Training new model from scratch""" ) _lowerCamelCase : Union[str, Any] = ViTMAEForPreTraining(__snake_case ) if training_args.do_train: _lowerCamelCase : List[Any] = ds["""train"""].column_names else: _lowerCamelCase : Union[str, Any] = ds["""validation"""].column_names if data_args.image_column_name is not None: _lowerCamelCase : str = data_args.image_column_name elif "image" in column_names: _lowerCamelCase : Optional[Any] = """image""" elif "img" in column_names: _lowerCamelCase : List[Any] = """img""" else: _lowerCamelCase : str = 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: _lowerCamelCase : Dict = image_processor.size["""shortest_edge"""] else: _lowerCamelCase : List[Any] = (image_processor.size["""height"""], image_processor.size["""width"""]) _lowerCamelCase : Tuple = Compose( [ Lambda(lambda __snake_case : img.convert("""RGB""" ) if img.mode != "RGB" else img ), RandomResizedCrop(__snake_case , scale=(0.2, 1.0) , interpolation=InterpolationMode.BICUBIC ), RandomHorizontalFlip(), ToTensor(), Normalize(mean=image_processor.image_mean , std=image_processor.image_std ), ] ) def preprocess_images(__snake_case : Optional[Any] ): _lowerCamelCase : Dict = [transforms(__snake_case ) 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: _lowerCamelCase : int = ds["""train"""].shuffle(seed=training_args.seed ).select(range(data_args.max_train_samples ) ) # Set the training transforms ds["train"].set_transform(__snake_case ) 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: _lowerCamelCase : Union[str, Any] = ( ds["""validation"""].shuffle(seed=training_args.seed ).select(range(data_args.max_eval_samples ) ) ) # Set the validation transforms ds["validation"].set_transform(__snake_case ) # Compute absolute learning rate _lowerCamelCase : Optional[Any] = ( training_args.train_batch_size * training_args.gradient_accumulation_steps * training_args.world_size ) if training_args.base_learning_rate is not None: _lowerCamelCase : Tuple = training_args.base_learning_rate * total_train_batch_size / 256 # Initialize our trainer _lowerCamelCase : Optional[Any] = Trainer( model=__snake_case , args=__snake_case , train_dataset=ds["""train"""] if training_args.do_train else None , eval_dataset=ds["""validation"""] if training_args.do_eval else None , tokenizer=__snake_case , data_collator=__snake_case , ) # Training if training_args.do_train: _lowerCamelCase : Any = None if training_args.resume_from_checkpoint is not None: _lowerCamelCase : List[Any] = training_args.resume_from_checkpoint elif last_checkpoint is not None: _lowerCamelCase : Union[str, Any] = last_checkpoint _lowerCamelCase : Optional[Any] = trainer.train(resume_from_checkpoint=__snake_case ) trainer.save_model() trainer.log_metrics("""train""" , train_result.metrics ) trainer.save_metrics("""train""" , train_result.metrics ) trainer.save_state() # Evaluation if training_args.do_eval: _lowerCamelCase : int = trainer.evaluate() trainer.log_metrics("""eval""" , __snake_case ) trainer.save_metrics("""eval""" , __snake_case ) # Write model card and (optionally) push to hub _lowerCamelCase : Optional[Any] = { """tasks""": """masked-auto-encoding""", """dataset""": data_args.dataset_name, """tags""": ["""masked-auto-encoding"""], } if training_args.push_to_hub: trainer.push_to_hub(**__snake_case ) else: trainer.create_model_card(**__snake_case ) def _snake_case ( __snake_case : Dict ): """simple docstring""" main() if __name__ == "__main__": main()
88
0
def SCREAMING_SNAKE_CASE__ ( snake_case__ :list , snake_case__ :list ) -> float: _validate_point(snake_case__ ) _validate_point(snake_case__ ) if len(snake_case__ ) != len(snake_case__ ): raise ValueError('Both points must be in the same n-dimensional space' ) return float(sum(abs(a - b ) for a, b in zip(snake_case__ , snake_case__ ) ) ) def SCREAMING_SNAKE_CASE__ ( snake_case__ :list[float] ) -> None: if point: if isinstance(snake_case__ , snake_case__ ): for item in point: if not isinstance(snake_case__ , (int, float) ): _lowercase = ( 'Expected a list of numbers as input, found ' F"""{type(snake_case__ ).__name__}""" ) raise TypeError(snake_case__ ) else: _lowercase = F"""Expected a list of numbers as input, found {type(snake_case__ ).__name__}""" raise TypeError(snake_case__ ) else: raise ValueError('Missing an input' ) def SCREAMING_SNAKE_CASE__ ( snake_case__ :list , snake_case__ :list ) -> float: _validate_point(snake_case__ ) _validate_point(snake_case__ ) if len(snake_case__ ) != len(snake_case__ ): raise ValueError('Both points must be in the same n-dimensional space' ) return float(sum(abs(x - y ) for x, y in zip(snake_case__ , snake_case__ ) ) ) if __name__ == "__main__": import doctest doctest.testmod()
67
"""simple docstring""" import numpy as np def _snake_case ( __snake_case : np.ndarray ): """simple docstring""" return 1 / (1 + np.exp(-vector )) def _snake_case ( __snake_case : np.ndarray ): """simple docstring""" return vector * sigmoid(__snake_case ) if __name__ == "__main__": import doctest doctest.testmod()
88
0
from ...configuration_utils import PretrainedConfig from ...utils import logging __A = logging.get_logger(__name__) __A = { "facebook/vit-mae-base": "https://huggingface.co/facebook/vit-mae-base/resolve/main/config.json", # See all ViT MAE models at https://huggingface.co/models?filter=vit-mae } class _A ( UpperCamelCase ): """simple docstring""" lowerCamelCase : Tuple = 'vit_mae' def __init__( self : str , __SCREAMING_SNAKE_CASE : List[Any]=768 , __SCREAMING_SNAKE_CASE : Dict=12 , __SCREAMING_SNAKE_CASE : Union[str, Any]=12 , __SCREAMING_SNAKE_CASE : int=3072 , __SCREAMING_SNAKE_CASE : List[str]="gelu" , __SCREAMING_SNAKE_CASE : Union[str, Any]=0.0 , __SCREAMING_SNAKE_CASE : Dict=0.0 , __SCREAMING_SNAKE_CASE : Union[str, Any]=0.02 , __SCREAMING_SNAKE_CASE : List[str]=1e-12 , __SCREAMING_SNAKE_CASE : Any=224 , __SCREAMING_SNAKE_CASE : str=16 , __SCREAMING_SNAKE_CASE : Tuple=3 , __SCREAMING_SNAKE_CASE : str=True , __SCREAMING_SNAKE_CASE : List[str]=16 , __SCREAMING_SNAKE_CASE : Union[str, Any]=512 , __SCREAMING_SNAKE_CASE : Dict=8 , __SCREAMING_SNAKE_CASE : Dict=2048 , __SCREAMING_SNAKE_CASE : Optional[Any]=0.75 , __SCREAMING_SNAKE_CASE : Any=False , **__SCREAMING_SNAKE_CASE : Optional[Any] , ) -> Optional[Any]: super().__init__(**__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =hidden_size __UpperCAmelCase =num_hidden_layers __UpperCAmelCase =num_attention_heads __UpperCAmelCase =intermediate_size __UpperCAmelCase =hidden_act __UpperCAmelCase =hidden_dropout_prob __UpperCAmelCase =attention_probs_dropout_prob __UpperCAmelCase =initializer_range __UpperCAmelCase =layer_norm_eps __UpperCAmelCase =image_size __UpperCAmelCase =patch_size __UpperCAmelCase =num_channels __UpperCAmelCase =qkv_bias __UpperCAmelCase =decoder_num_attention_heads __UpperCAmelCase =decoder_hidden_size __UpperCAmelCase =decoder_num_hidden_layers __UpperCAmelCase =decoder_intermediate_size __UpperCAmelCase =mask_ratio __UpperCAmelCase =norm_pix_loss
68
"""simple docstring""" from transformers import HfArgumentParser, TensorFlowBenchmark, TensorFlowBenchmarkArguments def _snake_case ( ): """simple docstring""" _lowerCamelCase : Any = HfArgumentParser(__snake_case ) _lowerCamelCase : int = parser.parse_args_into_dataclasses()[0] _lowerCamelCase : Dict = TensorFlowBenchmark(args=__snake_case ) try: _lowerCamelCase : Optional[int] = parser.parse_args_into_dataclasses()[0] except ValueError as e: _lowerCamelCase : Union[str, Any] = """Arg --no_{0} is no longer used, please use --no-{0} instead.""" _lowerCamelCase : List[str] = """ """.join(str(__snake_case ).split(""" """ )[:-1] ) _lowerCamelCase : Dict = """""" _lowerCamelCase : List[Any] = eval(str(__snake_case ).split(""" """ )[-1] ) _lowerCamelCase : Tuple = [] for arg in depreciated_args: # arg[2:] removes '--' if arg[2:] in TensorFlowBenchmark.deprecated_args: # arg[5:] removes '--no_' full_error_msg += arg_error_msg.format(arg[5:] ) else: wrong_args.append(__snake_case ) if len(__snake_case ) > 0: _lowerCamelCase : Tuple = full_error_msg + begin_error_msg + str(__snake_case ) raise ValueError(__snake_case ) benchmark.run() if __name__ == "__main__": main()
88
0
'''simple docstring''' import enum import shutil import sys a , a : List[str] = shutil.get_terminal_size() a : str = {'''UP''': '''A''', '''DOWN''': '''B''', '''RIGHT''': '''C''', '''LEFT''': '''D'''} class SCREAMING_SNAKE_CASE__ ( enum.Enum ): __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 1 def __UpperCAmelCase ( _UpperCAmelCase : int , _UpperCAmelCase : Tuple="" ) -> List[Any]: sys.stdout.write(str(_UpperCAmelCase ) + end ) sys.stdout.flush() def __UpperCAmelCase ( _UpperCAmelCase : int , _UpperCAmelCase : int , _UpperCAmelCase : List[str]="" ) -> Optional[int]: forceWrite(F'''\u001b[{color}m{content}\u001b[0m''' , _UpperCAmelCase ) def __UpperCAmelCase ( ) -> Union[str, Any]: forceWrite("\r" ) def __UpperCAmelCase ( _UpperCAmelCase : int , _UpperCAmelCase : str ) -> Optional[Any]: forceWrite(F'''\033[{num_lines}{CURSOR_TO_CHAR[direction.upper()]}''' ) def __UpperCAmelCase ( ) -> int: forceWrite(" " * TERMINAL_WIDTH ) reset_cursor() def __UpperCAmelCase ( ) -> Optional[int]: reset_cursor() forceWrite("-" * TERMINAL_WIDTH )
69
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging UpperCAmelCase = logging.get_logger(__name__) UpperCAmelCase = { """kssteven/ibert-roberta-base""": """https://huggingface.co/kssteven/ibert-roberta-base/resolve/main/config.json""", """kssteven/ibert-roberta-large""": """https://huggingface.co/kssteven/ibert-roberta-large/resolve/main/config.json""", """kssteven/ibert-roberta-large-mnli""": ( """https://huggingface.co/kssteven/ibert-roberta-large-mnli/resolve/main/config.json""" ), } class lowercase__ ( A_ ): __UpperCAmelCase = '''ibert''' def __init__( self , SCREAMING_SNAKE_CASE=3_0522 , SCREAMING_SNAKE_CASE=768 , SCREAMING_SNAKE_CASE=12 , SCREAMING_SNAKE_CASE=12 , SCREAMING_SNAKE_CASE=3072 , SCREAMING_SNAKE_CASE="gelu" , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=512 , SCREAMING_SNAKE_CASE=2 , SCREAMING_SNAKE_CASE=0.02 , SCREAMING_SNAKE_CASE=1e-1_2 , SCREAMING_SNAKE_CASE=1 , SCREAMING_SNAKE_CASE=0 , SCREAMING_SNAKE_CASE=2 , SCREAMING_SNAKE_CASE="absolute" , SCREAMING_SNAKE_CASE=False , SCREAMING_SNAKE_CASE="none" , **SCREAMING_SNAKE_CASE , ) -> Any: super().__init__(pad_token_id=SCREAMING_SNAKE_CASE , bos_token_id=SCREAMING_SNAKE_CASE , eos_token_id=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE) _lowerCamelCase : Optional[int] = vocab_size _lowerCamelCase : Dict = hidden_size _lowerCamelCase : List[str] = num_hidden_layers _lowerCamelCase : int = num_attention_heads _lowerCamelCase : Tuple = hidden_act _lowerCamelCase : str = intermediate_size _lowerCamelCase : Union[str, Any] = hidden_dropout_prob _lowerCamelCase : Tuple = attention_probs_dropout_prob _lowerCamelCase : Any = max_position_embeddings _lowerCamelCase : Dict = type_vocab_size _lowerCamelCase : List[Any] = initializer_range _lowerCamelCase : Dict = layer_norm_eps _lowerCamelCase : List[Any] = position_embedding_type _lowerCamelCase : Any = quant_mode _lowerCamelCase : List[str] = force_dequant class lowercase__ ( A_ ): @property def UpperCamelCase_ ( self) -> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": _lowerCamelCase : Dict = {0: """batch""", 1: """choice""", 2: """sequence"""} else: _lowerCamelCase : Optional[int] = {0: """batch""", 1: """sequence"""} return OrderedDict( [ ("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ])
88
0
import requests def _SCREAMING_SNAKE_CASE ( lowercase : str , lowercase : str ): '''simple docstring''' lowerCamelCase_ = {'Content-Type': 'application/json'} lowerCamelCase_ = requests.post(lowercase , json={'text': message_body} , headers=lowercase ) if response.status_code != 2_00: lowerCamelCase_ = ( 'Request to slack returned an error ' f"""{response.status_code}, the response is:\n{response.text}""" ) raise ValueError(lowercase ) if __name__ == "__main__": # Set the slack url to the one provided by Slack when you create the webhook at # https://my.slack.com/services/new/incoming-webhook/ send_slack_message("<YOUR MESSAGE BODY>", "<SLACK CHANNEL URL>")
70
"""simple docstring""" from __future__ import annotations import queue class lowercase__ : def __init__( self , SCREAMING_SNAKE_CASE) -> int: _lowerCamelCase : int = data _lowerCamelCase : List[str] = None _lowerCamelCase : Any = None def _snake_case ( ): """simple docstring""" print("""\n********Press N to stop entering at any point of time********\n""" ) _lowerCamelCase : Optional[int] = input("""Enter the value of the root node: """ ).strip().lower() _lowerCamelCase : queue.Queue = queue.Queue() _lowerCamelCase : Optional[int] = TreeNode(int(__snake_case ) ) q.put(__snake_case ) while not q.empty(): _lowerCamelCase : Tuple = q.get() _lowerCamelCase : Any = F'Enter the left node of {node_found.data}: ' _lowerCamelCase : Union[str, Any] = input(__snake_case ).strip().lower() or """n""" if check == "n": return tree_node _lowerCamelCase : Dict = TreeNode(int(__snake_case ) ) _lowerCamelCase : List[str] = left_node q.put(__snake_case ) _lowerCamelCase : Optional[int] = F'Enter the right node of {node_found.data}: ' _lowerCamelCase : Optional[Any] = input(__snake_case ).strip().lower() or """n""" if check == "n": return tree_node _lowerCamelCase : List[Any] = TreeNode(int(__snake_case ) ) _lowerCamelCase : List[Any] = right_node q.put(__snake_case ) raise def _snake_case ( __snake_case : TreeNode ): """simple docstring""" if not isinstance(__snake_case , __snake_case ) or not node: return print(node.data , end=""",""" ) pre_order(node.left ) pre_order(node.right ) def _snake_case ( __snake_case : TreeNode ): """simple docstring""" if not isinstance(__snake_case , __snake_case ) or not node: return in_order(node.left ) print(node.data , end=""",""" ) in_order(node.right ) def _snake_case ( __snake_case : TreeNode ): """simple docstring""" if not isinstance(__snake_case , __snake_case ) or not node: return post_order(node.left ) post_order(node.right ) print(node.data , end=""",""" ) def _snake_case ( __snake_case : TreeNode ): """simple docstring""" if not isinstance(__snake_case , __snake_case ) or not node: return _lowerCamelCase : queue.Queue = queue.Queue() q.put(__snake_case ) while not q.empty(): _lowerCamelCase : Any = q.get() print(node_dequeued.data , end=""",""" ) if node_dequeued.left: q.put(node_dequeued.left ) if node_dequeued.right: q.put(node_dequeued.right ) def _snake_case ( __snake_case : TreeNode ): """simple docstring""" if not isinstance(__snake_case , __snake_case ) or not node: return _lowerCamelCase : queue.Queue = queue.Queue() q.put(__snake_case ) while not q.empty(): _lowerCamelCase : Optional[Any] = [] while not q.empty(): _lowerCamelCase : Dict = q.get() print(node_dequeued.data , end=""",""" ) if node_dequeued.left: list_.append(node_dequeued.left ) if node_dequeued.right: list_.append(node_dequeued.right ) print() for node in list_: q.put(__snake_case ) def _snake_case ( __snake_case : TreeNode ): """simple docstring""" if not isinstance(__snake_case , __snake_case ) or not node: return _lowerCamelCase : list[TreeNode] = [] _lowerCamelCase : Optional[int] = node while n or stack: while n: # start from root node, find its left child print(n.data , end=""",""" ) stack.append(__snake_case ) _lowerCamelCase : Tuple = n.left # end of while means current node doesn't have left child _lowerCamelCase : Optional[Any] = stack.pop() # start to traverse its right child _lowerCamelCase : Dict = n.right def _snake_case ( __snake_case : TreeNode ): """simple docstring""" if not isinstance(__snake_case , __snake_case ) or not node: return _lowerCamelCase : list[TreeNode] = [] _lowerCamelCase : int = node while n or stack: while n: stack.append(__snake_case ) _lowerCamelCase : Any = n.left _lowerCamelCase : Optional[Any] = stack.pop() print(n.data , end=""",""" ) _lowerCamelCase : List[Any] = n.right def _snake_case ( __snake_case : TreeNode ): """simple docstring""" if not isinstance(__snake_case , __snake_case ) or not node: return _lowerCamelCase , _lowerCamelCase : Union[str, Any] = [], [] _lowerCamelCase : Optional[Any] = node stacka.append(__snake_case ) while stacka: # to find the reversed order of post order, store it in stack2 _lowerCamelCase : Union[str, Any] = stacka.pop() if n.left: stacka.append(n.left ) if n.right: stacka.append(n.right ) stacka.append(__snake_case ) while stacka: # pop up from stack2 will be the post order print(stacka.pop().data , end=""",""" ) def _snake_case ( __snake_case : str = "" , __snake_case : Any=50 , __snake_case : List[str]="*" ): """simple docstring""" if not s: return "\n" + width * char _lowerCamelCase , _lowerCamelCase : Optional[int] = divmod(width - len(__snake_case ) - 2 , 2 ) return F'{left * char} {s} {(left + extra) * char}' if __name__ == "__main__": import doctest doctest.testmod() print(prompt("""Binary Tree Traversals""")) UpperCAmelCase = build_tree() print(prompt("""Pre Order Traversal""")) pre_order(node) print(prompt() + """\n""") print(prompt("""In Order Traversal""")) in_order(node) print(prompt() + """\n""") print(prompt("""Post Order Traversal""")) post_order(node) print(prompt() + """\n""") print(prompt("""Level Order Traversal""")) level_order(node) print(prompt() + """\n""") print(prompt("""Actual Level Order Traversal""")) level_order_actual(node) print("""*""" * 50 + """\n""") print(prompt("""Pre Order Traversal - Iteration Version""")) pre_order_iter(node) print(prompt() + """\n""") print(prompt("""In Order Traversal - Iteration Version""")) in_order_iter(node) print(prompt() + """\n""") print(prompt("""Post Order Traversal - Iteration Version""")) post_order_iter(node) print(prompt())
88
0
'''simple docstring''' import math from dataclasses import dataclass from typing import Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, randn_tensor from .scheduling_utils import SchedulerMixin @dataclass # Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->UnCLIP class _snake_case (__SCREAMING_SNAKE_CASE): __A : torch.FloatTensor __A : Optional[torch.FloatTensor] =None def a__ ( _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : Optional[int]=0.999 , _SCREAMING_SNAKE_CASE : List[Any]="cosine" , ) -> Union[str, Any]: """simple docstring""" if alpha_transform_type == "cosine": def alpha_bar_fn(_SCREAMING_SNAKE_CASE : Union[str, Any] ): return math.cos((t + 0.008) / 1.008 * math.pi / 2 ) ** 2 elif alpha_transform_type == "exp": def alpha_bar_fn(_SCREAMING_SNAKE_CASE : Optional[Any] ): return math.exp(t * -12.0 ) else: raise ValueError(F'''Unsupported alpha_tranform_type: {alpha_transform_type}''' ) UpperCAmelCase_ : List[str] = [] for i in range(_SCREAMING_SNAKE_CASE ): UpperCAmelCase_ : Tuple = i / num_diffusion_timesteps UpperCAmelCase_ : int = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar_fn(_SCREAMING_SNAKE_CASE ) / alpha_bar_fn(_SCREAMING_SNAKE_CASE ) , _SCREAMING_SNAKE_CASE ) ) return torch.tensor(_SCREAMING_SNAKE_CASE , dtype=torch.floataa ) class _snake_case (__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE): @register_to_config def __init__( self ,_snake_case = 10_00 ,_snake_case = "fixed_small_log" ,_snake_case = True ,_snake_case = 1.0 ,_snake_case = "epsilon" ,_snake_case = "squaredcos_cap_v2" ,): if beta_schedule != "squaredcos_cap_v2": raise ValueError("UnCLIPScheduler only supports `beta_schedule`: 'squaredcos_cap_v2'" ) UpperCAmelCase_ : Optional[Any] = betas_for_alpha_bar(_snake_case ) UpperCAmelCase_ : Union[str, Any] = 1.0 - self.betas UpperCAmelCase_ : int = torch.cumprod(self.alphas ,dim=0 ) UpperCAmelCase_ : List[str] = torch.tensor(1.0 ) # standard deviation of the initial noise distribution UpperCAmelCase_ : int = 1.0 # setable values UpperCAmelCase_ : Any = None UpperCAmelCase_ : Union[str, Any] = torch.from_numpy(np.arange(0 ,_snake_case )[::-1].copy() ) UpperCAmelCase_ : Optional[Any] = variance_type def UpperCamelCase__ ( self ,_snake_case ,_snake_case = None ): return sample def UpperCamelCase__ ( self ,_snake_case ,_snake_case = None ): UpperCAmelCase_ : Optional[Any] = num_inference_steps UpperCAmelCase_ : Optional[Any] = (self.config.num_train_timesteps - 1) / (self.num_inference_steps - 1) UpperCAmelCase_ : Tuple = (np.arange(0 ,_snake_case ) * step_ratio).round()[::-1].copy().astype(np.intaa ) UpperCAmelCase_ : Tuple = torch.from_numpy(_snake_case ).to(_snake_case ) def UpperCamelCase__ ( self ,_snake_case ,_snake_case=None ,_snake_case=None ,_snake_case=None ): if prev_timestep is None: UpperCAmelCase_ : Any = t - 1 UpperCAmelCase_ : Tuple = self.alphas_cumprod[t] UpperCAmelCase_ : List[str] = self.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.one UpperCAmelCase_ : Tuple = 1 - alpha_prod_t UpperCAmelCase_ : Optional[Any] = 1 - alpha_prod_t_prev if prev_timestep == t - 1: UpperCAmelCase_ : Any = self.betas[t] else: UpperCAmelCase_ : Optional[int] = 1 - alpha_prod_t / alpha_prod_t_prev # For t > 0, compute predicted variance βt (see formula (6) and (7) from https://arxiv.org/pdf/2006.11239.pdf) # and sample from it to get previous sample # x_{t-1} ~ N(pred_prev_sample, variance) == add variance to pred_sample UpperCAmelCase_ : List[str] = beta_prod_t_prev / beta_prod_t * beta if variance_type is None: UpperCAmelCase_ : Dict = self.config.variance_type # hacks - were probably added for training stability if variance_type == "fixed_small_log": UpperCAmelCase_ : int = torch.log(torch.clamp(_snake_case ,min=1E-20 ) ) UpperCAmelCase_ : List[str] = torch.exp(0.5 * variance ) elif variance_type == "learned_range": # NOTE difference with DDPM scheduler UpperCAmelCase_ : Optional[Any] = variance.log() UpperCAmelCase_ : Union[str, Any] = beta.log() UpperCAmelCase_ : Dict = (predicted_variance + 1) / 2 UpperCAmelCase_ : List[str] = frac * max_log + (1 - frac) * min_log return variance def UpperCamelCase__ ( self ,_snake_case ,_snake_case ,_snake_case ,_snake_case = None ,_snake_case=None ,_snake_case = True ,): UpperCAmelCase_ : int = timestep if model_output.shape[1] == sample.shape[1] * 2 and self.variance_type == "learned_range": UpperCAmelCase_ , UpperCAmelCase_ : Any = torch.split(_snake_case ,sample.shape[1] ,dim=1 ) else: UpperCAmelCase_ : List[Any] = None # 1. compute alphas, betas if prev_timestep is None: UpperCAmelCase_ : Optional[int] = t - 1 UpperCAmelCase_ : int = self.alphas_cumprod[t] UpperCAmelCase_ : Optional[int] = self.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.one UpperCAmelCase_ : Dict = 1 - alpha_prod_t UpperCAmelCase_ : Dict = 1 - alpha_prod_t_prev if prev_timestep == t - 1: UpperCAmelCase_ : List[str] = self.betas[t] UpperCAmelCase_ : int = self.alphas[t] else: UpperCAmelCase_ : Optional[int] = 1 - alpha_prod_t / alpha_prod_t_prev UpperCAmelCase_ : List[str] = 1 - beta # 2. compute predicted original sample from predicted noise also called # "predicted x_0" of formula (15) from https://arxiv.org/pdf/2006.11239.pdf if self.config.prediction_type == "epsilon": UpperCAmelCase_ : Tuple = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 elif self.config.prediction_type == "sample": UpperCAmelCase_ : Optional[int] = model_output else: raise ValueError( f'''prediction_type given as {self.config.prediction_type} must be one of `epsilon` or `sample`''' " for the UnCLIPScheduler." ) # 3. Clip "predicted x_0" if self.config.clip_sample: UpperCAmelCase_ : Dict = torch.clamp( _snake_case ,-self.config.clip_sample_range ,self.config.clip_sample_range ) # 4. Compute coefficients for pred_original_sample x_0 and current sample x_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf UpperCAmelCase_ : int = (alpha_prod_t_prev ** 0.5 * beta) / beta_prod_t UpperCAmelCase_ : List[str] = alpha ** 0.5 * beta_prod_t_prev / beta_prod_t # 5. Compute predicted previous sample µ_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf UpperCAmelCase_ : List[str] = pred_original_sample_coeff * pred_original_sample + current_sample_coeff * sample # 6. Add noise UpperCAmelCase_ : Union[str, Any] = 0 if t > 0: UpperCAmelCase_ : Optional[Any] = randn_tensor( model_output.shape ,dtype=model_output.dtype ,generator=_snake_case ,device=model_output.device ) UpperCAmelCase_ : Any = self._get_variance( _snake_case ,predicted_variance=_snake_case ,prev_timestep=_snake_case ,) if self.variance_type == "fixed_small_log": UpperCAmelCase_ : Union[str, Any] = variance elif self.variance_type == "learned_range": UpperCAmelCase_ : List[str] = (0.5 * variance).exp() else: raise ValueError( f'''variance_type given as {self.variance_type} must be one of `fixed_small_log` or `learned_range`''' " for the UnCLIPScheduler." ) UpperCAmelCase_ : List[Any] = variance * variance_noise UpperCAmelCase_ : Tuple = pred_prev_sample + variance if not return_dict: return (pred_prev_sample,) return UnCLIPSchedulerOutput(prev_sample=_snake_case ,pred_original_sample=_snake_case ) def UpperCamelCase__ ( self ,_snake_case ,_snake_case ,_snake_case ,): # Make sure alphas_cumprod and timestep have same device and dtype as original_samples UpperCAmelCase_ : int = self.alphas_cumprod.to(device=original_samples.device ,dtype=original_samples.dtype ) UpperCAmelCase_ : str = timesteps.to(original_samples.device ) UpperCAmelCase_ : Dict = alphas_cumprod[timesteps] ** 0.5 UpperCAmelCase_ : str = sqrt_alpha_prod.flatten() while len(sqrt_alpha_prod.shape ) < len(original_samples.shape ): UpperCAmelCase_ : Dict = sqrt_alpha_prod.unsqueeze(-1 ) UpperCAmelCase_ : List[str] = (1 - alphas_cumprod[timesteps]) ** 0.5 UpperCAmelCase_ : Optional[int] = sqrt_one_minus_alpha_prod.flatten() while len(sqrt_one_minus_alpha_prod.shape ) < len(original_samples.shape ): UpperCAmelCase_ : Union[str, Any] = sqrt_one_minus_alpha_prod.unsqueeze(-1 ) UpperCAmelCase_ : Optional[Any] = sqrt_alpha_prod * original_samples + sqrt_one_minus_alpha_prod * noise return noisy_samples
71
"""simple docstring""" from __future__ import annotations import unittest from transformers import XGLMConfig, XGLMTokenizer, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers.models.xglm.modeling_tf_xglm import ( TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST, TFXGLMForCausalLM, TFXGLMModel, ) @require_tf class lowercase__ : __UpperCAmelCase = XGLMConfig __UpperCAmelCase = {} __UpperCAmelCase = '''gelu''' def __init__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=14 , SCREAMING_SNAKE_CASE=7 , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=99 , SCREAMING_SNAKE_CASE=32 , SCREAMING_SNAKE_CASE=2 , SCREAMING_SNAKE_CASE=4 , SCREAMING_SNAKE_CASE=37 , SCREAMING_SNAKE_CASE="gelu" , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=512 , SCREAMING_SNAKE_CASE=0.02 , ) -> List[str]: _lowerCamelCase : Optional[int] = parent _lowerCamelCase : int = batch_size _lowerCamelCase : str = seq_length _lowerCamelCase : Any = is_training _lowerCamelCase : int = use_input_mask _lowerCamelCase : Union[str, Any] = use_labels _lowerCamelCase : str = vocab_size _lowerCamelCase : List[str] = d_model _lowerCamelCase : List[Any] = num_hidden_layers _lowerCamelCase : Dict = num_attention_heads _lowerCamelCase : int = ffn_dim _lowerCamelCase : str = activation_function _lowerCamelCase : Optional[int] = activation_dropout _lowerCamelCase : Tuple = attention_dropout _lowerCamelCase : Tuple = max_position_embeddings _lowerCamelCase : Dict = initializer_range _lowerCamelCase : Optional[Any] = None _lowerCamelCase : Union[str, Any] = 0 _lowerCamelCase : List[Any] = 2 _lowerCamelCase : str = 1 def UpperCamelCase_ ( self) -> int: return XGLMConfig.from_pretrained("""facebook/xglm-564M""") def UpperCamelCase_ ( self) -> int: _lowerCamelCase : Union[str, Any] = tf.clip_by_value( ids_tensor([self.batch_size, self.seq_length] , self.vocab_size) , clip_value_min=0 , clip_value_max=3) _lowerCamelCase : str = None if self.use_input_mask: _lowerCamelCase : Union[str, Any] = random_attention_mask([self.batch_size, self.seq_length]) _lowerCamelCase : Tuple = self.get_config() _lowerCamelCase : Optional[int] = floats_tensor([self.num_hidden_layers, self.num_attention_heads] , 2) return ( config, input_ids, input_mask, head_mask, ) def UpperCamelCase_ ( self) -> Optional[int]: return XGLMConfig( vocab_size=self.vocab_size , d_model=self.hidden_size , num_layers=self.num_hidden_layers , attention_heads=self.num_attention_heads , ffn_dim=self.ffn_dim , activation_function=self.activation_function , activation_dropout=self.activation_dropout , attention_dropout=self.attention_dropout , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , use_cache=SCREAMING_SNAKE_CASE , bos_token_id=self.bos_token_id , eos_token_id=self.eos_token_id , pad_token_id=self.pad_token_id , return_dict=SCREAMING_SNAKE_CASE , ) def UpperCamelCase_ ( self) -> Optional[int]: _lowerCamelCase : List[Any] = self.prepare_config_and_inputs() ( ( _lowerCamelCase ) , ( _lowerCamelCase ) , ( _lowerCamelCase ) , ( _lowerCamelCase ) , ) : str = config_and_inputs _lowerCamelCase : Optional[Any] = { """input_ids""": input_ids, """head_mask""": head_mask, } return config, inputs_dict @require_tf class lowercase__ ( A_ ,A_ ,unittest.TestCase ): __UpperCAmelCase = (TFXGLMModel, TFXGLMForCausalLM) if is_tf_available() else () __UpperCAmelCase = (TFXGLMForCausalLM,) if is_tf_available() else () __UpperCAmelCase = ( {'''feature-extraction''': TFXGLMModel, '''text-generation''': TFXGLMForCausalLM} if is_tf_available() else {} ) __UpperCAmelCase = False __UpperCAmelCase = False __UpperCAmelCase = False def UpperCamelCase_ ( self) -> Optional[Any]: _lowerCamelCase : Optional[Any] = TFXGLMModelTester(self) _lowerCamelCase : str = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE , n_embd=37) def UpperCamelCase_ ( self) -> Dict: self.config_tester.run_common_tests() @slow def UpperCamelCase_ ( self) -> List[Any]: for model_name in TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _lowerCamelCase : Tuple = TFXGLMModel.from_pretrained(SCREAMING_SNAKE_CASE) self.assertIsNotNone(SCREAMING_SNAKE_CASE) @unittest.skip(reason="""Currently, model embeddings are going to undergo a major refactor.""") def UpperCamelCase_ ( self) -> List[Any]: super().test_resize_token_embeddings() @require_tf class lowercase__ ( unittest.TestCase ): @slow def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE=True) -> List[Any]: _lowerCamelCase : List[str] = TFXGLMForCausalLM.from_pretrained("""facebook/xglm-564M""") _lowerCamelCase : Union[str, Any] = tf.convert_to_tensor([[2, 268, 9865]] , dtype=tf.intaa) # The dog # </s> The dog is a very friendly dog. He is very affectionate and loves to play with other # fmt: off _lowerCamelCase : Dict = [2, 268, 9865, 67, 11, 1988, 5_7252, 9865, 5, 984, 67, 1988, 21_3838, 1658, 53, 7_0446, 33, 6657, 278, 1581] # fmt: on _lowerCamelCase : str = model.generate(SCREAMING_SNAKE_CASE , do_sample=SCREAMING_SNAKE_CASE , num_beams=1) if verify_outputs: self.assertListEqual(output_ids[0].numpy().tolist() , SCREAMING_SNAKE_CASE) @slow def UpperCamelCase_ ( self) -> int: _lowerCamelCase : int = XGLMTokenizer.from_pretrained("""facebook/xglm-564M""") _lowerCamelCase : Tuple = TFXGLMForCausalLM.from_pretrained("""facebook/xglm-564M""") tf.random.set_seed(0) _lowerCamelCase : Union[str, Any] = tokenizer("""Today is a nice day and""" , return_tensors="""tf""") _lowerCamelCase : Any = tokenized.input_ids # forces the generation to happen on CPU, to avoid GPU-related quirks (and assure same output regardless of the available devices) with tf.device(""":/CPU:0"""): _lowerCamelCase : Any = model.generate(SCREAMING_SNAKE_CASE , do_sample=SCREAMING_SNAKE_CASE , seed=[7, 0]) _lowerCamelCase : List[str] = tokenizer.decode(output_ids[0] , skip_special_tokens=SCREAMING_SNAKE_CASE) _lowerCamelCase : Any = ( """Today is a nice day and warm evening here over Southern Alberta!! Today when they closed schools due""" ) self.assertEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) @slow def UpperCamelCase_ ( self) -> List[Any]: _lowerCamelCase : Optional[Any] = TFXGLMForCausalLM.from_pretrained("""facebook/xglm-564M""") _lowerCamelCase : Any = XGLMTokenizer.from_pretrained("""facebook/xglm-564M""") _lowerCamelCase : List[Any] = """left""" # use different length sentences to test batching _lowerCamelCase : List[Any] = [ """This is an extremelly long sentence that only exists to test the ability of the model to cope with """ """left-padding, such as in batched generation. The output for the sequence below should be the same """ """regardless of whether left padding is applied or not. When""", """Hello, my dog is a little""", ] _lowerCamelCase : Union[str, Any] = tokenizer(SCREAMING_SNAKE_CASE , return_tensors="""tf""" , padding=SCREAMING_SNAKE_CASE) _lowerCamelCase : int = inputs["""input_ids"""] _lowerCamelCase : List[Any] = model.generate(input_ids=SCREAMING_SNAKE_CASE , attention_mask=inputs["""attention_mask"""] , max_new_tokens=12) _lowerCamelCase : List[str] = tokenizer(sentences[0] , return_tensors="""tf""").input_ids _lowerCamelCase : Optional[Any] = model.generate(input_ids=SCREAMING_SNAKE_CASE , max_new_tokens=12) _lowerCamelCase : Tuple = tokenizer(sentences[1] , return_tensors="""tf""").input_ids _lowerCamelCase : int = model.generate(input_ids=SCREAMING_SNAKE_CASE , max_new_tokens=12) _lowerCamelCase : Optional[int] = tokenizer.batch_decode(SCREAMING_SNAKE_CASE , skip_special_tokens=SCREAMING_SNAKE_CASE) _lowerCamelCase : Optional[Any] = tokenizer.decode(output_non_padded[0] , skip_special_tokens=SCREAMING_SNAKE_CASE) _lowerCamelCase : Union[str, Any] = tokenizer.decode(output_padded[0] , skip_special_tokens=SCREAMING_SNAKE_CASE) _lowerCamelCase : Tuple = [ """This is an extremelly long sentence that only exists to test the ability of the model to cope with """ """left-padding, such as in batched generation. The output for the sequence below should be the same """ """regardless of whether left padding is applied or not. When left padding is applied, the sequence will be """ """a single""", """Hello, my dog is a little bit of a shy one, but he is very friendly""", ] self.assertListEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) self.assertListEqual(SCREAMING_SNAKE_CASE , [non_padded_sentence, padded_sentence])
88
0
'''simple docstring''' import warnings from diffusers import StableDiffusionImgaImgPipeline # noqa F401 warnings.warn( '''The `image_to_image.py` script is outdated. Please use directly `from diffusers import''' ''' StableDiffusionImg2ImgPipeline` instead.''' )
72
"""simple docstring""" from collections import defaultdict def _snake_case ( __snake_case : str , __snake_case : str ): """simple docstring""" _lowerCamelCase : Tuple = first_str.lower().strip() _lowerCamelCase : int = second_str.lower().strip() # Remove whitespace _lowerCamelCase : Any = first_str.replace(""" """ , """""" ) _lowerCamelCase : List[str] = second_str.replace(""" """ , """""" ) # Strings of different lengths are not anagrams if len(__snake_case ) != len(__snake_case ): return False # Default values for count should be 0 _lowerCamelCase : defaultdict[str, int] = defaultdict(__snake_case ) # For each character in input strings, # increment count in the corresponding for i in range(len(__snake_case ) ): count[first_str[i]] += 1 count[second_str[i]] -= 1 return all(_count == 0 for _count in count.values() ) if __name__ == "__main__": from doctest import testmod testmod() UpperCAmelCase = input("""Enter the first string """).strip() UpperCAmelCase = input("""Enter the second string """).strip() UpperCAmelCase = check_anagrams(input_a, input_b) print(f'''{input_a} and {input_b} are {"" if status else "not "}anagrams.''')
88
0
from math import isqrt, loga def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = [True] * max_number for i in range(2 , isqrt(max_number - 1) + 1): if is_prime[i]: for j in range(i**2 , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = False return [i for i in range(2 , _UpperCAmelCase) if is_prime[i]] def lowerCamelCase__ (_UpperCAmelCase = 80_0800 , _UpperCAmelCase = 80_0800): SCREAMING_SNAKE_CASE = degree * loga(_UpperCAmelCase) SCREAMING_SNAKE_CASE = int(_UpperCAmelCase) SCREAMING_SNAKE_CASE = calculate_prime_numbers(_UpperCAmelCase) SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = len(_UpperCAmelCase) - 1 while left < right: while ( prime_numbers[right] * loga(prime_numbers[left]) + prime_numbers[left] * loga(prime_numbers[right]) > upper_bound ): right -= 1 hybrid_integers_count += right - left left += 1 return hybrid_integers_count if __name__ == "__main__": print(f"""{solution() = }""")
73
"""simple docstring""" from __future__ import annotations from numpy import array, cos, cross, floataa, radians, sin from numpy.typing import NDArray def _snake_case ( __snake_case : float , __snake_case : float , __snake_case : bool = False ): """simple docstring""" if radian_mode: return [magnitude * cos(__snake_case ), magnitude * sin(__snake_case )] return [magnitude * cos(radians(__snake_case ) ), magnitude * sin(radians(__snake_case ) )] def _snake_case ( __snake_case : NDArray[floataa] , __snake_case : NDArray[floataa] , __snake_case : float = 10**-1 ): """simple docstring""" _lowerCamelCase : NDArray[floataa] = cross(__snake_case , __snake_case ) _lowerCamelCase : float = sum(__snake_case ) return abs(__snake_case ) < eps if __name__ == "__main__": # Test to check if it works UpperCAmelCase = array( [ polar_force(718.4, 180 - 30), polar_force(879.54, 45), polar_force(100, -90), ] ) UpperCAmelCase = array([[0, 0], [0, 0], [0, 0]]) assert in_static_equilibrium(forces, location) # Problem 1 in image_data/2D_problems.jpg UpperCAmelCase = array( [ polar_force(30 * 9.81, 15), polar_force(215, 180 - 45), polar_force(264, 90 - 30), ] ) UpperCAmelCase = array([[0, 0], [0, 0], [0, 0]]) assert in_static_equilibrium(forces, location) # Problem in image_data/2D_problems_1.jpg UpperCAmelCase = array([[0, -2000], [0, -1200], [0, 1_5600], [0, -1_2400]]) UpperCAmelCase = array([[0, 0], [6, 0], [10, 0], [12, 0]]) assert in_static_equilibrium(forces, location) import doctest doctest.testmod()
88
0
import os import torch from ..logging import get_logger from .constants import FSDP_PYTORCH_VERSION, MODEL_NAME, OPTIMIZER_NAME from .versions import is_torch_version if is_torch_version(""">=""", FSDP_PYTORCH_VERSION): import torch.distributed.checkpoint as dist_cp from torch.distributed.checkpoint.default_planner import DefaultLoadPlanner, DefaultSavePlanner from torch.distributed.checkpoint.optimizer import load_sharded_optimizer_state_dict from torch.distributed.fsdp.fully_sharded_data_parallel import FullyShardedDataParallel as FSDP from torch.distributed.fsdp.fully_sharded_data_parallel import StateDictType lowercase_ = get_logger(__name__) def a__ ( snake_case , snake_case , snake_case , snake_case , snake_case=0 ): """simple docstring""" os.makedirs(snake_case , exist_ok=snake_case ) with FSDP.state_dict_type( snake_case , fsdp_plugin.state_dict_type , fsdp_plugin.state_dict_config , fsdp_plugin.optim_state_dict_config ): __SCREAMING_SNAKE_CASE : List[str] = model.state_dict() if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT: __SCREAMING_SNAKE_CASE : Optional[int] = F'''{MODEL_NAME}.bin''' if model_index == 0 else F'''{MODEL_NAME}_{model_index}.bin''' __SCREAMING_SNAKE_CASE : Optional[Any] = os.path.join(snake_case , snake_case ) if accelerator.process_index == 0: logger.info(F'''Saving model to {output_model_file}''' ) torch.save(snake_case , snake_case ) logger.info(F'''Model saved to {output_model_file}''' ) elif fsdp_plugin.state_dict_type == StateDictType.LOCAL_STATE_DICT: __SCREAMING_SNAKE_CASE : List[Any] = ( F'''{MODEL_NAME}_rank{accelerator.process_index}.bin''' if model_index == 0 else F'''{MODEL_NAME}_{model_index}_rank{accelerator.process_index}.bin''' ) __SCREAMING_SNAKE_CASE : str = os.path.join(snake_case , snake_case ) logger.info(F'''Saving model to {output_model_file}''' ) torch.save(snake_case , snake_case ) logger.info(F'''Model saved to {output_model_file}''' ) elif fsdp_plugin.state_dict_type == StateDictType.SHARDED_STATE_DICT: __SCREAMING_SNAKE_CASE : Optional[Any] = os.path.join(snake_case , F'''{MODEL_NAME}_{model_index}''' ) os.makedirs(snake_case , exist_ok=snake_case ) logger.info(F'''Saving model to {ckpt_dir}''' ) __SCREAMING_SNAKE_CASE : Optional[int] = {'''model''': state_dict} dist_cp.save_state_dict( state_dict=snake_case , storage_writer=dist_cp.FileSystemWriter(snake_case ) , planner=DefaultSavePlanner() , ) logger.info(F'''Model saved to {ckpt_dir}''' ) def a__ ( snake_case , snake_case , snake_case , snake_case , snake_case=0 ): """simple docstring""" accelerator.wait_for_everyone() with FSDP.state_dict_type( snake_case , fsdp_plugin.state_dict_type , fsdp_plugin.state_dict_config , fsdp_plugin.optim_state_dict_config ): if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT: if type(snake_case ) != FSDP and accelerator.process_index != 0: if not fsdp_plugin.sync_module_states: raise ValueError( '''Set the `sync_module_states` flag to `True` so that model states are synced across processes when ''' '''initializing FSDP object''' ) return __SCREAMING_SNAKE_CASE : Optional[int] = F'''{MODEL_NAME}.bin''' if model_index == 0 else F'''{MODEL_NAME}_{model_index}.bin''' __SCREAMING_SNAKE_CASE : int = os.path.join(snake_case , snake_case ) logger.info(F'''Loading model from {input_model_file}''' ) __SCREAMING_SNAKE_CASE : str = torch.load(snake_case ) logger.info(F'''Model loaded from {input_model_file}''' ) elif fsdp_plugin.state_dict_type == StateDictType.LOCAL_STATE_DICT: __SCREAMING_SNAKE_CASE : Optional[int] = ( F'''{MODEL_NAME}_rank{accelerator.process_index}.bin''' if model_index == 0 else F'''{MODEL_NAME}_{model_index}_rank{accelerator.process_index}.bin''' ) __SCREAMING_SNAKE_CASE : Tuple = os.path.join(snake_case , snake_case ) logger.info(F'''Loading model from {input_model_file}''' ) __SCREAMING_SNAKE_CASE : Optional[Any] = torch.load(snake_case ) logger.info(F'''Model loaded from {input_model_file}''' ) elif fsdp_plugin.state_dict_type == StateDictType.SHARDED_STATE_DICT: __SCREAMING_SNAKE_CASE : Union[str, Any] = ( os.path.join(snake_case , F'''{MODEL_NAME}_{model_index}''' ) if F'''{MODEL_NAME}''' not in input_dir else input_dir ) logger.info(F'''Loading model from {ckpt_dir}''' ) __SCREAMING_SNAKE_CASE : Union[str, Any] = {'''model''': model.state_dict()} dist_cp.load_state_dict( state_dict=snake_case , storage_reader=dist_cp.FileSystemReader(snake_case ) , planner=DefaultLoadPlanner() , ) __SCREAMING_SNAKE_CASE : Optional[int] = state_dict['''model'''] logger.info(F'''Model loaded from {ckpt_dir}''' ) model.load_state_dict(snake_case ) def a__ ( snake_case , snake_case , snake_case , snake_case , snake_case , snake_case=0 ): """simple docstring""" os.makedirs(snake_case , exist_ok=snake_case ) with FSDP.state_dict_type( snake_case , fsdp_plugin.state_dict_type , fsdp_plugin.state_dict_config , fsdp_plugin.optim_state_dict_config ): __SCREAMING_SNAKE_CASE : Optional[Any] = FSDP.optim_state_dict(snake_case , snake_case ) if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT: if accelerator.process_index == 0: __SCREAMING_SNAKE_CASE : Dict = ( F'''{OPTIMIZER_NAME}.bin''' if optimizer_index == 0 else F'''{OPTIMIZER_NAME}_{optimizer_index}.bin''' ) __SCREAMING_SNAKE_CASE : Union[str, Any] = os.path.join(snake_case , snake_case ) logger.info(F'''Saving Optimizer state to {output_optimizer_file}''' ) torch.save(snake_case , snake_case ) logger.info(F'''Optimizer state saved in {output_optimizer_file}''' ) else: __SCREAMING_SNAKE_CASE : List[str] = os.path.join(snake_case , F'''{OPTIMIZER_NAME}_{optimizer_index}''' ) os.makedirs(snake_case , exist_ok=snake_case ) logger.info(F'''Saving Optimizer state to {ckpt_dir}''' ) dist_cp.save_state_dict( state_dict={'''optimizer''': optim_state} , storage_writer=dist_cp.FileSystemWriter(snake_case ) , planner=DefaultSavePlanner() , ) logger.info(F'''Optimizer state saved in {ckpt_dir}''' ) def a__ ( snake_case , snake_case , snake_case , snake_case , snake_case , snake_case=0 ): """simple docstring""" accelerator.wait_for_everyone() with FSDP.state_dict_type( snake_case , fsdp_plugin.state_dict_type , fsdp_plugin.state_dict_config , fsdp_plugin.optim_state_dict_config ): if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT: __SCREAMING_SNAKE_CASE : Tuple = None # below check should work but currently it isn't working (mostly opytorch issue), # in the meantime disabling it at the cost of excess memory usage # if accelerator.process_index == 0 or not fsdp_plugin.optim_state_dict_config.rank0_only: __SCREAMING_SNAKE_CASE : int = ( F'''{OPTIMIZER_NAME}.bin''' if optimizer_index == 0 else F'''{OPTIMIZER_NAME}_{optimizer_index}.bin''' ) __SCREAMING_SNAKE_CASE : Any = os.path.join(snake_case , snake_case ) logger.info(F'''Loading Optimizer state from {input_optimizer_file}''' ) __SCREAMING_SNAKE_CASE : Union[str, Any] = torch.load(snake_case ) logger.info(F'''Optimizer state loaded from {input_optimizer_file}''' ) else: __SCREAMING_SNAKE_CASE : List[Any] = ( os.path.join(snake_case , F'''{OPTIMIZER_NAME}_{optimizer_index}''' ) if F'''{OPTIMIZER_NAME}''' not in input_dir else input_dir ) logger.info(F'''Loading Optimizer from {ckpt_dir}''' ) __SCREAMING_SNAKE_CASE : str = load_sharded_optimizer_state_dict( model_state_dict=model.state_dict() , optimizer_key='''optimizer''' , storage_reader=dist_cp.FileSystemReader(snake_case ) , ) __SCREAMING_SNAKE_CASE : Tuple = optim_state['''optimizer'''] logger.info(F'''Optimizer loaded from {ckpt_dir}''' ) __SCREAMING_SNAKE_CASE : List[str] = FSDP.optim_state_dict_to_load(snake_case , snake_case , snake_case ) optimizer.load_state_dict(snake_case )
74
"""simple docstring""" import random def _snake_case ( __snake_case : List[Any] , __snake_case : List[Any] , __snake_case : int ): """simple docstring""" _lowerCamelCase : List[str] = a[left_index] _lowerCamelCase : Dict = left_index + 1 for j in range(left_index + 1 , __snake_case ): if a[j] < pivot: _lowerCamelCase , _lowerCamelCase : List[str] = a[i], a[j] i += 1 _lowerCamelCase , _lowerCamelCase : Optional[int] = a[i - 1], a[left_index] return i - 1 def _snake_case ( __snake_case : Tuple , __snake_case : List[str] , __snake_case : List[str] ): """simple docstring""" if left < right: _lowerCamelCase : Any = random.randint(__snake_case , right - 1 ) _lowerCamelCase , _lowerCamelCase : Optional[Any] = ( a[left], a[pivot], ) # switches the pivot with the left most bound _lowerCamelCase : List[str] = partition(__snake_case , __snake_case , __snake_case ) quick_sort_random( __snake_case , __snake_case , __snake_case ) # recursive quicksort to the left of the pivot point quick_sort_random( __snake_case , pivot_index + 1 , __snake_case ) # recursive quicksort to the right of the pivot point def _snake_case ( ): """simple docstring""" _lowerCamelCase : Union[str, Any] = input("""Enter numbers separated by a comma:\n""" ).strip() _lowerCamelCase : int = [int(__snake_case ) for item in user_input.split(""",""" )] quick_sort_random(__snake_case , 0 , len(__snake_case ) ) print(__snake_case ) if __name__ == "__main__": main()
88
0
'''simple docstring''' from ...configuration_utils import PretrainedConfig UpperCamelCase__ = { '''google/tapas-base-finetuned-sqa''': ( '''https://huggingface.co/google/tapas-base-finetuned-sqa/resolve/main/config.json''' ), '''google/tapas-base-finetuned-wtq''': ( '''https://huggingface.co/google/tapas-base-finetuned-wtq/resolve/main/config.json''' ), '''google/tapas-base-finetuned-wikisql-supervised''': ( '''https://huggingface.co/google/tapas-base-finetuned-wikisql-supervised/resolve/main/config.json''' ), '''google/tapas-base-finetuned-tabfact''': ( '''https://huggingface.co/google/tapas-base-finetuned-tabfact/resolve/main/config.json''' ), } class lowerCamelCase_ ( __a ): lowerCAmelCase__ = 'tapas' def __init__( self : Optional[int] , _A : int=30_522 , _A : Optional[Any]=768 , _A : Dict=12 , _A : Tuple=12 , _A : List[Any]=3_072 , _A : Dict="gelu" , _A : List[Any]=0.1 , _A : Union[str, Any]=0.1 , _A : Any=1_024 , _A : Union[str, Any]=[3, 256, 256, 2, 256, 256, 10] , _A : Union[str, Any]=0.0_2 , _A : int=1e-12 , _A : Optional[Any]=0 , _A : int=1_0.0 , _A : List[str]=0 , _A : List[Any]=1.0 , _A : int=None , _A : List[str]=1.0 , _A : Optional[Any]=False , _A : Any=None , _A : Optional[Any]=1.0 , _A : Optional[int]=1.0 , _A : int=False , _A : Any=False , _A : Optional[Any]="ratio" , _A : Optional[Any]=None , _A : Union[str, Any]=None , _A : Any=64 , _A : Dict=32 , _A : int=False , _A : Dict=True , _A : Tuple=False , _A : Union[str, Any]=False , _A : int=True , _A : Tuple=False , _A : Optional[Any]=None , _A : Optional[int]=None , **_A : Optional[int] , ): '''simple docstring''' super().__init__(pad_token_id=_A , **_A ) # BERT hyperparameters (with updated max_position_embeddings and type_vocab_sizes) UpperCAmelCase__ : List[str] = vocab_size UpperCAmelCase__ : Optional[int] = hidden_size UpperCAmelCase__ : Union[str, Any] = num_hidden_layers UpperCAmelCase__ : int = num_attention_heads UpperCAmelCase__ : Any = hidden_act UpperCAmelCase__ : Any = intermediate_size UpperCAmelCase__ : Tuple = hidden_dropout_prob UpperCAmelCase__ : Optional[Any] = attention_probs_dropout_prob UpperCAmelCase__ : Optional[Any] = max_position_embeddings UpperCAmelCase__ : int = type_vocab_sizes UpperCAmelCase__ : Optional[Any] = initializer_range UpperCAmelCase__ : str = layer_norm_eps # Fine-tuning task hyperparameters UpperCAmelCase__ : Any = positive_label_weight UpperCAmelCase__ : Dict = num_aggregation_labels UpperCAmelCase__ : int = aggregation_loss_weight UpperCAmelCase__ : str = use_answer_as_supervision UpperCAmelCase__ : Any = answer_loss_importance UpperCAmelCase__ : Optional[int] = use_normalized_answer_loss UpperCAmelCase__ : str = huber_loss_delta UpperCAmelCase__ : Any = temperature UpperCAmelCase__ : str = aggregation_temperature UpperCAmelCase__ : Optional[Any] = use_gumbel_for_cells UpperCAmelCase__ : Optional[int] = use_gumbel_for_aggregation UpperCAmelCase__ : List[Any] = average_approximation_function UpperCAmelCase__ : Optional[Any] = cell_selection_preference UpperCAmelCase__ : Optional[Any] = answer_loss_cutoff UpperCAmelCase__ : Tuple = max_num_rows UpperCAmelCase__ : int = max_num_columns UpperCAmelCase__ : List[str] = average_logits_per_cell UpperCAmelCase__ : Any = select_one_column UpperCAmelCase__ : Tuple = allow_empty_column_selection UpperCAmelCase__ : List[Any] = init_cell_selection_weights_to_zero UpperCAmelCase__ : str = reset_position_index_per_cell UpperCAmelCase__ : Optional[int] = disable_per_token_loss # Aggregation hyperparameters UpperCAmelCase__ : Optional[int] = aggregation_labels UpperCAmelCase__ : List[Any] = no_aggregation_label_index if isinstance(self.aggregation_labels , _A ): UpperCAmelCase__ : Dict = {int(_A ): v for k, v in aggregation_labels.items()}
75
"""simple docstring""" import itertools import os from collections import Counter, defaultdict from concurrent.futures import ThreadPoolExecutor, as_completed import numpy as np import datasets from .execute import check_correctness UpperCAmelCase = """\ @misc{chen2021evaluating, title={Evaluating Large Language Models Trained on Code}, author={Mark Chen and Jerry Tworek and Heewoo Jun and Qiming Yuan \ and Henrique Ponde de Oliveira Pinto and Jared Kaplan and Harri Edwards \ and Yuri Burda and Nicholas Joseph and Greg Brockman and Alex Ray \ and Raul Puri and Gretchen Krueger and Michael Petrov and Heidy Khlaaf \ and Girish Sastry and Pamela Mishkin and Brooke Chan and Scott Gray \ and Nick Ryder and Mikhail Pavlov and Alethea Power and Lukasz Kaiser \ and Mohammad Bavarian and Clemens Winter and Philippe Tillet \ and Felipe Petroski Such and Dave Cummings and Matthias Plappert \ and Fotios Chantzis and Elizabeth Barnes and Ariel Herbert-Voss \ and William Hebgen Guss and Alex Nichol and Alex Paino and Nikolas Tezak \ and Jie Tang and Igor Babuschkin and Suchir Balaji and Shantanu Jain \ and William Saunders and Christopher Hesse and Andrew N. Carr \ and Jan Leike and Josh Achiam and Vedant Misra and Evan Morikawa \ and Alec Radford and Matthew Knight and Miles Brundage and Mira Murati \ and Katie Mayer and Peter Welinder and Bob McGrew and Dario Amodei \ and Sam McCandlish and Ilya Sutskever and Wojciech Zaremba}, year={2021}, eprint={2107.03374}, archivePrefix={arXiv}, primaryClass={cs.LG} } """ UpperCAmelCase = """\ This metric implements the evaluation harness for the HumanEval problem solving dataset described in the paper \"Evaluating Large Language Models Trained on Code\" (https://arxiv.org/abs/2107.03374). """ UpperCAmelCase = """ Calculates how good are predictions given some references, using certain scores Args: predictions: list of candidates to evaluate. Each candidates should be a list of strings with several code candidates to solve the problem. references: a list with a test for each prediction. Each test should evaluate the correctness of a code candidate. k: number of code candidates to consider in the evaluation (Default: [1, 10, 100]) num_workers: number of workers used to evaluate the canidate programs (Default: 4). timeout: Returns: pass_at_k: dict with pass rates for each k results: dict with granular results of each unittest Examples: >>> code_eval = datasets.load_metric(\"code_eval\") >>> test_cases = [\"assert add(2,3)==5\"] >>> candidates = [[\"def add(a,b): return a*b\", \"def add(a, b): return a+b\"]] >>> pass_at_k, results = code_eval.compute(references=test_cases, predictions=candidates, k=[1, 2]) >>> print(pass_at_k) {'pass@1': 0.5, 'pass@2': 1.0} """ UpperCAmelCase = """ ################################################################################ !!!WARNING!!! ################################################################################ The \"code_eval\" metric executes untrusted model-generated code in Python. Although it is highly unlikely that model-generated code will do something overtly malicious in response to this test suite, model-generated code may act destructively due to a lack of model capability or alignment. Users are strongly encouraged to sandbox this evaluation suite so that it does not perform destructive actions on their host or network. For more information on how OpenAI sandboxes its code, see the paper \"Evaluating Large Language Models Trained on Code\" (https://arxiv.org/abs/2107.03374). Once you have read this disclaimer and taken appropriate precautions, set the environment variable HF_ALLOW_CODE_EVAL=\"1\". Within Python you can to this with: >>> import os >>> os.environ[\"HF_ALLOW_CODE_EVAL\"] = \"1\" ################################################################################\ """ UpperCAmelCase = """The MIT License Copyright (c) OpenAI (https://openai.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.""" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION ,_KWARGS_DESCRIPTION ) class lowercase__ ( datasets.Metric ): def UpperCamelCase_ ( self) -> str: return datasets.MetricInfo( # This is the description that will appear on the metrics page. description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": datasets.Sequence(datasets.Value("""string""")), """references""": datasets.Value("""string"""), }) , homepage="""https://github.com/openai/human-eval""" , codebase_urls=["""https://github.com/openai/human-eval"""] , reference_urls=["""https://github.com/openai/human-eval"""] , license=_LICENSE , ) def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=[1, 10, 100] , SCREAMING_SNAKE_CASE=4 , SCREAMING_SNAKE_CASE=3.0) -> Union[str, Any]: if os.getenv("""HF_ALLOW_CODE_EVAL""" , 0) != "1": raise ValueError(_WARNING) if os.name == "nt": raise NotImplementedError("""This metric is currently not supported on Windows.""") with ThreadPoolExecutor(max_workers=SCREAMING_SNAKE_CASE) as executor: _lowerCamelCase : Optional[int] = [] _lowerCamelCase : Optional[int] = Counter() _lowerCamelCase : Any = 0 _lowerCamelCase : List[Any] = defaultdict(SCREAMING_SNAKE_CASE) for task_id, (candidates, test_case) in enumerate(zip(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE)): for candidate in candidates: _lowerCamelCase : Any = candidate + """\n""" + test_case _lowerCamelCase : Union[str, Any] = (test_program, timeout, task_id, completion_id[task_id]) _lowerCamelCase : List[str] = executor.submit(SCREAMING_SNAKE_CASE , *SCREAMING_SNAKE_CASE) futures.append(SCREAMING_SNAKE_CASE) completion_id[task_id] += 1 n_samples += 1 for future in as_completed(SCREAMING_SNAKE_CASE): _lowerCamelCase : int = future.result() results[result["task_id"]].append((result["""completion_id"""], result)) _lowerCamelCase , _lowerCamelCase : List[Any] = [], [] for result in results.values(): result.sort() _lowerCamelCase : List[str] = [r[1]["""passed"""] for r in result] total.append(len(SCREAMING_SNAKE_CASE)) correct.append(sum(SCREAMING_SNAKE_CASE)) _lowerCamelCase : List[Any] = np.array(SCREAMING_SNAKE_CASE) _lowerCamelCase : Union[str, Any] = np.array(SCREAMING_SNAKE_CASE) _lowerCamelCase : Union[str, Any] = k _lowerCamelCase : Optional[Any] = {F'pass@{k}': estimate_pass_at_k(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE).mean() for k in ks if (total >= k).all()} return pass_at_k, results def _snake_case ( __snake_case : List[str] , __snake_case : List[str] , __snake_case : List[str] ): """simple docstring""" def estimator(__snake_case : int , __snake_case : int , __snake_case : int ) -> float: if n - c < k: return 1.0 return 1.0 - np.prod(1.0 - k / np.arange(n - c + 1 , n + 1 ) ) if isinstance(__snake_case , __snake_case ): _lowerCamelCase : Optional[int] = itertools.repeat(__snake_case , len(__snake_case ) ) else: assert len(__snake_case ) == len(__snake_case ) _lowerCamelCase : List[str] = iter(__snake_case ) return np.array([estimator(int(__snake_case ) , int(__snake_case ) , __snake_case ) for n, c in zip(__snake_case , __snake_case )] )
88
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available a_ = { 'configuration_clipseg': [ 'CLIPSEG_PRETRAINED_CONFIG_ARCHIVE_MAP', 'CLIPSegConfig', 'CLIPSegTextConfig', 'CLIPSegVisionConfig', ], 'processing_clipseg': ['CLIPSegProcessor'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ = [ 'CLIPSEG_PRETRAINED_MODEL_ARCHIVE_LIST', 'CLIPSegModel', 'CLIPSegPreTrainedModel', 'CLIPSegTextModel', 'CLIPSegVisionModel', 'CLIPSegForImageSegmentation', ] if TYPE_CHECKING: from .configuration_clipseg import ( CLIPSEG_PRETRAINED_CONFIG_ARCHIVE_MAP, CLIPSegConfig, CLIPSegTextConfig, CLIPSegVisionConfig, ) from .processing_clipseg import CLIPSegProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_clipseg import ( CLIPSEG_PRETRAINED_MODEL_ARCHIVE_LIST, CLIPSegForImageSegmentation, CLIPSegModel, CLIPSegPreTrainedModel, CLIPSegTextModel, CLIPSegVisionModel, ) else: import sys a_ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
76
"""simple docstring""" from typing import Dict, List from nltk.translate import gleu_score import datasets from datasets import MetricInfo UpperCAmelCase = """\ @misc{wu2016googles, title={Google's Neural Machine Translation System: Bridging the Gap between Human and Machine Translation}, author={Yonghui Wu and Mike Schuster and Zhifeng Chen and Quoc V. Le and Mohammad Norouzi and Wolfgang Macherey and Maxim Krikun and Yuan Cao and Qin Gao and Klaus Macherey and Jeff Klingner and Apurva Shah and Melvin Johnson and Xiaobing Liu and Łukasz Kaiser and Stephan Gouws and Yoshikiyo Kato and Taku Kudo and Hideto Kazawa and Keith Stevens and George Kurian and Nishant Patil and Wei Wang and Cliff Young and Jason Smith and Jason Riesa and Alex Rudnick and Oriol Vinyals and Greg Corrado and Macduff Hughes and Jeffrey Dean}, year={2016}, eprint={1609.08144}, archivePrefix={arXiv}, primaryClass={cs.CL} } """ UpperCAmelCase = """\ The BLEU score has some undesirable properties when used for single sentences, as it was designed to be a corpus measure. We therefore use a slightly different score for our RL experiments which we call the 'GLEU score'. For the GLEU score, we record all sub-sequences of 1, 2, 3 or 4 tokens in output and target sequence (n-grams). We then compute a recall, which is the ratio of the number of matching n-grams to the number of total n-grams in the target (ground truth) sequence, and a precision, which is the ratio of the number of matching n-grams to the number of total n-grams in the generated output sequence. Then GLEU score is simply the minimum of recall and precision. This GLEU score's range is always between 0 (no matches) and 1 (all match) and it is symmetrical when switching output and target. According to our experiments, GLEU score correlates quite well with the BLEU metric on a corpus level but does not have its drawbacks for our per sentence reward objective. """ UpperCAmelCase = """\ Computes corpus-level Google BLEU (GLEU) score of translated segments against one or more references. Instead of averaging the sentence level GLEU scores (i.e. macro-average precision), Wu et al. (2016) sum up the matching tokens and the max of hypothesis and reference tokens for each sentence, then compute using the aggregate values. Args: predictions (list of str): list of translations to score. Each translation should be tokenized into a list of tokens. references (list of list of str): list of lists of references for each translation. Each reference should be tokenized into a list of tokens. min_len (int): The minimum order of n-gram this function should extract. Defaults to 1. max_len (int): The maximum order of n-gram this function should extract. Defaults to 4. Returns: 'google_bleu': google_bleu score Examples: Example 1: >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always', ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat'] >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which', ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never', ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat'] >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was', ... 'interested', 'in', 'world', 'history'] >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history', ... 'because', 'he', 'read', 'the', 'book'] >>> list_of_references = [[ref1a], [ref2a]] >>> hypotheses = [hyp1, hyp2] >>> google_bleu = datasets.load_metric(\"google_bleu\") >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references) >>> print(round(results[\"google_bleu\"], 2)) 0.44 Example 2: >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always', ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat'] >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which', ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never', ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat'] >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never', ... 'heed', 'the', 'cat', 'commands'] >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the', ... 'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions', ... 'of', 'the', 'cat'] >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was', ... 'interested', 'in', 'world', 'history'] >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history', ... 'because', 'he', 'read', 'the', 'book'] >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]] >>> hypotheses = [hyp1, hyp2] >>> google_bleu = datasets.load_metric(\"google_bleu\") >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references) >>> print(round(results[\"google_bleu\"], 2)) 0.61 Example 3: >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always', ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat'] >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which', ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never', ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat'] >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never', ... 'heed', 'the', 'cat', 'commands'] >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the', ... 'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions', ... 'of', 'the', 'cat'] >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was', ... 'interested', 'in', 'world', 'history'] >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history', ... 'because', 'he', 'read', 'the', 'book'] >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]] >>> hypotheses = [hyp1, hyp2] >>> google_bleu = datasets.load_metric(\"google_bleu\") >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references, min_len=2) >>> print(round(results[\"google_bleu\"], 2)) 0.53 Example 4: >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always', ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat'] >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which', ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never', ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat'] >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never', ... 'heed', 'the', 'cat', 'commands'] >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the', ... 'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions', ... 'of', 'the', 'cat'] >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was', ... 'interested', 'in', 'world', 'history'] >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history', ... 'because', 'he', 'read', 'the', 'book'] >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]] >>> hypotheses = [hyp1, hyp2] >>> google_bleu = datasets.load_metric(\"google_bleu\") >>> results = google_bleu.compute(predictions=hypotheses,references=list_of_references, min_len=2, max_len=6) >>> print(round(results[\"google_bleu\"], 2)) 0.4 """ @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION ,_KWARGS_DESCRIPTION ) class lowercase__ ( datasets.Metric ): def UpperCamelCase_ ( self) -> MetricInfo: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": datasets.Sequence(datasets.Value("""string""" , id="""token""") , id="""sequence"""), """references""": datasets.Sequence( datasets.Sequence(datasets.Value("""string""" , id="""token""") , id="""sequence""") , id="""references"""), }) , ) def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = 1 , SCREAMING_SNAKE_CASE = 4 , ) -> Dict[str, float]: return { "google_bleu": gleu_score.corpus_gleu( list_of_references=SCREAMING_SNAKE_CASE , hypotheses=SCREAMING_SNAKE_CASE , min_len=SCREAMING_SNAKE_CASE , max_len=SCREAMING_SNAKE_CASE) }
88
0
"""simple docstring""" from __future__ import annotations from random import choice def _UpperCamelCase ( UpperCamelCase ) -> Optional[Any]: """simple docstring""" return choice(UpperCamelCase ) def _UpperCamelCase ( UpperCamelCase , UpperCamelCase ) -> int: """simple docstring""" __UpperCAmelCase : List[Any] = random_pivot(UpperCamelCase ) # partition based on pivot # linear time __UpperCAmelCase : Optional[Any] = [e for e in lst if e < pivot] __UpperCAmelCase : List[str] = [e for e in lst if e > pivot] # if we get lucky, pivot might be the element we want. # we can easily see this: # small (elements smaller than k) # + pivot (kth element) # + big (elements larger than k) if len(UpperCamelCase ) == k - 1: return pivot # pivot is in elements bigger than k elif len(UpperCamelCase ) < k - 1: return kth_number(UpperCamelCase , k - len(UpperCamelCase ) - 1 ) # pivot is in elements smaller than k else: return kth_number(UpperCamelCase , UpperCamelCase ) if __name__ == "__main__": import doctest doctest.testmod()
77
"""simple docstring""" def _snake_case ( __snake_case : str , __snake_case : str ): """simple docstring""" _lowerCamelCase : str = len(__snake_case ) _lowerCamelCase : Union[str, Any] = len(__snake_case ) _lowerCamelCase : int = [[False for _ in range(m + 1 )] for _ in range(n + 1 )] _lowerCamelCase : Union[str, Any] = True for i in range(__snake_case ): for j in range(m + 1 ): if dp[i][j]: if j < m and a[i].upper() == b[j]: _lowerCamelCase : Tuple = True if a[i].islower(): _lowerCamelCase : Tuple = True return dp[n][m] if __name__ == "__main__": import doctest doctest.testmod()
88
0
'''simple docstring''' def lowerCAmelCase_ ( snake_case_ : Optional[Any]=2_81_23 ) -> str: '''simple docstring''' UpperCAmelCase_ = [1] * (limit + 1) for i in range(2 , int(limit**0.5 ) + 1 ): sum_divs[i * i] += i for k in range(i + 1 , limit // i + 1 ): sum_divs[k * i] += k + i UpperCAmelCase_ = set() UpperCAmelCase_ = 0 for n in range(1 , limit + 1 ): if sum_divs[n] > n: abundants.add(snake_case_ ) if not any((n - a in abundants) for a in abundants ): res += n return res if __name__ == "__main__": print(solution())
78
"""simple docstring""" import warnings from ...utils import logging from .image_processing_imagegpt import ImageGPTImageProcessor UpperCAmelCase = logging.get_logger(__name__) class lowercase__ ( A_ ): def __init__( self , *SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE) -> None: warnings.warn( """The class ImageGPTFeatureExtractor is deprecated and will be removed in version 5 of Transformers.""" """ Please use ImageGPTImageProcessor instead.""" , SCREAMING_SNAKE_CASE , ) super().__init__(*SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE)
88
0
import unittest from pathlib import Path from shutil import copyfile from transformers import SPIECE_UNDERLINE, is_sentencepiece_available from transformers.models.speech_to_text import SpeechaTextTokenizer from transformers.models.speech_to_text.tokenization_speech_to_text import VOCAB_FILES_NAMES, save_json from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin SCREAMING_SNAKE_CASE__ : Optional[int] = get_tests_dir("""fixtures/test_sentencepiece.model""") if is_sentencepiece_available(): import sentencepiece as sp SCREAMING_SNAKE_CASE__ : List[Any] = 5 SCREAMING_SNAKE_CASE__ : Any = 10 @require_sentencepiece @require_tokenizers class UpperCAmelCase_ ( __lowerCamelCase , unittest.TestCase ): __lowerCamelCase = SpeechaTextTokenizer __lowerCamelCase = False __lowerCamelCase = True def __UpperCAmelCase ( self ): super().setUp() UpperCAmelCase__ : List[str] = sp.SentencePieceProcessor() spm_model.Load(_lowerCAmelCase ) UpperCAmelCase__ : Tuple = ["""<s>""", """<pad>""", """</s>""", """<unk>"""] vocab += [spm_model.IdToPiece(id_ ) for id_ in range(len(_lowerCAmelCase ) )] UpperCAmelCase__ : int = dict(zip(_lowerCAmelCase , range(len(_lowerCAmelCase ) ) ) ) UpperCAmelCase__ : int = Path(self.tmpdirname ) save_json(_lowerCAmelCase , save_dir / VOCAB_FILES_NAMES["""vocab_file"""] ) if not (save_dir / VOCAB_FILES_NAMES["spm_file"]).exists(): copyfile(_lowerCAmelCase , save_dir / VOCAB_FILES_NAMES["""spm_file"""] ) UpperCAmelCase__ : List[Any] = SpeechaTextTokenizer.from_pretrained(self.tmpdirname ) tokenizer.save_pretrained(self.tmpdirname ) def __UpperCAmelCase ( self ): UpperCAmelCase__ : Any = """<pad>""" UpperCAmelCase__ : Optional[int] = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(_lowerCAmelCase ) , _lowerCAmelCase ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(_lowerCAmelCase ) , _lowerCAmelCase ) def __UpperCAmelCase ( self ): UpperCAmelCase__ : List[str] = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , """<s>""" ) self.assertEqual(vocab_keys[1] , """<pad>""" ) self.assertEqual(vocab_keys[-1] , """j""" ) self.assertEqual(len(_lowerCAmelCase ) , 1001 ) def __UpperCAmelCase ( self ): self.assertEqual(self.get_tokenizer().vocab_size , 1001 ) def __UpperCAmelCase ( self ): UpperCAmelCase__ : int = SpeechaTextTokenizer.from_pretrained(self.tmpdirname ) UpperCAmelCase__ : Tuple = tokenizer.tokenize("""This is a test""" ) self.assertListEqual(_lowerCAmelCase , ["""▁This""", """▁is""", """▁a""", """▁t""", """est"""] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(_lowerCAmelCase ) , [289, 50, 14, 174, 386] , ) UpperCAmelCase__ : Tuple = tokenizer.tokenize("""I was born in 92000, and this is falsé.""" ) self.assertListEqual( _lowerCAmelCase , [SPIECE_UNDERLINE + """I""", SPIECE_UNDERLINE + """was""", SPIECE_UNDERLINE + """b""", """or""", """n""", SPIECE_UNDERLINE + """in""", SPIECE_UNDERLINE + """""", """9""", """2""", """0""", """0""", """0""", """,""", SPIECE_UNDERLINE + """and""", SPIECE_UNDERLINE + """this""", SPIECE_UNDERLINE + """is""", SPIECE_UNDERLINE + """f""", """al""", """s""", """é""", """."""] , ) UpperCAmelCase__ : Any = tokenizer.convert_tokens_to_ids(_lowerCAmelCase ) self.assertListEqual(_lowerCAmelCase , [12, 25, 88, 59, 28, 23, 11, 4, 606, 351, 351, 351, 7, 16, 70, 50, 76, 84, 10, 4, 8] ) UpperCAmelCase__ : Dict = tokenizer.convert_ids_to_tokens(_lowerCAmelCase ) self.assertListEqual( _lowerCAmelCase , [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>""", """."""] , ) @slow def __UpperCAmelCase ( self ): # fmt: off UpperCAmelCase__ : str = {"""input_ids""": [[3791, 797, 31, 11, 64, 797, 31, 2429, 433, 12, 1176, 12, 20, 786, 915, 142, 2413, 240, 37, 3238, 797, 31, 11, 35, 93, 915, 142, 2413, 240, 37, 5540, 567, 1276, 93, 37, 610, 40, 62, 455, 657, 1042, 123, 780, 177, 37, 309, 241, 1298, 514, 20, 292, 2737, 114, 2469, 241, 85, 64, 302, 548, 528, 423, 4, 509, 406, 423, 37, 601, 4, 777, 302, 548, 528, 423, 284, 4, 3388, 511, 459, 4, 3555, 40, 321, 302, 705, 4, 3388, 511, 583, 326, 5, 5, 5, 62, 3310, 560, 177, 2680, 217, 1508, 32, 31, 853, 418, 64, 583, 511, 1605, 62, 35, 93, 560, 177, 2680, 217, 1508, 1521, 64, 583, 511, 519, 62, 20, 1515, 764, 20, 149, 261, 5625, 7972, 20, 5540, 567, 1276, 93, 3925, 1675, 11, 15, 802, 7972, 576, 217, 1508, 11, 35, 93, 1253, 2441, 15, 289, 652, 31, 416, 321, 3842, 115, 40, 911, 8, 476, 619, 4, 380, 142, 423, 335, 240, 35, 93, 264, 8, 11, 335, 569, 420, 163, 5, 2], [260, 548, 528, 423, 20, 451, 20, 2681, 1153, 3434, 20, 5540, 37, 567, 126, 1253, 2441, 3376, 449, 210, 431, 1563, 177, 767, 5540, 11, 1203, 472, 11, 2953, 685, 285, 364, 706, 1153, 20, 6799, 20, 2869, 20, 4464, 126, 40, 2429, 20, 1040, 866, 2664, 418, 20, 318, 20, 1726, 186, 20, 265, 522, 35, 93, 2191, 4634, 20, 1040, 12, 6799, 15, 228, 2356, 142, 31, 11, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [2575, 2666, 684, 1582, 1176, 12, 627, 149, 619, 20, 4902, 563, 11, 20, 149, 261, 3420, 2356, 174, 142, 4714, 131, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]], """attention_mask""": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=_lowerCAmelCase , model_name="""facebook/s2t-small-mustc-en-de-st""" , revision="""a14f04cf0776c02f62a8cb800cf7909e15ea23ad""" , ) @require_sentencepiece class UpperCAmelCase_ ( unittest.TestCase ): __lowerCamelCase = 'valhalla/s2t_mustc_multilinguial_medium' __lowerCamelCase = 'C\'est trop cool' __lowerCamelCase = 'Esto es genial' @classmethod def __UpperCAmelCase ( cls ): UpperCAmelCase__ : SpeechaTextTokenizer = SpeechaTextTokenizer.from_pretrained(cls.checkpoint_name ) return cls def __UpperCAmelCase ( self ): self.assertEqual(self.tokenizer.lang_code_to_id["""pt"""] , 4 ) self.assertEqual(self.tokenizer.lang_code_to_id["""ru"""] , 6 ) self.assertEqual(self.tokenizer.lang_code_to_id["""it"""] , 9 ) self.assertEqual(self.tokenizer.lang_code_to_id["""de"""] , 11 ) def __UpperCAmelCase ( self ): self.assertEqual(self.tokenizer.vocab_size , 10000 ) def __UpperCAmelCase ( self ): self.assertIn(_lowerCAmelCase , self.tokenizer.all_special_ids ) UpperCAmelCase__ : Union[str, Any] = [ES_CODE, 4, 1601, 47, 7647, 2] UpperCAmelCase__ : str = self.tokenizer.decode(_lowerCAmelCase , skip_special_tokens=_lowerCAmelCase ) UpperCAmelCase__ : Union[str, Any] = self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=_lowerCAmelCase ) self.assertEqual(_lowerCAmelCase , _lowerCAmelCase ) self.assertNotIn(self.tokenizer.eos_token , _lowerCAmelCase ) def __UpperCAmelCase ( self ): UpperCAmelCase__ : List[Any] = """fr""" UpperCAmelCase__ : List[Any] = self.tokenizer(self.french_text ).input_ids self.assertEqual(encoded[0] , _lowerCAmelCase ) self.assertEqual(encoded[-1] , self.tokenizer.eos_token_id ) def __UpperCAmelCase ( self ): UpperCAmelCase__ : List[Any] = """fr""" self.assertListEqual(self.tokenizer.prefix_tokens , [FR_CODE] ) UpperCAmelCase__ : Tuple = """es""" self.assertListEqual(self.tokenizer.prefix_tokens , [ES_CODE] )
79
"""simple docstring""" from math import isqrt, loga def _snake_case ( __snake_case : int ): """simple docstring""" _lowerCamelCase : List[str] = [True] * max_number for i in range(2 , isqrt(max_number - 1 ) + 1 ): if is_prime[i]: for j in range(i**2 , __snake_case , __snake_case ): _lowerCamelCase : Optional[int] = False return [i for i in range(2 , __snake_case ) if is_prime[i]] def _snake_case ( __snake_case : int = 800800 , __snake_case : int = 800800 ): """simple docstring""" _lowerCamelCase : Union[str, Any] = degree * loga(__snake_case ) _lowerCamelCase : Union[str, Any] = int(__snake_case ) _lowerCamelCase : Dict = calculate_prime_numbers(__snake_case ) _lowerCamelCase : Optional[int] = 0 _lowerCamelCase : Any = 0 _lowerCamelCase : Any = len(__snake_case ) - 1 while left < right: while ( prime_numbers[right] * loga(prime_numbers[left] ) + prime_numbers[left] * loga(prime_numbers[right] ) > upper_bound ): right -= 1 hybrid_integers_count += right - left left += 1 return hybrid_integers_count if __name__ == "__main__": print(f'''{solution() = }''')
88
0
from pathlib import Path import fire from tqdm import tqdm def snake_case ( lowerCamelCase="ro" , lowerCamelCase="en" , lowerCamelCase="wmt16" , lowerCamelCase=None ): '''simple docstring''' try: import datasets except (ModuleNotFoundError, ImportError): raise ImportError("""run pip install datasets""" ) __lowercase = F'{src_lang}-{tgt_lang}' print(F'Converting {dataset}-{pair}' ) __lowercase = datasets.load_dataset(lowerCamelCase , lowerCamelCase ) if save_dir is None: __lowercase = F'{dataset}-{pair}' __lowercase = Path(lowerCamelCase ) save_dir.mkdir(exist_ok=lowerCamelCase ) for split in ds.keys(): print(F'Splitting {split} with {ds[split].num_rows} records' ) # to save to val.source, val.target like summary datasets __lowercase = """val""" if split == """validation""" else split __lowercase = save_dir.joinpath(F'{fn}.source' ) __lowercase = save_dir.joinpath(F'{fn}.target' ) __lowercase = src_path.open("""w+""" ) __lowercase = tgt_path.open("""w+""" ) # reader is the bottleneck so writing one record at a time doesn't slow things down for x in tqdm(ds[split] ): __lowercase = x["""translation"""] src_fp.write(ex[src_lang] + """\n""" ) tgt_fp.write(ex[tgt_lang] + """\n""" ) print(F'Saved {dataset} dataset to {save_dir}' ) if __name__ == "__main__": fire.Fire(download_wmt_dataset)
80
"""simple docstring""" import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, StableDiffusionSAGPipeline, UNetaDConditionModel, ) from diffusers.utils import slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class lowercase__ ( A_ ,A_ ,unittest.TestCase ): __UpperCAmelCase = StableDiffusionSAGPipeline __UpperCAmelCase = TEXT_TO_IMAGE_PARAMS __UpperCAmelCase = TEXT_TO_IMAGE_BATCH_PARAMS __UpperCAmelCase = TEXT_TO_IMAGE_IMAGE_PARAMS __UpperCAmelCase = TEXT_TO_IMAGE_IMAGE_PARAMS __UpperCAmelCase = False def UpperCamelCase_ ( self) -> Optional[Any]: torch.manual_seed(0) _lowerCamelCase : Dict = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , cross_attention_dim=32 , ) _lowerCamelCase : int = DDIMScheduler( beta_start=0.0_00_85 , beta_end=0.0_12 , beta_schedule="""scaled_linear""" , clip_sample=SCREAMING_SNAKE_CASE , set_alpha_to_one=SCREAMING_SNAKE_CASE , ) torch.manual_seed(0) _lowerCamelCase : Tuple = 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 , ) torch.manual_seed(0) _lowerCamelCase : Tuple = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) _lowerCamelCase : List[Any] = CLIPTextModel(SCREAMING_SNAKE_CASE) _lowerCamelCase : Tuple = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""") _lowerCamelCase : List[Any] = { """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """safety_checker""": None, """feature_extractor""": None, } return components def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=0) -> List[Any]: if str(SCREAMING_SNAKE_CASE).startswith("""mps"""): _lowerCamelCase : List[str] = torch.manual_seed(SCREAMING_SNAKE_CASE) else: _lowerCamelCase : List[str] = torch.Generator(device=SCREAMING_SNAKE_CASE).manual_seed(SCREAMING_SNAKE_CASE) _lowerCamelCase : List[Any] = { """prompt""": """.""", """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 1.0, """sag_scale""": 1.0, """output_type""": """numpy""", } return inputs def UpperCamelCase_ ( self) -> Tuple: super().test_inference_batch_single_identical(expected_max_diff=3e-3) @slow @require_torch_gpu class lowercase__ ( unittest.TestCase ): def UpperCamelCase_ ( self) -> Union[str, Any]: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCamelCase_ ( self) -> Optional[Any]: _lowerCamelCase : Any = StableDiffusionSAGPipeline.from_pretrained("""CompVis/stable-diffusion-v1-4""") _lowerCamelCase : Union[str, Any] = sag_pipe.to(SCREAMING_SNAKE_CASE) sag_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE) _lowerCamelCase : Optional[int] = """.""" _lowerCamelCase : int = torch.manual_seed(0) _lowerCamelCase : Tuple = sag_pipe( [prompt] , generator=SCREAMING_SNAKE_CASE , guidance_scale=7.5 , sag_scale=1.0 , num_inference_steps=20 , output_type="""np""") _lowerCamelCase : Dict = output.images _lowerCamelCase : Tuple = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) _lowerCamelCase : Optional[Any] = np.array([0.15_68, 0.17_38, 0.16_95, 0.16_93, 0.15_07, 0.17_05, 0.15_47, 0.17_51, 0.19_49]) assert np.abs(image_slice.flatten() - expected_slice).max() < 5e-2 def UpperCamelCase_ ( self) -> List[str]: _lowerCamelCase : Optional[Any] = StableDiffusionSAGPipeline.from_pretrained("""stabilityai/stable-diffusion-2-1-base""") _lowerCamelCase : Dict = sag_pipe.to(SCREAMING_SNAKE_CASE) sag_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE) _lowerCamelCase : Union[str, Any] = """.""" _lowerCamelCase : List[str] = torch.manual_seed(0) _lowerCamelCase : int = sag_pipe( [prompt] , generator=SCREAMING_SNAKE_CASE , guidance_scale=7.5 , sag_scale=1.0 , num_inference_steps=20 , output_type="""np""") _lowerCamelCase : Any = output.images _lowerCamelCase : List[str] = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) _lowerCamelCase : Any = np.array([0.34_59, 0.28_76, 0.25_37, 0.30_02, 0.26_71, 0.21_60, 0.30_26, 0.22_62, 0.23_71]) assert np.abs(image_slice.flatten() - expected_slice).max() < 5e-2 def UpperCamelCase_ ( self) -> List[str]: _lowerCamelCase : int = StableDiffusionSAGPipeline.from_pretrained("""stabilityai/stable-diffusion-2-1-base""") _lowerCamelCase : Optional[Any] = sag_pipe.to(SCREAMING_SNAKE_CASE) sag_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE) _lowerCamelCase : Dict = """.""" _lowerCamelCase : Union[str, Any] = torch.manual_seed(0) _lowerCamelCase : Optional[int] = sag_pipe( [prompt] , width=768 , height=512 , generator=SCREAMING_SNAKE_CASE , guidance_scale=7.5 , sag_scale=1.0 , num_inference_steps=20 , output_type="""np""" , ) _lowerCamelCase : Union[str, Any] = output.images assert image.shape == (1, 512, 768, 3)
88
0
import warnings from ...utils import logging from .image_processing_imagegpt import ImageGPTImageProcessor _snake_case : int = logging.get_logger(__name__) class a (_lowerCAmelCase ): """simple docstring""" def __init__( self : Optional[int] , *lowerCamelCase : List[Any] , **lowerCamelCase : int ) -> None: warnings.warn( "The class ImageGPTFeatureExtractor is deprecated and will be removed in version 5 of Transformers." " Please use ImageGPTImageProcessor instead." , lowerCamelCase , ) super().__init__(*lowerCamelCase , **lowerCamelCase )
81
"""simple docstring""" import inspect import unittest import numpy as np from tests.test_modeling_common import floats_tensor from transformers import MaskaFormerConfig, is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MaskaFormerForUniversalSegmentation, MaskaFormerModel if is_vision_available(): from transformers import MaskaFormerImageProcessor if is_vision_available(): from PIL import Image class lowercase__ : def __init__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=2 , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=False , SCREAMING_SNAKE_CASE=10 , SCREAMING_SNAKE_CASE=3 , SCREAMING_SNAKE_CASE=32 * 8 , SCREAMING_SNAKE_CASE=32 * 8 , SCREAMING_SNAKE_CASE=4 , SCREAMING_SNAKE_CASE=64 , ) -> Optional[int]: _lowerCamelCase : List[str] = parent _lowerCamelCase : List[Any] = batch_size _lowerCamelCase : Tuple = is_training _lowerCamelCase : Tuple = use_auxiliary_loss _lowerCamelCase : Any = num_queries _lowerCamelCase : List[str] = num_channels _lowerCamelCase : List[str] = min_size _lowerCamelCase : Tuple = max_size _lowerCamelCase : str = num_labels _lowerCamelCase : Any = hidden_dim _lowerCamelCase : Dict = hidden_dim def UpperCamelCase_ ( self) -> List[str]: _lowerCamelCase : Union[str, Any] = floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size]).to( SCREAMING_SNAKE_CASE) _lowerCamelCase : List[Any] = torch.ones([self.batch_size, self.min_size, self.max_size] , device=SCREAMING_SNAKE_CASE) _lowerCamelCase : Union[str, Any] = ( torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size] , device=SCREAMING_SNAKE_CASE) > 0.5 ).float() _lowerCamelCase : Dict = (torch.rand((self.batch_size, self.num_labels) , device=SCREAMING_SNAKE_CASE) > 0.5).long() _lowerCamelCase : Optional[int] = self.get_config() return config, pixel_values, pixel_mask, mask_labels, class_labels def UpperCamelCase_ ( self) -> str: _lowerCamelCase : List[str] = MaskaFormerConfig( hidden_size=self.hidden_dim , ) _lowerCamelCase : Any = self.num_queries _lowerCamelCase : int = self.num_labels _lowerCamelCase : int = [1, 1, 1, 1] _lowerCamelCase : Any = self.num_channels _lowerCamelCase : Optional[Any] = 64 _lowerCamelCase : str = 128 _lowerCamelCase : Optional[Any] = self.hidden_dim _lowerCamelCase : Any = self.hidden_dim _lowerCamelCase : List[Any] = self.hidden_dim return config def UpperCamelCase_ ( self) -> Any: _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase : List[str] = self.prepare_config_and_inputs() _lowerCamelCase : str = {"""pixel_values""": pixel_values, """pixel_mask""": pixel_mask} return config, inputs_dict def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) -> Optional[int]: _lowerCamelCase : str = output.encoder_hidden_states _lowerCamelCase : int = output.pixel_decoder_hidden_states _lowerCamelCase : Optional[int] = output.transformer_decoder_hidden_states self.parent.assertTrue(len(SCREAMING_SNAKE_CASE) , len(config.backbone_config.depths)) self.parent.assertTrue(len(SCREAMING_SNAKE_CASE) , len(config.backbone_config.depths)) self.parent.assertTrue(len(SCREAMING_SNAKE_CASE) , config.decoder_layers) def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=False) -> List[str]: with torch.no_grad(): _lowerCamelCase : Optional[int] = MaskaFormerModel(config=SCREAMING_SNAKE_CASE) model.to(SCREAMING_SNAKE_CASE) model.eval() _lowerCamelCase : Optional[int] = model(pixel_values=SCREAMING_SNAKE_CASE , pixel_mask=SCREAMING_SNAKE_CASE) _lowerCamelCase : List[str] = model(SCREAMING_SNAKE_CASE , output_hidden_states=SCREAMING_SNAKE_CASE) self.parent.assertEqual( output.transformer_decoder_last_hidden_state.shape , (self.batch_size, self.num_queries, self.hidden_dim) , ) # let's ensure the other two hidden state exists self.parent.assertTrue(output.pixel_decoder_last_hidden_state is not None) self.parent.assertTrue(output.encoder_last_hidden_state is not None) if output_hidden_states: self.check_output_hidden_state(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) -> str: _lowerCamelCase : str = MaskaFormerForUniversalSegmentation(config=SCREAMING_SNAKE_CASE) model.to(SCREAMING_SNAKE_CASE) model.eval() def comm_check_on_output(SCREAMING_SNAKE_CASE): # let's still check that all the required stuff is there self.parent.assertTrue(result.transformer_decoder_last_hidden_state is not None) self.parent.assertTrue(result.pixel_decoder_last_hidden_state is not None) self.parent.assertTrue(result.encoder_last_hidden_state is not None) # okay, now we need to check the logits shape # due to the encoder compression, masks have a //4 spatial size self.parent.assertEqual( result.masks_queries_logits.shape , (self.batch_size, self.num_queries, self.min_size // 4, self.max_size // 4) , ) # + 1 for null class self.parent.assertEqual( result.class_queries_logits.shape , (self.batch_size, self.num_queries, self.num_labels + 1)) with torch.no_grad(): _lowerCamelCase : List[Any] = model(pixel_values=SCREAMING_SNAKE_CASE , pixel_mask=SCREAMING_SNAKE_CASE) _lowerCamelCase : List[Any] = model(SCREAMING_SNAKE_CASE) comm_check_on_output(SCREAMING_SNAKE_CASE) _lowerCamelCase : Optional[Any] = model( pixel_values=SCREAMING_SNAKE_CASE , pixel_mask=SCREAMING_SNAKE_CASE , mask_labels=SCREAMING_SNAKE_CASE , class_labels=SCREAMING_SNAKE_CASE) comm_check_on_output(SCREAMING_SNAKE_CASE) self.parent.assertTrue(result.loss is not None) self.parent.assertEqual(result.loss.shape , torch.Size([1])) @require_torch class lowercase__ ( A_ ,A_ ,unittest.TestCase ): __UpperCAmelCase = (MaskaFormerModel, MaskaFormerForUniversalSegmentation) if is_torch_available() else () __UpperCAmelCase = {'''feature-extraction''': MaskaFormerModel} if is_torch_available() else {} __UpperCAmelCase = False __UpperCAmelCase = False __UpperCAmelCase = False __UpperCAmelCase = False def UpperCamelCase_ ( self) -> Dict: _lowerCamelCase : Optional[int] = MaskaFormerModelTester(self) _lowerCamelCase : Union[str, Any] = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE , has_text_modality=SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self) -> List[str]: self.config_tester.run_common_tests() def UpperCamelCase_ ( self) -> int: _lowerCamelCase , _lowerCamelCase : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskaformer_model(SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE , output_hidden_states=SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self) -> Tuple: _lowerCamelCase : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_maskaformer_instance_segmentation_head_model(*SCREAMING_SNAKE_CASE) @unittest.skip(reason="""Mask2Former does not use inputs_embeds""") def UpperCamelCase_ ( self) -> Optional[int]: pass @unittest.skip(reason="""Mask2Former does not have a get_input_embeddings method""") def UpperCamelCase_ ( self) -> Tuple: pass @unittest.skip(reason="""Mask2Former is not a generative model""") def UpperCamelCase_ ( self) -> List[Any]: pass @unittest.skip(reason="""Mask2Former does not use token embeddings""") def UpperCamelCase_ ( self) -> Any: pass @require_torch_multi_gpu @unittest.skip( reason="""Mask2Former has some layers using `add_module` which doesn't work well with `nn.DataParallel`""") def UpperCamelCase_ ( self) -> Dict: pass @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""") def UpperCamelCase_ ( self) -> Optional[int]: pass def UpperCamelCase_ ( self) -> Optional[Any]: _lowerCamelCase , _lowerCamelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _lowerCamelCase : Dict = model_class(SCREAMING_SNAKE_CASE) _lowerCamelCase : Any = inspect.signature(model.forward) # signature.parameters is an OrderedDict => so arg_names order is deterministic _lowerCamelCase : str = [*signature.parameters.keys()] _lowerCamelCase : int = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , SCREAMING_SNAKE_CASE) @slow def UpperCamelCase_ ( self) -> Optional[int]: for model_name in ["facebook/mask2former-swin-small-coco-instance"]: _lowerCamelCase : Optional[int] = MaskaFormerModel.from_pretrained(SCREAMING_SNAKE_CASE) self.assertIsNotNone(SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self) -> Optional[Any]: _lowerCamelCase : Dict = (self.model_tester.min_size,) * 2 _lowerCamelCase : str = { """pixel_values""": torch.randn((2, 3, *size) , device=SCREAMING_SNAKE_CASE), """mask_labels""": torch.randn((2, 10, *size) , device=SCREAMING_SNAKE_CASE), """class_labels""": torch.zeros(2 , 10 , device=SCREAMING_SNAKE_CASE).long(), } _lowerCamelCase : List[str] = self.model_tester.get_config() _lowerCamelCase : Tuple = MaskaFormerForUniversalSegmentation(SCREAMING_SNAKE_CASE).to(SCREAMING_SNAKE_CASE) _lowerCamelCase : Union[str, Any] = model(**SCREAMING_SNAKE_CASE) self.assertTrue(outputs.loss is not None) def UpperCamelCase_ ( self) -> Tuple: _lowerCamelCase , _lowerCamelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskaformer_model(SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE , output_hidden_states=SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self) -> Optional[int]: _lowerCamelCase , _lowerCamelCase : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _lowerCamelCase : str = model_class(SCREAMING_SNAKE_CASE).to(SCREAMING_SNAKE_CASE) _lowerCamelCase : Union[str, Any] = model(**SCREAMING_SNAKE_CASE , output_attentions=SCREAMING_SNAKE_CASE) self.assertTrue(outputs.attentions is not None) def UpperCamelCase_ ( self) -> Optional[Any]: if not self.model_tester.is_training: return _lowerCamelCase : Any = self.all_model_classes[1] _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs() _lowerCamelCase : List[Any] = model_class(SCREAMING_SNAKE_CASE) model.to(SCREAMING_SNAKE_CASE) model.train() _lowerCamelCase : int = model(SCREAMING_SNAKE_CASE , mask_labels=SCREAMING_SNAKE_CASE , class_labels=SCREAMING_SNAKE_CASE).loss loss.backward() def UpperCamelCase_ ( self) -> Optional[Any]: _lowerCamelCase : Any = self.all_model_classes[1] _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase : int = self.model_tester.prepare_config_and_inputs() _lowerCamelCase : int = True _lowerCamelCase : Optional[Any] = True _lowerCamelCase : str = model_class(SCREAMING_SNAKE_CASE).to(SCREAMING_SNAKE_CASE) model.train() _lowerCamelCase : List[Any] = model(SCREAMING_SNAKE_CASE , mask_labels=SCREAMING_SNAKE_CASE , class_labels=SCREAMING_SNAKE_CASE) _lowerCamelCase : Tuple = outputs.encoder_hidden_states[0] encoder_hidden_states.retain_grad() _lowerCamelCase : int = outputs.pixel_decoder_hidden_states[0] pixel_decoder_hidden_states.retain_grad() _lowerCamelCase : str = outputs.transformer_decoder_hidden_states[0] transformer_decoder_hidden_states.retain_grad() _lowerCamelCase : Optional[int] = outputs.attentions[0] attentions.retain_grad() outputs.loss.backward(retain_graph=SCREAMING_SNAKE_CASE) self.assertIsNotNone(encoder_hidden_states.grad) self.assertIsNotNone(pixel_decoder_hidden_states.grad) self.assertIsNotNone(transformer_decoder_hidden_states.grad) self.assertIsNotNone(attentions.grad) UpperCAmelCase = 1e-4 def _snake_case ( ): """simple docstring""" _lowerCamelCase : List[str] = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_vision @slow class lowercase__ ( unittest.TestCase ): @cached_property def UpperCamelCase_ ( self) -> int: return "facebook/mask2former-swin-small-coco-instance" @cached_property def UpperCamelCase_ ( self) -> Union[str, Any]: return MaskaFormerImageProcessor.from_pretrained(self.model_checkpoints) if is_vision_available() else None def UpperCamelCase_ ( self) -> Optional[Any]: _lowerCamelCase : Tuple = MaskaFormerModel.from_pretrained(self.model_checkpoints).to(SCREAMING_SNAKE_CASE) _lowerCamelCase : str = self.default_image_processor _lowerCamelCase : List[str] = prepare_img() _lowerCamelCase : Union[str, Any] = image_processor(SCREAMING_SNAKE_CASE , return_tensors="""pt""").to(SCREAMING_SNAKE_CASE) _lowerCamelCase : Union[str, Any] = inputs["""pixel_values"""].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0) # check size self.assertEqual(SCREAMING_SNAKE_CASE , (1, 3, 384, 384)) with torch.no_grad(): _lowerCamelCase : Dict = model(**SCREAMING_SNAKE_CASE) _lowerCamelCase : List[Any] = torch.tensor( [[-0.27_90, -1.07_17, -1.16_68], [-0.51_28, -0.31_28, -0.49_87], [-0.58_32, 0.19_71, -0.01_97]]).to(SCREAMING_SNAKE_CASE) self.assertTrue( torch.allclose( outputs.encoder_last_hidden_state[0, 0, :3, :3] , SCREAMING_SNAKE_CASE , atol=SCREAMING_SNAKE_CASE)) _lowerCamelCase : Any = torch.tensor( [[0.89_73, 1.18_47, 1.17_76], [1.19_34, 1.50_40, 1.51_28], [1.11_53, 1.44_86, 1.49_51]]).to(SCREAMING_SNAKE_CASE) self.assertTrue( torch.allclose( outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3] , SCREAMING_SNAKE_CASE , atol=SCREAMING_SNAKE_CASE)) _lowerCamelCase : Dict = torch.tensor( [[2.11_52, 1.70_00, -0.86_03], [1.58_08, 1.80_04, -0.93_53], [1.60_43, 1.74_95, -0.59_99]]).to(SCREAMING_SNAKE_CASE) self.assertTrue( torch.allclose( outputs.transformer_decoder_last_hidden_state[0, :3, :3] , SCREAMING_SNAKE_CASE , atol=SCREAMING_SNAKE_CASE)) def UpperCamelCase_ ( self) -> Any: _lowerCamelCase : Optional[Any] = MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints).to(SCREAMING_SNAKE_CASE).eval() _lowerCamelCase : Optional[Any] = self.default_image_processor _lowerCamelCase : Any = prepare_img() _lowerCamelCase : Dict = image_processor(SCREAMING_SNAKE_CASE , return_tensors="""pt""").to(SCREAMING_SNAKE_CASE) _lowerCamelCase : Union[str, Any] = inputs["""pixel_values"""].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0) # check size self.assertEqual(SCREAMING_SNAKE_CASE , (1, 3, 384, 384)) with torch.no_grad(): _lowerCamelCase : List[str] = model(**SCREAMING_SNAKE_CASE) # masks_queries_logits _lowerCamelCase : str = outputs.masks_queries_logits self.assertEqual( masks_queries_logits.shape , (1, model.config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4)) _lowerCamelCase : Any = [ [-8.78_39, -9.00_56, -8.81_21], [-7.41_04, -7.03_13, -6.54_01], [-6.61_05, -6.34_27, -6.46_75], ] _lowerCamelCase : List[Any] = torch.tensor(SCREAMING_SNAKE_CASE).to(SCREAMING_SNAKE_CASE) self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , SCREAMING_SNAKE_CASE , atol=SCREAMING_SNAKE_CASE)) # class_queries_logits _lowerCamelCase : List[str] = outputs.class_queries_logits self.assertEqual(class_queries_logits.shape , (1, model.config.num_queries, model.config.num_labels + 1)) _lowerCamelCase : Optional[Any] = torch.tensor( [ [1.83_24, -8.08_35, -4.19_22], [0.84_50, -9.00_50, -3.60_53], [0.30_45, -7.72_93, -3.02_75], ]).to(SCREAMING_SNAKE_CASE) self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , SCREAMING_SNAKE_CASE , atol=SCREAMING_SNAKE_CASE)) def UpperCamelCase_ ( self) -> int: _lowerCamelCase : Tuple = MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints).to(SCREAMING_SNAKE_CASE).eval() _lowerCamelCase : str = self.default_image_processor _lowerCamelCase : Tuple = image_processor( [np.zeros((3, 800, 1333)), np.zeros((3, 800, 1333))] , segmentation_maps=[np.zeros((384, 384)).astype(np.floataa), np.zeros((384, 384)).astype(np.floataa)] , return_tensors="""pt""" , ) _lowerCamelCase : Optional[Any] = inputs["""pixel_values"""].to(SCREAMING_SNAKE_CASE) _lowerCamelCase : Any = [el.to(SCREAMING_SNAKE_CASE) for el in inputs["""mask_labels"""]] _lowerCamelCase : Union[str, Any] = [el.to(SCREAMING_SNAKE_CASE) for el in inputs["""class_labels"""]] with torch.no_grad(): _lowerCamelCase : Any = model(**SCREAMING_SNAKE_CASE) self.assertTrue(outputs.loss is not None)
88
0
"""simple docstring""" from dataclasses import dataclass from typing import Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, randn_tensor from .scheduling_utils import SchedulerMixin @dataclass class lowercase__ ( SCREAMING_SNAKE_CASE ): '''simple docstring''' UpperCamelCase = 42 UpperCamelCase = 42 UpperCamelCase = None class lowercase__ ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): '''simple docstring''' UpperCamelCase = 2 @register_to_config def __init__( self : List[Any] , _UpperCAmelCase : float = 0.02 , _UpperCAmelCase : float = 100 , _UpperCAmelCase : float = 1.007 , _UpperCAmelCase : float = 80 , _UpperCAmelCase : float = 0.05 , _UpperCAmelCase : float = 50 , ) -> Optional[int]: '''simple docstring''' UpperCAmelCase_ = sigma_max # setable values UpperCAmelCase_ = None UpperCAmelCase_ = None UpperCAmelCase_ = None # sigma(t_i) def lowercase__ ( self : List[Any] , _UpperCAmelCase : torch.FloatTensor , _UpperCAmelCase : Optional[int] = None ) -> torch.FloatTensor: '''simple docstring''' return sample def lowercase__ ( self : str , _UpperCAmelCase : int , _UpperCAmelCase : Union[str, torch.device] = None ) -> Tuple: '''simple docstring''' UpperCAmelCase_ = num_inference_steps UpperCAmelCase_ = np.arange(0 , self.num_inference_steps )[::-1].copy() UpperCAmelCase_ = torch.from_numpy(_UpperCAmelCase ).to(_UpperCAmelCase ) UpperCAmelCase_ = [ ( self.config.sigma_max**2 * (self.config.sigma_min**2 / self.config.sigma_max**2) ** (i / (num_inference_steps - 1)) ) for i in self.timesteps ] UpperCAmelCase_ = torch.tensor(_UpperCAmelCase , dtype=torch.floataa , device=_UpperCAmelCase ) def lowercase__ ( self : Any , _UpperCAmelCase : torch.FloatTensor , _UpperCAmelCase : float , _UpperCAmelCase : Optional[torch.Generator] = None ) -> Tuple[torch.FloatTensor, float]: '''simple docstring''' if self.config.s_min <= sigma <= self.config.s_max: UpperCAmelCase_ = min(self.config.s_churn / self.num_inference_steps , 2**0.5 - 1 ) else: UpperCAmelCase_ = 0 # sample eps ~ N(0, S_noise^2 * I) UpperCAmelCase_ = self.config.s_noise * randn_tensor(sample.shape , generator=_UpperCAmelCase ).to(sample.device ) UpperCAmelCase_ = sigma + gamma * sigma UpperCAmelCase_ = sample + ((sigma_hat**2 - sigma**2) ** 0.5 * eps) return sample_hat, sigma_hat def lowercase__ ( self : Optional[int] , _UpperCAmelCase : torch.FloatTensor , _UpperCAmelCase : float , _UpperCAmelCase : float , _UpperCAmelCase : torch.FloatTensor , _UpperCAmelCase : bool = True , ) -> Union[KarrasVeOutput, Tuple]: '''simple docstring''' UpperCAmelCase_ = sample_hat + sigma_hat * model_output UpperCAmelCase_ = (sample_hat - pred_original_sample) / sigma_hat UpperCAmelCase_ = sample_hat + (sigma_prev - sigma_hat) * derivative if not return_dict: return (sample_prev, derivative) return KarrasVeOutput( prev_sample=_UpperCAmelCase , derivative=_UpperCAmelCase , pred_original_sample=_UpperCAmelCase ) def lowercase__ ( self : Optional[int] , _UpperCAmelCase : torch.FloatTensor , _UpperCAmelCase : float , _UpperCAmelCase : float , _UpperCAmelCase : torch.FloatTensor , _UpperCAmelCase : torch.FloatTensor , _UpperCAmelCase : torch.FloatTensor , _UpperCAmelCase : bool = True , ) -> Union[KarrasVeOutput, Tuple]: '''simple docstring''' UpperCAmelCase_ = sample_prev + sigma_prev * model_output UpperCAmelCase_ = (sample_prev - pred_original_sample) / sigma_prev UpperCAmelCase_ = sample_hat + (sigma_prev - sigma_hat) * (0.5 * derivative + 0.5 * derivative_corr) if not return_dict: return (sample_prev, derivative) return KarrasVeOutput( prev_sample=_UpperCAmelCase , derivative=_UpperCAmelCase , pred_original_sample=_UpperCAmelCase ) def lowercase__ ( self : Tuple , _UpperCAmelCase : Tuple , _UpperCAmelCase : List[str] , _UpperCAmelCase : Union[str, Any] ) -> List[str]: '''simple docstring''' raise NotImplementedError()
82
"""simple docstring""" from collections import OrderedDict from ...utils import logging from .auto_factory import _BaseAutoModelClass, _LazyAutoMapping, auto_class_update from .configuration_auto import CONFIG_MAPPING_NAMES UpperCAmelCase = logging.get_logger(__name__) UpperCAmelCase = OrderedDict( [ # Base model mapping ("""albert""", """FlaxAlbertModel"""), ("""bart""", """FlaxBartModel"""), ("""beit""", """FlaxBeitModel"""), ("""bert""", """FlaxBertModel"""), ("""big_bird""", """FlaxBigBirdModel"""), ("""blenderbot""", """FlaxBlenderbotModel"""), ("""blenderbot-small""", """FlaxBlenderbotSmallModel"""), ("""clip""", """FlaxCLIPModel"""), ("""distilbert""", """FlaxDistilBertModel"""), ("""electra""", """FlaxElectraModel"""), ("""gpt-sw3""", """FlaxGPT2Model"""), ("""gpt2""", """FlaxGPT2Model"""), ("""gpt_neo""", """FlaxGPTNeoModel"""), ("""gptj""", """FlaxGPTJModel"""), ("""longt5""", """FlaxLongT5Model"""), ("""marian""", """FlaxMarianModel"""), ("""mbart""", """FlaxMBartModel"""), ("""mt5""", """FlaxMT5Model"""), ("""opt""", """FlaxOPTModel"""), ("""pegasus""", """FlaxPegasusModel"""), ("""regnet""", """FlaxRegNetModel"""), ("""resnet""", """FlaxResNetModel"""), ("""roberta""", """FlaxRobertaModel"""), ("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormModel"""), ("""roformer""", """FlaxRoFormerModel"""), ("""t5""", """FlaxT5Model"""), ("""vision-text-dual-encoder""", """FlaxVisionTextDualEncoderModel"""), ("""vit""", """FlaxViTModel"""), ("""wav2vec2""", """FlaxWav2Vec2Model"""), ("""whisper""", """FlaxWhisperModel"""), ("""xglm""", """FlaxXGLMModel"""), ("""xlm-roberta""", """FlaxXLMRobertaModel"""), ] ) UpperCAmelCase = OrderedDict( [ # Model for pre-training mapping ("""albert""", """FlaxAlbertForPreTraining"""), ("""bart""", """FlaxBartForConditionalGeneration"""), ("""bert""", """FlaxBertForPreTraining"""), ("""big_bird""", """FlaxBigBirdForPreTraining"""), ("""electra""", """FlaxElectraForPreTraining"""), ("""longt5""", """FlaxLongT5ForConditionalGeneration"""), ("""mbart""", """FlaxMBartForConditionalGeneration"""), ("""mt5""", """FlaxMT5ForConditionalGeneration"""), ("""roberta""", """FlaxRobertaForMaskedLM"""), ("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormForMaskedLM"""), ("""roformer""", """FlaxRoFormerForMaskedLM"""), ("""t5""", """FlaxT5ForConditionalGeneration"""), ("""wav2vec2""", """FlaxWav2Vec2ForPreTraining"""), ("""whisper""", """FlaxWhisperForConditionalGeneration"""), ("""xlm-roberta""", """FlaxXLMRobertaForMaskedLM"""), ] ) UpperCAmelCase = OrderedDict( [ # Model for Masked LM mapping ("""albert""", """FlaxAlbertForMaskedLM"""), ("""bart""", """FlaxBartForConditionalGeneration"""), ("""bert""", """FlaxBertForMaskedLM"""), ("""big_bird""", """FlaxBigBirdForMaskedLM"""), ("""distilbert""", """FlaxDistilBertForMaskedLM"""), ("""electra""", """FlaxElectraForMaskedLM"""), ("""mbart""", """FlaxMBartForConditionalGeneration"""), ("""roberta""", """FlaxRobertaForMaskedLM"""), ("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormForMaskedLM"""), ("""roformer""", """FlaxRoFormerForMaskedLM"""), ("""xlm-roberta""", """FlaxXLMRobertaForMaskedLM"""), ] ) UpperCAmelCase = OrderedDict( [ # Model for Seq2Seq Causal LM mapping ("""bart""", """FlaxBartForConditionalGeneration"""), ("""blenderbot""", """FlaxBlenderbotForConditionalGeneration"""), ("""blenderbot-small""", """FlaxBlenderbotSmallForConditionalGeneration"""), ("""encoder-decoder""", """FlaxEncoderDecoderModel"""), ("""longt5""", """FlaxLongT5ForConditionalGeneration"""), ("""marian""", """FlaxMarianMTModel"""), ("""mbart""", """FlaxMBartForConditionalGeneration"""), ("""mt5""", """FlaxMT5ForConditionalGeneration"""), ("""pegasus""", """FlaxPegasusForConditionalGeneration"""), ("""t5""", """FlaxT5ForConditionalGeneration"""), ] ) UpperCAmelCase = OrderedDict( [ # Model for Image-classsification ("""beit""", """FlaxBeitForImageClassification"""), ("""regnet""", """FlaxRegNetForImageClassification"""), ("""resnet""", """FlaxResNetForImageClassification"""), ("""vit""", """FlaxViTForImageClassification"""), ] ) UpperCAmelCase = OrderedDict( [ ("""vision-encoder-decoder""", """FlaxVisionEncoderDecoderModel"""), ] ) UpperCAmelCase = OrderedDict( [ # Model for Causal LM mapping ("""bart""", """FlaxBartForCausalLM"""), ("""bert""", """FlaxBertForCausalLM"""), ("""big_bird""", """FlaxBigBirdForCausalLM"""), ("""electra""", """FlaxElectraForCausalLM"""), ("""gpt-sw3""", """FlaxGPT2LMHeadModel"""), ("""gpt2""", """FlaxGPT2LMHeadModel"""), ("""gpt_neo""", """FlaxGPTNeoForCausalLM"""), ("""gptj""", """FlaxGPTJForCausalLM"""), ("""opt""", """FlaxOPTForCausalLM"""), ("""roberta""", """FlaxRobertaForCausalLM"""), ("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormForCausalLM"""), ("""xglm""", """FlaxXGLMForCausalLM"""), ("""xlm-roberta""", """FlaxXLMRobertaForCausalLM"""), ] ) UpperCAmelCase = OrderedDict( [ # Model for Sequence Classification mapping ("""albert""", """FlaxAlbertForSequenceClassification"""), ("""bart""", """FlaxBartForSequenceClassification"""), ("""bert""", """FlaxBertForSequenceClassification"""), ("""big_bird""", """FlaxBigBirdForSequenceClassification"""), ("""distilbert""", """FlaxDistilBertForSequenceClassification"""), ("""electra""", """FlaxElectraForSequenceClassification"""), ("""mbart""", """FlaxMBartForSequenceClassification"""), ("""roberta""", """FlaxRobertaForSequenceClassification"""), ("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormForSequenceClassification"""), ("""roformer""", """FlaxRoFormerForSequenceClassification"""), ("""xlm-roberta""", """FlaxXLMRobertaForSequenceClassification"""), ] ) UpperCAmelCase = OrderedDict( [ # Model for Question Answering mapping ("""albert""", """FlaxAlbertForQuestionAnswering"""), ("""bart""", """FlaxBartForQuestionAnswering"""), ("""bert""", """FlaxBertForQuestionAnswering"""), ("""big_bird""", """FlaxBigBirdForQuestionAnswering"""), ("""distilbert""", """FlaxDistilBertForQuestionAnswering"""), ("""electra""", """FlaxElectraForQuestionAnswering"""), ("""mbart""", """FlaxMBartForQuestionAnswering"""), ("""roberta""", """FlaxRobertaForQuestionAnswering"""), ("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormForQuestionAnswering"""), ("""roformer""", """FlaxRoFormerForQuestionAnswering"""), ("""xlm-roberta""", """FlaxXLMRobertaForQuestionAnswering"""), ] ) UpperCAmelCase = OrderedDict( [ # Model for Token Classification mapping ("""albert""", """FlaxAlbertForTokenClassification"""), ("""bert""", """FlaxBertForTokenClassification"""), ("""big_bird""", """FlaxBigBirdForTokenClassification"""), ("""distilbert""", """FlaxDistilBertForTokenClassification"""), ("""electra""", """FlaxElectraForTokenClassification"""), ("""roberta""", """FlaxRobertaForTokenClassification"""), ("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormForTokenClassification"""), ("""roformer""", """FlaxRoFormerForTokenClassification"""), ("""xlm-roberta""", """FlaxXLMRobertaForTokenClassification"""), ] ) UpperCAmelCase = OrderedDict( [ # Model for Multiple Choice mapping ("""albert""", """FlaxAlbertForMultipleChoice"""), ("""bert""", """FlaxBertForMultipleChoice"""), ("""big_bird""", """FlaxBigBirdForMultipleChoice"""), ("""distilbert""", """FlaxDistilBertForMultipleChoice"""), ("""electra""", """FlaxElectraForMultipleChoice"""), ("""roberta""", """FlaxRobertaForMultipleChoice"""), ("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormForMultipleChoice"""), ("""roformer""", """FlaxRoFormerForMultipleChoice"""), ("""xlm-roberta""", """FlaxXLMRobertaForMultipleChoice"""), ] ) UpperCAmelCase = OrderedDict( [ ("""bert""", """FlaxBertForNextSentencePrediction"""), ] ) UpperCAmelCase = OrderedDict( [ ("""speech-encoder-decoder""", """FlaxSpeechEncoderDecoderModel"""), ("""whisper""", """FlaxWhisperForConditionalGeneration"""), ] ) UpperCAmelCase = OrderedDict( [ ("""whisper""", """FlaxWhisperForAudioClassification"""), ] ) UpperCAmelCase = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_MAPPING_NAMES) UpperCAmelCase = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_PRETRAINING_MAPPING_NAMES) UpperCAmelCase = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MASKED_LM_MAPPING_NAMES) UpperCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES ) UpperCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES ) UpperCAmelCase = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES) UpperCAmelCase = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_CAUSAL_LM_MAPPING_NAMES) UpperCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES ) UpperCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES ) UpperCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES ) UpperCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES ) UpperCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING_NAMES ) UpperCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES ) UpperCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES ) class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_MAPPING UpperCAmelCase = auto_class_update(FlaxAutoModel) class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_PRETRAINING_MAPPING UpperCAmelCase = auto_class_update(FlaxAutoModelForPreTraining, head_doc="""pretraining""") class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_CAUSAL_LM_MAPPING UpperCAmelCase = auto_class_update(FlaxAutoModelForCausalLM, head_doc="""causal language modeling""") class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_MASKED_LM_MAPPING UpperCAmelCase = auto_class_update(FlaxAutoModelForMaskedLM, head_doc="""masked language modeling""") class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING UpperCAmelCase = auto_class_update( FlaxAutoModelForSeqaSeqLM, head_doc="""sequence-to-sequence language modeling""", checkpoint_for_example="""t5-base""" ) class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING UpperCAmelCase = auto_class_update( FlaxAutoModelForSequenceClassification, head_doc="""sequence classification""" ) class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING UpperCAmelCase = auto_class_update(FlaxAutoModelForQuestionAnswering, head_doc="""question answering""") class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING UpperCAmelCase = auto_class_update( FlaxAutoModelForTokenClassification, head_doc="""token classification""" ) class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING UpperCAmelCase = auto_class_update(FlaxAutoModelForMultipleChoice, head_doc="""multiple choice""") class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING UpperCAmelCase = auto_class_update( FlaxAutoModelForNextSentencePrediction, head_doc="""next sentence prediction""" ) class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING UpperCAmelCase = auto_class_update( FlaxAutoModelForImageClassification, head_doc="""image classification""" ) class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING UpperCAmelCase = auto_class_update(FlaxAutoModelForVisionaSeq, head_doc="""vision-to-text modeling""") class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING UpperCAmelCase = auto_class_update( FlaxAutoModelForSpeechSeqaSeq, head_doc="""sequence-to-sequence speech-to-text modeling""" )
88
0
"""simple docstring""" from collections import defaultdict from graphs.minimum_spanning_tree_prims import prisms_algorithm as mst def snake_case_ ( ): '''simple docstring''' _lowerCamelCase , _lowerCamelCase : Optional[int] = 9, 14 # noqa: F841 _lowerCamelCase : Dict = [ [0, 1, 4], [0, 7, 8], [1, 2, 8], [7, 8, 7], [7, 6, 1], [2, 8, 2], [8, 6, 6], [2, 3, 7], [2, 5, 4], [6, 5, 2], [3, 5, 14], [3, 4, 9], [5, 4, 10], [1, 7, 11], ] _lowerCamelCase : Union[str, Any] = defaultdict(A_ ) for nodea, nodea, cost in edges: adjancency[nodea].append([nodea, cost] ) adjancency[nodea].append([nodea, cost] ) _lowerCamelCase : List[str] = mst(A_ ) _lowerCamelCase : Union[str, Any] = [ [7, 6, 1], [2, 8, 2], [6, 5, 2], [0, 1, 4], [2, 5, 4], [2, 3, 7], [0, 7, 8], [3, 4, 9], ] for answer in expected: _lowerCamelCase : str = tuple(answer[:2] ) _lowerCamelCase : Union[str, Any] = tuple(edge[::-1] ) assert edge in result or reverse in result
83
"""simple docstring""" # limitations under the License. # NOTE: This file is deprecated and will be removed in a future version. # It only exists so that temporarely `from diffusers.pipelines import DiffusionPipeline` works from .pipelines import DiffusionPipeline, ImagePipelineOutput # noqa: F401 from .utils import deprecate deprecate( """pipelines_utils""", """0.22.0""", """Importing `DiffusionPipeline` or `ImagePipelineOutput` from diffusers.pipeline_utils is deprecated. Please import from diffusers.pipelines.pipeline_utils instead.""", standard_warn=False, stacklevel=3, )
88
0
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 UpperCAmelCase_ ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): lowercase = 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}}' ) lowercase = DatasetInfosDict.from_directory(__SCREAMING_SNAKE_CASE ) assert dataset_infos assert dataset_infos["default"].dataset_size == 42 @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=42 , ), ] , ) def UpperCAmelCase_ ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): lowercase = str(__SCREAMING_SNAKE_CASE ) dataset_info.write_to_directory(__SCREAMING_SNAKE_CASE ) lowercase = DatasetInfo.from_directory(__SCREAMING_SNAKE_CASE ) assert dataset_info == reloaded assert os.path.exists(os.path.join(__SCREAMING_SNAKE_CASE , 'dataset_info.json' ) ) def UpperCAmelCase_ ( ): lowercase = 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': 42}] , download_checksums={} , download_size=1337 , post_processing_size=442 , dataset_size=1234 , size_in_bytes=1337 + 442 + 1234 , ) lowercase = dataset_info._to_yaml_dict() assert sorted(__SCREAMING_SNAKE_CASE ) == 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) ) lowercase = yaml.safe_dump(__SCREAMING_SNAKE_CASE ) lowercase = yaml.safe_load(__SCREAMING_SNAKE_CASE ) assert dataset_info_yaml_dict == reloaded def UpperCAmelCase_ ( ): lowercase = DatasetInfo() lowercase = 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=42 , ) } ), DatasetInfosDict( { 'v1': DatasetInfo(dataset_size=42 ), 'v2': DatasetInfo(dataset_size=1337 ), } ), ] , ) def UpperCAmelCase_ ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): lowercase = str(__SCREAMING_SNAKE_CASE ) dataset_infos_dict.write_to_directory(__SCREAMING_SNAKE_CASE ) lowercase = DatasetInfosDict.from_directory(__SCREAMING_SNAKE_CASE ) # the config_name of the dataset_infos_dict take over the attribute for config_name, dataset_info in dataset_infos_dict.items(): lowercase = 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 lowercase = 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(__SCREAMING_SNAKE_CASE , 'README.md' ) )
84
"""simple docstring""" def _snake_case ( __snake_case : list[list[int]] , __snake_case : int , __snake_case : int , __snake_case : list[int] ): """simple docstring""" 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 _snake_case ( __snake_case : list[list[int]] , __snake_case : list[int] , __snake_case : int ): """simple docstring""" if curr_ind == len(__snake_case ): # 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(__snake_case ) ): if valid_connection(__snake_case , __snake_case , __snake_case , __snake_case ): # Insert current vertex into path as next transition _lowerCamelCase : List[str] = next_ver # Validate created path if util_hamilton_cycle(__snake_case , __snake_case , curr_ind + 1 ): return True # Backtrack _lowerCamelCase : Tuple = -1 return False def _snake_case ( __snake_case : list[list[int]] , __snake_case : int = 0 ): """simple docstring""" _lowerCamelCase : Any = [-1] * (len(__snake_case ) + 1) # initialize start and end of path with starting index _lowerCamelCase : Optional[int] = start_index # evaluate and if we find answer return path either return empty array return path if util_hamilton_cycle(__snake_case , __snake_case , 1 ) else []
88
0
import tempfile import torch from diffusers import ( DEISMultistepScheduler, DPMSolverMultistepScheduler, DPMSolverSinglestepScheduler, UniPCMultistepScheduler, ) from .test_schedulers import SchedulerCommonTest class snake_case ( UpperCamelCase_ ): lowercase_ = (DEISMultistepScheduler,) lowercase_ = (('num_inference_steps', 25),) def __lowercase( self : List[str] , **a_ : int )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = { 'num_train_timesteps': 1000, 'beta_start': 0.0001, 'beta_end': 0.02, 'beta_schedule': 'linear', 'solver_order': 2, } config.update(**a_ ) return config def __lowercase( self : Optional[int] , a_ : List[str]=0 , **a_ : str )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = dict(self.forward_default_kwargs ) SCREAMING_SNAKE_CASE__ : str = kwargs.pop('num_inference_steps' , a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.dummy_sample SCREAMING_SNAKE_CASE__ : List[Any] = 0.1 * sample SCREAMING_SNAKE_CASE__ : int = [residual + 0.2, residual + 0.15, residual + 0.10] for scheduler_class in self.scheduler_classes: SCREAMING_SNAKE_CASE__ : Dict = self.get_scheduler_config(**a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = scheduler_class(**a_ ) scheduler.set_timesteps(a_ ) # copy over dummy past residuals SCREAMING_SNAKE_CASE__ : List[Any] = dummy_past_residuals[: scheduler.config.solver_order] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(a_ ) SCREAMING_SNAKE_CASE__ : Dict = scheduler_class.from_pretrained(a_ ) new_scheduler.set_timesteps(a_ ) # copy over dummy past residuals SCREAMING_SNAKE_CASE__ : Union[str, Any] = dummy_past_residuals[: new_scheduler.config.solver_order] SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] = sample, sample for t in range(a_ , time_step + scheduler.config.solver_order + 1 ): SCREAMING_SNAKE_CASE__ : Optional[int] = scheduler.step(a_ , a_ , a_ , **a_ ).prev_sample SCREAMING_SNAKE_CASE__ : List[Any] = new_scheduler.step(a_ , a_ , a_ , **a_ ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical" def __lowercase( self : int )-> Dict: """simple docstring""" pass def __lowercase( self : List[str] , a_ : int=0 , **a_ : Optional[Any] )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = dict(self.forward_default_kwargs ) SCREAMING_SNAKE_CASE__ : str = kwargs.pop('num_inference_steps' , a_ ) SCREAMING_SNAKE_CASE__ : str = self.dummy_sample SCREAMING_SNAKE_CASE__ : Dict = 0.1 * sample SCREAMING_SNAKE_CASE__ : Optional[int] = [residual + 0.2, residual + 0.15, residual + 0.10] for scheduler_class in self.scheduler_classes: SCREAMING_SNAKE_CASE__ : int = self.get_scheduler_config() SCREAMING_SNAKE_CASE__ : List[Any] = scheduler_class(**a_ ) scheduler.set_timesteps(a_ ) # copy over dummy past residuals (must be after setting timesteps) SCREAMING_SNAKE_CASE__ : List[str] = dummy_past_residuals[: scheduler.config.solver_order] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(a_ ) SCREAMING_SNAKE_CASE__ : str = scheduler_class.from_pretrained(a_ ) # copy over dummy past residuals new_scheduler.set_timesteps(a_ ) # copy over dummy past residual (must be after setting timesteps) SCREAMING_SNAKE_CASE__ : List[Any] = dummy_past_residuals[: new_scheduler.config.solver_order] SCREAMING_SNAKE_CASE__ : Optional[int] = scheduler.step(a_ , a_ , a_ , **a_ ).prev_sample SCREAMING_SNAKE_CASE__ : Any = new_scheduler.step(a_ , a_ , a_ , **a_ ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical" def __lowercase( self : Dict , a_ : List[str]=None , **a_ : List[Any] )-> Any: """simple docstring""" if scheduler is None: SCREAMING_SNAKE_CASE__ : str = self.scheduler_classes[0] SCREAMING_SNAKE_CASE__ : Dict = self.get_scheduler_config(**a_ ) SCREAMING_SNAKE_CASE__ : int = scheduler_class(**a_ ) SCREAMING_SNAKE_CASE__ : Dict = self.scheduler_classes[0] SCREAMING_SNAKE_CASE__ : int = self.get_scheduler_config(**a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = scheduler_class(**a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = 10 SCREAMING_SNAKE_CASE__ : List[Any] = self.dummy_model() SCREAMING_SNAKE_CASE__ : Optional[int] = self.dummy_sample_deter scheduler.set_timesteps(a_ ) for i, t in enumerate(scheduler.timesteps ): SCREAMING_SNAKE_CASE__ : List[Any] = model(a_ , a_ ) SCREAMING_SNAKE_CASE__ : Any = scheduler.step(a_ , a_ , a_ ).prev_sample return sample def __lowercase( self : List[Any] )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = dict(self.forward_default_kwargs ) SCREAMING_SNAKE_CASE__ : Optional[Any] = kwargs.pop('num_inference_steps' , a_ ) for scheduler_class in self.scheduler_classes: SCREAMING_SNAKE_CASE__ : Optional[int] = self.get_scheduler_config() SCREAMING_SNAKE_CASE__ : Tuple = scheduler_class(**a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = self.dummy_sample SCREAMING_SNAKE_CASE__ : int = 0.1 * sample if num_inference_steps is not None and hasattr(a_ , 'set_timesteps' ): scheduler.set_timesteps(a_ ) elif num_inference_steps is not None and not hasattr(a_ , 'set_timesteps' ): SCREAMING_SNAKE_CASE__ : int = num_inference_steps # copy over dummy past residuals (must be done after set_timesteps) SCREAMING_SNAKE_CASE__ : List[Any] = [residual + 0.2, residual + 0.15, residual + 0.10] SCREAMING_SNAKE_CASE__ : str = dummy_past_residuals[: scheduler.config.solver_order] SCREAMING_SNAKE_CASE__ : Tuple = scheduler.timesteps[5] SCREAMING_SNAKE_CASE__ : List[str] = scheduler.timesteps[6] SCREAMING_SNAKE_CASE__ : Optional[int] = scheduler.step(a_ , a_ , a_ , **a_ ).prev_sample SCREAMING_SNAKE_CASE__ : str = scheduler.step(a_ , a_ , a_ , **a_ ).prev_sample self.assertEqual(output_a.shape , sample.shape ) self.assertEqual(output_a.shape , output_a.shape ) def __lowercase( self : Tuple )-> Any: """simple docstring""" # make sure that iterating over schedulers with same config names gives same results # for defaults SCREAMING_SNAKE_CASE__ : List[str] = DEISMultistepScheduler(**self.get_scheduler_config() ) SCREAMING_SNAKE_CASE__ : str = self.full_loop(scheduler=a_ ) SCREAMING_SNAKE_CASE__ : int = torch.mean(torch.abs(a_ ) ) assert abs(result_mean.item() - 0.2_3916 ) < 1e-3 SCREAMING_SNAKE_CASE__ : Tuple = DPMSolverSinglestepScheduler.from_config(scheduler.config ) SCREAMING_SNAKE_CASE__ : int = DPMSolverMultistepScheduler.from_config(scheduler.config ) SCREAMING_SNAKE_CASE__ : Any = UniPCMultistepScheduler.from_config(scheduler.config ) SCREAMING_SNAKE_CASE__ : Optional[int] = DEISMultistepScheduler.from_config(scheduler.config ) SCREAMING_SNAKE_CASE__ : Any = self.full_loop(scheduler=a_ ) SCREAMING_SNAKE_CASE__ : Tuple = torch.mean(torch.abs(a_ ) ) assert abs(result_mean.item() - 0.2_3916 ) < 1e-3 def __lowercase( self : Tuple )-> Tuple: """simple docstring""" for timesteps in [25, 50, 100, 999, 1000]: self.check_over_configs(num_train_timesteps=a_ ) def __lowercase( self : str )-> Tuple: """simple docstring""" self.check_over_configs(thresholding=a_ ) for order in [1, 2, 3]: for solver_type in ["logrho"]: for threshold in [0.5, 1.0, 2.0]: for prediction_type in ["epsilon", "sample"]: self.check_over_configs( thresholding=a_ , prediction_type=a_ , sample_max_value=a_ , algorithm_type='deis' , solver_order=a_ , solver_type=a_ , ) def __lowercase( self : Optional[int] )-> int: """simple docstring""" for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=a_ ) def __lowercase( self : str )-> Dict: """simple docstring""" for algorithm_type in ["deis"]: for solver_type in ["logrho"]: for order in [1, 2, 3]: for prediction_type in ["epsilon", "sample"]: self.check_over_configs( solver_order=a_ , solver_type=a_ , prediction_type=a_ , algorithm_type=a_ , ) SCREAMING_SNAKE_CASE__ : Tuple = self.full_loop( solver_order=a_ , solver_type=a_ , prediction_type=a_ , algorithm_type=a_ , ) assert not torch.isnan(a_ ).any(), "Samples have nan numbers" def __lowercase( self : Optional[Any] )-> List[str]: """simple docstring""" self.check_over_configs(lower_order_final=a_ ) self.check_over_configs(lower_order_final=a_ ) def __lowercase( self : List[Any] )-> str: """simple docstring""" for num_inference_steps in [1, 2, 3, 5, 10, 50, 100, 999, 1000]: self.check_over_forward(num_inference_steps=a_ , time_step=0 ) def __lowercase( self : str )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.full_loop() SCREAMING_SNAKE_CASE__ : Any = torch.mean(torch.abs(a_ ) ) assert abs(result_mean.item() - 0.2_3916 ) < 1e-3 def __lowercase( self : Any )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.full_loop(prediction_type='v_prediction' ) SCREAMING_SNAKE_CASE__ : List[str] = torch.mean(torch.abs(a_ ) ) assert abs(result_mean.item() - 0.091 ) < 1e-3 def __lowercase( self : int )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.scheduler_classes[0] SCREAMING_SNAKE_CASE__ : str = self.get_scheduler_config(thresholding=a_ , dynamic_thresholding_ratio=0 ) SCREAMING_SNAKE_CASE__ : str = scheduler_class(**a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = 10 SCREAMING_SNAKE_CASE__ : Optional[Any] = self.dummy_model() SCREAMING_SNAKE_CASE__ : str = self.dummy_sample_deter.half() scheduler.set_timesteps(a_ ) for i, t in enumerate(scheduler.timesteps ): SCREAMING_SNAKE_CASE__ : int = model(a_ , a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = scheduler.step(a_ , a_ , a_ ).prev_sample assert sample.dtype == torch.floataa
85
"""simple docstring""" import mpmath # for roots of unity import numpy as np class lowercase__ : def __init__( self , SCREAMING_SNAKE_CASE=None , SCREAMING_SNAKE_CASE=None) -> Tuple: # Input as list _lowerCamelCase : Any = list(poly_a or [0])[:] _lowerCamelCase : Optional[Any] = list(poly_b or [0])[:] # Remove leading zero coefficients while self.polyA[-1] == 0: self.polyA.pop() _lowerCamelCase : int = len(self.polyA) while self.polyB[-1] == 0: self.polyB.pop() _lowerCamelCase : Union[str, Any] = len(self.polyB) # Add 0 to make lengths equal a power of 2 _lowerCamelCase : List[Any] = int( 2 ** np.ceil(np.loga(len(self.polyA) + len(self.polyB) - 1))) while len(self.polyA) < self.c_max_length: self.polyA.append(0) while len(self.polyB) < self.c_max_length: self.polyB.append(0) # A complex root used for the fourier transform _lowerCamelCase : Optional[Any] = complex(mpmath.root(x=1 , n=self.c_max_length , k=1)) # The product _lowerCamelCase : int = self.__multiply() def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE) -> List[str]: _lowerCamelCase : Dict = [[x] for x in self.polyA] if which == """A""" else [[x] for x in self.polyB] # Corner case if len(SCREAMING_SNAKE_CASE) <= 1: return dft[0] # _lowerCamelCase : str = self.c_max_length // 2 while next_ncol > 0: _lowerCamelCase : Dict = [[] for i in range(SCREAMING_SNAKE_CASE)] _lowerCamelCase : Tuple = self.root**next_ncol # First half of next step _lowerCamelCase : int = 1 for j in range(self.c_max_length // (next_ncol * 2)): for i in range(SCREAMING_SNAKE_CASE): new_dft[i].append(dft[i][j] + current_root * dft[i + next_ncol][j]) current_root *= root # Second half of next step _lowerCamelCase : Optional[int] = 1 for j in range(self.c_max_length // (next_ncol * 2)): for i in range(SCREAMING_SNAKE_CASE): new_dft[i].append(dft[i][j] - current_root * dft[i + next_ncol][j]) current_root *= root # Update _lowerCamelCase : Union[str, Any] = new_dft _lowerCamelCase : List[str] = next_ncol // 2 return dft[0] def UpperCamelCase_ ( self) -> str: _lowerCamelCase : Optional[Any] = self.__dft("""A""") _lowerCamelCase : List[str] = self.__dft("""B""") _lowerCamelCase : List[Any] = [[dft_a[i] * dft_b[i] for i in range(self.c_max_length)]] del dft_a del dft_b # Corner Case if len(inverce_c[0]) <= 1: return inverce_c[0] # Inverse DFT _lowerCamelCase : List[str] = 2 while next_ncol <= self.c_max_length: _lowerCamelCase : Any = [[] for i in range(SCREAMING_SNAKE_CASE)] _lowerCamelCase : List[Any] = self.root ** (next_ncol // 2) _lowerCamelCase : str = 1 # First half of next step for j in range(self.c_max_length // next_ncol): for i in range(next_ncol // 2): # Even positions new_inverse_c[i].append( ( inverce_c[i][j] + inverce_c[i][j + self.c_max_length // next_ncol] ) / 2) # Odd positions new_inverse_c[i + next_ncol // 2].append( ( inverce_c[i][j] - inverce_c[i][j + self.c_max_length // next_ncol] ) / (2 * current_root)) current_root *= root # Update _lowerCamelCase : Any = new_inverse_c next_ncol *= 2 # Unpack _lowerCamelCase : Optional[Any] = [round(x[0].real , 8) + round(x[0].imag , 8) * 1j for x in inverce_c] # Remove leading 0's while inverce_c[-1] == 0: inverce_c.pop() return inverce_c def __str__( self) -> Any: _lowerCamelCase : Dict = """A = """ + """ + """.join( F'{coef}*x^{i}' for coef, i in enumerate(self.polyA[: self.len_A])) _lowerCamelCase : List[Any] = """B = """ + """ + """.join( F'{coef}*x^{i}' for coef, i in enumerate(self.polyB[: self.len_B])) _lowerCamelCase : int = """A*B = """ + """ + """.join( F'{coef}*x^{i}' for coef, i in enumerate(self.product)) return F'{a}\n{b}\n{c}' # Unit tests if __name__ == "__main__": import doctest doctest.testmod()
88
0
from bisect import bisect from itertools import accumulate def __snake_case ( __UpperCamelCase : int ,__UpperCamelCase : Tuple ,__UpperCamelCase : str ,__UpperCamelCase : str ): """simple docstring""" A_ = sorted(zip(__UpperCamelCase ,__UpperCamelCase ) ,key=lambda __UpperCamelCase : x[0] / x[1] ,reverse=__UpperCamelCase ) A_ , A_ = [i[0] for i in r], [i[1] for i in r] A_ = list(accumulate(__UpperCamelCase ) ) A_ = bisect(__UpperCamelCase ,__UpperCamelCase ) return ( 0 if k == 0 else sum(vl[:k] ) + (w - acc[k - 1]) * (vl[k]) / (wt[k]) if k != n else sum(vl[:k] ) ) if __name__ == "__main__": import doctest doctest.testmod()
86
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) UpperCAmelCase = { """configuration_vision_encoder_decoder""": ["""VisionEncoderDecoderConfig""", """VisionEncoderDecoderOnnxConfig"""] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase = ["""VisionEncoderDecoderModel"""] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase = ["""TFVisionEncoderDecoderModel"""] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase = ["""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 UpperCAmelCase = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
88
0
import unittest import numpy as np from transformers import RobertaPreLayerNormConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask if is_flax_available(): import jax.numpy as jnp from transformers.models.roberta_prelayernorm.modeling_flax_roberta_prelayernorm import ( FlaxRobertaPreLayerNormForCausalLM, FlaxRobertaPreLayerNormForMaskedLM, FlaxRobertaPreLayerNormForMultipleChoice, FlaxRobertaPreLayerNormForQuestionAnswering, FlaxRobertaPreLayerNormForSequenceClassification, FlaxRobertaPreLayerNormForTokenClassification, FlaxRobertaPreLayerNormModel, ) class UpperCamelCase_ ( unittest.TestCase ): '''simple docstring''' def __init__( self : List[str] , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : str=13 , UpperCAmelCase__ : List[str]=7 , UpperCAmelCase__ : Any=True , UpperCAmelCase__ : Optional[Any]=True , UpperCAmelCase__ : int=True , UpperCAmelCase__ : Optional[Any]=True , UpperCAmelCase__ : Any=99 , UpperCAmelCase__ : Optional[int]=32 , UpperCAmelCase__ : Any=5 , UpperCAmelCase__ : Tuple=4 , UpperCAmelCase__ : Union[str, Any]=37 , UpperCAmelCase__ : int="gelu" , UpperCAmelCase__ : List[str]=0.1 , UpperCAmelCase__ : Tuple=0.1 , UpperCAmelCase__ : Optional[Any]=512 , UpperCAmelCase__ : Any=16 , UpperCAmelCase__ : Dict=2 , UpperCAmelCase__ : Dict=0.02 , UpperCAmelCase__ : Dict=4 , ) ->Optional[Any]: '''simple docstring''' A__ = parent A__ = batch_size A__ = seq_length A__ = is_training A__ = use_attention_mask A__ = use_token_type_ids A__ = use_labels A__ = vocab_size A__ = hidden_size A__ = num_hidden_layers A__ = num_attention_heads A__ = intermediate_size A__ = hidden_act A__ = hidden_dropout_prob A__ = attention_probs_dropout_prob A__ = max_position_embeddings A__ = type_vocab_size A__ = type_sequence_label_size A__ = initializer_range A__ = num_choices def SCREAMING_SNAKE_CASE ( self : Union[str, Any]) ->List[str]: '''simple docstring''' A__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size) A__ = None if self.use_attention_mask: A__ = random_attention_mask([self.batch_size, self.seq_length]) A__ = None if self.use_token_type_ids: A__ = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size) A__ = RobertaPreLayerNormConfig( 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 , ) return config, input_ids, token_type_ids, attention_mask def SCREAMING_SNAKE_CASE ( self : Tuple) ->int: '''simple docstring''' A__ = self.prepare_config_and_inputs() A__ , A__ , A__ , A__ = config_and_inputs A__ = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': attention_mask} return config, inputs_dict def SCREAMING_SNAKE_CASE ( self : Optional[Any]) ->Optional[Any]: '''simple docstring''' A__ = self.prepare_config_and_inputs() A__ , A__ , A__ , A__ = config_and_inputs A__ = True A__ = floats_tensor([self.batch_size, self.seq_length, self.hidden_size]) A__ = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2) return ( config, input_ids, token_type_ids, encoder_hidden_states, encoder_attention_mask, ) @require_flax # Copied from tests.models.roberta.test_modelling_flax_roberta.FlaxRobertaPreLayerNormModelTest with ROBERTA->ROBERTA_PRELAYERNORM,Roberta->RobertaPreLayerNorm,roberta-base->andreasmadsen/efficient_mlm_m0.40 class UpperCamelCase_ ( UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' UpperCAmelCase__ = True UpperCAmelCase__ = ( ( FlaxRobertaPreLayerNormModel, FlaxRobertaPreLayerNormForCausalLM, FlaxRobertaPreLayerNormForMaskedLM, FlaxRobertaPreLayerNormForSequenceClassification, FlaxRobertaPreLayerNormForTokenClassification, FlaxRobertaPreLayerNormForMultipleChoice, FlaxRobertaPreLayerNormForQuestionAnswering, ) if is_flax_available() else () ) def SCREAMING_SNAKE_CASE ( self : List[Any]) ->Optional[int]: '''simple docstring''' A__ = FlaxRobertaPreLayerNormModelTester(self) @slow def SCREAMING_SNAKE_CASE ( self : Union[str, Any]) ->str: '''simple docstring''' for model_class_name in self.all_model_classes: A__ = model_class_name.from_pretrained('''andreasmadsen/efficient_mlm_m0.40''' , from_pt=UpperCAmelCase__) A__ = model(np.ones((1, 1))) self.assertIsNotNone(UpperCAmelCase__) @require_flax class UpperCamelCase_ ( unittest.TestCase ): '''simple docstring''' @slow def SCREAMING_SNAKE_CASE ( self : str) ->Optional[int]: '''simple docstring''' A__ = FlaxRobertaPreLayerNormForMaskedLM.from_pretrained('''andreasmadsen/efficient_mlm_m0.40''' , from_pt=UpperCAmelCase__) A__ = np.array([[0, 31_414, 232, 328, 740, 1_140, 12_695, 69, 46_078, 1_588, 2]] , dtype=jnp.intaa) A__ = model(UpperCAmelCase__)[0] A__ = [1, 11, 50_265] self.assertEqual(list(output.shape) , UpperCAmelCase__) # compare the actual values for a slice. A__ = np.array( [[[40.4880, 18.0199, -5.2367], [-1.8877, -4.0885, 10.7085], [-2.2613, -5.6110, 7.2665]]] , dtype=np.floataa) self.assertTrue(np.allclose(output[:, :3, :3] , UpperCAmelCase__ , atol=1e-4)) @slow def SCREAMING_SNAKE_CASE ( self : str) ->Any: '''simple docstring''' A__ = FlaxRobertaPreLayerNormModel.from_pretrained('''andreasmadsen/efficient_mlm_m0.40''' , from_pt=UpperCAmelCase__) A__ = np.array([[0, 31_414, 232, 328, 740, 1_140, 12_695, 69, 46_078, 1_588, 2]] , dtype=jnp.intaa) A__ = model(UpperCAmelCase__)[0] # compare the actual values for a slice. A__ = np.array( [[[0.0208, -0.0356, 0.0237], [-0.1569, -0.0411, -0.2626], [0.1879, 0.0125, -0.0089]]] , dtype=np.floataa) self.assertTrue(np.allclose(output[:, :3, :3] , UpperCAmelCase__ , atol=1e-4))
87
"""simple docstring""" from datetime import datetime import matplotlib.pyplot as plt import torch def _snake_case ( __snake_case : List[str] ): """simple docstring""" for param in module.parameters(): _lowerCamelCase : Optional[Any] = False def _snake_case ( ): """simple docstring""" _lowerCamelCase : Any = """cuda""" if torch.cuda.is_available() else """cpu""" if torch.backends.mps.is_available() and torch.backends.mps.is_built(): _lowerCamelCase : Any = """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 _snake_case ( __snake_case : Union[str, Any] ): """simple docstring""" _lowerCamelCase : int = plt.imshow(__snake_case ) fig.axes.get_xaxis().set_visible(__snake_case ) fig.axes.get_yaxis().set_visible(__snake_case ) plt.show() def _snake_case ( ): """simple docstring""" _lowerCamelCase : Tuple = datetime.now() _lowerCamelCase : Optional[Any] = current_time.strftime("""%H:%M:%S""" ) return timestamp
88
0
# Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from pathlib import Path import torch from ...utils import is_npu_available, is_xpu_available from .config_args import ClusterConfig, default_json_config_file from .config_utils import SubcommandHelpFormatter SCREAMING_SNAKE_CASE : str = "Create a default config file for Accelerate with only a few flags set." def UpperCamelCase_( lowerCamelCase_="no" , lowerCamelCase_ = default_json_config_file , lowerCamelCase_ = False ) -> Tuple: _lowercase : Optional[Any] = Path(lowerCamelCase_ ) path.parent.mkdir(parents=lowerCamelCase_ , exist_ok=lowerCamelCase_ ) if path.exists(): print( F'''Configuration already exists at {save_location}, will not override. Run `accelerate config` manually or pass a different `save_location`.''' ) return False _lowercase : Optional[Any] = mixed_precision.lower() if mixed_precision not in ["no", "fp16", "bf16", "fp8"]: raise ValueError( F'''`mixed_precision` should be one of \'no\', \'fp16\', \'bf16\', or \'fp8\'. Received {mixed_precision}''' ) _lowercase : Optional[Any] = { 'compute_environment': 'LOCAL_MACHINE', 'mixed_precision': mixed_precision, } if torch.cuda.is_available(): _lowercase : str = torch.cuda.device_count() _lowercase : Dict = num_gpus _lowercase : List[Any] = False if num_gpus > 1: _lowercase : Dict = 'MULTI_GPU' else: _lowercase : Optional[int] = 'NO' elif is_xpu_available() and use_xpu: _lowercase : Any = torch.xpu.device_count() _lowercase : List[str] = num_xpus _lowercase : int = False if num_xpus > 1: _lowercase : Optional[Any] = 'MULTI_XPU' else: _lowercase : Optional[Any] = 'NO' elif is_npu_available(): _lowercase : Union[str, Any] = torch.npu.device_count() _lowercase : Dict = num_npus _lowercase : str = False if num_npus > 1: _lowercase : List[str] = 'MULTI_NPU' else: _lowercase : Union[str, Any] = 'NO' else: _lowercase : int = 0 _lowercase : Dict = True _lowercase : Optional[int] = 1 _lowercase : List[str] = 'NO' _lowercase : Tuple = ClusterConfig(**lowerCamelCase_ ) config.to_json_file(lowerCamelCase_ ) return path def UpperCamelCase_( lowerCamelCase_ , lowerCamelCase_ ) -> List[Any]: _lowercase : Union[str, Any] = parser.add_parser('default' , parents=lowerCamelCase_ , help=lowerCamelCase_ , formatter_class=lowerCamelCase_ ) parser.add_argument( '--config_file' , default=lowerCamelCase_ , help=( 'The path to use to store the config file. Will default to a file named default_config.yaml in the cache ' 'location, which is the content of the environment `HF_HOME` suffixed with \'accelerate\', or if you don\'t have ' 'such an environment variable, your cache directory (\'~/.cache\' or the content of `XDG_CACHE_HOME`) suffixed ' 'with \'huggingface\'.' ) , dest='save_location' , ) parser.add_argument( '--mixed_precision' , choices=['no', 'fp16', 'bf16'] , type=lowerCamelCase_ , help='Whether or not to use mixed precision training. ' 'Choose between FP16 and BF16 (bfloat16) training. ' 'BF16 training is only supported on Nvidia Ampere GPUs and PyTorch 1.10 or later.' , default='no' , ) parser.set_defaults(func=lowerCamelCase_ ) return parser def UpperCamelCase_( lowerCamelCase_ ) -> int: _lowercase : List[str] = write_basic_config(args.mixed_precision , args.save_location ) if config_file: print(F'''accelerate configuration saved at {config_file}''' )
89
"""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 UpperCAmelCase = 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 lowercase__ : __UpperCAmelCase = field( default='''cifar10''' ,metadata={'''help''': '''Name of a dataset from the datasets package'''} ) __UpperCAmelCase = field( default=A_ ,metadata={'''help''': '''The configuration name of the dataset to use (via the datasets library).'''} ) __UpperCAmelCase = field( default=A_ ,metadata={'''help''': '''The column name of the images in the files.'''} ) __UpperCAmelCase = field(default=A_ ,metadata={'''help''': '''A folder containing the training data.'''} ) __UpperCAmelCase = field(default=A_ ,metadata={'''help''': '''A folder containing the validation data.'''} ) __UpperCAmelCase = field( default=0.1_5 ,metadata={'''help''': '''Percent to split off of train for validation.'''} ) __UpperCAmelCase = field( default=A_ ,metadata={ '''help''': ( '''For debugging purposes or quicker training, truncate the number of training examples to this ''' '''value if set.''' ) } ,) __UpperCAmelCase = field( default=A_ ,metadata={ '''help''': ( '''For debugging purposes or quicker training, truncate the number of evaluation examples to this ''' '''value if set.''' ) } ,) def UpperCamelCase_ ( self) -> Any: _lowerCamelCase : Any = {} if self.train_dir is not None: _lowerCamelCase : int = self.train_dir if self.validation_dir is not None: _lowerCamelCase : Tuple = self.validation_dir _lowerCamelCase : Optional[int] = data_files if data_files else None @dataclass class lowercase__ : __UpperCAmelCase = field( default=A_ ,metadata={ '''help''': ( '''The model checkpoint for weights initialization.Don\'t set if you want to train a model from scratch.''' ) } ,) __UpperCAmelCase = field( default=A_ ,metadata={'''help''': '''Pretrained config name or path if not the same as model_name_or_path'''} ) __UpperCAmelCase = field( default=A_ ,metadata={ '''help''': ( '''Override some existing default config settings when a model is trained from scratch. Example: ''' '''n_embd=10,resid_pdrop=0.2,scale_attn_weights=false,summary_type=cls_index''' ) } ,) __UpperCAmelCase = field( default=A_ ,metadata={'''help''': '''Where do you want to store the pretrained models downloaded from s3'''} ) __UpperCAmelCase = field( default='''main''' ,metadata={'''help''': '''The specific model version to use (can be a branch name, tag name or commit id).'''} ,) __UpperCAmelCase = field(default=A_ ,metadata={'''help''': '''Name or path of preprocessor config.'''} ) __UpperCAmelCase = field( default=A_ ,metadata={ '''help''': ( '''Will use the token generated when running `huggingface-cli login` (necessary to use this script ''' '''with private models).''' ) } ,) __UpperCAmelCase = field( default=0.7_5 ,metadata={'''help''': '''The ratio of the number of masked tokens in the input sequence.'''} ) __UpperCAmelCase = field( default=A_ ,metadata={'''help''': '''Whether or not to train with normalized pixel values as target.'''} ) @dataclass class lowercase__ ( A_ ): __UpperCAmelCase = field( default=1e-3 ,metadata={'''help''': '''Base learning rate: absolute_lr = base_lr * total_batch_size / 256.'''} ) def _snake_case ( __snake_case : Optional[Any] ): """simple docstring""" _lowerCamelCase : int = torch.stack([example["""pixel_values"""] for example in examples] ) return {"pixel_values": pixel_values} def _snake_case ( ): """simple docstring""" _lowerCamelCase : Tuple = 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. _lowerCamelCase , _lowerCamelCase , _lowerCamelCase : Union[str, Any] = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: _lowerCamelCase , _lowerCamelCase , _lowerCamelCase : Dict = 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""" , __snake_case , __snake_case ) # Setup logging logging.basicConfig( format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""" , datefmt="""%m/%d/%Y %H:%M:%S""" , handlers=[logging.StreamHandler(sys.stdout )] , ) if training_args.should_log: # The default of training_args.log_level is passive, so we set log level at info here to have that default. transformers.utils.logging.set_verbosity_info() _lowerCamelCase : Union[str, Any] = training_args.get_process_log_level() logger.setLevel(__snake_case ) transformers.utils.logging.set_verbosity(__snake_case ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Log on each process the small summary: logger.warning( F'Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}' + F'distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}' ) logger.info(F'Training/evaluation parameters {training_args}' ) # Detecting last checkpoint. _lowerCamelCase : List[Any] = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: _lowerCamelCase : Optional[int] = 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. _lowerCamelCase : Optional[Any] = 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. _lowerCamelCase : Tuple = None if """validation""" in ds.keys() else data_args.train_val_split if isinstance(data_args.train_val_split , __snake_case ) and data_args.train_val_split > 0.0: _lowerCamelCase : List[str] = ds["""train"""].train_test_split(data_args.train_val_split ) _lowerCamelCase : Union[str, Any] = split["""train"""] _lowerCamelCase : Optional[int] = 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. _lowerCamelCase : 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: _lowerCamelCase : Dict = ViTMAEConfig.from_pretrained(model_args.config_name , **__snake_case ) elif model_args.model_name_or_path: _lowerCamelCase : Union[str, Any] = ViTMAEConfig.from_pretrained(model_args.model_name_or_path , **__snake_case ) else: _lowerCamelCase : Optional[Any] = 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: _lowerCamelCase : str = ViTImageProcessor.from_pretrained(model_args.image_processor_name , **__snake_case ) elif model_args.model_name_or_path: _lowerCamelCase : Dict = ViTImageProcessor.from_pretrained(model_args.model_name_or_path , **__snake_case ) else: _lowerCamelCase : Union[str, Any] = ViTImageProcessor() # create model if model_args.model_name_or_path: _lowerCamelCase : List[Any] = ViTMAEForPreTraining.from_pretrained( model_args.model_name_or_path , from_tf=bool(""".ckpt""" in model_args.model_name_or_path ) , config=__snake_case , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) else: logger.info("""Training new model from scratch""" ) _lowerCamelCase : Union[str, Any] = ViTMAEForPreTraining(__snake_case ) if training_args.do_train: _lowerCamelCase : List[Any] = ds["""train"""].column_names else: _lowerCamelCase : Union[str, Any] = ds["""validation"""].column_names if data_args.image_column_name is not None: _lowerCamelCase : str = data_args.image_column_name elif "image" in column_names: _lowerCamelCase : Optional[Any] = """image""" elif "img" in column_names: _lowerCamelCase : List[Any] = """img""" else: _lowerCamelCase : str = 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: _lowerCamelCase : Dict = image_processor.size["""shortest_edge"""] else: _lowerCamelCase : List[Any] = (image_processor.size["""height"""], image_processor.size["""width"""]) _lowerCamelCase : Tuple = Compose( [ Lambda(lambda __snake_case : img.convert("""RGB""" ) if img.mode != "RGB" else img ), RandomResizedCrop(__snake_case , scale=(0.2, 1.0) , interpolation=InterpolationMode.BICUBIC ), RandomHorizontalFlip(), ToTensor(), Normalize(mean=image_processor.image_mean , std=image_processor.image_std ), ] ) def preprocess_images(__snake_case : Optional[Any] ): _lowerCamelCase : Dict = [transforms(__snake_case ) 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: _lowerCamelCase : int = ds["""train"""].shuffle(seed=training_args.seed ).select(range(data_args.max_train_samples ) ) # Set the training transforms ds["train"].set_transform(__snake_case ) 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: _lowerCamelCase : Union[str, Any] = ( ds["""validation"""].shuffle(seed=training_args.seed ).select(range(data_args.max_eval_samples ) ) ) # Set the validation transforms ds["validation"].set_transform(__snake_case ) # Compute absolute learning rate _lowerCamelCase : Optional[Any] = ( training_args.train_batch_size * training_args.gradient_accumulation_steps * training_args.world_size ) if training_args.base_learning_rate is not None: _lowerCamelCase : Tuple = training_args.base_learning_rate * total_train_batch_size / 256 # Initialize our trainer _lowerCamelCase : Optional[Any] = Trainer( model=__snake_case , args=__snake_case , train_dataset=ds["""train"""] if training_args.do_train else None , eval_dataset=ds["""validation"""] if training_args.do_eval else None , tokenizer=__snake_case , data_collator=__snake_case , ) # Training if training_args.do_train: _lowerCamelCase : Any = None if training_args.resume_from_checkpoint is not None: _lowerCamelCase : List[Any] = training_args.resume_from_checkpoint elif last_checkpoint is not None: _lowerCamelCase : Union[str, Any] = last_checkpoint _lowerCamelCase : Optional[Any] = trainer.train(resume_from_checkpoint=__snake_case ) trainer.save_model() trainer.log_metrics("""train""" , train_result.metrics ) trainer.save_metrics("""train""" , train_result.metrics ) trainer.save_state() # Evaluation if training_args.do_eval: _lowerCamelCase : int = trainer.evaluate() trainer.log_metrics("""eval""" , __snake_case ) trainer.save_metrics("""eval""" , __snake_case ) # Write model card and (optionally) push to hub _lowerCamelCase : Optional[Any] = { """tasks""": """masked-auto-encoding""", """dataset""": data_args.dataset_name, """tags""": ["""masked-auto-encoding"""], } if training_args.push_to_hub: trainer.push_to_hub(**__snake_case ) else: trainer.create_model_card(**__snake_case ) def _snake_case ( __snake_case : Dict ): """simple docstring""" main() if __name__ == "__main__": main()
88
0
'''simple docstring''' import json import os import unittest from transformers.models.xlm.tokenization_xlm import VOCAB_FILES_NAMES, XLMTokenizer from transformers.testing_utils import slow from ...test_tokenization_common import TokenizerTesterMixin class a__ ( a__ , unittest.TestCase ): '''simple docstring''' lowercase__ : List[str] = XLMTokenizer lowercase__ : Optional[int] = False def __SCREAMING_SNAKE_CASE ( self ) -> List[Any]: super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt lowerCAmelCase__ = [ '''l''', '''o''', '''w''', '''e''', '''r''', '''s''', '''t''', '''i''', '''d''', '''n''', '''w</w>''', '''r</w>''', '''t</w>''', '''lo''', '''low''', '''er</w>''', '''low</w>''', '''lowest</w>''', '''newer</w>''', '''wider</w>''', '''<unk>''', ] lowerCAmelCase__ = dict(zip(lowerCamelCase_ , range(len(lowerCamelCase_ ) ) ) ) lowerCAmelCase__ = ['''l o 123''', '''lo w 1456''', '''e r</w> 1789''', ''''''] lowerCAmelCase__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) lowerCAmelCase__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''merges_file'''] ) with open(self.vocab_file , '''w''' ) as fp: fp.write(json.dumps(lowerCamelCase_ ) ) with open(self.merges_file , '''w''' ) as fp: fp.write('''\n'''.join(lowerCamelCase_ ) ) def __SCREAMING_SNAKE_CASE ( self , lowerCamelCase_ ) -> Optional[Any]: lowerCAmelCase__ = '''lower newer''' lowerCAmelCase__ = '''lower newer''' return input_text, output_text def __SCREAMING_SNAKE_CASE ( self ) -> List[Any]: lowerCAmelCase__ = XLMTokenizer(self.vocab_file , self.merges_file ) lowerCAmelCase__ = '''lower''' lowerCAmelCase__ = ['''low''', '''er</w>'''] lowerCAmelCase__ = tokenizer.tokenize(lowerCamelCase_ ) self.assertListEqual(lowerCamelCase_ , lowerCamelCase_ ) lowerCAmelCase__ = tokens + ['''<unk>'''] lowerCAmelCase__ = [14, 15, 20] self.assertListEqual(tokenizer.convert_tokens_to_ids(lowerCamelCase_ ) , lowerCamelCase_ ) @slow def __SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]: lowerCAmelCase__ = XLMTokenizer.from_pretrained('''xlm-mlm-en-2048''' ) lowerCAmelCase__ = tokenizer.encode('''sequence builders''' , add_special_tokens=lowerCamelCase_ ) lowerCAmelCase__ = tokenizer.encode('''multi-sequence build''' , add_special_tokens=lowerCamelCase_ ) lowerCAmelCase__ = tokenizer.build_inputs_with_special_tokens(lowerCamelCase_ ) lowerCAmelCase__ = tokenizer.build_inputs_with_special_tokens(lowerCamelCase_ , lowerCamelCase_ ) assert encoded_sentence == [0] + text + [1] assert encoded_pair == [0] + text + [1] + text_a + [1]
90
"""simple docstring""" import numpy as np def _snake_case ( __snake_case : np.ndarray ): """simple docstring""" return 1 / (1 + np.exp(-vector )) def _snake_case ( __snake_case : np.ndarray ): """simple docstring""" return vector * sigmoid(__snake_case ) if __name__ == "__main__": import doctest doctest.testmod()
88
0
"""simple docstring""" import os import sys import tempfile import unittest import unittest.mock as mock from pathlib import Path from huggingface_hub import HfFolder, delete_repo from huggingface_hub.file_download import http_get from requests.exceptions import HTTPError from transformers import ( AlbertTokenizer, AutoTokenizer, BertTokenizer, BertTokenizerFast, GPTaTokenizerFast, is_tokenizers_available, ) from transformers.testing_utils import TOKEN, USER, is_staging_test, require_tokenizers from transformers.tokenization_utils import Trie sys.path.append(str(Path(__file__).parent.parent / '''utils''')) from test_module.custom_tokenization import CustomTokenizer # noqa E402 if is_tokenizers_available(): from test_module.custom_tokenization_fast import CustomTokenizerFast class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Any: # A mock response for an HTTP head request to emulate server down A = mock.Mock() A = 500 A = {} A = HTTPError A = {} # Download this model to make sure it's in the cache. A = BertTokenizer.from_pretrained('hf-internal-testing/tiny-random-bert' ) # Under the mock environment we get a 500 error when trying to reach the tokenizer. with mock.patch('requests.Session.request' ,return_value=A_ ) as mock_head: A = BertTokenizer.from_pretrained('hf-internal-testing/tiny-random-bert' ) # This check we did call the fake head request mock_head.assert_called() @require_tokenizers def _SCREAMING_SNAKE_CASE ( self : int ) -> Optional[int]: # A mock response for an HTTP head request to emulate server down A = mock.Mock() A = 500 A = {} A = HTTPError A = {} # Download this model to make sure it's in the cache. A = GPTaTokenizerFast.from_pretrained('gpt2' ) # Under the mock environment we get a 500 error when trying to reach the tokenizer. with mock.patch('requests.Session.request' ,return_value=A_ ) as mock_head: A = GPTaTokenizerFast.from_pretrained('gpt2' ) # This check we did call the fake head request mock_head.assert_called() def _SCREAMING_SNAKE_CASE ( self : Any ) -> int: # This test is for deprecated behavior and can be removed in v5 try: A = tempfile.mktemp() with open(A_ ,'wb' ) as f: http_get('https://huggingface.co/albert-base-v1/resolve/main/spiece.model' ,A_ ) A = AlbertTokenizer.from_pretrained(A_ ) finally: os.remove(A_ ) # Supporting this legacy load introduced a weird bug where the tokenizer would load local files if they are in # the current folder and have the right name. if os.path.isfile('tokenizer.json' ): # We skip the test if the user has a `tokenizer.json` in this folder to avoid deleting it. return try: with open('tokenizer.json' ,'wb' ) as f: http_get('https://huggingface.co/hf-internal-testing/tiny-random-bert/blob/main/tokenizer.json' ,A_ ) A = AutoTokenizer.from_pretrained('hf-internal-testing/tiny-random-gpt2' ) # The tiny random BERT has a vocab size of 1024, tiny gpt2 as a vocab size of 1000 self.assertEqual(tokenizer.vocab_size ,1000 ) # Tokenizer should depend on the remote checkpoint, not the local tokenizer.json file. finally: os.remove('tokenizer.json' ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Any: # This test is for deprecated behavior and can be removed in v5 A = AlbertTokenizer.from_pretrained('https://huggingface.co/albert-base-v1/resolve/main/spiece.model' ) @is_staging_test class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' _lowerCamelCase: Optional[Any] = ['''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''bla''', '''blou'''] @classmethod def _SCREAMING_SNAKE_CASE ( cls : Optional[Any] ) -> Optional[Any]: A = TOKEN HfFolder.save_token(A_ ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : str ) -> List[Any]: try: delete_repo(token=cls._token ,repo_id='test-tokenizer' ) except HTTPError: pass try: delete_repo(token=cls._token ,repo_id='valid_org/test-tokenizer-org' ) except HTTPError: pass try: delete_repo(token=cls._token ,repo_id='test-dynamic-tokenizer' ) except HTTPError: pass def _SCREAMING_SNAKE_CASE ( self : Any ) -> List[Any]: with tempfile.TemporaryDirectory() as tmp_dir: A = os.path.join(A_ ,'vocab.txt' ) with open(A_ ,'w' ,encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in self.vocab_tokens] ) ) A = BertTokenizer(A_ ) tokenizer.push_to_hub('test-tokenizer' ,use_auth_token=self._token ) A = BertTokenizer.from_pretrained(F'{USER}/test-tokenizer' ) self.assertDictEqual(new_tokenizer.vocab ,tokenizer.vocab ) # Reset repo delete_repo(token=self._token ,repo_id='test-tokenizer' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained(A_ ,repo_id='test-tokenizer' ,push_to_hub=A_ ,use_auth_token=self._token ) A = BertTokenizer.from_pretrained(F'{USER}/test-tokenizer' ) self.assertDictEqual(new_tokenizer.vocab ,tokenizer.vocab ) def _SCREAMING_SNAKE_CASE ( self : Any ) -> Tuple: with tempfile.TemporaryDirectory() as tmp_dir: A = os.path.join(A_ ,'vocab.txt' ) with open(A_ ,'w' ,encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in self.vocab_tokens] ) ) A = BertTokenizer(A_ ) tokenizer.push_to_hub('valid_org/test-tokenizer-org' ,use_auth_token=self._token ) A = BertTokenizer.from_pretrained('valid_org/test-tokenizer-org' ) self.assertDictEqual(new_tokenizer.vocab ,tokenizer.vocab ) # Reset repo delete_repo(token=self._token ,repo_id='valid_org/test-tokenizer-org' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained( A_ ,repo_id='valid_org/test-tokenizer-org' ,push_to_hub=A_ ,use_auth_token=self._token ) A = BertTokenizer.from_pretrained('valid_org/test-tokenizer-org' ) self.assertDictEqual(new_tokenizer.vocab ,tokenizer.vocab ) @require_tokenizers def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> List[str]: CustomTokenizer.register_for_auto_class() with tempfile.TemporaryDirectory() as tmp_dir: A = os.path.join(A_ ,'vocab.txt' ) with open(A_ ,'w' ,encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in self.vocab_tokens] ) ) A = CustomTokenizer(A_ ) # No fast custom tokenizer tokenizer.push_to_hub('test-dynamic-tokenizer' ,use_auth_token=self._token ) A = AutoTokenizer.from_pretrained(F'{USER}/test-dynamic-tokenizer' ,trust_remote_code=A_ ) # Can't make an isinstance check because the new_model.config is from the CustomTokenizer class of a dynamic module self.assertEqual(tokenizer.__class__.__name__ ,'CustomTokenizer' ) # Fast and slow custom tokenizer CustomTokenizerFast.register_for_auto_class() with tempfile.TemporaryDirectory() as tmp_dir: A = os.path.join(A_ ,'vocab.txt' ) with open(A_ ,'w' ,encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in self.vocab_tokens] ) ) A = BertTokenizerFast.from_pretrained(A_ ) bert_tokenizer.save_pretrained(A_ ) A = CustomTokenizerFast.from_pretrained(A_ ) tokenizer.push_to_hub('test-dynamic-tokenizer' ,use_auth_token=self._token ) A = AutoTokenizer.from_pretrained(F'{USER}/test-dynamic-tokenizer' ,trust_remote_code=A_ ) # Can't make an isinstance check because the new_model.config is from the FakeConfig class of a dynamic module self.assertEqual(tokenizer.__class__.__name__ ,'CustomTokenizerFast' ) A = AutoTokenizer.from_pretrained( F'{USER}/test-dynamic-tokenizer' ,use_fast=A_ ,trust_remote_code=A_ ) # Can't make an isinstance check because the new_model.config is from the FakeConfig class of a dynamic module self.assertEqual(tokenizer.__class__.__name__ ,'CustomTokenizer' ) class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Dict: A = Trie() trie.add('Hello 友達' ) self.assertEqual(trie.data ,{'H': {'e': {'l': {'l': {'o': {' ': {'友': {'達': {'': 1}}}}}}}}} ) trie.add('Hello' ) trie.data self.assertEqual(trie.data ,{'H': {'e': {'l': {'l': {'o': {'': 1, ' ': {'友': {'達': {'': 1}}}}}}}}} ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> List[Any]: A = Trie() self.assertEqual(trie.split('[CLS] This is a extra_id_100' ) ,['[CLS] This is a extra_id_100'] ) trie.add('[CLS]' ) trie.add('extra_id_1' ) trie.add('extra_id_100' ) self.assertEqual(trie.split('[CLS] This is a extra_id_100' ) ,['[CLS]', ' This is a ', 'extra_id_100'] ) def _SCREAMING_SNAKE_CASE ( self : str ) -> List[str]: A = Trie() trie.add('A' ) self.assertEqual(trie.split('ABC' ) ,['A', 'BC'] ) self.assertEqual(trie.split('BCA' ) ,['BC', 'A'] ) def _SCREAMING_SNAKE_CASE ( self : Any ) -> Union[str, Any]: A = Trie() trie.add('TOKEN]' ) trie.add('[SPECIAL_TOKEN]' ) self.assertEqual(trie.split('This is something [SPECIAL_TOKEN]' ) ,['This is something ', '[SPECIAL_TOKEN]'] ) def _SCREAMING_SNAKE_CASE ( self : Any ) -> Tuple: A = Trie() trie.add('A' ) trie.add('P' ) trie.add('[SPECIAL_TOKEN]' ) self.assertEqual(trie.split('This is something [SPECIAL_TOKEN]' ) ,['This is something ', '[SPECIAL_TOKEN]'] ) def _SCREAMING_SNAKE_CASE ( self : Tuple ) -> int: A = Trie() trie.add('AB' ) trie.add('B' ) trie.add('C' ) self.assertEqual(trie.split('ABC' ) ,['AB', 'C'] ) def _SCREAMING_SNAKE_CASE ( self : Dict ) -> Optional[Any]: A = Trie() trie.add('ABC' ) trie.add('B' ) trie.add('CD' ) self.assertEqual(trie.split('ABCD' ) ,['ABC', 'D'] ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> List[str]: # Even if the offsets are wrong, we necessarily output correct string # parts. A = Trie() A = trie.cut_text('ABC' ,[0, 0, 2, 1, 2, 3] ) self.assertEqual(A_ ,['AB', 'C'] )
91
"""simple docstring""" from transformers import HfArgumentParser, TensorFlowBenchmark, TensorFlowBenchmarkArguments def _snake_case ( ): """simple docstring""" _lowerCamelCase : Any = HfArgumentParser(__snake_case ) _lowerCamelCase : int = parser.parse_args_into_dataclasses()[0] _lowerCamelCase : Dict = TensorFlowBenchmark(args=__snake_case ) try: _lowerCamelCase : Optional[int] = parser.parse_args_into_dataclasses()[0] except ValueError as e: _lowerCamelCase : Union[str, Any] = """Arg --no_{0} is no longer used, please use --no-{0} instead.""" _lowerCamelCase : List[str] = """ """.join(str(__snake_case ).split(""" """ )[:-1] ) _lowerCamelCase : Dict = """""" _lowerCamelCase : List[Any] = eval(str(__snake_case ).split(""" """ )[-1] ) _lowerCamelCase : Tuple = [] for arg in depreciated_args: # arg[2:] removes '--' if arg[2:] in TensorFlowBenchmark.deprecated_args: # arg[5:] removes '--no_' full_error_msg += arg_error_msg.format(arg[5:] ) else: wrong_args.append(__snake_case ) if len(__snake_case ) > 0: _lowerCamelCase : Tuple = full_error_msg + begin_error_msg + str(__snake_case ) raise ValueError(__snake_case ) benchmark.run() if __name__ == "__main__": main()
88
0
'''simple docstring''' def _lowerCAmelCase ( __magic_name__ : str ) -> bool: if not all(x.isalpha() for x in string ): raise ValueError('''String must only contain alphabetic characters.''' ) lowercase : List[Any] =sorted(string.lower() ) return len(__magic_name__ ) == len(set(__magic_name__ ) ) if __name__ == "__main__": UpperCamelCase_ = input("""Enter a string """).strip() UpperCamelCase_ = is_isogram(input_str) print(f'''{input_str} is {'an' if isogram else 'not an'} isogram.''')
92
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging UpperCAmelCase = logging.get_logger(__name__) UpperCAmelCase = { """kssteven/ibert-roberta-base""": """https://huggingface.co/kssteven/ibert-roberta-base/resolve/main/config.json""", """kssteven/ibert-roberta-large""": """https://huggingface.co/kssteven/ibert-roberta-large/resolve/main/config.json""", """kssteven/ibert-roberta-large-mnli""": ( """https://huggingface.co/kssteven/ibert-roberta-large-mnli/resolve/main/config.json""" ), } class lowercase__ ( A_ ): __UpperCAmelCase = '''ibert''' def __init__( self , SCREAMING_SNAKE_CASE=3_0522 , SCREAMING_SNAKE_CASE=768 , SCREAMING_SNAKE_CASE=12 , SCREAMING_SNAKE_CASE=12 , SCREAMING_SNAKE_CASE=3072 , SCREAMING_SNAKE_CASE="gelu" , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=512 , SCREAMING_SNAKE_CASE=2 , SCREAMING_SNAKE_CASE=0.02 , SCREAMING_SNAKE_CASE=1e-1_2 , SCREAMING_SNAKE_CASE=1 , SCREAMING_SNAKE_CASE=0 , SCREAMING_SNAKE_CASE=2 , SCREAMING_SNAKE_CASE="absolute" , SCREAMING_SNAKE_CASE=False , SCREAMING_SNAKE_CASE="none" , **SCREAMING_SNAKE_CASE , ) -> Any: super().__init__(pad_token_id=SCREAMING_SNAKE_CASE , bos_token_id=SCREAMING_SNAKE_CASE , eos_token_id=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE) _lowerCamelCase : Optional[int] = vocab_size _lowerCamelCase : Dict = hidden_size _lowerCamelCase : List[str] = num_hidden_layers _lowerCamelCase : int = num_attention_heads _lowerCamelCase : Tuple = hidden_act _lowerCamelCase : str = intermediate_size _lowerCamelCase : Union[str, Any] = hidden_dropout_prob _lowerCamelCase : Tuple = attention_probs_dropout_prob _lowerCamelCase : Any = max_position_embeddings _lowerCamelCase : Dict = type_vocab_size _lowerCamelCase : List[Any] = initializer_range _lowerCamelCase : Dict = layer_norm_eps _lowerCamelCase : List[Any] = position_embedding_type _lowerCamelCase : Any = quant_mode _lowerCamelCase : List[str] = force_dequant class lowercase__ ( A_ ): @property def UpperCamelCase_ ( self) -> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": _lowerCamelCase : Dict = {0: """batch""", 1: """choice""", 2: """sequence"""} else: _lowerCamelCase : Optional[int] = {0: """batch""", 1: """sequence"""} return OrderedDict( [ ("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ])
88
0
"""simple docstring""" import collections import inspect import unittest from typing import Dict, List, Tuple from transformers import MaskFormerSwinConfig from transformers.testing_utils import require_torch, require_torch_multi_gpu, torch_device from transformers.utils import is_torch_available from ...test_backbone_common import BackboneTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import MaskFormerSwinBackbone from transformers.models.maskformer import MaskFormerSwinModel class _lowerCAmelCase : """simple docstring""" def __init__( self , __UpperCAmelCase , __UpperCAmelCase=1_3 , __UpperCAmelCase=3_2 , __UpperCAmelCase=2 , __UpperCAmelCase=3 , __UpperCAmelCase=1_6 , __UpperCAmelCase=[1, 2, 1] , __UpperCAmelCase=[2, 2, 4] , __UpperCAmelCase=2 , __UpperCAmelCase=2.0 , __UpperCAmelCase=True , __UpperCAmelCase=0.0 , __UpperCAmelCase=0.0 , __UpperCAmelCase=0.1 , __UpperCAmelCase="gelu" , __UpperCAmelCase=False , __UpperCAmelCase=True , __UpperCAmelCase=0.02 , __UpperCAmelCase=1E-5 , __UpperCAmelCase=True , __UpperCAmelCase=None , __UpperCAmelCase=True , __UpperCAmelCase=1_0 , __UpperCAmelCase=8 , __UpperCAmelCase=["stage1", "stage2", "stage3"] , __UpperCAmelCase=[1, 2, 3] , ): '''simple docstring''' lowerCAmelCase__ :Tuple = parent lowerCAmelCase__ :str = batch_size lowerCAmelCase__ :List[str] = image_size lowerCAmelCase__ :Optional[int] = patch_size lowerCAmelCase__ :List[str] = num_channels lowerCAmelCase__ :Tuple = embed_dim lowerCAmelCase__ :Optional[int] = depths lowerCAmelCase__ :Optional[Any] = num_heads lowerCAmelCase__ :List[str] = window_size lowerCAmelCase__ :int = mlp_ratio lowerCAmelCase__ :Union[str, Any] = qkv_bias lowerCAmelCase__ :Any = hidden_dropout_prob lowerCAmelCase__ :str = attention_probs_dropout_prob lowerCAmelCase__ :Union[str, Any] = drop_path_rate lowerCAmelCase__ :List[Any] = hidden_act lowerCAmelCase__ :str = use_absolute_embeddings lowerCAmelCase__ :int = patch_norm lowerCAmelCase__ :Tuple = layer_norm_eps lowerCAmelCase__ :Optional[int] = initializer_range lowerCAmelCase__ :List[Any] = is_training lowerCAmelCase__ :Optional[Any] = scope lowerCAmelCase__ :int = use_labels lowerCAmelCase__ :str = type_sequence_label_size lowerCAmelCase__ :List[str] = encoder_stride lowerCAmelCase__ :Tuple = out_features lowerCAmelCase__ :Tuple = out_indices def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :int = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) lowerCAmelCase__ :Any = None if self.use_labels: lowerCAmelCase__ :Optional[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) lowerCAmelCase__ :Any = self.get_config() return config, pixel_values, labels def snake_case ( self ): '''simple docstring''' return MaskFormerSwinConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , embed_dim=self.embed_dim , depths=self.depths , num_heads=self.num_heads , window_size=self.window_size , mlp_ratio=self.mlp_ratio , qkv_bias=self.qkv_bias , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , drop_path_rate=self.drop_path_rate , hidden_act=self.hidden_act , use_absolute_embeddings=self.use_absolute_embeddings , path_norm=self.patch_norm , layer_norm_eps=self.layer_norm_eps , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , out_features=self.out_features , out_indices=self.out_indices , ) def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Tuple = MaskFormerSwinModel(config=__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() lowerCAmelCase__ :int = model(__UpperCAmelCase ) lowerCAmelCase__ :List[str] = ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths ) - 1)) lowerCAmelCase__ :Tuple = int(config.embed_dim * 2 ** (len(config.depths ) - 1) ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, expected_seq_len, expected_dim) ) def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :List[str] = MaskFormerSwinBackbone(config=__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() lowerCAmelCase__ :int = model(__UpperCAmelCase ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) , len(config.out_features ) ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [1_3, 1_6, 1_6, 1_6] ) # verify channels self.parent.assertEqual(len(model.channels ) , len(config.out_features ) ) self.parent.assertListEqual(model.channels , [1_6, 3_2, 6_4] ) # verify ValueError with self.parent.assertRaises(__UpperCAmelCase ): lowerCAmelCase__ :List[str] = ['stem'] lowerCAmelCase__ :Dict = MaskFormerSwinBackbone(config=__UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[str] = self.prepare_config_and_inputs() lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :List[Any] = config_and_inputs lowerCAmelCase__ :Any = {'pixel_values': pixel_values} return config, inputs_dict @require_torch class _lowerCAmelCase ( a , a , unittest.TestCase ): """simple docstring""" __magic_name__ :Dict = ( ( MaskFormerSwinModel, MaskFormerSwinBackbone, ) if is_torch_available() else () ) __magic_name__ :List[Any] = {"""feature-extraction""": MaskFormerSwinModel} if is_torch_available() else {} __magic_name__ :List[str] = False __magic_name__ :Optional[Any] = False __magic_name__ :Union[str, Any] = False __magic_name__ :Optional[Any] = False __magic_name__ :str = False def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Dict = MaskFormerSwinModelTester(self ) lowerCAmelCase__ :Any = ConfigTester(self , config_class=__UpperCAmelCase , embed_dim=3_7 ) @require_torch_multi_gpu @unittest.skip( reason=( '`MaskFormerSwinModel` outputs `hidden_states_spatial_dimensions` which doesn\'t work well with' ' `nn.DataParallel`' ) ) def snake_case ( self ): '''simple docstring''' pass def snake_case ( self ): '''simple docstring''' self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def snake_case ( self ): '''simple docstring''' return def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_backbone(*__UpperCAmelCase ) @unittest.skip('Swin does not use inputs_embeds' ) def snake_case ( self ): '''simple docstring''' pass @unittest.skip('Swin does not support feedforward chunking' ) def snake_case ( self ): '''simple docstring''' pass def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ , lowerCAmelCase__ :List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCAmelCase__ :str = model_class(__UpperCAmelCase ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) lowerCAmelCase__ :Optional[Any] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(__UpperCAmelCase , nn.Linear ) ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ , lowerCAmelCase__ :List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCAmelCase__ :Union[str, Any] = model_class(__UpperCAmelCase ) lowerCAmelCase__ :List[str] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowerCAmelCase__ :Union[str, Any] = [*signature.parameters.keys()] lowerCAmelCase__ :Union[str, Any] = ['pixel_values'] self.assertListEqual(arg_names[:1] , __UpperCAmelCase ) @unittest.skip(reason='MaskFormerSwin is only used as backbone and doesn\'t support output_attentions' ) def snake_case ( self ): '''simple docstring''' pass @unittest.skip(reason='MaskFormerSwin is only used as an internal backbone' ) def snake_case ( self ): '''simple docstring''' pass def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :str = model_class(__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() with torch.no_grad(): lowerCAmelCase__ :Dict = model(**self._prepare_for_class(__UpperCAmelCase , __UpperCAmelCase ) ) lowerCAmelCase__ :Tuple = outputs.hidden_states lowerCAmelCase__ :Any = getattr( self.model_tester , 'expected_num_hidden_layers' , len(self.model_tester.depths ) + 1 ) self.assertEqual(len(__UpperCAmelCase ) , __UpperCAmelCase ) # Swin has a different seq_length lowerCAmelCase__ :Dict = ( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) lowerCAmelCase__ :Any = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [num_patches, self.model_tester.embed_dim] , ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ , lowerCAmelCase__ :str = self.model_tester.prepare_config_and_inputs_for_common() lowerCAmelCase__ :List[Any] = ( self.model_tester.image_size if isinstance(self.model_tester.image_size , collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) for model_class in self.all_model_classes: lowerCAmelCase__ :Dict = True self.check_hidden_states_output(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] lowerCAmelCase__ :Dict = True self.check_hidden_states_output(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ , lowerCAmelCase__ :Any = self.model_tester.prepare_config_and_inputs_for_common() lowerCAmelCase__ :Any = 3 lowerCAmelCase__ :List[Any] = ( self.model_tester.image_size if isinstance(self.model_tester.image_size , collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) lowerCAmelCase__ :str = ( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) lowerCAmelCase__ :Union[str, Any] = image_size[0] + patch_size[0] - (image_size[0] % patch_size[0]) lowerCAmelCase__ :List[str] = image_size[1] + patch_size[1] - (image_size[1] % patch_size[1]) for model_class in self.all_model_classes: lowerCAmelCase__ :Tuple = True self.check_hidden_states_output(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , (padded_height, padded_width) ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] lowerCAmelCase__ :str = True self.check_hidden_states_output(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , (padded_height, padded_width) ) @unittest.skip(reason='MaskFormerSwin doesn\'t have pretrained checkpoints' ) def snake_case ( self ): '''simple docstring''' pass @unittest.skip(reason='This will be fixed once MaskFormerSwin is replaced by native Swin' ) def snake_case ( self ): '''simple docstring''' pass @unittest.skip(reason='This will be fixed once MaskFormerSwin is replaced by native Swin' ) def snake_case ( self ): '''simple docstring''' pass def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ , lowerCAmelCase__ :List[str] = self.model_tester.prepare_config_and_inputs_for_common() def set_nan_tensor_to_zero(__UpperCAmelCase ): lowerCAmelCase__ :List[Any] = 0 return t def check_equivalence(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase={} ): with torch.no_grad(): lowerCAmelCase__ :List[str] = model(**__UpperCAmelCase , return_dict=__UpperCAmelCase , **__UpperCAmelCase ) lowerCAmelCase__ :Any = model(**__UpperCAmelCase , return_dict=__UpperCAmelCase , **__UpperCAmelCase ).to_tuple() def recursive_check(__UpperCAmelCase , __UpperCAmelCase ): if isinstance(__UpperCAmelCase , (List, Tuple) ): for tuple_iterable_value, dict_iterable_value in zip(__UpperCAmelCase , __UpperCAmelCase ): recursive_check(__UpperCAmelCase , __UpperCAmelCase ) elif isinstance(__UpperCAmelCase , __UpperCAmelCase ): for tuple_iterable_value, dict_iterable_value in zip( tuple_object.values() , dict_object.values() ): recursive_check(__UpperCAmelCase , __UpperCAmelCase ) elif tuple_object is None: return else: self.assertTrue( torch.allclose( set_nan_tensor_to_zero(__UpperCAmelCase ) , set_nan_tensor_to_zero(__UpperCAmelCase ) , atol=1E-5 ) , msg=( 'Tuple and dict output are not equal. Difference:' F" {torch.max(torch.abs(tuple_object - dict_object ) )}. Tuple has `nan`:" F" {torch.isnan(__UpperCAmelCase ).any()} and `inf`: {torch.isinf(__UpperCAmelCase )}. Dict has" F" `nan`: {torch.isnan(__UpperCAmelCase ).any()} and `inf`: {torch.isinf(__UpperCAmelCase )}." ) , ) recursive_check(__UpperCAmelCase , __UpperCAmelCase ) for model_class in self.all_model_classes: lowerCAmelCase__ :str = model_class(__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() lowerCAmelCase__ :List[str] = self._prepare_for_class(__UpperCAmelCase , __UpperCAmelCase ) lowerCAmelCase__ :int = self._prepare_for_class(__UpperCAmelCase , __UpperCAmelCase ) check_equivalence(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) lowerCAmelCase__ :Optional[int] = self._prepare_for_class(__UpperCAmelCase , __UpperCAmelCase , return_labels=__UpperCAmelCase ) lowerCAmelCase__ :Dict = self._prepare_for_class(__UpperCAmelCase , __UpperCAmelCase , return_labels=__UpperCAmelCase ) check_equivalence(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) lowerCAmelCase__ :Union[str, Any] = self._prepare_for_class(__UpperCAmelCase , __UpperCAmelCase ) lowerCAmelCase__ :Optional[Any] = self._prepare_for_class(__UpperCAmelCase , __UpperCAmelCase ) check_equivalence(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , {'output_hidden_states': True} ) lowerCAmelCase__ :int = self._prepare_for_class(__UpperCAmelCase , __UpperCAmelCase , return_labels=__UpperCAmelCase ) lowerCAmelCase__ :Dict = self._prepare_for_class(__UpperCAmelCase , __UpperCAmelCase , return_labels=__UpperCAmelCase ) check_equivalence(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , {'output_hidden_states': True} ) @require_torch class _lowerCAmelCase ( unittest.TestCase , a ): """simple docstring""" __magic_name__ :Dict = (MaskFormerSwinBackbone,) if is_torch_available() else () __magic_name__ :str = MaskFormerSwinConfig def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :str = MaskFormerSwinModelTester(self ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ , lowerCAmelCase__ :List[str] = self.model_tester.prepare_config_and_inputs_for_common() lowerCAmelCase__ :Optional[Any] = inputs_dict['pixel_values'].shape[0] for backbone_class in self.all_model_classes: lowerCAmelCase__ :Optional[int] = backbone_class(__UpperCAmelCase ) backbone.to(__UpperCAmelCase ) backbone.eval() lowerCAmelCase__ :List[str] = backbone(**__UpperCAmelCase ) # Test default outputs and verify feature maps self.assertIsInstance(outputs.feature_maps , __UpperCAmelCase ) self.assertTrue(len(outputs.feature_maps ) == len(backbone.channels ) ) for feature_map, n_channels in zip(outputs.feature_maps , backbone.channels ): self.assertTrue(feature_map.shape[:2] , (batch_size, n_channels) ) self.assertIsNone(outputs.hidden_states ) self.assertIsNone(outputs.attentions ) # Test output_hidden_states=True lowerCAmelCase__ :Any = backbone(**__UpperCAmelCase , output_hidden_states=__UpperCAmelCase ) self.assertIsNotNone(outputs.hidden_states ) self.assertTrue(len(outputs.hidden_states ) , len(backbone.stage_names ) ) # We skip the stem layer for hidden_states, n_channels in zip(outputs.hidden_states[1:] , backbone.channels ): for hidden_state in hidden_states: # Hidden states are in the format (batch_size, (height * width), n_channels) lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :Tuple = hidden_state.shape self.assertTrue((h_batch_size, h_n_channels) , (batch_size, n_channels) ) # Test output_attentions=True if self.has_attentions: lowerCAmelCase__ :Tuple = backbone(**__UpperCAmelCase , output_attentions=__UpperCAmelCase ) self.assertIsNotNone(outputs.attentions )
93
"""simple docstring""" from __future__ import annotations import queue class lowercase__ : def __init__( self , SCREAMING_SNAKE_CASE) -> int: _lowerCamelCase : int = data _lowerCamelCase : List[str] = None _lowerCamelCase : Any = None def _snake_case ( ): """simple docstring""" print("""\n********Press N to stop entering at any point of time********\n""" ) _lowerCamelCase : Optional[int] = input("""Enter the value of the root node: """ ).strip().lower() _lowerCamelCase : queue.Queue = queue.Queue() _lowerCamelCase : Optional[int] = TreeNode(int(__snake_case ) ) q.put(__snake_case ) while not q.empty(): _lowerCamelCase : Tuple = q.get() _lowerCamelCase : Any = F'Enter the left node of {node_found.data}: ' _lowerCamelCase : Union[str, Any] = input(__snake_case ).strip().lower() or """n""" if check == "n": return tree_node _lowerCamelCase : Dict = TreeNode(int(__snake_case ) ) _lowerCamelCase : List[str] = left_node q.put(__snake_case ) _lowerCamelCase : Optional[int] = F'Enter the right node of {node_found.data}: ' _lowerCamelCase : Optional[Any] = input(__snake_case ).strip().lower() or """n""" if check == "n": return tree_node _lowerCamelCase : List[Any] = TreeNode(int(__snake_case ) ) _lowerCamelCase : List[Any] = right_node q.put(__snake_case ) raise def _snake_case ( __snake_case : TreeNode ): """simple docstring""" if not isinstance(__snake_case , __snake_case ) or not node: return print(node.data , end=""",""" ) pre_order(node.left ) pre_order(node.right ) def _snake_case ( __snake_case : TreeNode ): """simple docstring""" if not isinstance(__snake_case , __snake_case ) or not node: return in_order(node.left ) print(node.data , end=""",""" ) in_order(node.right ) def _snake_case ( __snake_case : TreeNode ): """simple docstring""" if not isinstance(__snake_case , __snake_case ) or not node: return post_order(node.left ) post_order(node.right ) print(node.data , end=""",""" ) def _snake_case ( __snake_case : TreeNode ): """simple docstring""" if not isinstance(__snake_case , __snake_case ) or not node: return _lowerCamelCase : queue.Queue = queue.Queue() q.put(__snake_case ) while not q.empty(): _lowerCamelCase : Any = q.get() print(node_dequeued.data , end=""",""" ) if node_dequeued.left: q.put(node_dequeued.left ) if node_dequeued.right: q.put(node_dequeued.right ) def _snake_case ( __snake_case : TreeNode ): """simple docstring""" if not isinstance(__snake_case , __snake_case ) or not node: return _lowerCamelCase : queue.Queue = queue.Queue() q.put(__snake_case ) while not q.empty(): _lowerCamelCase : Optional[Any] = [] while not q.empty(): _lowerCamelCase : Dict = q.get() print(node_dequeued.data , end=""",""" ) if node_dequeued.left: list_.append(node_dequeued.left ) if node_dequeued.right: list_.append(node_dequeued.right ) print() for node in list_: q.put(__snake_case ) def _snake_case ( __snake_case : TreeNode ): """simple docstring""" if not isinstance(__snake_case , __snake_case ) or not node: return _lowerCamelCase : list[TreeNode] = [] _lowerCamelCase : Optional[int] = node while n or stack: while n: # start from root node, find its left child print(n.data , end=""",""" ) stack.append(__snake_case ) _lowerCamelCase : Tuple = n.left # end of while means current node doesn't have left child _lowerCamelCase : Optional[Any] = stack.pop() # start to traverse its right child _lowerCamelCase : Dict = n.right def _snake_case ( __snake_case : TreeNode ): """simple docstring""" if not isinstance(__snake_case , __snake_case ) or not node: return _lowerCamelCase : list[TreeNode] = [] _lowerCamelCase : int = node while n or stack: while n: stack.append(__snake_case ) _lowerCamelCase : Any = n.left _lowerCamelCase : Optional[Any] = stack.pop() print(n.data , end=""",""" ) _lowerCamelCase : List[Any] = n.right def _snake_case ( __snake_case : TreeNode ): """simple docstring""" if not isinstance(__snake_case , __snake_case ) or not node: return _lowerCamelCase , _lowerCamelCase : Union[str, Any] = [], [] _lowerCamelCase : Optional[Any] = node stacka.append(__snake_case ) while stacka: # to find the reversed order of post order, store it in stack2 _lowerCamelCase : Union[str, Any] = stacka.pop() if n.left: stacka.append(n.left ) if n.right: stacka.append(n.right ) stacka.append(__snake_case ) while stacka: # pop up from stack2 will be the post order print(stacka.pop().data , end=""",""" ) def _snake_case ( __snake_case : str = "" , __snake_case : Any=50 , __snake_case : List[str]="*" ): """simple docstring""" if not s: return "\n" + width * char _lowerCamelCase , _lowerCamelCase : Optional[int] = divmod(width - len(__snake_case ) - 2 , 2 ) return F'{left * char} {s} {(left + extra) * char}' if __name__ == "__main__": import doctest doctest.testmod() print(prompt("""Binary Tree Traversals""")) UpperCAmelCase = build_tree() print(prompt("""Pre Order Traversal""")) pre_order(node) print(prompt() + """\n""") print(prompt("""In Order Traversal""")) in_order(node) print(prompt() + """\n""") print(prompt("""Post Order Traversal""")) post_order(node) print(prompt() + """\n""") print(prompt("""Level Order Traversal""")) level_order(node) print(prompt() + """\n""") print(prompt("""Actual Level Order Traversal""")) level_order_actual(node) print("""*""" * 50 + """\n""") print(prompt("""Pre Order Traversal - Iteration Version""")) pre_order_iter(node) print(prompt() + """\n""") print(prompt("""In Order Traversal - Iteration Version""")) in_order_iter(node) print(prompt() + """\n""") print(prompt("""Post Order Traversal - Iteration Version""")) post_order_iter(node) print(prompt())
88
0
'''simple docstring''' import json import os import tempfile from transformers.testing_utils import check_json_file_has_correct_format class UpperCAmelCase_ : """simple docstring""" UpperCamelCase_ = None def A__ ( self : List[str] ) -> str: '''simple docstring''' lowercase : Any =self.feature_extraction_class(**self.feat_extract_dict ) lowercase : Dict =json.loads(feat_extract.to_json_string() ) for key, value in self.feat_extract_dict.items(): self.assertEqual(obj[key] , UpperCAmelCase ) def A__ ( self : Any ) -> List[Any]: '''simple docstring''' lowercase : List[Any] =self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: lowercase : List[str] =os.path.join(UpperCAmelCase , '''feat_extract.json''' ) feat_extract_first.to_json_file(UpperCAmelCase ) lowercase : str =self.feature_extraction_class.from_json_file(UpperCAmelCase ) self.assertEqual(feat_extract_second.to_dict() , feat_extract_first.to_dict() ) def A__ ( self : Dict ) -> int: '''simple docstring''' lowercase : List[Any] =self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: lowercase : Optional[int] =feat_extract_first.save_pretrained(UpperCAmelCase )[0] check_json_file_has_correct_format(UpperCAmelCase ) lowercase : Optional[int] =self.feature_extraction_class.from_pretrained(UpperCAmelCase ) self.assertEqual(feat_extract_second.to_dict() , feat_extract_first.to_dict() ) def A__ ( self : List[str] ) -> Optional[int]: '''simple docstring''' lowercase : Union[str, Any] =self.feature_extraction_class() self.assertIsNotNone(UpperCAmelCase )
94
"""simple docstring""" from __future__ import annotations import unittest from transformers import XGLMConfig, XGLMTokenizer, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers.models.xglm.modeling_tf_xglm import ( TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST, TFXGLMForCausalLM, TFXGLMModel, ) @require_tf class lowercase__ : __UpperCAmelCase = XGLMConfig __UpperCAmelCase = {} __UpperCAmelCase = '''gelu''' def __init__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=14 , SCREAMING_SNAKE_CASE=7 , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=99 , SCREAMING_SNAKE_CASE=32 , SCREAMING_SNAKE_CASE=2 , SCREAMING_SNAKE_CASE=4 , SCREAMING_SNAKE_CASE=37 , SCREAMING_SNAKE_CASE="gelu" , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=512 , SCREAMING_SNAKE_CASE=0.02 , ) -> List[str]: _lowerCamelCase : Optional[int] = parent _lowerCamelCase : int = batch_size _lowerCamelCase : str = seq_length _lowerCamelCase : Any = is_training _lowerCamelCase : int = use_input_mask _lowerCamelCase : Union[str, Any] = use_labels _lowerCamelCase : str = vocab_size _lowerCamelCase : List[str] = d_model _lowerCamelCase : List[Any] = num_hidden_layers _lowerCamelCase : Dict = num_attention_heads _lowerCamelCase : int = ffn_dim _lowerCamelCase : str = activation_function _lowerCamelCase : Optional[int] = activation_dropout _lowerCamelCase : Tuple = attention_dropout _lowerCamelCase : Tuple = max_position_embeddings _lowerCamelCase : Dict = initializer_range _lowerCamelCase : Optional[Any] = None _lowerCamelCase : Union[str, Any] = 0 _lowerCamelCase : List[Any] = 2 _lowerCamelCase : str = 1 def UpperCamelCase_ ( self) -> int: return XGLMConfig.from_pretrained("""facebook/xglm-564M""") def UpperCamelCase_ ( self) -> int: _lowerCamelCase : Union[str, Any] = tf.clip_by_value( ids_tensor([self.batch_size, self.seq_length] , self.vocab_size) , clip_value_min=0 , clip_value_max=3) _lowerCamelCase : str = None if self.use_input_mask: _lowerCamelCase : Union[str, Any] = random_attention_mask([self.batch_size, self.seq_length]) _lowerCamelCase : Tuple = self.get_config() _lowerCamelCase : Optional[int] = floats_tensor([self.num_hidden_layers, self.num_attention_heads] , 2) return ( config, input_ids, input_mask, head_mask, ) def UpperCamelCase_ ( self) -> Optional[int]: return XGLMConfig( vocab_size=self.vocab_size , d_model=self.hidden_size , num_layers=self.num_hidden_layers , attention_heads=self.num_attention_heads , ffn_dim=self.ffn_dim , activation_function=self.activation_function , activation_dropout=self.activation_dropout , attention_dropout=self.attention_dropout , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , use_cache=SCREAMING_SNAKE_CASE , bos_token_id=self.bos_token_id , eos_token_id=self.eos_token_id , pad_token_id=self.pad_token_id , return_dict=SCREAMING_SNAKE_CASE , ) def UpperCamelCase_ ( self) -> Optional[int]: _lowerCamelCase : List[Any] = self.prepare_config_and_inputs() ( ( _lowerCamelCase ) , ( _lowerCamelCase ) , ( _lowerCamelCase ) , ( _lowerCamelCase ) , ) : str = config_and_inputs _lowerCamelCase : Optional[Any] = { """input_ids""": input_ids, """head_mask""": head_mask, } return config, inputs_dict @require_tf class lowercase__ ( A_ ,A_ ,unittest.TestCase ): __UpperCAmelCase = (TFXGLMModel, TFXGLMForCausalLM) if is_tf_available() else () __UpperCAmelCase = (TFXGLMForCausalLM,) if is_tf_available() else () __UpperCAmelCase = ( {'''feature-extraction''': TFXGLMModel, '''text-generation''': TFXGLMForCausalLM} if is_tf_available() else {} ) __UpperCAmelCase = False __UpperCAmelCase = False __UpperCAmelCase = False def UpperCamelCase_ ( self) -> Optional[Any]: _lowerCamelCase : Optional[Any] = TFXGLMModelTester(self) _lowerCamelCase : str = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE , n_embd=37) def UpperCamelCase_ ( self) -> Dict: self.config_tester.run_common_tests() @slow def UpperCamelCase_ ( self) -> List[Any]: for model_name in TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _lowerCamelCase : Tuple = TFXGLMModel.from_pretrained(SCREAMING_SNAKE_CASE) self.assertIsNotNone(SCREAMING_SNAKE_CASE) @unittest.skip(reason="""Currently, model embeddings are going to undergo a major refactor.""") def UpperCamelCase_ ( self) -> List[Any]: super().test_resize_token_embeddings() @require_tf class lowercase__ ( unittest.TestCase ): @slow def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE=True) -> List[Any]: _lowerCamelCase : List[str] = TFXGLMForCausalLM.from_pretrained("""facebook/xglm-564M""") _lowerCamelCase : Union[str, Any] = tf.convert_to_tensor([[2, 268, 9865]] , dtype=tf.intaa) # The dog # </s> The dog is a very friendly dog. He is very affectionate and loves to play with other # fmt: off _lowerCamelCase : Dict = [2, 268, 9865, 67, 11, 1988, 5_7252, 9865, 5, 984, 67, 1988, 21_3838, 1658, 53, 7_0446, 33, 6657, 278, 1581] # fmt: on _lowerCamelCase : str = model.generate(SCREAMING_SNAKE_CASE , do_sample=SCREAMING_SNAKE_CASE , num_beams=1) if verify_outputs: self.assertListEqual(output_ids[0].numpy().tolist() , SCREAMING_SNAKE_CASE) @slow def UpperCamelCase_ ( self) -> int: _lowerCamelCase : int = XGLMTokenizer.from_pretrained("""facebook/xglm-564M""") _lowerCamelCase : Tuple = TFXGLMForCausalLM.from_pretrained("""facebook/xglm-564M""") tf.random.set_seed(0) _lowerCamelCase : Union[str, Any] = tokenizer("""Today is a nice day and""" , return_tensors="""tf""") _lowerCamelCase : Any = tokenized.input_ids # forces the generation to happen on CPU, to avoid GPU-related quirks (and assure same output regardless of the available devices) with tf.device(""":/CPU:0"""): _lowerCamelCase : Any = model.generate(SCREAMING_SNAKE_CASE , do_sample=SCREAMING_SNAKE_CASE , seed=[7, 0]) _lowerCamelCase : List[str] = tokenizer.decode(output_ids[0] , skip_special_tokens=SCREAMING_SNAKE_CASE) _lowerCamelCase : Any = ( """Today is a nice day and warm evening here over Southern Alberta!! Today when they closed schools due""" ) self.assertEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) @slow def UpperCamelCase_ ( self) -> List[Any]: _lowerCamelCase : Optional[Any] = TFXGLMForCausalLM.from_pretrained("""facebook/xglm-564M""") _lowerCamelCase : Any = XGLMTokenizer.from_pretrained("""facebook/xglm-564M""") _lowerCamelCase : List[Any] = """left""" # use different length sentences to test batching _lowerCamelCase : List[Any] = [ """This is an extremelly long sentence that only exists to test the ability of the model to cope with """ """left-padding, such as in batched generation. The output for the sequence below should be the same """ """regardless of whether left padding is applied or not. When""", """Hello, my dog is a little""", ] _lowerCamelCase : Union[str, Any] = tokenizer(SCREAMING_SNAKE_CASE , return_tensors="""tf""" , padding=SCREAMING_SNAKE_CASE) _lowerCamelCase : int = inputs["""input_ids"""] _lowerCamelCase : List[Any] = model.generate(input_ids=SCREAMING_SNAKE_CASE , attention_mask=inputs["""attention_mask"""] , max_new_tokens=12) _lowerCamelCase : List[str] = tokenizer(sentences[0] , return_tensors="""tf""").input_ids _lowerCamelCase : Optional[Any] = model.generate(input_ids=SCREAMING_SNAKE_CASE , max_new_tokens=12) _lowerCamelCase : Tuple = tokenizer(sentences[1] , return_tensors="""tf""").input_ids _lowerCamelCase : int = model.generate(input_ids=SCREAMING_SNAKE_CASE , max_new_tokens=12) _lowerCamelCase : Optional[int] = tokenizer.batch_decode(SCREAMING_SNAKE_CASE , skip_special_tokens=SCREAMING_SNAKE_CASE) _lowerCamelCase : Optional[Any] = tokenizer.decode(output_non_padded[0] , skip_special_tokens=SCREAMING_SNAKE_CASE) _lowerCamelCase : Union[str, Any] = tokenizer.decode(output_padded[0] , skip_special_tokens=SCREAMING_SNAKE_CASE) _lowerCamelCase : Tuple = [ """This is an extremelly long sentence that only exists to test the ability of the model to cope with """ """left-padding, such as in batched generation. The output for the sequence below should be the same """ """regardless of whether left padding is applied or not. When left padding is applied, the sequence will be """ """a single""", """Hello, my dog is a little bit of a shy one, but he is very friendly""", ] self.assertListEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) self.assertListEqual(SCREAMING_SNAKE_CASE , [non_padded_sentence, padded_sentence])
88
0
"""simple docstring""" import unittest from transformers.testing_utils import require_bsa from transformers.utils import is_bsa_available from ...test_feature_extraction_common import FeatureExtractionSavingTestMixin if is_bsa_available(): from transformers import MarkupLMFeatureExtractor class UpperCamelCase_ (unittest.TestCase ): def __init__( self : str , lowerCAmelCase_ : Any ) -> Tuple: UpperCAmelCase_ : List[str] = parent def _SCREAMING_SNAKE_CASE ( self : Tuple ) -> Optional[Any]: return {} def snake_case ( ): UpperCAmelCase_ : Dict = "<HTML>\n\n <HEAD>\n <TITLE>sample document</TITLE>\n </HEAD>\n\n <BODY BGCOLOR=\"FFFFFF\">\n <HR>\n <a href=\"http://google.com\">Goog</a>\n <H1>This is one header</H1>\n <H2>This is a another Header</H2>\n <P>Travel from\n <P>\n <B>SFO to JFK</B>\n <BR>\n <B><I>on May 2, 2015 at 2:00 pm. For details go to confirm.com </I></B>\n <HR>\n <div style=\"color:#0000FF\">\n <h3>Traveler <b> name </b> is\n <p> John Doe </p>\n </div>" UpperCAmelCase_ : List[Any] = "\n <!DOCTYPE html>\n <html>\n <body>\n\n <h1>My First Heading</h1>\n <p>My first paragraph.</p>\n\n </body>\n </html>\n " return [html_string_a, html_string_a] @require_bsa class UpperCamelCase_ (__A , unittest.TestCase ): __magic_name__ = MarkupLMFeatureExtractor if is_bsa_available() else None def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Optional[int]: UpperCAmelCase_ : List[str] = MarkupLMFeatureExtractionTester(self ) @property def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Optional[Any]: return self.feature_extract_tester.prepare_feat_extract_dict() def _SCREAMING_SNAKE_CASE ( self : Any ) -> Optional[int]: # Initialize feature_extractor UpperCAmelCase_ : Optional[Any] = self.feature_extraction_class() # Test not batched input UpperCAmelCase_ : Dict = get_html_strings()[0] UpperCAmelCase_ : Dict = feature_extractor(lowerCAmelCase_ ) # fmt: off UpperCAmelCase_ : Union[str, Any] = [["sample document", "Goog", "This is one header", "This is a another Header", "Travel from", "SFO to JFK", "on May 2, 2015 at 2:00 pm. For details go to confirm.com", "Traveler", "name", "is", "John Doe"]] UpperCAmelCase_ : List[str] = [["/html/head/title", "/html/body/a", "/html/body/h1", "/html/body/h2", "/html/body/p", "/html/body/p/p/b[1]", "/html/body/p/p/b[2]/i", "/html/body/p/p/div/h3", "/html/body/p/p/div/h3/b", "/html/body/p/p/div/h3", "/html/body/p/p/div/h3/p"]] # fmt: on self.assertEqual(encoding.nodes , lowerCAmelCase_ ) self.assertEqual(encoding.xpaths , lowerCAmelCase_ ) # Test batched UpperCAmelCase_ : Any = get_html_strings() UpperCAmelCase_ : List[Any] = feature_extractor(lowerCAmelCase_ ) # fmt: off UpperCAmelCase_ : List[Any] = expected_nodes + [["My First Heading", "My first paragraph."]] UpperCAmelCase_ : Tuple = expected_xpaths + [["/html/body/h1", "/html/body/p"]] self.assertEqual(len(encoding.nodes ) , 2 ) self.assertEqual(len(encoding.xpaths ) , 2 ) self.assertEqual(encoding.nodes , lowerCAmelCase_ ) self.assertEqual(encoding.xpaths , lowerCAmelCase_ )
95
"""simple docstring""" from collections import defaultdict def _snake_case ( __snake_case : str , __snake_case : str ): """simple docstring""" _lowerCamelCase : Tuple = first_str.lower().strip() _lowerCamelCase : int = second_str.lower().strip() # Remove whitespace _lowerCamelCase : Any = first_str.replace(""" """ , """""" ) _lowerCamelCase : List[str] = second_str.replace(""" """ , """""" ) # Strings of different lengths are not anagrams if len(__snake_case ) != len(__snake_case ): return False # Default values for count should be 0 _lowerCamelCase : defaultdict[str, int] = defaultdict(__snake_case ) # For each character in input strings, # increment count in the corresponding for i in range(len(__snake_case ) ): count[first_str[i]] += 1 count[second_str[i]] -= 1 return all(_count == 0 for _count in count.values() ) if __name__ == "__main__": from doctest import testmod testmod() UpperCAmelCase = input("""Enter the first string """).strip() UpperCAmelCase = input("""Enter the second string """).strip() UpperCAmelCase = check_anagrams(input_a, input_b) print(f'''{input_a} and {input_b} are {"" if status else "not "}anagrams.''')
88
0
"""simple docstring""" from argparse import ArgumentParser from .env import EnvironmentCommand def a ( ) -> Tuple: __magic_name__: Optional[int] = ArgumentParser("""Diffusers CLI tool""" , usage="""diffusers-cli <command> [<args>]""" ) __magic_name__: Any = parser.add_subparsers(help="""diffusers-cli command helpers""" ) # Register commands EnvironmentCommand.register_subcommand(__UpperCAmelCase ) # Let's go __magic_name__: int = parser.parse_args() if not hasattr(__UpperCAmelCase , """func""" ): parser.print_help() exit(1 ) # Run __magic_name__: Optional[Any] = args.func(__UpperCAmelCase ) service.run() if __name__ == "__main__": main()
96
"""simple docstring""" from __future__ import annotations from numpy import array, cos, cross, floataa, radians, sin from numpy.typing import NDArray def _snake_case ( __snake_case : float , __snake_case : float , __snake_case : bool = False ): """simple docstring""" if radian_mode: return [magnitude * cos(__snake_case ), magnitude * sin(__snake_case )] return [magnitude * cos(radians(__snake_case ) ), magnitude * sin(radians(__snake_case ) )] def _snake_case ( __snake_case : NDArray[floataa] , __snake_case : NDArray[floataa] , __snake_case : float = 10**-1 ): """simple docstring""" _lowerCamelCase : NDArray[floataa] = cross(__snake_case , __snake_case ) _lowerCamelCase : float = sum(__snake_case ) return abs(__snake_case ) < eps if __name__ == "__main__": # Test to check if it works UpperCAmelCase = array( [ polar_force(718.4, 180 - 30), polar_force(879.54, 45), polar_force(100, -90), ] ) UpperCAmelCase = array([[0, 0], [0, 0], [0, 0]]) assert in_static_equilibrium(forces, location) # Problem 1 in image_data/2D_problems.jpg UpperCAmelCase = array( [ polar_force(30 * 9.81, 15), polar_force(215, 180 - 45), polar_force(264, 90 - 30), ] ) UpperCAmelCase = array([[0, 0], [0, 0], [0, 0]]) assert in_static_equilibrium(forces, location) # Problem in image_data/2D_problems_1.jpg UpperCAmelCase = array([[0, -2000], [0, -1200], [0, 1_5600], [0, -1_2400]]) UpperCAmelCase = array([[0, 0], [6, 0], [10, 0], [12, 0]]) assert in_static_equilibrium(forces, location) import doctest doctest.testmod()
88
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) __a = { 'configuration_roberta_prelayernorm': [ 'ROBERTA_PRELAYERNORM_PRETRAINED_CONFIG_ARCHIVE_MAP', 'RobertaPreLayerNormConfig', 'RobertaPreLayerNormOnnxConfig', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __a = [ 'ROBERTA_PRELAYERNORM_PRETRAINED_MODEL_ARCHIVE_LIST', 'RobertaPreLayerNormForCausalLM', 'RobertaPreLayerNormForMaskedLM', 'RobertaPreLayerNormForMultipleChoice', 'RobertaPreLayerNormForQuestionAnswering', 'RobertaPreLayerNormForSequenceClassification', 'RobertaPreLayerNormForTokenClassification', 'RobertaPreLayerNormModel', 'RobertaPreLayerNormPreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __a = [ 'TF_ROBERTA_PRELAYERNORM_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFRobertaPreLayerNormForCausalLM', 'TFRobertaPreLayerNormForMaskedLM', 'TFRobertaPreLayerNormForMultipleChoice', 'TFRobertaPreLayerNormForQuestionAnswering', 'TFRobertaPreLayerNormForSequenceClassification', 'TFRobertaPreLayerNormForTokenClassification', 'TFRobertaPreLayerNormMainLayer', 'TFRobertaPreLayerNormModel', 'TFRobertaPreLayerNormPreTrainedModel', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __a = [ 'FlaxRobertaPreLayerNormForCausalLM', 'FlaxRobertaPreLayerNormForMaskedLM', 'FlaxRobertaPreLayerNormForMultipleChoice', 'FlaxRobertaPreLayerNormForQuestionAnswering', 'FlaxRobertaPreLayerNormForSequenceClassification', 'FlaxRobertaPreLayerNormForTokenClassification', 'FlaxRobertaPreLayerNormModel', 'FlaxRobertaPreLayerNormPreTrainedModel', ] if TYPE_CHECKING: from .configuration_roberta_prelayernorm import ( ROBERTA_PRELAYERNORM_PRETRAINED_CONFIG_ARCHIVE_MAP, RobertaPreLayerNormConfig, RobertaPreLayerNormOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_roberta_prelayernorm import ( ROBERTA_PRELAYERNORM_PRETRAINED_MODEL_ARCHIVE_LIST, RobertaPreLayerNormForCausalLM, RobertaPreLayerNormForMaskedLM, RobertaPreLayerNormForMultipleChoice, RobertaPreLayerNormForQuestionAnswering, RobertaPreLayerNormForSequenceClassification, RobertaPreLayerNormForTokenClassification, RobertaPreLayerNormModel, RobertaPreLayerNormPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_roberta_prelayernorm import ( TF_ROBERTA_PRELAYERNORM_PRETRAINED_MODEL_ARCHIVE_LIST, TFRobertaPreLayerNormForCausalLM, TFRobertaPreLayerNormForMaskedLM, TFRobertaPreLayerNormForMultipleChoice, TFRobertaPreLayerNormForQuestionAnswering, TFRobertaPreLayerNormForSequenceClassification, TFRobertaPreLayerNormForTokenClassification, TFRobertaPreLayerNormMainLayer, TFRobertaPreLayerNormModel, TFRobertaPreLayerNormPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_roberta_prelayernorm import ( FlaxRobertaPreLayerNormForCausalLM, FlaxRobertaPreLayerNormForMaskedLM, FlaxRobertaPreLayerNormForMultipleChoice, FlaxRobertaPreLayerNormForQuestionAnswering, FlaxRobertaPreLayerNormForSequenceClassification, FlaxRobertaPreLayerNormForTokenClassification, FlaxRobertaPreLayerNormModel, FlaxRobertaPreLayerNormPreTrainedModel, ) else: import sys __a = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
97
"""simple docstring""" import random def _snake_case ( __snake_case : List[Any] , __snake_case : List[Any] , __snake_case : int ): """simple docstring""" _lowerCamelCase : List[str] = a[left_index] _lowerCamelCase : Dict = left_index + 1 for j in range(left_index + 1 , __snake_case ): if a[j] < pivot: _lowerCamelCase , _lowerCamelCase : List[str] = a[i], a[j] i += 1 _lowerCamelCase , _lowerCamelCase : Optional[int] = a[i - 1], a[left_index] return i - 1 def _snake_case ( __snake_case : Tuple , __snake_case : List[str] , __snake_case : List[str] ): """simple docstring""" if left < right: _lowerCamelCase : Any = random.randint(__snake_case , right - 1 ) _lowerCamelCase , _lowerCamelCase : Optional[Any] = ( a[left], a[pivot], ) # switches the pivot with the left most bound _lowerCamelCase : List[str] = partition(__snake_case , __snake_case , __snake_case ) quick_sort_random( __snake_case , __snake_case , __snake_case ) # recursive quicksort to the left of the pivot point quick_sort_random( __snake_case , pivot_index + 1 , __snake_case ) # recursive quicksort to the right of the pivot point def _snake_case ( ): """simple docstring""" _lowerCamelCase : Union[str, Any] = input("""Enter numbers separated by a comma:\n""" ).strip() _lowerCamelCase : int = [int(__snake_case ) for item in user_input.split(""",""" )] quick_sort_random(__snake_case , 0 , len(__snake_case ) ) print(__snake_case ) if __name__ == "__main__": main()
88
0
'''simple docstring''' from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxSeqaSeqConfigWithPast from ...utils import logging lowercase__ : List[Any] = logging.get_logger(__name__) lowercase__ : str = { 'google/umt5-small': 'https://huggingface.co/google/umt5-small/resolve/main/config.json', # See all umt5 models at https://huggingface.co/models?filter=umt5 } class __lowerCAmelCase ( __magic_name__ ): """simple docstring""" _snake_case : str = 'umt5' _snake_case : Dict = ['past_key_values'] def __init__( self : Union[str, Any] , lowerCAmelCase__ : Optional[Any]=250112 , lowerCAmelCase__ : Optional[int]=512 , lowerCAmelCase__ : Optional[int]=64 , lowerCAmelCase__ : Optional[int]=1024 , lowerCAmelCase__ : Optional[int]=8 , lowerCAmelCase__ : Dict=None , lowerCAmelCase__ : List[str]=6 , lowerCAmelCase__ : Tuple=32 , lowerCAmelCase__ : Any=128 , lowerCAmelCase__ : int=0.1 , lowerCAmelCase__ : int=1e-6 , lowerCAmelCase__ : Union[str, Any]=1.0 , lowerCAmelCase__ : Union[str, Any]="gated-gelu" , lowerCAmelCase__ : Optional[Any]=True , lowerCAmelCase__ : List[Any]=True , lowerCAmelCase__ : Any="T5Tokenizer" , lowerCAmelCase__ : Optional[int]=True , lowerCAmelCase__ : Dict=0 , lowerCAmelCase__ : str=1 , lowerCAmelCase__ : int=0 , **lowerCAmelCase__ : Dict , ) -> int: '''simple docstring''' super().__init__( is_encoder_decoder=lowerCAmelCase__ , tokenizer_class=lowerCAmelCase__ , tie_word_embeddings=lowerCAmelCase__ , pad_token_id=lowerCAmelCase__ , eos_token_id=lowerCAmelCase__ , decoder_start_token_id=lowerCAmelCase__ , **lowerCAmelCase__ , ) _UpperCamelCase = vocab_size _UpperCamelCase = d_model _UpperCamelCase = d_kv _UpperCamelCase = d_ff _UpperCamelCase = num_layers _UpperCamelCase = ( num_decoder_layers if num_decoder_layers is not None else self.num_layers ) # default = symmetry _UpperCamelCase = num_heads _UpperCamelCase = relative_attention_num_buckets _UpperCamelCase = relative_attention_max_distance _UpperCamelCase = dropout_rate _UpperCamelCase = layer_norm_epsilon _UpperCamelCase = initializer_factor _UpperCamelCase = feed_forward_proj _UpperCamelCase = use_cache _UpperCamelCase = self.feed_forward_proj.split('''-''' ) _UpperCamelCase = act_info[-1] _UpperCamelCase = act_info[0] == '''gated''' if len(lowerCAmelCase__ ) > 1 and act_info[0] != "gated" or len(lowerCAmelCase__ ) > 2: raise ValueError( f"""`feed_forward_proj`: {feed_forward_proj} is not a valid activation function of the dense layer.""" '''Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. ''' '''\'gated-gelu\' or \'relu\'''' ) if feed_forward_proj == "gated-gelu": _UpperCamelCase = '''gelu_new''' @property def snake_case__ ( self : Tuple ) -> Optional[Any]: '''simple docstring''' return self.d_model @property def snake_case__ ( self : List[str] ) -> List[Any]: '''simple docstring''' return self.num_heads @property def snake_case__ ( self : Optional[int] ) -> Any: '''simple docstring''' return self.num_layers class __lowerCAmelCase ( __magic_name__ ): """simple docstring""" @property # Copied from transformers.models.t5.configuration_t5.T5OnnxConfig.inputs def snake_case__ ( self : Dict ) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' _UpperCamelCase = { '''input_ids''': {0: '''batch''', 1: '''encoder_sequence'''}, '''attention_mask''': {0: '''batch''', 1: '''encoder_sequence'''}, } if self.use_past: _UpperCamelCase = '''past_encoder_sequence + sequence''' _UpperCamelCase = {0: '''batch'''} _UpperCamelCase = {0: '''batch''', 1: '''past_decoder_sequence + sequence'''} else: _UpperCamelCase = {0: '''batch''', 1: '''decoder_sequence'''} _UpperCamelCase = {0: '''batch''', 1: '''decoder_sequence'''} if self.use_past: self.fill_with_past_key_values_(lowerCAmelCase__ , direction='''inputs''' ) return common_inputs @property # Copied from transformers.models.t5.configuration_t5.T5OnnxConfig.default_onnx_opset def snake_case__ ( self : Tuple ) -> int: '''simple docstring''' return 13 @property def snake_case__ ( self : Optional[Any] ) -> float: '''simple docstring''' return 5e-4
98
"""simple docstring""" import itertools import os from collections import Counter, defaultdict from concurrent.futures import ThreadPoolExecutor, as_completed import numpy as np import datasets from .execute import check_correctness UpperCAmelCase = """\ @misc{chen2021evaluating, title={Evaluating Large Language Models Trained on Code}, author={Mark Chen and Jerry Tworek and Heewoo Jun and Qiming Yuan \ and Henrique Ponde de Oliveira Pinto and Jared Kaplan and Harri Edwards \ and Yuri Burda and Nicholas Joseph and Greg Brockman and Alex Ray \ and Raul Puri and Gretchen Krueger and Michael Petrov and Heidy Khlaaf \ and Girish Sastry and Pamela Mishkin and Brooke Chan and Scott Gray \ and Nick Ryder and Mikhail Pavlov and Alethea Power and Lukasz Kaiser \ and Mohammad Bavarian and Clemens Winter and Philippe Tillet \ and Felipe Petroski Such and Dave Cummings and Matthias Plappert \ and Fotios Chantzis and Elizabeth Barnes and Ariel Herbert-Voss \ and William Hebgen Guss and Alex Nichol and Alex Paino and Nikolas Tezak \ and Jie Tang and Igor Babuschkin and Suchir Balaji and Shantanu Jain \ and William Saunders and Christopher Hesse and Andrew N. Carr \ and Jan Leike and Josh Achiam and Vedant Misra and Evan Morikawa \ and Alec Radford and Matthew Knight and Miles Brundage and Mira Murati \ and Katie Mayer and Peter Welinder and Bob McGrew and Dario Amodei \ and Sam McCandlish and Ilya Sutskever and Wojciech Zaremba}, year={2021}, eprint={2107.03374}, archivePrefix={arXiv}, primaryClass={cs.LG} } """ UpperCAmelCase = """\ This metric implements the evaluation harness for the HumanEval problem solving dataset described in the paper \"Evaluating Large Language Models Trained on Code\" (https://arxiv.org/abs/2107.03374). """ UpperCAmelCase = """ Calculates how good are predictions given some references, using certain scores Args: predictions: list of candidates to evaluate. Each candidates should be a list of strings with several code candidates to solve the problem. references: a list with a test for each prediction. Each test should evaluate the correctness of a code candidate. k: number of code candidates to consider in the evaluation (Default: [1, 10, 100]) num_workers: number of workers used to evaluate the canidate programs (Default: 4). timeout: Returns: pass_at_k: dict with pass rates for each k results: dict with granular results of each unittest Examples: >>> code_eval = datasets.load_metric(\"code_eval\") >>> test_cases = [\"assert add(2,3)==5\"] >>> candidates = [[\"def add(a,b): return a*b\", \"def add(a, b): return a+b\"]] >>> pass_at_k, results = code_eval.compute(references=test_cases, predictions=candidates, k=[1, 2]) >>> print(pass_at_k) {'pass@1': 0.5, 'pass@2': 1.0} """ UpperCAmelCase = """ ################################################################################ !!!WARNING!!! ################################################################################ The \"code_eval\" metric executes untrusted model-generated code in Python. Although it is highly unlikely that model-generated code will do something overtly malicious in response to this test suite, model-generated code may act destructively due to a lack of model capability or alignment. Users are strongly encouraged to sandbox this evaluation suite so that it does not perform destructive actions on their host or network. For more information on how OpenAI sandboxes its code, see the paper \"Evaluating Large Language Models Trained on Code\" (https://arxiv.org/abs/2107.03374). Once you have read this disclaimer and taken appropriate precautions, set the environment variable HF_ALLOW_CODE_EVAL=\"1\". Within Python you can to this with: >>> import os >>> os.environ[\"HF_ALLOW_CODE_EVAL\"] = \"1\" ################################################################################\ """ UpperCAmelCase = """The MIT License Copyright (c) OpenAI (https://openai.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.""" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION ,_KWARGS_DESCRIPTION ) class lowercase__ ( datasets.Metric ): def UpperCamelCase_ ( self) -> str: return datasets.MetricInfo( # This is the description that will appear on the metrics page. description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": datasets.Sequence(datasets.Value("""string""")), """references""": datasets.Value("""string"""), }) , homepage="""https://github.com/openai/human-eval""" , codebase_urls=["""https://github.com/openai/human-eval"""] , reference_urls=["""https://github.com/openai/human-eval"""] , license=_LICENSE , ) def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=[1, 10, 100] , SCREAMING_SNAKE_CASE=4 , SCREAMING_SNAKE_CASE=3.0) -> Union[str, Any]: if os.getenv("""HF_ALLOW_CODE_EVAL""" , 0) != "1": raise ValueError(_WARNING) if os.name == "nt": raise NotImplementedError("""This metric is currently not supported on Windows.""") with ThreadPoolExecutor(max_workers=SCREAMING_SNAKE_CASE) as executor: _lowerCamelCase : Optional[int] = [] _lowerCamelCase : Optional[int] = Counter() _lowerCamelCase : Any = 0 _lowerCamelCase : List[Any] = defaultdict(SCREAMING_SNAKE_CASE) for task_id, (candidates, test_case) in enumerate(zip(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE)): for candidate in candidates: _lowerCamelCase : Any = candidate + """\n""" + test_case _lowerCamelCase : Union[str, Any] = (test_program, timeout, task_id, completion_id[task_id]) _lowerCamelCase : List[str] = executor.submit(SCREAMING_SNAKE_CASE , *SCREAMING_SNAKE_CASE) futures.append(SCREAMING_SNAKE_CASE) completion_id[task_id] += 1 n_samples += 1 for future in as_completed(SCREAMING_SNAKE_CASE): _lowerCamelCase : int = future.result() results[result["task_id"]].append((result["""completion_id"""], result)) _lowerCamelCase , _lowerCamelCase : List[Any] = [], [] for result in results.values(): result.sort() _lowerCamelCase : List[str] = [r[1]["""passed"""] for r in result] total.append(len(SCREAMING_SNAKE_CASE)) correct.append(sum(SCREAMING_SNAKE_CASE)) _lowerCamelCase : List[Any] = np.array(SCREAMING_SNAKE_CASE) _lowerCamelCase : Union[str, Any] = np.array(SCREAMING_SNAKE_CASE) _lowerCamelCase : Union[str, Any] = k _lowerCamelCase : Optional[Any] = {F'pass@{k}': estimate_pass_at_k(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE).mean() for k in ks if (total >= k).all()} return pass_at_k, results def _snake_case ( __snake_case : List[str] , __snake_case : List[str] , __snake_case : List[str] ): """simple docstring""" def estimator(__snake_case : int , __snake_case : int , __snake_case : int ) -> float: if n - c < k: return 1.0 return 1.0 - np.prod(1.0 - k / np.arange(n - c + 1 , n + 1 ) ) if isinstance(__snake_case , __snake_case ): _lowerCamelCase : Optional[int] = itertools.repeat(__snake_case , len(__snake_case ) ) else: assert len(__snake_case ) == len(__snake_case ) _lowerCamelCase : List[str] = iter(__snake_case ) return np.array([estimator(int(__snake_case ) , int(__snake_case ) , __snake_case ) for n, c in zip(__snake_case , __snake_case )] )
88
0
import random from typing import Any def a (lowerCAmelCase__ ): for _ in range(len(lowerCAmelCase__ ) ): __a = random.randint(0 , len(lowerCAmelCase__ ) - 1 ) __a = random.randint(0 , len(lowerCAmelCase__ ) - 1 ) __a , __a = data[b], data[a] return data if __name__ == "__main__": SCREAMING_SNAKE_CASE = [0, 1, 2, 3, 4, 5, 6, 7] SCREAMING_SNAKE_CASE = ['python', 'says', 'hello', '!'] print('Fisher-Yates Shuffle:') print('List', integers, strings) print('FY Shuffle', fisher_yates_shuffle(integers), fisher_yates_shuffle(strings))
99
"""simple docstring""" from typing import Dict, List from nltk.translate import gleu_score import datasets from datasets import MetricInfo UpperCAmelCase = """\ @misc{wu2016googles, title={Google's Neural Machine Translation System: Bridging the Gap between Human and Machine Translation}, author={Yonghui Wu and Mike Schuster and Zhifeng Chen and Quoc V. Le and Mohammad Norouzi and Wolfgang Macherey and Maxim Krikun and Yuan Cao and Qin Gao and Klaus Macherey and Jeff Klingner and Apurva Shah and Melvin Johnson and Xiaobing Liu and Łukasz Kaiser and Stephan Gouws and Yoshikiyo Kato and Taku Kudo and Hideto Kazawa and Keith Stevens and George Kurian and Nishant Patil and Wei Wang and Cliff Young and Jason Smith and Jason Riesa and Alex Rudnick and Oriol Vinyals and Greg Corrado and Macduff Hughes and Jeffrey Dean}, year={2016}, eprint={1609.08144}, archivePrefix={arXiv}, primaryClass={cs.CL} } """ UpperCAmelCase = """\ The BLEU score has some undesirable properties when used for single sentences, as it was designed to be a corpus measure. We therefore use a slightly different score for our RL experiments which we call the 'GLEU score'. For the GLEU score, we record all sub-sequences of 1, 2, 3 or 4 tokens in output and target sequence (n-grams). We then compute a recall, which is the ratio of the number of matching n-grams to the number of total n-grams in the target (ground truth) sequence, and a precision, which is the ratio of the number of matching n-grams to the number of total n-grams in the generated output sequence. Then GLEU score is simply the minimum of recall and precision. This GLEU score's range is always between 0 (no matches) and 1 (all match) and it is symmetrical when switching output and target. According to our experiments, GLEU score correlates quite well with the BLEU metric on a corpus level but does not have its drawbacks for our per sentence reward objective. """ UpperCAmelCase = """\ Computes corpus-level Google BLEU (GLEU) score of translated segments against one or more references. Instead of averaging the sentence level GLEU scores (i.e. macro-average precision), Wu et al. (2016) sum up the matching tokens and the max of hypothesis and reference tokens for each sentence, then compute using the aggregate values. Args: predictions (list of str): list of translations to score. Each translation should be tokenized into a list of tokens. references (list of list of str): list of lists of references for each translation. Each reference should be tokenized into a list of tokens. min_len (int): The minimum order of n-gram this function should extract. Defaults to 1. max_len (int): The maximum order of n-gram this function should extract. Defaults to 4. Returns: 'google_bleu': google_bleu score Examples: Example 1: >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always', ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat'] >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which', ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never', ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat'] >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was', ... 'interested', 'in', 'world', 'history'] >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history', ... 'because', 'he', 'read', 'the', 'book'] >>> list_of_references = [[ref1a], [ref2a]] >>> hypotheses = [hyp1, hyp2] >>> google_bleu = datasets.load_metric(\"google_bleu\") >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references) >>> print(round(results[\"google_bleu\"], 2)) 0.44 Example 2: >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always', ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat'] >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which', ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never', ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat'] >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never', ... 'heed', 'the', 'cat', 'commands'] >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the', ... 'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions', ... 'of', 'the', 'cat'] >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was', ... 'interested', 'in', 'world', 'history'] >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history', ... 'because', 'he', 'read', 'the', 'book'] >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]] >>> hypotheses = [hyp1, hyp2] >>> google_bleu = datasets.load_metric(\"google_bleu\") >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references) >>> print(round(results[\"google_bleu\"], 2)) 0.61 Example 3: >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always', ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat'] >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which', ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never', ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat'] >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never', ... 'heed', 'the', 'cat', 'commands'] >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the', ... 'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions', ... 'of', 'the', 'cat'] >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was', ... 'interested', 'in', 'world', 'history'] >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history', ... 'because', 'he', 'read', 'the', 'book'] >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]] >>> hypotheses = [hyp1, hyp2] >>> google_bleu = datasets.load_metric(\"google_bleu\") >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references, min_len=2) >>> print(round(results[\"google_bleu\"], 2)) 0.53 Example 4: >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always', ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat'] >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which', ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never', ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat'] >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never', ... 'heed', 'the', 'cat', 'commands'] >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the', ... 'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions', ... 'of', 'the', 'cat'] >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was', ... 'interested', 'in', 'world', 'history'] >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history', ... 'because', 'he', 'read', 'the', 'book'] >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]] >>> hypotheses = [hyp1, hyp2] >>> google_bleu = datasets.load_metric(\"google_bleu\") >>> results = google_bleu.compute(predictions=hypotheses,references=list_of_references, min_len=2, max_len=6) >>> print(round(results[\"google_bleu\"], 2)) 0.4 """ @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION ,_KWARGS_DESCRIPTION ) class lowercase__ ( datasets.Metric ): def UpperCamelCase_ ( self) -> MetricInfo: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": datasets.Sequence(datasets.Value("""string""" , id="""token""") , id="""sequence"""), """references""": datasets.Sequence( datasets.Sequence(datasets.Value("""string""" , id="""token""") , id="""sequence""") , id="""references"""), }) , ) def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = 1 , SCREAMING_SNAKE_CASE = 4 , ) -> Dict[str, float]: return { "google_bleu": gleu_score.corpus_gleu( list_of_references=SCREAMING_SNAKE_CASE , hypotheses=SCREAMING_SNAKE_CASE , min_len=SCREAMING_SNAKE_CASE , max_len=SCREAMING_SNAKE_CASE) }
88
0
from __future__ import annotations import unittest from transformers import MobileBertConfig, is_tf_available from transformers.models.auto import get_values from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TF_MODEL_FOR_PRETRAINING_MAPPING, TFMobileBertForMaskedLM, TFMobileBertForMultipleChoice, TFMobileBertForNextSentencePrediction, TFMobileBertForPreTraining, TFMobileBertForQuestionAnswering, TFMobileBertForSequenceClassification, TFMobileBertForTokenClassification, TFMobileBertModel, ) @require_tf class __snake_case ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' lowerCamelCase__ : Optional[Any] = ( ( TFMobileBertModel, TFMobileBertForMaskedLM, TFMobileBertForNextSentencePrediction, TFMobileBertForPreTraining, TFMobileBertForQuestionAnswering, TFMobileBertForSequenceClassification, TFMobileBertForTokenClassification, TFMobileBertForMultipleChoice, ) if is_tf_available() else () ) lowerCamelCase__ : Union[str, Any] = ( { """feature-extraction""": TFMobileBertModel, """fill-mask""": TFMobileBertForMaskedLM, """question-answering""": TFMobileBertForQuestionAnswering, """text-classification""": TFMobileBertForSequenceClassification, """token-classification""": TFMobileBertForTokenClassification, """zero-shot""": TFMobileBertForSequenceClassification, } if is_tf_available() else {} ) lowerCamelCase__ : List[str] = False lowerCamelCase__ : int = False def lowercase_ ( self , A_ , A_ , A_=False ): '''simple docstring''' SCREAMING_SNAKE_CASE__ = super()._prepare_for_class(A_ , A_ , return_labels=A_ ) if return_labels: if model_class in get_values(A_ ): SCREAMING_SNAKE_CASE__ = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa ) return inputs_dict class __snake_case ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self , A_ , A_=13 , A_=7 , A_=True , A_=True , A_=True , A_=True , A_=99 , A_=32 , A_=32 , A_=2 , A_=4 , A_=37 , A_="gelu" , A_=0.1 , A_=0.1 , A_=5_12 , A_=16 , A_=2 , A_=0.02 , A_=3 , A_=4 , A_=None , ): '''simple docstring''' SCREAMING_SNAKE_CASE__ = parent SCREAMING_SNAKE_CASE__ = batch_size SCREAMING_SNAKE_CASE__ = seq_length SCREAMING_SNAKE_CASE__ = is_training SCREAMING_SNAKE_CASE__ = use_input_mask SCREAMING_SNAKE_CASE__ = use_token_type_ids SCREAMING_SNAKE_CASE__ = use_labels SCREAMING_SNAKE_CASE__ = vocab_size SCREAMING_SNAKE_CASE__ = hidden_size SCREAMING_SNAKE_CASE__ = num_hidden_layers SCREAMING_SNAKE_CASE__ = num_attention_heads SCREAMING_SNAKE_CASE__ = intermediate_size SCREAMING_SNAKE_CASE__ = hidden_act SCREAMING_SNAKE_CASE__ = hidden_dropout_prob SCREAMING_SNAKE_CASE__ = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ = max_position_embeddings SCREAMING_SNAKE_CASE__ = type_vocab_size SCREAMING_SNAKE_CASE__ = type_sequence_label_size SCREAMING_SNAKE_CASE__ = initializer_range SCREAMING_SNAKE_CASE__ = num_labels SCREAMING_SNAKE_CASE__ = num_choices SCREAMING_SNAKE_CASE__ = scope SCREAMING_SNAKE_CASE__ = embedding_size def lowercase_ ( self ): '''simple docstring''' SCREAMING_SNAKE_CASE__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE__ = None if self.use_input_mask: SCREAMING_SNAKE_CASE__ = random_attention_mask([self.batch_size, self.seq_length] ) SCREAMING_SNAKE_CASE__ = None if self.use_token_type_ids: SCREAMING_SNAKE_CASE__ = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = None if self.use_labels: SCREAMING_SNAKE_CASE__ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) SCREAMING_SNAKE_CASE__ = ids_tensor([self.batch_size] , self.num_choices ) SCREAMING_SNAKE_CASE__ = MobileBertConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , embedding_size=self.embedding_size , ) return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def lowercase_ ( self , A_ , A_ , A_ , A_ , A_ , A_ , A_ ): '''simple docstring''' SCREAMING_SNAKE_CASE__ = TFMobileBertModel(config=A_ ) SCREAMING_SNAKE_CASE__ = {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids} SCREAMING_SNAKE_CASE__ = model(A_ ) SCREAMING_SNAKE_CASE__ = [input_ids, input_mask] SCREAMING_SNAKE_CASE__ = model(A_ ) SCREAMING_SNAKE_CASE__ = model(A_ ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def lowercase_ ( self , A_ , A_ , A_ , A_ , A_ , A_ , A_ ): '''simple docstring''' SCREAMING_SNAKE_CASE__ = TFMobileBertForMaskedLM(config=A_ ) SCREAMING_SNAKE_CASE__ = {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids} SCREAMING_SNAKE_CASE__ = model(A_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def lowercase_ ( self , A_ , A_ , A_ , A_ , A_ , A_ , A_ ): '''simple docstring''' SCREAMING_SNAKE_CASE__ = TFMobileBertForNextSentencePrediction(config=A_ ) SCREAMING_SNAKE_CASE__ = {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids} SCREAMING_SNAKE_CASE__ = model(A_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, 2) ) def lowercase_ ( self , A_ , A_ , A_ , A_ , A_ , A_ , A_ ): '''simple docstring''' SCREAMING_SNAKE_CASE__ = TFMobileBertForPreTraining(config=A_ ) SCREAMING_SNAKE_CASE__ = {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids} SCREAMING_SNAKE_CASE__ = model(A_ ) self.parent.assertEqual( result.prediction_logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) self.parent.assertEqual(result.seq_relationship_logits.shape , (self.batch_size, 2) ) def lowercase_ ( self , A_ , A_ , A_ , A_ , A_ , A_ , A_ ): '''simple docstring''' SCREAMING_SNAKE_CASE__ = self.num_labels SCREAMING_SNAKE_CASE__ = TFMobileBertForSequenceClassification(config=A_ ) SCREAMING_SNAKE_CASE__ = {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids} SCREAMING_SNAKE_CASE__ = model(A_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def lowercase_ ( self , A_ , A_ , A_ , A_ , A_ , A_ , A_ ): '''simple docstring''' SCREAMING_SNAKE_CASE__ = self.num_choices SCREAMING_SNAKE_CASE__ = TFMobileBertForMultipleChoice(config=A_ ) SCREAMING_SNAKE_CASE__ = tf.tile(tf.expand_dims(A_ , 1 ) , (1, self.num_choices, 1) ) SCREAMING_SNAKE_CASE__ = tf.tile(tf.expand_dims(A_ , 1 ) , (1, self.num_choices, 1) ) SCREAMING_SNAKE_CASE__ = tf.tile(tf.expand_dims(A_ , 1 ) , (1, self.num_choices, 1) ) SCREAMING_SNAKE_CASE__ = { '''input_ids''': multiple_choice_inputs_ids, '''attention_mask''': multiple_choice_input_mask, '''token_type_ids''': multiple_choice_token_type_ids, } SCREAMING_SNAKE_CASE__ = model(A_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def lowercase_ ( self , A_ , A_ , A_ , A_ , A_ , A_ , A_ ): '''simple docstring''' SCREAMING_SNAKE_CASE__ = self.num_labels SCREAMING_SNAKE_CASE__ = TFMobileBertForTokenClassification(config=A_ ) SCREAMING_SNAKE_CASE__ = {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids} SCREAMING_SNAKE_CASE__ = model(A_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def lowercase_ ( self , A_ , A_ , A_ , A_ , A_ , A_ , A_ ): '''simple docstring''' SCREAMING_SNAKE_CASE__ = TFMobileBertForQuestionAnswering(config=A_ ) SCREAMING_SNAKE_CASE__ = {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids} SCREAMING_SNAKE_CASE__ = model(A_ ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def lowercase_ ( self ): '''simple docstring''' SCREAMING_SNAKE_CASE__ = self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ) = config_and_inputs SCREAMING_SNAKE_CASE__ = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask} return config, inputs_dict def lowercase_ ( self ): '''simple docstring''' SCREAMING_SNAKE_CASE__ = TFMobileBertModelTest.TFMobileBertModelTester(self ) SCREAMING_SNAKE_CASE__ = ConfigTester(self , config_class=A_ , hidden_size=37 ) def lowercase_ ( self ): '''simple docstring''' self.config_tester.run_common_tests() def lowercase_ ( self ): '''simple docstring''' SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_model(*A_ ) def lowercase_ ( self ): '''simple docstring''' SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_masked_lm(*A_ ) def lowercase_ ( self ): '''simple docstring''' SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_multiple_choice(*A_ ) def lowercase_ ( self ): '''simple docstring''' SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_next_sequence_prediction(*A_ ) def lowercase_ ( self ): '''simple docstring''' SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_pretraining(*A_ ) def lowercase_ ( self ): '''simple docstring''' SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_question_answering(*A_ ) def lowercase_ ( self ): '''simple docstring''' SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_sequence_classification(*A_ ) def lowercase_ ( self ): '''simple docstring''' SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_token_classification(*A_ ) @slow def lowercase_ ( self ): '''simple docstring''' for model_name in ["google/mobilebert-uncased"]: SCREAMING_SNAKE_CASE__ = TFMobileBertModel.from_pretrained(A_ ) self.assertIsNotNone(A_ ) @require_tf class __snake_case ( unittest.TestCase ): '''simple docstring''' @slow def lowercase_ ( self ): '''simple docstring''' SCREAMING_SNAKE_CASE__ = TFMobileBertForPreTraining.from_pretrained('''google/mobilebert-uncased''' ) SCREAMING_SNAKE_CASE__ = tf.constant([[0, 1, 2, 3, 4, 5]] ) SCREAMING_SNAKE_CASE__ = model(A_ )[0] SCREAMING_SNAKE_CASE__ = [1, 6, 3_05_22] self.assertEqual(output.shape , A_ ) SCREAMING_SNAKE_CASE__ = tf.constant( [ [ [-4.5919547, -9.248295, -9.645256], [-6.7306175, -6.440284, -6.6052837], [-7.2743506, -6.7847915, -6.024673], ] ] ) tf.debugging.assert_near(output[:, :3, :3] , A_ , atol=1E-4 )
100
"""simple docstring""" def _snake_case ( __snake_case : str , __snake_case : str ): """simple docstring""" _lowerCamelCase : str = len(__snake_case ) _lowerCamelCase : Union[str, Any] = len(__snake_case ) _lowerCamelCase : int = [[False for _ in range(m + 1 )] for _ in range(n + 1 )] _lowerCamelCase : Union[str, Any] = True for i in range(__snake_case ): for j in range(m + 1 ): if dp[i][j]: if j < m and a[i].upper() == b[j]: _lowerCamelCase : Tuple = True if a[i].islower(): _lowerCamelCase : Tuple = True return dp[n][m] if __name__ == "__main__": import doctest doctest.testmod()
88
0
from __future__ import annotations from collections.abc import Iterable, Iterator from dataclasses import dataclass lowerCAmelCase__ : Dict =(3, 9, -11, 0, 7, 5, 1, -1) lowerCAmelCase__ : Optional[int] =(4, 6, 2, 0, 8, 10, 3, -2) @dataclass class __lowercase : """simple docstring""" _UpperCAmelCase = 42 _UpperCAmelCase = 42 class __lowercase : """simple docstring""" def __init__( self , lowerCAmelCase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Node | None = None for i in sorted(lowerCAmelCase__ , reverse=lowerCAmelCase__ ): SCREAMING_SNAKE_CASE_ : Dict = Node(lowerCAmelCase__ , self.head ) def __iter__( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = self.head while node: yield node.data SCREAMING_SNAKE_CASE_ : List[str] = node.next_node def __len__( self ): """simple docstring""" return sum(1 for _ in self ) def __str__( self ): """simple docstring""" return " -> ".join([str(lowerCAmelCase__ ) for node in self] ) def a__ ( A__, A__ ): return SortedLinkedList(list(A__ ) + list(A__ ) ) if __name__ == "__main__": import doctest doctest.testmod() lowerCAmelCase__ : Dict =SortedLinkedList print(merge_lists(SSL(test_data_odd), SSL(test_data_even)))
101
"""simple docstring""" import warnings from ...utils import logging from .image_processing_imagegpt import ImageGPTImageProcessor UpperCAmelCase = logging.get_logger(__name__) class lowercase__ ( A_ ): def __init__( self , *SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE) -> None: warnings.warn( """The class ImageGPTFeatureExtractor is deprecated and will be removed in version 5 of Transformers.""" """ Please use ImageGPTImageProcessor instead.""" , SCREAMING_SNAKE_CASE , ) super().__init__(*SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE)
88
0
"""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_albert import AlbertTokenizer else: __magic_name__ : Dict = None __magic_name__ : Union[str, Any] = logging.get_logger(__name__) __magic_name__ : int = {"""vocab_file""": """spiece.model""", """tokenizer_file""": """tokenizer.json"""} __magic_name__ : Optional[int] = { """vocab_file""": { """albert-base-v1""": """https://huggingface.co/albert-base-v1/resolve/main/spiece.model""", """albert-large-v1""": """https://huggingface.co/albert-large-v1/resolve/main/spiece.model""", """albert-xlarge-v1""": """https://huggingface.co/albert-xlarge-v1/resolve/main/spiece.model""", """albert-xxlarge-v1""": """https://huggingface.co/albert-xxlarge-v1/resolve/main/spiece.model""", """albert-base-v2""": """https://huggingface.co/albert-base-v2/resolve/main/spiece.model""", """albert-large-v2""": """https://huggingface.co/albert-large-v2/resolve/main/spiece.model""", """albert-xlarge-v2""": """https://huggingface.co/albert-xlarge-v2/resolve/main/spiece.model""", """albert-xxlarge-v2""": """https://huggingface.co/albert-xxlarge-v2/resolve/main/spiece.model""", }, """tokenizer_file""": { """albert-base-v1""": """https://huggingface.co/albert-base-v1/resolve/main/tokenizer.json""", """albert-large-v1""": """https://huggingface.co/albert-large-v1/resolve/main/tokenizer.json""", """albert-xlarge-v1""": """https://huggingface.co/albert-xlarge-v1/resolve/main/tokenizer.json""", """albert-xxlarge-v1""": """https://huggingface.co/albert-xxlarge-v1/resolve/main/tokenizer.json""", """albert-base-v2""": """https://huggingface.co/albert-base-v2/resolve/main/tokenizer.json""", """albert-large-v2""": """https://huggingface.co/albert-large-v2/resolve/main/tokenizer.json""", """albert-xlarge-v2""": """https://huggingface.co/albert-xlarge-v2/resolve/main/tokenizer.json""", """albert-xxlarge-v2""": """https://huggingface.co/albert-xxlarge-v2/resolve/main/tokenizer.json""", }, } __magic_name__ : Tuple = { """albert-base-v1""": 5_1_2, """albert-large-v1""": 5_1_2, """albert-xlarge-v1""": 5_1_2, """albert-xxlarge-v1""": 5_1_2, """albert-base-v2""": 5_1_2, """albert-large-v2""": 5_1_2, """albert-xlarge-v2""": 5_1_2, """albert-xxlarge-v2""": 5_1_2, } __magic_name__ : List[Any] = """▁""" class lowercase__ ( __SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCAmelCase : Optional[int] = VOCAB_FILES_NAMES __lowerCAmelCase : Optional[int] = PRETRAINED_VOCAB_FILES_MAP __lowerCAmelCase : List[str] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __lowerCAmelCase : Optional[int] = AlbertTokenizer def __init__( self , _A=None , _A=None , _A=True , _A=True , _A=False , _A="[CLS]" , _A="[SEP]" , _A="<unk>" , _A="[SEP]" , _A="<pad>" , _A="[CLS]" , _A="[MASK]" , **_A , ): '''simple docstring''' UpperCamelCase : List[str] = ( AddedToken(_A , lstrip=_A , rstrip=_A , normalized=_A ) if isinstance(_A , _A ) else mask_token ) super().__init__( _A , tokenizer_file=_A , do_lower_case=_A , remove_space=_A , keep_accents=_A , bos_token=_A , eos_token=_A , unk_token=_A , sep_token=_A , pad_token=_A , cls_token=_A , mask_token=_A , **_A , ) UpperCamelCase : Dict = do_lower_case UpperCamelCase : str = remove_space UpperCamelCase : List[str] = keep_accents UpperCamelCase : Optional[int] = vocab_file UpperCamelCase : Tuple = False if not self.vocab_file else True def _a ( self , _A , _A = None ): '''simple docstring''' UpperCamelCase : Dict = [self.sep_token_id] UpperCamelCase : Optional[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 _a ( self , _A , _A = None ): '''simple docstring''' UpperCamelCase : Tuple = [self.sep_token_id] UpperCamelCase : 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 _a ( self , _A , _A = None ): '''simple docstring''' 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(_A ): logger.error(f"""Vocabulary path ({save_directory}) should be a directory""" ) return UpperCamelCase : List[Any] = os.path.join( _A , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_A ): copyfile(self.vocab_file , _A ) return (out_vocab_file,)
102
"""simple docstring""" from math import isqrt, loga def _snake_case ( __snake_case : int ): """simple docstring""" _lowerCamelCase : List[str] = [True] * max_number for i in range(2 , isqrt(max_number - 1 ) + 1 ): if is_prime[i]: for j in range(i**2 , __snake_case , __snake_case ): _lowerCamelCase : Optional[int] = False return [i for i in range(2 , __snake_case ) if is_prime[i]] def _snake_case ( __snake_case : int = 800800 , __snake_case : int = 800800 ): """simple docstring""" _lowerCamelCase : Union[str, Any] = degree * loga(__snake_case ) _lowerCamelCase : Union[str, Any] = int(__snake_case ) _lowerCamelCase : Dict = calculate_prime_numbers(__snake_case ) _lowerCamelCase : Optional[int] = 0 _lowerCamelCase : Any = 0 _lowerCamelCase : Any = len(__snake_case ) - 1 while left < right: while ( prime_numbers[right] * loga(prime_numbers[left] ) + prime_numbers[left] * loga(prime_numbers[right] ) > upper_bound ): right -= 1 hybrid_integers_count += right - left left += 1 return hybrid_integers_count if __name__ == "__main__": print(f'''{solution() = }''')
88
0
"""simple docstring""" from __future__ import annotations import unittest from transformers import is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import numpy import tensorflow as tf from transformers import ( TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, TF_DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, TF_DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST, BertConfig, DPRConfig, TFDPRContextEncoder, TFDPRQuestionEncoder, TFDPRReader, ) class UpperCAmelCase : def __init__( self : List[Any] , __lowerCamelCase : Optional[int] , __lowerCamelCase : Union[str, Any]=1_3 , __lowerCamelCase : str=7 , __lowerCamelCase : Optional[int]=True , __lowerCamelCase : str=True , __lowerCamelCase : int=True , __lowerCamelCase : List[Any]=True , __lowerCamelCase : Optional[int]=9_9 , __lowerCamelCase : str=3_2 , __lowerCamelCase : Optional[int]=2 , __lowerCamelCase : Union[str, Any]=4 , __lowerCamelCase : Optional[Any]=3_7 , __lowerCamelCase : List[str]="gelu" , __lowerCamelCase : List[Any]=0.1 , __lowerCamelCase : int=0.1 , __lowerCamelCase : Any=5_1_2 , __lowerCamelCase : Any=1_6 , __lowerCamelCase : Dict=2 , __lowerCamelCase : Optional[int]=0.0_2 , __lowerCamelCase : Any=3 , __lowerCamelCase : Optional[int]=4 , __lowerCamelCase : Optional[Any]=None , __lowerCamelCase : List[str]=0 , ): """simple docstring""" _snake_case = parent _snake_case = batch_size _snake_case = seq_length _snake_case = is_training _snake_case = use_input_mask _snake_case = use_token_type_ids _snake_case = use_labels _snake_case = vocab_size _snake_case = hidden_size _snake_case = num_hidden_layers _snake_case = num_attention_heads _snake_case = intermediate_size _snake_case = hidden_act _snake_case = hidden_dropout_prob _snake_case = attention_probs_dropout_prob _snake_case = max_position_embeddings _snake_case = type_vocab_size _snake_case = type_sequence_label_size _snake_case = initializer_range _snake_case = num_labels _snake_case = num_choices _snake_case = scope _snake_case = projection_dim def __UpperCAmelCase ( self : List[Any] ): """simple docstring""" _snake_case = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _snake_case = None if self.use_input_mask: # follow test_modeling_tf_ctrl.py _snake_case = random_attention_mask([self.batch_size, self.seq_length] ) _snake_case = None if self.use_token_type_ids: _snake_case = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) _snake_case = None _snake_case = None _snake_case = None if self.use_labels: _snake_case = ids_tensor([self.batch_size] , self.type_sequence_label_size ) _snake_case = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) _snake_case = ids_tensor([self.batch_size] , self.num_choices ) _snake_case = BertConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=__lowerCamelCase , initializer_range=self.initializer_range , ) _snake_case = DPRConfig(projection_dim=self.projection_dim , **config.to_dict() ) return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def __UpperCAmelCase ( self : Optional[int] , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : List[Any] , __lowerCamelCase : int , __lowerCamelCase : List[Any] , __lowerCamelCase : Dict , __lowerCamelCase : Any , __lowerCamelCase : Tuple ): """simple docstring""" _snake_case = TFDPRContextEncoder(config=__lowerCamelCase ) _snake_case = model(__lowerCamelCase , attention_mask=__lowerCamelCase , token_type_ids=__lowerCamelCase ) _snake_case = model(__lowerCamelCase , token_type_ids=__lowerCamelCase ) _snake_case = model(__lowerCamelCase ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.projection_dim or self.hidden_size) ) def __UpperCAmelCase ( self : List[Any] , __lowerCamelCase : List[str] , __lowerCamelCase : List[Any] , __lowerCamelCase : Dict , __lowerCamelCase : Any , __lowerCamelCase : str , __lowerCamelCase : str , __lowerCamelCase : List[str] ): """simple docstring""" _snake_case = TFDPRQuestionEncoder(config=__lowerCamelCase ) _snake_case = model(__lowerCamelCase , attention_mask=__lowerCamelCase , token_type_ids=__lowerCamelCase ) _snake_case = model(__lowerCamelCase , token_type_ids=__lowerCamelCase ) _snake_case = model(__lowerCamelCase ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.projection_dim or self.hidden_size) ) def __UpperCAmelCase ( self : List[Any] , __lowerCamelCase : str , __lowerCamelCase : Tuple , __lowerCamelCase : List[str] , __lowerCamelCase : Dict , __lowerCamelCase : Tuple , __lowerCamelCase : Tuple , __lowerCamelCase : Optional[int] ): """simple docstring""" _snake_case = TFDPRReader(config=__lowerCamelCase ) _snake_case = model(__lowerCamelCase , attention_mask=__lowerCamelCase ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.relevance_logits.shape , (self.batch_size,) ) def __UpperCAmelCase ( self : Optional[Any] ): """simple docstring""" _snake_case = self.prepare_config_and_inputs() ( ( _snake_case ) , ( _snake_case ) , ( _snake_case ) , ( _snake_case ) , ( _snake_case ) , ( _snake_case ) , ( _snake_case ) , ) = config_and_inputs _snake_case = {'''input_ids''': input_ids} return config, inputs_dict @require_tf class UpperCAmelCase ( __SCREAMING_SNAKE_CASE,__SCREAMING_SNAKE_CASE,unittest.TestCase ): A__ : Any = ( ( TFDPRContextEncoder, TFDPRQuestionEncoder, TFDPRReader, ) if is_tf_available() else () ) A__ : Optional[int] = {'''feature-extraction''': TFDPRQuestionEncoder} if is_tf_available() else {} A__ : List[Any] = False A__ : Any = False A__ : Optional[int] = False A__ : Optional[Any] = False A__ : str = False def __UpperCAmelCase ( self : Dict ): """simple docstring""" _snake_case = TFDPRModelTester(self ) _snake_case = ConfigTester(self , config_class=__lowerCamelCase , hidden_size=3_7 ) def __UpperCAmelCase ( self : Tuple ): """simple docstring""" self.config_tester.run_common_tests() def __UpperCAmelCase ( self : Union[str, Any] ): """simple docstring""" _snake_case = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_dpr_context_encoder(*__lowerCamelCase ) def __UpperCAmelCase ( self : Union[str, Any] ): """simple docstring""" _snake_case = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_dpr_question_encoder(*__lowerCamelCase ) def __UpperCAmelCase ( self : Any ): """simple docstring""" _snake_case = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_dpr_reader(*__lowerCamelCase ) @slow def __UpperCAmelCase ( self : Optional[Any] ): """simple docstring""" for model_name in TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _snake_case = TFDPRContextEncoder.from_pretrained(__lowerCamelCase ) self.assertIsNotNone(__lowerCamelCase ) for model_name in TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _snake_case = TFDPRContextEncoder.from_pretrained(__lowerCamelCase ) self.assertIsNotNone(__lowerCamelCase ) for model_name in TF_DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _snake_case = TFDPRQuestionEncoder.from_pretrained(__lowerCamelCase ) self.assertIsNotNone(__lowerCamelCase ) for model_name in TF_DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _snake_case = TFDPRReader.from_pretrained(__lowerCamelCase ) self.assertIsNotNone(__lowerCamelCase ) @require_tf class UpperCAmelCase ( unittest.TestCase ): @slow def __UpperCAmelCase ( self : str ): """simple docstring""" _snake_case = TFDPRQuestionEncoder.from_pretrained('''facebook/dpr-question_encoder-single-nq-base''' ) _snake_case = tf.constant( [[1_0_1, 7_5_9_2, 1_0_1_0, 2_0_0_3, 2_0_2_6, 3_8_9_9, 1_0_1_4_0, 1_0_2_9, 1_0_2]] ) # [CLS] hello, is my dog cute? [SEP] _snake_case = model(__lowerCamelCase )[0] # embedding shape = (1, 768) # compare the actual values for a slice. _snake_case = tf.constant( [ [ 0.0_3_2_3_6_2_5_3, 0.1_2_7_5_3_3_3_5, 0.1_6_8_1_8_5_0_9, 0.0_0_2_7_9_7_8_6, 0.3_8_9_6_9_3_3, 0.2_4_2_6_4_9_4_5, 0.2_1_7_8_9_7_1, -0.0_2_3_3_5_2_2_7, -0.0_8_4_8_1_9_5_9, -0.1_4_3_2_4_1_1_7, ] ] ) self.assertTrue(numpy.allclose(output[:, :1_0].numpy() , expected_slice.numpy() , atol=1E-4 ) )
103
"""simple docstring""" import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, StableDiffusionSAGPipeline, UNetaDConditionModel, ) from diffusers.utils import slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class lowercase__ ( A_ ,A_ ,unittest.TestCase ): __UpperCAmelCase = StableDiffusionSAGPipeline __UpperCAmelCase = TEXT_TO_IMAGE_PARAMS __UpperCAmelCase = TEXT_TO_IMAGE_BATCH_PARAMS __UpperCAmelCase = TEXT_TO_IMAGE_IMAGE_PARAMS __UpperCAmelCase = TEXT_TO_IMAGE_IMAGE_PARAMS __UpperCAmelCase = False def UpperCamelCase_ ( self) -> Optional[Any]: torch.manual_seed(0) _lowerCamelCase : Dict = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , cross_attention_dim=32 , ) _lowerCamelCase : int = DDIMScheduler( beta_start=0.0_00_85 , beta_end=0.0_12 , beta_schedule="""scaled_linear""" , clip_sample=SCREAMING_SNAKE_CASE , set_alpha_to_one=SCREAMING_SNAKE_CASE , ) torch.manual_seed(0) _lowerCamelCase : Tuple = 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 , ) torch.manual_seed(0) _lowerCamelCase : Tuple = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) _lowerCamelCase : List[Any] = CLIPTextModel(SCREAMING_SNAKE_CASE) _lowerCamelCase : Tuple = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""") _lowerCamelCase : List[Any] = { """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """safety_checker""": None, """feature_extractor""": None, } return components def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=0) -> List[Any]: if str(SCREAMING_SNAKE_CASE).startswith("""mps"""): _lowerCamelCase : List[str] = torch.manual_seed(SCREAMING_SNAKE_CASE) else: _lowerCamelCase : List[str] = torch.Generator(device=SCREAMING_SNAKE_CASE).manual_seed(SCREAMING_SNAKE_CASE) _lowerCamelCase : List[Any] = { """prompt""": """.""", """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 1.0, """sag_scale""": 1.0, """output_type""": """numpy""", } return inputs def UpperCamelCase_ ( self) -> Tuple: super().test_inference_batch_single_identical(expected_max_diff=3e-3) @slow @require_torch_gpu class lowercase__ ( unittest.TestCase ): def UpperCamelCase_ ( self) -> Union[str, Any]: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCamelCase_ ( self) -> Optional[Any]: _lowerCamelCase : Any = StableDiffusionSAGPipeline.from_pretrained("""CompVis/stable-diffusion-v1-4""") _lowerCamelCase : Union[str, Any] = sag_pipe.to(SCREAMING_SNAKE_CASE) sag_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE) _lowerCamelCase : Optional[int] = """.""" _lowerCamelCase : int = torch.manual_seed(0) _lowerCamelCase : Tuple = sag_pipe( [prompt] , generator=SCREAMING_SNAKE_CASE , guidance_scale=7.5 , sag_scale=1.0 , num_inference_steps=20 , output_type="""np""") _lowerCamelCase : Dict = output.images _lowerCamelCase : Tuple = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) _lowerCamelCase : Optional[Any] = np.array([0.15_68, 0.17_38, 0.16_95, 0.16_93, 0.15_07, 0.17_05, 0.15_47, 0.17_51, 0.19_49]) assert np.abs(image_slice.flatten() - expected_slice).max() < 5e-2 def UpperCamelCase_ ( self) -> List[str]: _lowerCamelCase : Optional[Any] = StableDiffusionSAGPipeline.from_pretrained("""stabilityai/stable-diffusion-2-1-base""") _lowerCamelCase : Dict = sag_pipe.to(SCREAMING_SNAKE_CASE) sag_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE) _lowerCamelCase : Union[str, Any] = """.""" _lowerCamelCase : List[str] = torch.manual_seed(0) _lowerCamelCase : int = sag_pipe( [prompt] , generator=SCREAMING_SNAKE_CASE , guidance_scale=7.5 , sag_scale=1.0 , num_inference_steps=20 , output_type="""np""") _lowerCamelCase : Any = output.images _lowerCamelCase : List[str] = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) _lowerCamelCase : Any = np.array([0.34_59, 0.28_76, 0.25_37, 0.30_02, 0.26_71, 0.21_60, 0.30_26, 0.22_62, 0.23_71]) assert np.abs(image_slice.flatten() - expected_slice).max() < 5e-2 def UpperCamelCase_ ( self) -> List[str]: _lowerCamelCase : int = StableDiffusionSAGPipeline.from_pretrained("""stabilityai/stable-diffusion-2-1-base""") _lowerCamelCase : Optional[Any] = sag_pipe.to(SCREAMING_SNAKE_CASE) sag_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE) _lowerCamelCase : Dict = """.""" _lowerCamelCase : Union[str, Any] = torch.manual_seed(0) _lowerCamelCase : Optional[int] = sag_pipe( [prompt] , width=768 , height=512 , generator=SCREAMING_SNAKE_CASE , guidance_scale=7.5 , sag_scale=1.0 , num_inference_steps=20 , output_type="""np""" , ) _lowerCamelCase : Union[str, Any] = output.images assert image.shape == (1, 512, 768, 3)
88
0
"""simple docstring""" import argparse import shutil from pathlib import Path from tqdm import tqdm from transformers import AutoTokenizer def _lowerCamelCase ( UpperCAmelCase_ : Optional[int], UpperCAmelCase_ : Tuple, UpperCAmelCase_ : str, UpperCAmelCase_ : Any=1024 ) -> List[Any]: """simple docstring""" A__ , A__ = [], [] A__ = list(zip(UpperCAmelCase_, UpperCAmelCase_ ) ) A__ , A__ = sorted_examples[0] def is_too_big(UpperCAmelCase_ : str ): return tok(UpperCAmelCase_, return_tensors="pt" ).input_ids.shape[1] > max_tokens for src, tgt in tqdm(sorted_examples[1:] ): A__ = new_src + " " + src A__ = new_tgt + " " + tgt if is_too_big(UpperCAmelCase_ ) or is_too_big(UpperCAmelCase_ ): # cant fit, finalize example finished_src.append(UpperCAmelCase_ ) finished_tgt.append(UpperCAmelCase_ ) A__ , A__ = src, tgt else: # can fit, keep adding A__ , A__ = cand_src, cand_tgt # cleanup if new_src: assert new_tgt finished_src.append(UpperCAmelCase_ ) finished_tgt.append(UpperCAmelCase_ ) return finished_src, finished_tgt def _lowerCamelCase ( UpperCAmelCase_ : Union[str, Any], UpperCAmelCase_ : Path, UpperCAmelCase_ : int, UpperCAmelCase_ : Dict ) -> str: """simple docstring""" A__ = Path(UpperCAmelCase_ ) save_path.mkdir(exist_ok=UpperCAmelCase_ ) for split in ["train"]: A__ , A__ = data_dir / F"""{split}.source""", data_dir / F"""{split}.target""" A__ = [x.rstrip() for x in Path(UpperCAmelCase_ ).open().readlines()] A__ = [x.rstrip() for x in Path(UpperCAmelCase_ ).open().readlines()] A__ , A__ = pack_examples(UpperCAmelCase_, UpperCAmelCase_, UpperCAmelCase_, UpperCAmelCase_ ) print(F"""packed {split} split from {len(UpperCAmelCase_ )} examples -> {len(UpperCAmelCase_ )}.""" ) Path(save_path / F"""{split}.source""" ).open("w" ).write("\n".join(UpperCAmelCase_ ) ) Path(save_path / F"""{split}.target""" ).open("w" ).write("\n".join(UpperCAmelCase_ ) ) for split in ["val", "test"]: A__ , A__ = data_dir / F"""{split}.source""", data_dir / F"""{split}.target""" shutil.copyfile(UpperCAmelCase_, save_path / F"""{split}.source""" ) shutil.copyfile(UpperCAmelCase_, save_path / F"""{split}.target""" ) def _lowerCamelCase ( ) -> Union[str, Any]: """simple docstring""" A__ = argparse.ArgumentParser() parser.add_argument("--tok_name", type=UpperCAmelCase_, help="like facebook/bart-large-cnn,t5-base, etc." ) parser.add_argument("--max_seq_len", type=UpperCAmelCase_, default=128 ) parser.add_argument("--data_dir", type=UpperCAmelCase_ ) parser.add_argument("--save_path", type=UpperCAmelCase_ ) A__ = parser.parse_args() A__ = AutoTokenizer.from_pretrained(args.tok_name ) return pack_data_dir(UpperCAmelCase_, Path(args.data_dir ), args.max_seq_len, args.save_path ) if __name__ == "__main__": packer_cli()
104
"""simple docstring""" import inspect import unittest import numpy as np from tests.test_modeling_common import floats_tensor from transformers import MaskaFormerConfig, is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MaskaFormerForUniversalSegmentation, MaskaFormerModel if is_vision_available(): from transformers import MaskaFormerImageProcessor if is_vision_available(): from PIL import Image class lowercase__ : def __init__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=2 , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=False , SCREAMING_SNAKE_CASE=10 , SCREAMING_SNAKE_CASE=3 , SCREAMING_SNAKE_CASE=32 * 8 , SCREAMING_SNAKE_CASE=32 * 8 , SCREAMING_SNAKE_CASE=4 , SCREAMING_SNAKE_CASE=64 , ) -> Optional[int]: _lowerCamelCase : List[str] = parent _lowerCamelCase : List[Any] = batch_size _lowerCamelCase : Tuple = is_training _lowerCamelCase : Tuple = use_auxiliary_loss _lowerCamelCase : Any = num_queries _lowerCamelCase : List[str] = num_channels _lowerCamelCase : List[str] = min_size _lowerCamelCase : Tuple = max_size _lowerCamelCase : str = num_labels _lowerCamelCase : Any = hidden_dim _lowerCamelCase : Dict = hidden_dim def UpperCamelCase_ ( self) -> List[str]: _lowerCamelCase : Union[str, Any] = floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size]).to( SCREAMING_SNAKE_CASE) _lowerCamelCase : List[Any] = torch.ones([self.batch_size, self.min_size, self.max_size] , device=SCREAMING_SNAKE_CASE) _lowerCamelCase : Union[str, Any] = ( torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size] , device=SCREAMING_SNAKE_CASE) > 0.5 ).float() _lowerCamelCase : Dict = (torch.rand((self.batch_size, self.num_labels) , device=SCREAMING_SNAKE_CASE) > 0.5).long() _lowerCamelCase : Optional[int] = self.get_config() return config, pixel_values, pixel_mask, mask_labels, class_labels def UpperCamelCase_ ( self) -> str: _lowerCamelCase : List[str] = MaskaFormerConfig( hidden_size=self.hidden_dim , ) _lowerCamelCase : Any = self.num_queries _lowerCamelCase : int = self.num_labels _lowerCamelCase : int = [1, 1, 1, 1] _lowerCamelCase : Any = self.num_channels _lowerCamelCase : Optional[Any] = 64 _lowerCamelCase : str = 128 _lowerCamelCase : Optional[Any] = self.hidden_dim _lowerCamelCase : Any = self.hidden_dim _lowerCamelCase : List[Any] = self.hidden_dim return config def UpperCamelCase_ ( self) -> Any: _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase : List[str] = self.prepare_config_and_inputs() _lowerCamelCase : str = {"""pixel_values""": pixel_values, """pixel_mask""": pixel_mask} return config, inputs_dict def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) -> Optional[int]: _lowerCamelCase : str = output.encoder_hidden_states _lowerCamelCase : int = output.pixel_decoder_hidden_states _lowerCamelCase : Optional[int] = output.transformer_decoder_hidden_states self.parent.assertTrue(len(SCREAMING_SNAKE_CASE) , len(config.backbone_config.depths)) self.parent.assertTrue(len(SCREAMING_SNAKE_CASE) , len(config.backbone_config.depths)) self.parent.assertTrue(len(SCREAMING_SNAKE_CASE) , config.decoder_layers) def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=False) -> List[str]: with torch.no_grad(): _lowerCamelCase : Optional[int] = MaskaFormerModel(config=SCREAMING_SNAKE_CASE) model.to(SCREAMING_SNAKE_CASE) model.eval() _lowerCamelCase : Optional[int] = model(pixel_values=SCREAMING_SNAKE_CASE , pixel_mask=SCREAMING_SNAKE_CASE) _lowerCamelCase : List[str] = model(SCREAMING_SNAKE_CASE , output_hidden_states=SCREAMING_SNAKE_CASE) self.parent.assertEqual( output.transformer_decoder_last_hidden_state.shape , (self.batch_size, self.num_queries, self.hidden_dim) , ) # let's ensure the other two hidden state exists self.parent.assertTrue(output.pixel_decoder_last_hidden_state is not None) self.parent.assertTrue(output.encoder_last_hidden_state is not None) if output_hidden_states: self.check_output_hidden_state(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) -> str: _lowerCamelCase : str = MaskaFormerForUniversalSegmentation(config=SCREAMING_SNAKE_CASE) model.to(SCREAMING_SNAKE_CASE) model.eval() def comm_check_on_output(SCREAMING_SNAKE_CASE): # let's still check that all the required stuff is there self.parent.assertTrue(result.transformer_decoder_last_hidden_state is not None) self.parent.assertTrue(result.pixel_decoder_last_hidden_state is not None) self.parent.assertTrue(result.encoder_last_hidden_state is not None) # okay, now we need to check the logits shape # due to the encoder compression, masks have a //4 spatial size self.parent.assertEqual( result.masks_queries_logits.shape , (self.batch_size, self.num_queries, self.min_size // 4, self.max_size // 4) , ) # + 1 for null class self.parent.assertEqual( result.class_queries_logits.shape , (self.batch_size, self.num_queries, self.num_labels + 1)) with torch.no_grad(): _lowerCamelCase : List[Any] = model(pixel_values=SCREAMING_SNAKE_CASE , pixel_mask=SCREAMING_SNAKE_CASE) _lowerCamelCase : List[Any] = model(SCREAMING_SNAKE_CASE) comm_check_on_output(SCREAMING_SNAKE_CASE) _lowerCamelCase : Optional[Any] = model( pixel_values=SCREAMING_SNAKE_CASE , pixel_mask=SCREAMING_SNAKE_CASE , mask_labels=SCREAMING_SNAKE_CASE , class_labels=SCREAMING_SNAKE_CASE) comm_check_on_output(SCREAMING_SNAKE_CASE) self.parent.assertTrue(result.loss is not None) self.parent.assertEqual(result.loss.shape , torch.Size([1])) @require_torch class lowercase__ ( A_ ,A_ ,unittest.TestCase ): __UpperCAmelCase = (MaskaFormerModel, MaskaFormerForUniversalSegmentation) if is_torch_available() else () __UpperCAmelCase = {'''feature-extraction''': MaskaFormerModel} if is_torch_available() else {} __UpperCAmelCase = False __UpperCAmelCase = False __UpperCAmelCase = False __UpperCAmelCase = False def UpperCamelCase_ ( self) -> Dict: _lowerCamelCase : Optional[int] = MaskaFormerModelTester(self) _lowerCamelCase : Union[str, Any] = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE , has_text_modality=SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self) -> List[str]: self.config_tester.run_common_tests() def UpperCamelCase_ ( self) -> int: _lowerCamelCase , _lowerCamelCase : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskaformer_model(SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE , output_hidden_states=SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self) -> Tuple: _lowerCamelCase : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_maskaformer_instance_segmentation_head_model(*SCREAMING_SNAKE_CASE) @unittest.skip(reason="""Mask2Former does not use inputs_embeds""") def UpperCamelCase_ ( self) -> Optional[int]: pass @unittest.skip(reason="""Mask2Former does not have a get_input_embeddings method""") def UpperCamelCase_ ( self) -> Tuple: pass @unittest.skip(reason="""Mask2Former is not a generative model""") def UpperCamelCase_ ( self) -> List[Any]: pass @unittest.skip(reason="""Mask2Former does not use token embeddings""") def UpperCamelCase_ ( self) -> Any: pass @require_torch_multi_gpu @unittest.skip( reason="""Mask2Former has some layers using `add_module` which doesn't work well with `nn.DataParallel`""") def UpperCamelCase_ ( self) -> Dict: pass @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""") def UpperCamelCase_ ( self) -> Optional[int]: pass def UpperCamelCase_ ( self) -> Optional[Any]: _lowerCamelCase , _lowerCamelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _lowerCamelCase : Dict = model_class(SCREAMING_SNAKE_CASE) _lowerCamelCase : Any = inspect.signature(model.forward) # signature.parameters is an OrderedDict => so arg_names order is deterministic _lowerCamelCase : str = [*signature.parameters.keys()] _lowerCamelCase : int = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , SCREAMING_SNAKE_CASE) @slow def UpperCamelCase_ ( self) -> Optional[int]: for model_name in ["facebook/mask2former-swin-small-coco-instance"]: _lowerCamelCase : Optional[int] = MaskaFormerModel.from_pretrained(SCREAMING_SNAKE_CASE) self.assertIsNotNone(SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self) -> Optional[Any]: _lowerCamelCase : Dict = (self.model_tester.min_size,) * 2 _lowerCamelCase : str = { """pixel_values""": torch.randn((2, 3, *size) , device=SCREAMING_SNAKE_CASE), """mask_labels""": torch.randn((2, 10, *size) , device=SCREAMING_SNAKE_CASE), """class_labels""": torch.zeros(2 , 10 , device=SCREAMING_SNAKE_CASE).long(), } _lowerCamelCase : List[str] = self.model_tester.get_config() _lowerCamelCase : Tuple = MaskaFormerForUniversalSegmentation(SCREAMING_SNAKE_CASE).to(SCREAMING_SNAKE_CASE) _lowerCamelCase : Union[str, Any] = model(**SCREAMING_SNAKE_CASE) self.assertTrue(outputs.loss is not None) def UpperCamelCase_ ( self) -> Tuple: _lowerCamelCase , _lowerCamelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskaformer_model(SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE , output_hidden_states=SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self) -> Optional[int]: _lowerCamelCase , _lowerCamelCase : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _lowerCamelCase : str = model_class(SCREAMING_SNAKE_CASE).to(SCREAMING_SNAKE_CASE) _lowerCamelCase : Union[str, Any] = model(**SCREAMING_SNAKE_CASE , output_attentions=SCREAMING_SNAKE_CASE) self.assertTrue(outputs.attentions is not None) def UpperCamelCase_ ( self) -> Optional[Any]: if not self.model_tester.is_training: return _lowerCamelCase : Any = self.all_model_classes[1] _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs() _lowerCamelCase : List[Any] = model_class(SCREAMING_SNAKE_CASE) model.to(SCREAMING_SNAKE_CASE) model.train() _lowerCamelCase : int = model(SCREAMING_SNAKE_CASE , mask_labels=SCREAMING_SNAKE_CASE , class_labels=SCREAMING_SNAKE_CASE).loss loss.backward() def UpperCamelCase_ ( self) -> Optional[Any]: _lowerCamelCase : Any = self.all_model_classes[1] _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase : int = self.model_tester.prepare_config_and_inputs() _lowerCamelCase : int = True _lowerCamelCase : Optional[Any] = True _lowerCamelCase : str = model_class(SCREAMING_SNAKE_CASE).to(SCREAMING_SNAKE_CASE) model.train() _lowerCamelCase : List[Any] = model(SCREAMING_SNAKE_CASE , mask_labels=SCREAMING_SNAKE_CASE , class_labels=SCREAMING_SNAKE_CASE) _lowerCamelCase : Tuple = outputs.encoder_hidden_states[0] encoder_hidden_states.retain_grad() _lowerCamelCase : int = outputs.pixel_decoder_hidden_states[0] pixel_decoder_hidden_states.retain_grad() _lowerCamelCase : str = outputs.transformer_decoder_hidden_states[0] transformer_decoder_hidden_states.retain_grad() _lowerCamelCase : Optional[int] = outputs.attentions[0] attentions.retain_grad() outputs.loss.backward(retain_graph=SCREAMING_SNAKE_CASE) self.assertIsNotNone(encoder_hidden_states.grad) self.assertIsNotNone(pixel_decoder_hidden_states.grad) self.assertIsNotNone(transformer_decoder_hidden_states.grad) self.assertIsNotNone(attentions.grad) UpperCAmelCase = 1e-4 def _snake_case ( ): """simple docstring""" _lowerCamelCase : List[str] = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_vision @slow class lowercase__ ( unittest.TestCase ): @cached_property def UpperCamelCase_ ( self) -> int: return "facebook/mask2former-swin-small-coco-instance" @cached_property def UpperCamelCase_ ( self) -> Union[str, Any]: return MaskaFormerImageProcessor.from_pretrained(self.model_checkpoints) if is_vision_available() else None def UpperCamelCase_ ( self) -> Optional[Any]: _lowerCamelCase : Tuple = MaskaFormerModel.from_pretrained(self.model_checkpoints).to(SCREAMING_SNAKE_CASE) _lowerCamelCase : str = self.default_image_processor _lowerCamelCase : List[str] = prepare_img() _lowerCamelCase : Union[str, Any] = image_processor(SCREAMING_SNAKE_CASE , return_tensors="""pt""").to(SCREAMING_SNAKE_CASE) _lowerCamelCase : Union[str, Any] = inputs["""pixel_values"""].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0) # check size self.assertEqual(SCREAMING_SNAKE_CASE , (1, 3, 384, 384)) with torch.no_grad(): _lowerCamelCase : Dict = model(**SCREAMING_SNAKE_CASE) _lowerCamelCase : List[Any] = torch.tensor( [[-0.27_90, -1.07_17, -1.16_68], [-0.51_28, -0.31_28, -0.49_87], [-0.58_32, 0.19_71, -0.01_97]]).to(SCREAMING_SNAKE_CASE) self.assertTrue( torch.allclose( outputs.encoder_last_hidden_state[0, 0, :3, :3] , SCREAMING_SNAKE_CASE , atol=SCREAMING_SNAKE_CASE)) _lowerCamelCase : Any = torch.tensor( [[0.89_73, 1.18_47, 1.17_76], [1.19_34, 1.50_40, 1.51_28], [1.11_53, 1.44_86, 1.49_51]]).to(SCREAMING_SNAKE_CASE) self.assertTrue( torch.allclose( outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3] , SCREAMING_SNAKE_CASE , atol=SCREAMING_SNAKE_CASE)) _lowerCamelCase : Dict = torch.tensor( [[2.11_52, 1.70_00, -0.86_03], [1.58_08, 1.80_04, -0.93_53], [1.60_43, 1.74_95, -0.59_99]]).to(SCREAMING_SNAKE_CASE) self.assertTrue( torch.allclose( outputs.transformer_decoder_last_hidden_state[0, :3, :3] , SCREAMING_SNAKE_CASE , atol=SCREAMING_SNAKE_CASE)) def UpperCamelCase_ ( self) -> Any: _lowerCamelCase : Optional[Any] = MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints).to(SCREAMING_SNAKE_CASE).eval() _lowerCamelCase : Optional[Any] = self.default_image_processor _lowerCamelCase : Any = prepare_img() _lowerCamelCase : Dict = image_processor(SCREAMING_SNAKE_CASE , return_tensors="""pt""").to(SCREAMING_SNAKE_CASE) _lowerCamelCase : Union[str, Any] = inputs["""pixel_values"""].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0) # check size self.assertEqual(SCREAMING_SNAKE_CASE , (1, 3, 384, 384)) with torch.no_grad(): _lowerCamelCase : List[str] = model(**SCREAMING_SNAKE_CASE) # masks_queries_logits _lowerCamelCase : str = outputs.masks_queries_logits self.assertEqual( masks_queries_logits.shape , (1, model.config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4)) _lowerCamelCase : Any = [ [-8.78_39, -9.00_56, -8.81_21], [-7.41_04, -7.03_13, -6.54_01], [-6.61_05, -6.34_27, -6.46_75], ] _lowerCamelCase : List[Any] = torch.tensor(SCREAMING_SNAKE_CASE).to(SCREAMING_SNAKE_CASE) self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , SCREAMING_SNAKE_CASE , atol=SCREAMING_SNAKE_CASE)) # class_queries_logits _lowerCamelCase : List[str] = outputs.class_queries_logits self.assertEqual(class_queries_logits.shape , (1, model.config.num_queries, model.config.num_labels + 1)) _lowerCamelCase : Optional[Any] = torch.tensor( [ [1.83_24, -8.08_35, -4.19_22], [0.84_50, -9.00_50, -3.60_53], [0.30_45, -7.72_93, -3.02_75], ]).to(SCREAMING_SNAKE_CASE) self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , SCREAMING_SNAKE_CASE , atol=SCREAMING_SNAKE_CASE)) def UpperCamelCase_ ( self) -> int: _lowerCamelCase : Tuple = MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints).to(SCREAMING_SNAKE_CASE).eval() _lowerCamelCase : str = self.default_image_processor _lowerCamelCase : Tuple = image_processor( [np.zeros((3, 800, 1333)), np.zeros((3, 800, 1333))] , segmentation_maps=[np.zeros((384, 384)).astype(np.floataa), np.zeros((384, 384)).astype(np.floataa)] , return_tensors="""pt""" , ) _lowerCamelCase : Optional[Any] = inputs["""pixel_values"""].to(SCREAMING_SNAKE_CASE) _lowerCamelCase : Any = [el.to(SCREAMING_SNAKE_CASE) for el in inputs["""mask_labels"""]] _lowerCamelCase : Union[str, Any] = [el.to(SCREAMING_SNAKE_CASE) for el in inputs["""class_labels"""]] with torch.no_grad(): _lowerCamelCase : Any = model(**SCREAMING_SNAKE_CASE) self.assertTrue(outputs.loss is not None)
88
0
import warnings from ...utils import logging from .image_processing_clip import CLIPImageProcessor UpperCamelCase__ : List[Any] = logging.get_logger(__name__) class lowerCAmelCase_ ( lowerCamelCase_ ): def __init__( self ,*snake_case__ ,**snake_case__ ): warnings.warn( 'The class CLIPFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please' ' use CLIPImageProcessor instead.' ,snake_case__ ,) super().__init__(*snake_case__ ,**snake_case__ )
105
"""simple docstring""" from collections import OrderedDict from ...utils import logging from .auto_factory import _BaseAutoModelClass, _LazyAutoMapping, auto_class_update from .configuration_auto import CONFIG_MAPPING_NAMES UpperCAmelCase = logging.get_logger(__name__) UpperCAmelCase = OrderedDict( [ # Base model mapping ("""albert""", """FlaxAlbertModel"""), ("""bart""", """FlaxBartModel"""), ("""beit""", """FlaxBeitModel"""), ("""bert""", """FlaxBertModel"""), ("""big_bird""", """FlaxBigBirdModel"""), ("""blenderbot""", """FlaxBlenderbotModel"""), ("""blenderbot-small""", """FlaxBlenderbotSmallModel"""), ("""clip""", """FlaxCLIPModel"""), ("""distilbert""", """FlaxDistilBertModel"""), ("""electra""", """FlaxElectraModel"""), ("""gpt-sw3""", """FlaxGPT2Model"""), ("""gpt2""", """FlaxGPT2Model"""), ("""gpt_neo""", """FlaxGPTNeoModel"""), ("""gptj""", """FlaxGPTJModel"""), ("""longt5""", """FlaxLongT5Model"""), ("""marian""", """FlaxMarianModel"""), ("""mbart""", """FlaxMBartModel"""), ("""mt5""", """FlaxMT5Model"""), ("""opt""", """FlaxOPTModel"""), ("""pegasus""", """FlaxPegasusModel"""), ("""regnet""", """FlaxRegNetModel"""), ("""resnet""", """FlaxResNetModel"""), ("""roberta""", """FlaxRobertaModel"""), ("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormModel"""), ("""roformer""", """FlaxRoFormerModel"""), ("""t5""", """FlaxT5Model"""), ("""vision-text-dual-encoder""", """FlaxVisionTextDualEncoderModel"""), ("""vit""", """FlaxViTModel"""), ("""wav2vec2""", """FlaxWav2Vec2Model"""), ("""whisper""", """FlaxWhisperModel"""), ("""xglm""", """FlaxXGLMModel"""), ("""xlm-roberta""", """FlaxXLMRobertaModel"""), ] ) UpperCAmelCase = OrderedDict( [ # Model for pre-training mapping ("""albert""", """FlaxAlbertForPreTraining"""), ("""bart""", """FlaxBartForConditionalGeneration"""), ("""bert""", """FlaxBertForPreTraining"""), ("""big_bird""", """FlaxBigBirdForPreTraining"""), ("""electra""", """FlaxElectraForPreTraining"""), ("""longt5""", """FlaxLongT5ForConditionalGeneration"""), ("""mbart""", """FlaxMBartForConditionalGeneration"""), ("""mt5""", """FlaxMT5ForConditionalGeneration"""), ("""roberta""", """FlaxRobertaForMaskedLM"""), ("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormForMaskedLM"""), ("""roformer""", """FlaxRoFormerForMaskedLM"""), ("""t5""", """FlaxT5ForConditionalGeneration"""), ("""wav2vec2""", """FlaxWav2Vec2ForPreTraining"""), ("""whisper""", """FlaxWhisperForConditionalGeneration"""), ("""xlm-roberta""", """FlaxXLMRobertaForMaskedLM"""), ] ) UpperCAmelCase = OrderedDict( [ # Model for Masked LM mapping ("""albert""", """FlaxAlbertForMaskedLM"""), ("""bart""", """FlaxBartForConditionalGeneration"""), ("""bert""", """FlaxBertForMaskedLM"""), ("""big_bird""", """FlaxBigBirdForMaskedLM"""), ("""distilbert""", """FlaxDistilBertForMaskedLM"""), ("""electra""", """FlaxElectraForMaskedLM"""), ("""mbart""", """FlaxMBartForConditionalGeneration"""), ("""roberta""", """FlaxRobertaForMaskedLM"""), ("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormForMaskedLM"""), ("""roformer""", """FlaxRoFormerForMaskedLM"""), ("""xlm-roberta""", """FlaxXLMRobertaForMaskedLM"""), ] ) UpperCAmelCase = OrderedDict( [ # Model for Seq2Seq Causal LM mapping ("""bart""", """FlaxBartForConditionalGeneration"""), ("""blenderbot""", """FlaxBlenderbotForConditionalGeneration"""), ("""blenderbot-small""", """FlaxBlenderbotSmallForConditionalGeneration"""), ("""encoder-decoder""", """FlaxEncoderDecoderModel"""), ("""longt5""", """FlaxLongT5ForConditionalGeneration"""), ("""marian""", """FlaxMarianMTModel"""), ("""mbart""", """FlaxMBartForConditionalGeneration"""), ("""mt5""", """FlaxMT5ForConditionalGeneration"""), ("""pegasus""", """FlaxPegasusForConditionalGeneration"""), ("""t5""", """FlaxT5ForConditionalGeneration"""), ] ) UpperCAmelCase = OrderedDict( [ # Model for Image-classsification ("""beit""", """FlaxBeitForImageClassification"""), ("""regnet""", """FlaxRegNetForImageClassification"""), ("""resnet""", """FlaxResNetForImageClassification"""), ("""vit""", """FlaxViTForImageClassification"""), ] ) UpperCAmelCase = OrderedDict( [ ("""vision-encoder-decoder""", """FlaxVisionEncoderDecoderModel"""), ] ) UpperCAmelCase = OrderedDict( [ # Model for Causal LM mapping ("""bart""", """FlaxBartForCausalLM"""), ("""bert""", """FlaxBertForCausalLM"""), ("""big_bird""", """FlaxBigBirdForCausalLM"""), ("""electra""", """FlaxElectraForCausalLM"""), ("""gpt-sw3""", """FlaxGPT2LMHeadModel"""), ("""gpt2""", """FlaxGPT2LMHeadModel"""), ("""gpt_neo""", """FlaxGPTNeoForCausalLM"""), ("""gptj""", """FlaxGPTJForCausalLM"""), ("""opt""", """FlaxOPTForCausalLM"""), ("""roberta""", """FlaxRobertaForCausalLM"""), ("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormForCausalLM"""), ("""xglm""", """FlaxXGLMForCausalLM"""), ("""xlm-roberta""", """FlaxXLMRobertaForCausalLM"""), ] ) UpperCAmelCase = OrderedDict( [ # Model for Sequence Classification mapping ("""albert""", """FlaxAlbertForSequenceClassification"""), ("""bart""", """FlaxBartForSequenceClassification"""), ("""bert""", """FlaxBertForSequenceClassification"""), ("""big_bird""", """FlaxBigBirdForSequenceClassification"""), ("""distilbert""", """FlaxDistilBertForSequenceClassification"""), ("""electra""", """FlaxElectraForSequenceClassification"""), ("""mbart""", """FlaxMBartForSequenceClassification"""), ("""roberta""", """FlaxRobertaForSequenceClassification"""), ("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormForSequenceClassification"""), ("""roformer""", """FlaxRoFormerForSequenceClassification"""), ("""xlm-roberta""", """FlaxXLMRobertaForSequenceClassification"""), ] ) UpperCAmelCase = OrderedDict( [ # Model for Question Answering mapping ("""albert""", """FlaxAlbertForQuestionAnswering"""), ("""bart""", """FlaxBartForQuestionAnswering"""), ("""bert""", """FlaxBertForQuestionAnswering"""), ("""big_bird""", """FlaxBigBirdForQuestionAnswering"""), ("""distilbert""", """FlaxDistilBertForQuestionAnswering"""), ("""electra""", """FlaxElectraForQuestionAnswering"""), ("""mbart""", """FlaxMBartForQuestionAnswering"""), ("""roberta""", """FlaxRobertaForQuestionAnswering"""), ("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormForQuestionAnswering"""), ("""roformer""", """FlaxRoFormerForQuestionAnswering"""), ("""xlm-roberta""", """FlaxXLMRobertaForQuestionAnswering"""), ] ) UpperCAmelCase = OrderedDict( [ # Model for Token Classification mapping ("""albert""", """FlaxAlbertForTokenClassification"""), ("""bert""", """FlaxBertForTokenClassification"""), ("""big_bird""", """FlaxBigBirdForTokenClassification"""), ("""distilbert""", """FlaxDistilBertForTokenClassification"""), ("""electra""", """FlaxElectraForTokenClassification"""), ("""roberta""", """FlaxRobertaForTokenClassification"""), ("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormForTokenClassification"""), ("""roformer""", """FlaxRoFormerForTokenClassification"""), ("""xlm-roberta""", """FlaxXLMRobertaForTokenClassification"""), ] ) UpperCAmelCase = OrderedDict( [ # Model for Multiple Choice mapping ("""albert""", """FlaxAlbertForMultipleChoice"""), ("""bert""", """FlaxBertForMultipleChoice"""), ("""big_bird""", """FlaxBigBirdForMultipleChoice"""), ("""distilbert""", """FlaxDistilBertForMultipleChoice"""), ("""electra""", """FlaxElectraForMultipleChoice"""), ("""roberta""", """FlaxRobertaForMultipleChoice"""), ("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormForMultipleChoice"""), ("""roformer""", """FlaxRoFormerForMultipleChoice"""), ("""xlm-roberta""", """FlaxXLMRobertaForMultipleChoice"""), ] ) UpperCAmelCase = OrderedDict( [ ("""bert""", """FlaxBertForNextSentencePrediction"""), ] ) UpperCAmelCase = OrderedDict( [ ("""speech-encoder-decoder""", """FlaxSpeechEncoderDecoderModel"""), ("""whisper""", """FlaxWhisperForConditionalGeneration"""), ] ) UpperCAmelCase = OrderedDict( [ ("""whisper""", """FlaxWhisperForAudioClassification"""), ] ) UpperCAmelCase = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_MAPPING_NAMES) UpperCAmelCase = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_PRETRAINING_MAPPING_NAMES) UpperCAmelCase = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MASKED_LM_MAPPING_NAMES) UpperCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES ) UpperCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES ) UpperCAmelCase = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES) UpperCAmelCase = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_CAUSAL_LM_MAPPING_NAMES) UpperCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES ) UpperCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES ) UpperCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES ) UpperCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES ) UpperCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING_NAMES ) UpperCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES ) UpperCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES ) class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_MAPPING UpperCAmelCase = auto_class_update(FlaxAutoModel) class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_PRETRAINING_MAPPING UpperCAmelCase = auto_class_update(FlaxAutoModelForPreTraining, head_doc="""pretraining""") class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_CAUSAL_LM_MAPPING UpperCAmelCase = auto_class_update(FlaxAutoModelForCausalLM, head_doc="""causal language modeling""") class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_MASKED_LM_MAPPING UpperCAmelCase = auto_class_update(FlaxAutoModelForMaskedLM, head_doc="""masked language modeling""") class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING UpperCAmelCase = auto_class_update( FlaxAutoModelForSeqaSeqLM, head_doc="""sequence-to-sequence language modeling""", checkpoint_for_example="""t5-base""" ) class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING UpperCAmelCase = auto_class_update( FlaxAutoModelForSequenceClassification, head_doc="""sequence classification""" ) class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING UpperCAmelCase = auto_class_update(FlaxAutoModelForQuestionAnswering, head_doc="""question answering""") class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING UpperCAmelCase = auto_class_update( FlaxAutoModelForTokenClassification, head_doc="""token classification""" ) class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING UpperCAmelCase = auto_class_update(FlaxAutoModelForMultipleChoice, head_doc="""multiple choice""") class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING UpperCAmelCase = auto_class_update( FlaxAutoModelForNextSentencePrediction, head_doc="""next sentence prediction""" ) class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING UpperCAmelCase = auto_class_update( FlaxAutoModelForImageClassification, head_doc="""image classification""" ) class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING UpperCAmelCase = auto_class_update(FlaxAutoModelForVisionaSeq, head_doc="""vision-to-text modeling""") class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING UpperCAmelCase = auto_class_update( FlaxAutoModelForSpeechSeqaSeq, head_doc="""sequence-to-sequence speech-to-text modeling""" )
88
0
# This model implementation is heavily inspired by https://github.com/haofanwang/ControlNet-for-Diffusers/ import gc import random import tempfile import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, ControlNetModel, DDIMScheduler, StableDiffusionControlNetImgaImgPipeline, UNetaDConditionModel, ) from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_controlnet import MultiControlNetModel from diffusers.utils import floats_tensor, load_image, load_numpy, randn_tensor, slow, torch_device from diffusers.utils.import_utils import is_xformers_available 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 ( PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin, ) enable_full_determinism() class lowerCAmelCase__ ( _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , unittest.TestCase ): A_ : Optional[Any] = StableDiffusionControlNetImgaImgPipeline A_ : Union[str, Any] = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'height', 'width'} A_ : Union[str, Any] = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS A_ : Optional[Any] = IMAGE_TO_IMAGE_IMAGE_PARAMS.union({'control_image'} ) A_ : str = IMAGE_TO_IMAGE_IMAGE_PARAMS def __UpperCamelCase ( self : Optional[Any] ) -> List[str]: torch.manual_seed(0 ) A = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D') , up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D') , cross_attention_dim=32 , ) torch.manual_seed(0 ) A = ControlNetModel( block_out_channels=(32, 64) , layers_per_block=2 , in_channels=4 , down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D') , cross_attention_dim=32 , conditioning_embedding_out_channels=(16, 32) , ) torch.manual_seed(0 ) A = DDIMScheduler( beta_start=0.0_0_0_8_5 , beta_end=0.0_1_2 , beta_schedule='scaled_linear' , clip_sample=__UpperCamelCase , set_alpha_to_one=__UpperCamelCase , ) torch.manual_seed(0 ) A = 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 , ) torch.manual_seed(0 ) A = 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=1_000 , ) A = CLIPTextModel(__UpperCamelCase ) A = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) A = { 'unet': unet, 'controlnet': controlnet, 'scheduler': scheduler, 'vae': vae, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'safety_checker': None, 'feature_extractor': None, } return components def __UpperCamelCase ( self : str , __UpperCamelCase : Dict , __UpperCamelCase : Union[str, Any]=0 ) -> Union[str, Any]: if str(__UpperCamelCase ).startswith('mps' ): A = torch.manual_seed(__UpperCamelCase ) else: A = torch.Generator(device=__UpperCamelCase ).manual_seed(__UpperCamelCase ) A = 2 A = randn_tensor( (1, 3, 32 * controlnet_embedder_scale_factor, 32 * controlnet_embedder_scale_factor) , generator=__UpperCamelCase , device=torch.device(__UpperCamelCase ) , ) A = floats_tensor(control_image.shape , rng=random.Random(__UpperCamelCase ) ).to(__UpperCamelCase ) A = image.cpu().permute(0 , 2 , 3 , 1 )[0] A = Image.fromarray(np.uinta(__UpperCamelCase ) ).convert('RGB' ).resize((64, 64) ) A = { 'prompt': 'A painting of a squirrel eating a burger', 'generator': generator, 'num_inference_steps': 2, 'guidance_scale': 6.0, 'output_type': 'numpy', 'image': image, 'control_image': control_image, } return inputs def __UpperCamelCase ( self : Optional[int] ) -> List[str]: return self._test_attention_slicing_forward_pass(expected_max_diff=2e-3 ) @unittest.skipIf( torch_device != 'cuda' or not is_xformers_available() , reason='XFormers attention is only available with CUDA and `xformers` installed' , ) def __UpperCamelCase ( self : List[str] ) -> Optional[int]: self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=2e-3 ) def __UpperCamelCase ( self : List[str] ) -> Tuple: self._test_inference_batch_single_identical(expected_max_diff=2e-3 ) class lowerCAmelCase__ ( _lowerCamelCase , _lowerCamelCase , unittest.TestCase ): A_ : str = StableDiffusionControlNetImgaImgPipeline A_ : Optional[int] = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'height', 'width'} A_ : Any = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS A_ : Dict = frozenset([] ) # TO_DO: add image_params once refactored VaeImageProcessor.preprocess def __UpperCamelCase ( self : Tuple ) -> Optional[Any]: torch.manual_seed(0 ) A = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D') , up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D') , cross_attention_dim=32 , ) torch.manual_seed(0 ) def init_weights(__UpperCamelCase : Dict ): if isinstance(__UpperCamelCase , torch.nn.Convad ): torch.nn.init.normal(m.weight ) m.bias.data.fill_(1.0 ) A = ControlNetModel( block_out_channels=(32, 64) , layers_per_block=2 , in_channels=4 , down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D') , cross_attention_dim=32 , conditioning_embedding_out_channels=(16, 32) , ) controlneta.controlnet_down_blocks.apply(__UpperCamelCase ) torch.manual_seed(0 ) A = ControlNetModel( block_out_channels=(32, 64) , layers_per_block=2 , in_channels=4 , down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D') , cross_attention_dim=32 , conditioning_embedding_out_channels=(16, 32) , ) controlneta.controlnet_down_blocks.apply(__UpperCamelCase ) torch.manual_seed(0 ) A = DDIMScheduler( beta_start=0.0_0_0_8_5 , beta_end=0.0_1_2 , beta_schedule='scaled_linear' , clip_sample=__UpperCamelCase , set_alpha_to_one=__UpperCamelCase , ) torch.manual_seed(0 ) A = 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 , ) torch.manual_seed(0 ) A = 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=1_000 , ) A = CLIPTextModel(__UpperCamelCase ) A = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) A = MultiControlNetModel([controlneta, controlneta] ) A = { 'unet': unet, 'controlnet': controlnet, 'scheduler': scheduler, 'vae': vae, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'safety_checker': None, 'feature_extractor': None, } return components def __UpperCamelCase ( self : Union[str, Any] , __UpperCamelCase : List[Any] , __UpperCamelCase : Optional[int]=0 ) -> Optional[Any]: if str(__UpperCamelCase ).startswith('mps' ): A = torch.manual_seed(__UpperCamelCase ) else: A = torch.Generator(device=__UpperCamelCase ).manual_seed(__UpperCamelCase ) A = 2 A = [ randn_tensor( (1, 3, 32 * controlnet_embedder_scale_factor, 32 * controlnet_embedder_scale_factor) , generator=__UpperCamelCase , device=torch.device(__UpperCamelCase ) , ), randn_tensor( (1, 3, 32 * controlnet_embedder_scale_factor, 32 * controlnet_embedder_scale_factor) , generator=__UpperCamelCase , device=torch.device(__UpperCamelCase ) , ), ] A = floats_tensor(control_image[0].shape , rng=random.Random(__UpperCamelCase ) ).to(__UpperCamelCase ) A = image.cpu().permute(0 , 2 , 3 , 1 )[0] A = Image.fromarray(np.uinta(__UpperCamelCase ) ).convert('RGB' ).resize((64, 64) ) A = { 'prompt': 'A painting of a squirrel eating a burger', 'generator': generator, 'num_inference_steps': 2, 'guidance_scale': 6.0, 'output_type': 'numpy', 'image': image, 'control_image': control_image, } return inputs def __UpperCamelCase ( self : Any ) -> List[Any]: A = self.get_dummy_components() A = self.pipeline_class(**__UpperCamelCase ) pipe.to(__UpperCamelCase ) A = 1_0.0 A = 4 A = self.get_dummy_inputs(__UpperCamelCase ) A = steps A = scale A = pipe(**__UpperCamelCase )[0] A = self.get_dummy_inputs(__UpperCamelCase ) A = steps A = scale A = pipe(**__UpperCamelCase , control_guidance_start=0.1 , control_guidance_end=0.2 )[0] A = self.get_dummy_inputs(__UpperCamelCase ) A = steps A = scale A = pipe(**__UpperCamelCase , control_guidance_start=[0.1, 0.3] , control_guidance_end=[0.2, 0.7] )[0] A = self.get_dummy_inputs(__UpperCamelCase ) A = steps A = scale A = pipe(**__UpperCamelCase , control_guidance_start=0.4 , control_guidance_end=[0.5, 0.8] )[0] # make sure that all outputs are different assert np.sum(np.abs(output_a - output_a ) ) > 1e-3 assert np.sum(np.abs(output_a - output_a ) ) > 1e-3 assert np.sum(np.abs(output_a - output_a ) ) > 1e-3 def __UpperCamelCase ( self : Dict ) -> Dict: return self._test_attention_slicing_forward_pass(expected_max_diff=2e-3 ) @unittest.skipIf( torch_device != 'cuda' or not is_xformers_available() , reason='XFormers attention is only available with CUDA and `xformers` installed' , ) def __UpperCamelCase ( self : Optional[Any] ) -> List[str]: self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=2e-3 ) def __UpperCamelCase ( self : Any ) -> List[Any]: self._test_inference_batch_single_identical(expected_max_diff=2e-3 ) def __UpperCamelCase ( self : Optional[int] ) -> int: A = self.get_dummy_components() A = self.pipeline_class(**__UpperCamelCase ) pipe.to(__UpperCamelCase ) pipe.set_progress_bar_config(disable=__UpperCamelCase ) with tempfile.TemporaryDirectory() as tmpdir: try: # save_pretrained is not implemented for Multi-ControlNet pipe.save_pretrained(__UpperCamelCase ) except NotImplementedError: pass @slow @require_torch_gpu class lowerCAmelCase__ ( unittest.TestCase ): def __UpperCamelCase ( self : Optional[Any] ) -> List[str]: super().tearDown() gc.collect() torch.cuda.empty_cache() def __UpperCamelCase ( self : List[Any] ) -> str: A = ControlNetModel.from_pretrained('lllyasviel/sd-controlnet-canny' ) A = StableDiffusionControlNetImgaImgPipeline.from_pretrained( 'runwayml/stable-diffusion-v1-5' , safety_checker=__UpperCamelCase , controlnet=__UpperCamelCase ) pipe.enable_model_cpu_offload() pipe.set_progress_bar_config(disable=__UpperCamelCase ) A = torch.Generator(device='cpu' ).manual_seed(0 ) A = 'evil space-punk bird' A = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/bird_canny.png' ).resize((512, 512) ) A = load_image( 'https://huggingface.co/lllyasviel/sd-controlnet-canny/resolve/main/images/bird.png' ).resize((512, 512) ) A = pipe( __UpperCamelCase , __UpperCamelCase , control_image=__UpperCamelCase , generator=__UpperCamelCase , output_type='np' , num_inference_steps=50 , strength=0.6 , ) A = output.images[0] assert image.shape == (512, 512, 3) A = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/img2img.npy' ) assert np.abs(expected_image - image ).max() < 9e-2
106
"""simple docstring""" # limitations under the License. # NOTE: This file is deprecated and will be removed in a future version. # It only exists so that temporarely `from diffusers.pipelines import DiffusionPipeline` works from .pipelines import DiffusionPipeline, ImagePipelineOutput # noqa: F401 from .utils import deprecate deprecate( """pipelines_utils""", """0.22.0""", """Importing `DiffusionPipeline` or `ImagePipelineOutput` from diffusers.pipeline_utils is deprecated. Please import from diffusers.pipelines.pipeline_utils instead.""", standard_warn=False, stacklevel=3, )
88
0
'''simple docstring''' import inspect import unittest from transformers import DPTConfig from transformers.file_utils import is_torch_available, is_vision_available from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_vision, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import MODEL_MAPPING, DPTForDepthEstimation, DPTForSemanticSegmentation, DPTModel from transformers.models.dpt.modeling_dpt import DPT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import DPTImageProcessor class lowercase_ : """simple docstring""" def __init__( self : Union[str, Any], UpperCamelCase__ : Any, UpperCamelCase__ : Optional[Any]=2, UpperCamelCase__ : Union[str, Any]=32, UpperCamelCase__ : Optional[Any]=16, UpperCamelCase__ : Union[str, Any]=3, UpperCamelCase__ : Optional[int]=True, UpperCamelCase__ : Union[str, Any]=True, UpperCamelCase__ : Union[str, Any]=32, UpperCamelCase__ : Union[str, Any]=4, UpperCamelCase__ : List[str]=[0, 1, 2, 3], UpperCamelCase__ : List[Any]=4, UpperCamelCase__ : Any=37, UpperCamelCase__ : List[Any]="gelu", UpperCamelCase__ : Any=0.1, UpperCamelCase__ : List[str]=0.1, UpperCamelCase__ : Tuple=0.02, UpperCamelCase__ : Optional[int]=3, UpperCamelCase__ : int=[1, 3_84, 24, 24], UpperCamelCase__ : int=True, UpperCamelCase__ : Optional[Any]=None, ) -> str: _A = parent _A = batch_size _A = image_size _A = patch_size _A = num_channels _A = is_training _A = use_labels _A = hidden_size _A = num_hidden_layers _A = backbone_out_indices _A = num_attention_heads _A = intermediate_size _A = hidden_act _A = hidden_dropout_prob _A = attention_probs_dropout_prob _A = initializer_range _A = num_labels _A = backbone_featmap_shape _A = scope _A = is_hybrid # sequence length of DPT = num_patches + 1 (we add 1 for the [CLS] token) _A = (image_size // patch_size) ** 2 _A = num_patches + 1 def __UpperCAmelCase ( self : Optional[Any] ) -> Union[str, Any]: _A = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) _A = None if self.use_labels: _A = ids_tensor([self.batch_size, self.image_size, self.image_size], self.num_labels ) _A = self.get_config() return config, pixel_values, labels def __UpperCAmelCase ( self : Optional[Any] ) -> int: _A = { 'global_padding': 'same', 'layer_type': 'bottleneck', 'depths': [3, 4, 9], 'out_features': ['stage1', 'stage2', 'stage3'], 'embedding_dynamic_padding': True, 'hidden_sizes': [96, 1_92, 3_84, 7_68], 'num_groups': 2, } return DPTConfig( image_size=self.image_size, patch_size=self.patch_size, num_channels=self.num_channels, hidden_size=self.hidden_size, num_hidden_layers=self.num_hidden_layers, backbone_out_indices=self.backbone_out_indices, num_attention_heads=self.num_attention_heads, intermediate_size=self.intermediate_size, hidden_act=self.hidden_act, hidden_dropout_prob=self.hidden_dropout_prob, attention_probs_dropout_prob=self.attention_probs_dropout_prob, is_decoder=UpperCamelCase__, initializer_range=self.initializer_range, is_hybrid=self.is_hybrid, backbone_config=UpperCamelCase__, backbone_featmap_shape=self.backbone_featmap_shape, ) def __UpperCAmelCase ( self : int, UpperCamelCase__ : str, UpperCamelCase__ : int, UpperCamelCase__ : List[str] ) -> str: _A = DPTModel(config=UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() _A = model(UpperCamelCase__ ) self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size) ) def __UpperCAmelCase ( self : Tuple, UpperCamelCase__ : List[str], UpperCamelCase__ : List[Any], UpperCamelCase__ : int ) -> Union[str, Any]: _A = self.num_labels _A = DPTForDepthEstimation(UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() _A = model(UpperCamelCase__ ) self.parent.assertEqual(result.predicted_depth.shape, (self.batch_size, self.image_size, self.image_size) ) def __UpperCAmelCase ( self : Tuple, UpperCamelCase__ : Optional[Any], UpperCamelCase__ : Union[str, Any], UpperCamelCase__ : int ) -> Any: _A = self.num_labels _A = DPTForSemanticSegmentation(UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() _A = model(UpperCamelCase__, labels=UpperCamelCase__ ) self.parent.assertEqual( result.logits.shape, (self.batch_size, self.num_labels, self.image_size, self.image_size) ) def __UpperCAmelCase ( self : Tuple ) -> Optional[int]: _A = self.prepare_config_and_inputs() _A , _A , _A = config_and_inputs _A = {'pixel_values': pixel_values} return config, inputs_dict @require_torch class lowercase_ ( _UpperCamelCase , _UpperCamelCase , unittest.TestCase ): """simple docstring""" __lowerCAmelCase = (DPTModel, DPTForDepthEstimation, DPTForSemanticSegmentation) if is_torch_available() else () __lowerCAmelCase = ( { "depth-estimation": DPTForDepthEstimation, "feature-extraction": DPTModel, "image-segmentation": DPTForSemanticSegmentation, } if is_torch_available() else {} ) __lowerCAmelCase = False __lowerCAmelCase = False __lowerCAmelCase = False def __UpperCAmelCase ( self : List[Any] ) -> Optional[Any]: _A = DPTModelTester(self ) _A = ConfigTester(self, config_class=UpperCamelCase__, has_text_modality=UpperCamelCase__, hidden_size=37 ) def __UpperCAmelCase ( self : Tuple ) -> Union[str, Any]: self.config_tester.run_common_tests() @unittest.skip(reason='DPT does not use inputs_embeds' ) def __UpperCAmelCase ( self : Union[str, Any] ) -> str: pass def __UpperCAmelCase ( self : Optional[Any] ) -> List[Any]: _A , _A = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _A = model_class(UpperCamelCase__ ) self.assertIsInstance(model.get_input_embeddings(), (nn.Module) ) _A = model.get_output_embeddings() self.assertTrue(x is None or isinstance(UpperCamelCase__, nn.Linear ) ) def __UpperCAmelCase ( self : Union[str, Any] ) -> Tuple: _A , _A = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _A = model_class(UpperCamelCase__ ) _A = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic _A = [*signature.parameters.keys()] _A = ['pixel_values'] self.assertListEqual(arg_names[:1], UpperCamelCase__ ) def __UpperCAmelCase ( self : str ) -> Optional[int]: _A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCamelCase__ ) def __UpperCAmelCase ( self : int ) -> Optional[int]: _A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_depth_estimation(*UpperCamelCase__ ) def __UpperCAmelCase ( self : Any ) -> List[Any]: _A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*UpperCamelCase__ ) def __UpperCAmelCase ( self : List[Any] ) -> Optional[Any]: for model_class in self.all_model_classes: if model_class.__name__ == "DPTForDepthEstimation": continue _A , _A = self.model_tester.prepare_config_and_inputs_for_common() _A = True if model_class in get_values(UpperCamelCase__ ): continue _A = model_class(UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.train() _A = self._prepare_for_class(UpperCamelCase__, UpperCamelCase__, return_labels=UpperCamelCase__ ) _A = model(**UpperCamelCase__ ).loss loss.backward() def __UpperCAmelCase ( self : Any ) -> List[Any]: for model_class in self.all_model_classes: if model_class.__name__ == "DPTForDepthEstimation": continue _A , _A = self.model_tester.prepare_config_and_inputs_for_common() _A = False _A = True if model_class in get_values(UpperCamelCase__ ) or not model_class.supports_gradient_checkpointing: continue _A = model_class(UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.gradient_checkpointing_enable() model.train() _A = self._prepare_for_class(UpperCamelCase__, UpperCamelCase__, return_labels=UpperCamelCase__ ) _A = model(**UpperCamelCase__ ).loss loss.backward() def __UpperCAmelCase ( self : int ) -> List[Any]: _A , _A = self.model_tester.prepare_config_and_inputs_for_common() _A = _config_zero_init(UpperCamelCase__ ) for model_class in self.all_model_classes: _A = model_class(config=UpperCamelCase__ ) # Skip the check for the backbone _A = [] for name, module in model.named_modules(): if module.__class__.__name__ == "DPTViTHybridEmbeddings": _A = [f'{name}.{key}' for key in module.state_dict().keys()] break for name, param in model.named_parameters(): if param.requires_grad: if name in backbone_params: continue self.assertIn( ((param.data.mean() * 1e9).round() / 1e9).item(), [0.0, 1.0], msg=f'Parameter {name} of model {model_class} seems not properly initialized', ) @unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.' ) def __UpperCAmelCase ( self : Optional[int] ) -> int: pass @slow def __UpperCAmelCase ( self : Optional[Any] ) -> Dict: for model_name in DPT_PRETRAINED_MODEL_ARCHIVE_LIST[1:]: _A = DPTModel.from_pretrained(UpperCamelCase__ ) self.assertIsNotNone(UpperCamelCase__ ) def __UpperCAmelCase ( self : Any ) -> List[Any]: # We do this test only for DPTForDepthEstimation since it is the only model that uses readout_type _A , _A = self.model_tester.prepare_config_and_inputs_for_common() _A = 'add' with self.assertRaises(UpperCamelCase__ ): _A = DPTForDepthEstimation(UpperCamelCase__ ) def _SCREAMING_SNAKE_CASE ( ): _A = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_torch @require_vision @slow class lowercase_ ( unittest.TestCase ): """simple docstring""" def __UpperCAmelCase ( self : int ) -> List[str]: _A = DPTImageProcessor.from_pretrained('Intel/dpt-hybrid-midas' ) _A = DPTForDepthEstimation.from_pretrained('Intel/dpt-hybrid-midas' ).to(UpperCamelCase__ ) _A = prepare_img() _A = image_processor(images=UpperCamelCase__, return_tensors='pt' ).to(UpperCamelCase__ ) # forward pass with torch.no_grad(): _A = model(**UpperCamelCase__ ) _A = outputs.predicted_depth # verify the predicted depth _A = torch.Size((1, 3_84, 3_84) ) self.assertEqual(predicted_depth.shape, UpperCamelCase__ ) _A = torch.tensor( [[[5.6_437, 5.6_146, 5.6_511], [5.4_371, 5.5_649, 5.5_958], [5.5_215, 5.5_184, 5.5_293]]] ).to(UpperCamelCase__ ) self.assertTrue(torch.allclose(outputs.predicted_depth[:3, :3, :3] / 1_00, UpperCamelCase__, atol=1e-4 ) )
107
"""simple docstring""" def _snake_case ( __snake_case : list[list[int]] , __snake_case : int , __snake_case : int , __snake_case : list[int] ): """simple docstring""" 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 _snake_case ( __snake_case : list[list[int]] , __snake_case : list[int] , __snake_case : int ): """simple docstring""" if curr_ind == len(__snake_case ): # 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(__snake_case ) ): if valid_connection(__snake_case , __snake_case , __snake_case , __snake_case ): # Insert current vertex into path as next transition _lowerCamelCase : List[str] = next_ver # Validate created path if util_hamilton_cycle(__snake_case , __snake_case , curr_ind + 1 ): return True # Backtrack _lowerCamelCase : Tuple = -1 return False def _snake_case ( __snake_case : list[list[int]] , __snake_case : int = 0 ): """simple docstring""" _lowerCamelCase : Any = [-1] * (len(__snake_case ) + 1) # initialize start and end of path with starting index _lowerCamelCase : Optional[int] = start_index # evaluate and if we find answer return path either return empty array return path if util_hamilton_cycle(__snake_case , __snake_case , 1 ) else []
88
0
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
108
"""simple docstring""" import mpmath # for roots of unity import numpy as np class lowercase__ : def __init__( self , SCREAMING_SNAKE_CASE=None , SCREAMING_SNAKE_CASE=None) -> Tuple: # Input as list _lowerCamelCase : Any = list(poly_a or [0])[:] _lowerCamelCase : Optional[Any] = list(poly_b or [0])[:] # Remove leading zero coefficients while self.polyA[-1] == 0: self.polyA.pop() _lowerCamelCase : int = len(self.polyA) while self.polyB[-1] == 0: self.polyB.pop() _lowerCamelCase : Union[str, Any] = len(self.polyB) # Add 0 to make lengths equal a power of 2 _lowerCamelCase : List[Any] = int( 2 ** np.ceil(np.loga(len(self.polyA) + len(self.polyB) - 1))) while len(self.polyA) < self.c_max_length: self.polyA.append(0) while len(self.polyB) < self.c_max_length: self.polyB.append(0) # A complex root used for the fourier transform _lowerCamelCase : Optional[Any] = complex(mpmath.root(x=1 , n=self.c_max_length , k=1)) # The product _lowerCamelCase : int = self.__multiply() def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE) -> List[str]: _lowerCamelCase : Dict = [[x] for x in self.polyA] if which == """A""" else [[x] for x in self.polyB] # Corner case if len(SCREAMING_SNAKE_CASE) <= 1: return dft[0] # _lowerCamelCase : str = self.c_max_length // 2 while next_ncol > 0: _lowerCamelCase : Dict = [[] for i in range(SCREAMING_SNAKE_CASE)] _lowerCamelCase : Tuple = self.root**next_ncol # First half of next step _lowerCamelCase : int = 1 for j in range(self.c_max_length // (next_ncol * 2)): for i in range(SCREAMING_SNAKE_CASE): new_dft[i].append(dft[i][j] + current_root * dft[i + next_ncol][j]) current_root *= root # Second half of next step _lowerCamelCase : Optional[int] = 1 for j in range(self.c_max_length // (next_ncol * 2)): for i in range(SCREAMING_SNAKE_CASE): new_dft[i].append(dft[i][j] - current_root * dft[i + next_ncol][j]) current_root *= root # Update _lowerCamelCase : Union[str, Any] = new_dft _lowerCamelCase : List[str] = next_ncol // 2 return dft[0] def UpperCamelCase_ ( self) -> str: _lowerCamelCase : Optional[Any] = self.__dft("""A""") _lowerCamelCase : List[str] = self.__dft("""B""") _lowerCamelCase : List[Any] = [[dft_a[i] * dft_b[i] for i in range(self.c_max_length)]] del dft_a del dft_b # Corner Case if len(inverce_c[0]) <= 1: return inverce_c[0] # Inverse DFT _lowerCamelCase : List[str] = 2 while next_ncol <= self.c_max_length: _lowerCamelCase : Any = [[] for i in range(SCREAMING_SNAKE_CASE)] _lowerCamelCase : List[Any] = self.root ** (next_ncol // 2) _lowerCamelCase : str = 1 # First half of next step for j in range(self.c_max_length // next_ncol): for i in range(next_ncol // 2): # Even positions new_inverse_c[i].append( ( inverce_c[i][j] + inverce_c[i][j + self.c_max_length // next_ncol] ) / 2) # Odd positions new_inverse_c[i + next_ncol // 2].append( ( inverce_c[i][j] - inverce_c[i][j + self.c_max_length // next_ncol] ) / (2 * current_root)) current_root *= root # Update _lowerCamelCase : Any = new_inverse_c next_ncol *= 2 # Unpack _lowerCamelCase : Optional[Any] = [round(x[0].real , 8) + round(x[0].imag , 8) * 1j for x in inverce_c] # Remove leading 0's while inverce_c[-1] == 0: inverce_c.pop() return inverce_c def __str__( self) -> Any: _lowerCamelCase : Dict = """A = """ + """ + """.join( F'{coef}*x^{i}' for coef, i in enumerate(self.polyA[: self.len_A])) _lowerCamelCase : List[Any] = """B = """ + """ + """.join( F'{coef}*x^{i}' for coef, i in enumerate(self.polyB[: self.len_B])) _lowerCamelCase : int = """A*B = """ + """ + """.join( F'{coef}*x^{i}' for coef, i in enumerate(self.product)) return F'{a}\n{b}\n{c}' # Unit tests if __name__ == "__main__": import doctest doctest.testmod()
88
0
'''simple docstring''' import dataclasses import json import warnings from dataclasses import dataclass, field from time import time from typing import List from ..utils import logging a = logging.get_logger(__name__) def __magic_name__ ( __UpperCAmelCase=None , __UpperCAmelCase=None ) -> Dict: '''simple docstring''' return field(default_factory=lambda: default , metadata=__UpperCAmelCase ) @dataclass class __a : __UpperCamelCase : List[str] = list_field( default=[], metadata={ 'help': ( 'Model checkpoints to be provided to the AutoModel classes. Leave blank to benchmark the base version' ' of all available models' ) }, ) __UpperCamelCase : List[int] = list_field( default=[8], metadata={'help': 'List of batch sizes for which memory and time performance will be evaluated'} ) __UpperCamelCase : List[int] = list_field( default=[8, 32, 128, 512], metadata={'help': 'List of sequence lengths for which memory and time performance will be evaluated'}, ) __UpperCamelCase : bool = field( default=_snake_case, metadata={'help': 'Whether to benchmark inference of model. Inference can be disabled via --no-inference.'}, ) __UpperCamelCase : bool = field( default=_snake_case, metadata={'help': 'Whether to run on available cuda devices. Cuda can be disabled via --no-cuda.'}, ) __UpperCamelCase : bool = field( default=_snake_case, metadata={'help': 'Whether to run on available tpu devices. TPU can be disabled via --no-tpu.'} ) __UpperCamelCase : bool = field(default=_snake_case, metadata={'help': 'Use FP16 to accelerate inference.'} ) __UpperCamelCase : bool = field(default=_snake_case, metadata={'help': 'Benchmark training of model'} ) __UpperCamelCase : bool = field(default=_snake_case, metadata={'help': 'Verbose memory tracing'} ) __UpperCamelCase : bool = field( default=_snake_case, metadata={'help': 'Whether to perform speed measurements. Speed measurements can be disabled via --no-speed.'}, ) __UpperCamelCase : bool = field( default=_snake_case, metadata={ 'help': 'Whether to perform memory measurements. Memory measurements can be disabled via --no-memory' }, ) __UpperCamelCase : bool = field(default=_snake_case, metadata={'help': 'Trace memory line by line'} ) __UpperCamelCase : bool = field(default=_snake_case, metadata={'help': 'Save result to a CSV file'} ) __UpperCamelCase : bool = field(default=_snake_case, metadata={'help': 'Save all print statements in a log file'} ) __UpperCamelCase : bool = field(default=_snake_case, metadata={'help': 'Whether to print environment information'} ) __UpperCamelCase : bool = field( default=_snake_case, metadata={ 'help': ( 'Whether to use multiprocessing for memory and speed measurement. It is highly recommended to use' ' multiprocessing for accurate CPU and GPU memory measurements. This option should only be disabled' ' for debugging / testing and on TPU.' ) }, ) __UpperCamelCase : str = field( default=F'inference_time_{round(time() )}.csv', metadata={'help': 'CSV filename used if saving time results to csv.'}, ) __UpperCamelCase : str = field( default=F'inference_memory_{round(time() )}.csv', metadata={'help': 'CSV filename used if saving memory results to csv.'}, ) __UpperCamelCase : str = field( default=F'train_time_{round(time() )}.csv', metadata={'help': 'CSV filename used if saving time results to csv for training.'}, ) __UpperCamelCase : str = field( default=F'train_memory_{round(time() )}.csv', metadata={'help': 'CSV filename used if saving memory results to csv for training.'}, ) __UpperCamelCase : str = field( default=F'env_info_{round(time() )}.csv', metadata={'help': 'CSV filename used if saving environment information.'}, ) __UpperCamelCase : str = field( default=F'log_{round(time() )}.csv', metadata={'help': 'Log filename used if print statements are saved in log.'}, ) __UpperCamelCase : int = field(default=3, metadata={'help': 'Times an experiment will be run.'} ) __UpperCamelCase : bool = field( default=_snake_case, metadata={ 'help': ( 'Instead of loading the model as defined in `config.architectures` if exists, just load the pretrain' ' model weights.' ) }, ) def UpperCAmelCase__ ( self : List[Any] ): '''simple docstring''' warnings.warn( f"""The class {self.__class__} is deprecated. Hugging Face Benchmarking utils""" """ are deprecated in general and it is advised to use external Benchmarking libraries """ """ to benchmark Transformer models.""" ,lowerCamelCase ,) def UpperCAmelCase__ ( self : int ): '''simple docstring''' return json.dumps(dataclasses.asdict(self ) ,indent=2 ) @property def UpperCAmelCase__ ( self : str ): '''simple docstring''' if len(self.models ) <= 0: raise ValueError( """Please make sure you provide at least one model name / model identifier, *e.g.* `--models""" """ bert-base-cased` or `args.models = ['bert-base-cased'].""" ) return self.models @property def UpperCAmelCase__ ( self : Tuple ): '''simple docstring''' if not self.multi_process: return False elif self.is_tpu: logger.info("""Multiprocessing is currently not possible on TPU.""" ) return False else: return True
109
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) UpperCAmelCase = { """configuration_vision_encoder_decoder""": ["""VisionEncoderDecoderConfig""", """VisionEncoderDecoderOnnxConfig"""] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase = ["""VisionEncoderDecoderModel"""] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase = ["""TFVisionEncoderDecoderModel"""] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase = ["""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 UpperCAmelCase = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
88
0
"""simple docstring""" import os from math import logaa def lowerCamelCase ( _snake_case = "base_exp.txt" ): UpperCAmelCase__ : float = 0 UpperCAmelCase__ : Union[str, Any] = 0 for i, line in enumerate(open(os.path.join(os.path.dirname(_snake_case ) ,_snake_case ) ) ): UpperCAmelCase__ , UpperCAmelCase__ : Dict = list(map(_snake_case ,line.split(',' ) ) ) if x * logaa(_snake_case ) > largest: UpperCAmelCase__ : List[str] = x * logaa(_snake_case ) UpperCAmelCase__ : List[str] = i + 1 return result if __name__ == "__main__": print(solution())
110
"""simple docstring""" from datetime import datetime import matplotlib.pyplot as plt import torch def _snake_case ( __snake_case : List[str] ): """simple docstring""" for param in module.parameters(): _lowerCamelCase : Optional[Any] = False def _snake_case ( ): """simple docstring""" _lowerCamelCase : Any = """cuda""" if torch.cuda.is_available() else """cpu""" if torch.backends.mps.is_available() and torch.backends.mps.is_built(): _lowerCamelCase : Any = """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 _snake_case ( __snake_case : Union[str, Any] ): """simple docstring""" _lowerCamelCase : int = plt.imshow(__snake_case ) fig.axes.get_xaxis().set_visible(__snake_case ) fig.axes.get_yaxis().set_visible(__snake_case ) plt.show() def _snake_case ( ): """simple docstring""" _lowerCamelCase : Tuple = datetime.now() _lowerCamelCase : Optional[Any] = current_time.strftime("""%H:%M:%S""" ) return timestamp
88
0
import torch def _A ( ): if torch.cuda.is_available(): a__ : Tuple = torch.cuda.device_count() else: a__ : str = 0 print(F"""Successfully ran on {num_gpus} GPUs""" ) if __name__ == "__main__": main()
112
"""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 UpperCAmelCase = 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 lowercase__ : __UpperCAmelCase = field( default='''cifar10''' ,metadata={'''help''': '''Name of a dataset from the datasets package'''} ) __UpperCAmelCase = field( default=A_ ,metadata={'''help''': '''The configuration name of the dataset to use (via the datasets library).'''} ) __UpperCAmelCase = field( default=A_ ,metadata={'''help''': '''The column name of the images in the files.'''} ) __UpperCAmelCase = field(default=A_ ,metadata={'''help''': '''A folder containing the training data.'''} ) __UpperCAmelCase = field(default=A_ ,metadata={'''help''': '''A folder containing the validation data.'''} ) __UpperCAmelCase = field( default=0.1_5 ,metadata={'''help''': '''Percent to split off of train for validation.'''} ) __UpperCAmelCase = field( default=A_ ,metadata={ '''help''': ( '''For debugging purposes or quicker training, truncate the number of training examples to this ''' '''value if set.''' ) } ,) __UpperCAmelCase = field( default=A_ ,metadata={ '''help''': ( '''For debugging purposes or quicker training, truncate the number of evaluation examples to this ''' '''value if set.''' ) } ,) def UpperCamelCase_ ( self) -> Any: _lowerCamelCase : Any = {} if self.train_dir is not None: _lowerCamelCase : int = self.train_dir if self.validation_dir is not None: _lowerCamelCase : Tuple = self.validation_dir _lowerCamelCase : Optional[int] = data_files if data_files else None @dataclass class lowercase__ : __UpperCAmelCase = field( default=A_ ,metadata={ '''help''': ( '''The model checkpoint for weights initialization.Don\'t set if you want to train a model from scratch.''' ) } ,) __UpperCAmelCase = field( default=A_ ,metadata={'''help''': '''Pretrained config name or path if not the same as model_name_or_path'''} ) __UpperCAmelCase = field( default=A_ ,metadata={ '''help''': ( '''Override some existing default config settings when a model is trained from scratch. Example: ''' '''n_embd=10,resid_pdrop=0.2,scale_attn_weights=false,summary_type=cls_index''' ) } ,) __UpperCAmelCase = field( default=A_ ,metadata={'''help''': '''Where do you want to store the pretrained models downloaded from s3'''} ) __UpperCAmelCase = field( default='''main''' ,metadata={'''help''': '''The specific model version to use (can be a branch name, tag name or commit id).'''} ,) __UpperCAmelCase = field(default=A_ ,metadata={'''help''': '''Name or path of preprocessor config.'''} ) __UpperCAmelCase = field( default=A_ ,metadata={ '''help''': ( '''Will use the token generated when running `huggingface-cli login` (necessary to use this script ''' '''with private models).''' ) } ,) __UpperCAmelCase = field( default=0.7_5 ,metadata={'''help''': '''The ratio of the number of masked tokens in the input sequence.'''} ) __UpperCAmelCase = field( default=A_ ,metadata={'''help''': '''Whether or not to train with normalized pixel values as target.'''} ) @dataclass class lowercase__ ( A_ ): __UpperCAmelCase = field( default=1e-3 ,metadata={'''help''': '''Base learning rate: absolute_lr = base_lr * total_batch_size / 256.'''} ) def _snake_case ( __snake_case : Optional[Any] ): """simple docstring""" _lowerCamelCase : int = torch.stack([example["""pixel_values"""] for example in examples] ) return {"pixel_values": pixel_values} def _snake_case ( ): """simple docstring""" _lowerCamelCase : Tuple = 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. _lowerCamelCase , _lowerCamelCase , _lowerCamelCase : Union[str, Any] = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: _lowerCamelCase , _lowerCamelCase , _lowerCamelCase : Dict = 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""" , __snake_case , __snake_case ) # Setup logging logging.basicConfig( format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""" , datefmt="""%m/%d/%Y %H:%M:%S""" , handlers=[logging.StreamHandler(sys.stdout )] , ) if training_args.should_log: # The default of training_args.log_level is passive, so we set log level at info here to have that default. transformers.utils.logging.set_verbosity_info() _lowerCamelCase : Union[str, Any] = training_args.get_process_log_level() logger.setLevel(__snake_case ) transformers.utils.logging.set_verbosity(__snake_case ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Log on each process the small summary: logger.warning( F'Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}' + F'distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}' ) logger.info(F'Training/evaluation parameters {training_args}' ) # Detecting last checkpoint. _lowerCamelCase : List[Any] = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: _lowerCamelCase : Optional[int] = 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. _lowerCamelCase : Optional[Any] = 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. _lowerCamelCase : Tuple = None if """validation""" in ds.keys() else data_args.train_val_split if isinstance(data_args.train_val_split , __snake_case ) and data_args.train_val_split > 0.0: _lowerCamelCase : List[str] = ds["""train"""].train_test_split(data_args.train_val_split ) _lowerCamelCase : Union[str, Any] = split["""train"""] _lowerCamelCase : Optional[int] = 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. _lowerCamelCase : 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: _lowerCamelCase : Dict = ViTMAEConfig.from_pretrained(model_args.config_name , **__snake_case ) elif model_args.model_name_or_path: _lowerCamelCase : Union[str, Any] = ViTMAEConfig.from_pretrained(model_args.model_name_or_path , **__snake_case ) else: _lowerCamelCase : Optional[Any] = 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: _lowerCamelCase : str = ViTImageProcessor.from_pretrained(model_args.image_processor_name , **__snake_case ) elif model_args.model_name_or_path: _lowerCamelCase : Dict = ViTImageProcessor.from_pretrained(model_args.model_name_or_path , **__snake_case ) else: _lowerCamelCase : Union[str, Any] = ViTImageProcessor() # create model if model_args.model_name_or_path: _lowerCamelCase : List[Any] = ViTMAEForPreTraining.from_pretrained( model_args.model_name_or_path , from_tf=bool(""".ckpt""" in model_args.model_name_or_path ) , config=__snake_case , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) else: logger.info("""Training new model from scratch""" ) _lowerCamelCase : Union[str, Any] = ViTMAEForPreTraining(__snake_case ) if training_args.do_train: _lowerCamelCase : List[Any] = ds["""train"""].column_names else: _lowerCamelCase : Union[str, Any] = ds["""validation"""].column_names if data_args.image_column_name is not None: _lowerCamelCase : str = data_args.image_column_name elif "image" in column_names: _lowerCamelCase : Optional[Any] = """image""" elif "img" in column_names: _lowerCamelCase : List[Any] = """img""" else: _lowerCamelCase : str = 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: _lowerCamelCase : Dict = image_processor.size["""shortest_edge"""] else: _lowerCamelCase : List[Any] = (image_processor.size["""height"""], image_processor.size["""width"""]) _lowerCamelCase : Tuple = Compose( [ Lambda(lambda __snake_case : img.convert("""RGB""" ) if img.mode != "RGB" else img ), RandomResizedCrop(__snake_case , scale=(0.2, 1.0) , interpolation=InterpolationMode.BICUBIC ), RandomHorizontalFlip(), ToTensor(), Normalize(mean=image_processor.image_mean , std=image_processor.image_std ), ] ) def preprocess_images(__snake_case : Optional[Any] ): _lowerCamelCase : Dict = [transforms(__snake_case ) 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: _lowerCamelCase : int = ds["""train"""].shuffle(seed=training_args.seed ).select(range(data_args.max_train_samples ) ) # Set the training transforms ds["train"].set_transform(__snake_case ) 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: _lowerCamelCase : Union[str, Any] = ( ds["""validation"""].shuffle(seed=training_args.seed ).select(range(data_args.max_eval_samples ) ) ) # Set the validation transforms ds["validation"].set_transform(__snake_case ) # Compute absolute learning rate _lowerCamelCase : Optional[Any] = ( training_args.train_batch_size * training_args.gradient_accumulation_steps * training_args.world_size ) if training_args.base_learning_rate is not None: _lowerCamelCase : Tuple = training_args.base_learning_rate * total_train_batch_size / 256 # Initialize our trainer _lowerCamelCase : Optional[Any] = Trainer( model=__snake_case , args=__snake_case , train_dataset=ds["""train"""] if training_args.do_train else None , eval_dataset=ds["""validation"""] if training_args.do_eval else None , tokenizer=__snake_case , data_collator=__snake_case , ) # Training if training_args.do_train: _lowerCamelCase : Any = None if training_args.resume_from_checkpoint is not None: _lowerCamelCase : List[Any] = training_args.resume_from_checkpoint elif last_checkpoint is not None: _lowerCamelCase : Union[str, Any] = last_checkpoint _lowerCamelCase : Optional[Any] = trainer.train(resume_from_checkpoint=__snake_case ) trainer.save_model() trainer.log_metrics("""train""" , train_result.metrics ) trainer.save_metrics("""train""" , train_result.metrics ) trainer.save_state() # Evaluation if training_args.do_eval: _lowerCamelCase : int = trainer.evaluate() trainer.log_metrics("""eval""" , __snake_case ) trainer.save_metrics("""eval""" , __snake_case ) # Write model card and (optionally) push to hub _lowerCamelCase : Optional[Any] = { """tasks""": """masked-auto-encoding""", """dataset""": data_args.dataset_name, """tags""": ["""masked-auto-encoding"""], } if training_args.push_to_hub: trainer.push_to_hub(**__snake_case ) else: trainer.create_model_card(**__snake_case ) def _snake_case ( __snake_case : Dict ): """simple docstring""" main() if __name__ == "__main__": main()
88
0
from collections import OrderedDict from typing import TYPE_CHECKING, Any, Mapping, Optional, Union from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging if TYPE_CHECKING: from ... import FeatureExtractionMixin, PreTrainedTokenizerBase, TensorType lowerCamelCase__ = logging.get_logger(__name__) lowerCamelCase__ = { """microsoft/deberta-v2-xlarge""": """https://huggingface.co/microsoft/deberta-v2-xlarge/resolve/main/config.json""", """microsoft/deberta-v2-xxlarge""": """https://huggingface.co/microsoft/deberta-v2-xxlarge/resolve/main/config.json""", """microsoft/deberta-v2-xlarge-mnli""": ( """https://huggingface.co/microsoft/deberta-v2-xlarge-mnli/resolve/main/config.json""" ), """microsoft/deberta-v2-xxlarge-mnli""": ( """https://huggingface.co/microsoft/deberta-v2-xxlarge-mnli/resolve/main/config.json""" ), } class snake_case__ ( A_): '''simple docstring''' lowerCamelCase : List[Any] = "deberta-v2" def __init__( self , a__=12_81_00 , a__=15_36 , a__=24 , a__=24 , a__=61_44 , a__="gelu" , a__=0.1 , a__=0.1 , a__=5_12 , a__=0 , a__=0.02 , a__=1e-7 , a__=False , a__=-1 , a__=0 , a__=True , a__=None , a__=0 , a__="gelu" , **a__ , ) -> Tuple: '''simple docstring''' super().__init__(**a__ ) __snake_case :Optional[Any] = hidden_size __snake_case :Dict = num_hidden_layers __snake_case :int = num_attention_heads __snake_case :int = intermediate_size __snake_case :List[str] = hidden_act __snake_case :List[str] = hidden_dropout_prob __snake_case :List[Any] = attention_probs_dropout_prob __snake_case :List[Any] = max_position_embeddings __snake_case :Tuple = type_vocab_size __snake_case :Tuple = initializer_range __snake_case :Optional[int] = relative_attention __snake_case :Optional[int] = max_relative_positions __snake_case :Optional[int] = pad_token_id __snake_case :Any = position_biased_input # Backwards compatibility if type(a__ ) == str: __snake_case :Optional[int] = [x.strip() for x in pos_att_type.lower().split("""|""" )] __snake_case :int = pos_att_type __snake_case :Optional[Any] = vocab_size __snake_case :Optional[Any] = layer_norm_eps __snake_case :Optional[Any] = kwargs.get("""pooler_hidden_size""" , a__ ) __snake_case :Any = pooler_dropout __snake_case :Optional[int] = pooler_hidden_act class snake_case__ ( A_): '''simple docstring''' @property def __lowercase ( self ) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' if self.task == "multiple-choice": __snake_case :List[str] = {0: """batch""", 1: """choice""", 2: """sequence"""} else: __snake_case :int = {0: """batch""", 1: """sequence"""} if self._config.type_vocab_size > 0: return OrderedDict( [("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ("""token_type_ids""", dynamic_axis)] ) else: return OrderedDict([("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis)] ) @property def __lowercase ( self ) -> int: '''simple docstring''' return 12 def __lowercase ( self , a__ , a__ = -1 , a__ = -1 , a__ = -1 , a__ = False , a__ = None , a__ = 3 , a__ = 40 , a__ = 40 , a__ = None , ) -> Mapping[str, Any]: '''simple docstring''' __snake_case :int = super().generate_dummy_inputs(preprocessor=a__ , framework=a__ ) if self._config.type_vocab_size == 0 and "token_type_ids" in dummy_inputs: del dummy_inputs["token_type_ids"] return dummy_inputs
455
"""simple docstring""" import numpy as np def _snake_case ( __snake_case : np.ndarray ): """simple docstring""" return 1 / (1 + np.exp(-vector )) def _snake_case ( __snake_case : np.ndarray ): """simple docstring""" return vector * sigmoid(__snake_case ) if __name__ == "__main__": import doctest doctest.testmod()
88
0
from ....configuration_utils import PretrainedConfig from ....utils import logging lowercase : int = logging.get_logger(__name__) lowercase : str = { """speechbrain/m-ctc-t-large""": """https://huggingface.co/speechbrain/m-ctc-t-large/resolve/main/config.json""", # See all M-CTC-T models at https://huggingface.co/models?filter=mctct } class A__ ( A_ ): """simple docstring""" __A : Any = '''mctct''' def __init__( self , lowercase=8065 , lowercase=1536 , lowercase=36 , lowercase=6144 , lowercase=4 , lowercase=384 , lowercase=920 , lowercase=1e-5 , lowercase=0.3 , lowercase="relu" , lowercase=0.02 , lowercase=0.3 , lowercase=0.3 , lowercase=1 , lowercase=0 , lowercase=2 , lowercase=1 , lowercase=0.3 , lowercase=1 , lowercase=(7,) , lowercase=(3,) , lowercase=80 , lowercase=1 , lowercase=None , lowercase="sum" , lowercase=False , **lowercase , ) -> Dict: '''simple docstring''' super().__init__(**lowercase , pad_token_id=lowercase , bos_token_id=lowercase , eos_token_id=lowercase) a__ : List[Any] = vocab_size a__ : Optional[Any] = hidden_size a__ : int = num_hidden_layers a__ : Tuple = intermediate_size a__ : Any = num_attention_heads a__ : List[str] = attention_head_dim a__ : Any = max_position_embeddings a__ : int = layer_norm_eps a__ : str = layerdrop a__ : Optional[Any] = hidden_act a__ : int = initializer_range a__ : List[str] = hidden_dropout_prob a__ : Union[str, Any] = attention_probs_dropout_prob a__ : Optional[Any] = pad_token_id a__ : List[str] = bos_token_id a__ : int = eos_token_id a__ : int = conv_glu_dim a__ : Any = conv_dropout a__ : int = num_conv_layers a__ : str = input_feat_per_channel a__ : int = input_channels a__ : List[Any] = conv_channels a__ : Optional[int] = ctc_loss_reduction a__ : Union[str, Any] = ctc_zero_infinity # prevents config testing fail with exporting to json a__ : List[Any] = list(lowercase) a__ : Tuple = list(lowercase) if len(self.conv_kernel) != self.num_conv_layers: raise ValueError( 'Configuration for convolutional module is incorrect. ' 'It is required that `len(config.conv_kernel)` == `config.num_conv_layers` ' F'but is `len(config.conv_kernel) = {len(self.conv_kernel)}`, ' F'`config.num_conv_layers = {self.num_conv_layers}`.')
302
"""simple docstring""" from transformers import HfArgumentParser, TensorFlowBenchmark, TensorFlowBenchmarkArguments def _snake_case ( ): """simple docstring""" _lowerCamelCase : Any = HfArgumentParser(__snake_case ) _lowerCamelCase : int = parser.parse_args_into_dataclasses()[0] _lowerCamelCase : Dict = TensorFlowBenchmark(args=__snake_case ) try: _lowerCamelCase : Optional[int] = parser.parse_args_into_dataclasses()[0] except ValueError as e: _lowerCamelCase : Union[str, Any] = """Arg --no_{0} is no longer used, please use --no-{0} instead.""" _lowerCamelCase : List[str] = """ """.join(str(__snake_case ).split(""" """ )[:-1] ) _lowerCamelCase : Dict = """""" _lowerCamelCase : List[Any] = eval(str(__snake_case ).split(""" """ )[-1] ) _lowerCamelCase : Tuple = [] for arg in depreciated_args: # arg[2:] removes '--' if arg[2:] in TensorFlowBenchmark.deprecated_args: # arg[5:] removes '--no_' full_error_msg += arg_error_msg.format(arg[5:] ) else: wrong_args.append(__snake_case ) if len(__snake_case ) > 0: _lowerCamelCase : Tuple = full_error_msg + begin_error_msg + str(__snake_case ) raise ValueError(__snake_case ) benchmark.run() if __name__ == "__main__": main()
88
0
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging __UpperCAmelCase = logging.get_logger(__name__) __UpperCAmelCase = { '''kssteven/ibert-roberta-base''': '''https://huggingface.co/kssteven/ibert-roberta-base/resolve/main/config.json''', '''kssteven/ibert-roberta-large''': '''https://huggingface.co/kssteven/ibert-roberta-large/resolve/main/config.json''', '''kssteven/ibert-roberta-large-mnli''': ( '''https://huggingface.co/kssteven/ibert-roberta-large-mnli/resolve/main/config.json''' ), } class lowerCAmelCase_ ( A_ ): UpperCAmelCase__ : Optional[Any] = "ibert" def __init__( self, SCREAMING_SNAKE_CASE_=3_0522, SCREAMING_SNAKE_CASE_=768, SCREAMING_SNAKE_CASE_=12, SCREAMING_SNAKE_CASE_=12, SCREAMING_SNAKE_CASE_=3072, SCREAMING_SNAKE_CASE_="gelu", SCREAMING_SNAKE_CASE_=0.1, SCREAMING_SNAKE_CASE_=0.1, SCREAMING_SNAKE_CASE_=512, SCREAMING_SNAKE_CASE_=2, SCREAMING_SNAKE_CASE_=0.02, SCREAMING_SNAKE_CASE_=1e-12, SCREAMING_SNAKE_CASE_=1, SCREAMING_SNAKE_CASE_=0, SCREAMING_SNAKE_CASE_=2, SCREAMING_SNAKE_CASE_="absolute", SCREAMING_SNAKE_CASE_=False, SCREAMING_SNAKE_CASE_="none", **SCREAMING_SNAKE_CASE_, ) -> Any: super().__init__(pad_token_id=SCREAMING_SNAKE_CASE_, bos_token_id=SCREAMING_SNAKE_CASE_, eos_token_id=SCREAMING_SNAKE_CASE_, **SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = vocab_size UpperCamelCase : Dict = hidden_size UpperCamelCase : List[str] = num_hidden_layers UpperCamelCase : int = num_attention_heads UpperCamelCase : Tuple = hidden_act UpperCamelCase : str = intermediate_size UpperCamelCase : Union[str, Any] = hidden_dropout_prob UpperCamelCase : Tuple = attention_probs_dropout_prob UpperCamelCase : Any = max_position_embeddings UpperCamelCase : Dict = type_vocab_size UpperCamelCase : List[Any] = initializer_range UpperCamelCase : Dict = layer_norm_eps UpperCamelCase : List[Any] = position_embedding_type UpperCamelCase : Any = quant_mode UpperCamelCase : List[str] = force_dequant class lowerCAmelCase_ ( A_ ): @property def snake_case_ ( self ) -> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": UpperCamelCase : Dict = {0: """batch""", 1: """choice""", 2: """sequence"""} else: UpperCamelCase : Optional[int] = {0: """batch""", 1: """sequence"""} return OrderedDict( [ ('input_ids', dynamic_axis), ('attention_mask', dynamic_axis), ] )
40
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging UpperCAmelCase = logging.get_logger(__name__) UpperCAmelCase = { """kssteven/ibert-roberta-base""": """https://huggingface.co/kssteven/ibert-roberta-base/resolve/main/config.json""", """kssteven/ibert-roberta-large""": """https://huggingface.co/kssteven/ibert-roberta-large/resolve/main/config.json""", """kssteven/ibert-roberta-large-mnli""": ( """https://huggingface.co/kssteven/ibert-roberta-large-mnli/resolve/main/config.json""" ), } class lowercase__ ( A_ ): __UpperCAmelCase = '''ibert''' def __init__( self , SCREAMING_SNAKE_CASE=3_0522 , SCREAMING_SNAKE_CASE=768 , SCREAMING_SNAKE_CASE=12 , SCREAMING_SNAKE_CASE=12 , SCREAMING_SNAKE_CASE=3072 , SCREAMING_SNAKE_CASE="gelu" , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=512 , SCREAMING_SNAKE_CASE=2 , SCREAMING_SNAKE_CASE=0.02 , SCREAMING_SNAKE_CASE=1e-1_2 , SCREAMING_SNAKE_CASE=1 , SCREAMING_SNAKE_CASE=0 , SCREAMING_SNAKE_CASE=2 , SCREAMING_SNAKE_CASE="absolute" , SCREAMING_SNAKE_CASE=False , SCREAMING_SNAKE_CASE="none" , **SCREAMING_SNAKE_CASE , ) -> Any: super().__init__(pad_token_id=SCREAMING_SNAKE_CASE , bos_token_id=SCREAMING_SNAKE_CASE , eos_token_id=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE) _lowerCamelCase : Optional[int] = vocab_size _lowerCamelCase : Dict = hidden_size _lowerCamelCase : List[str] = num_hidden_layers _lowerCamelCase : int = num_attention_heads _lowerCamelCase : Tuple = hidden_act _lowerCamelCase : str = intermediate_size _lowerCamelCase : Union[str, Any] = hidden_dropout_prob _lowerCamelCase : Tuple = attention_probs_dropout_prob _lowerCamelCase : Any = max_position_embeddings _lowerCamelCase : Dict = type_vocab_size _lowerCamelCase : List[Any] = initializer_range _lowerCamelCase : Dict = layer_norm_eps _lowerCamelCase : List[Any] = position_embedding_type _lowerCamelCase : Any = quant_mode _lowerCamelCase : List[str] = force_dequant class lowercase__ ( A_ ): @property def UpperCamelCase_ ( self) -> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": _lowerCamelCase : Dict = {0: """batch""", 1: """choice""", 2: """sequence"""} else: _lowerCamelCase : Optional[int] = {0: """batch""", 1: """sequence"""} return OrderedDict( [ ("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ])
88
0
'''simple docstring''' import argparse import torch from transformers import GPTaLMHeadModel, RobertaForMaskedLM if __name__ == "__main__": lowercase : Any = argparse.ArgumentParser( description=( 'Extraction some layers of the full RobertaForMaskedLM or GPT2LMHeadModel for Transfer Learned' ' Distillation' ) ) parser.add_argument('--model_type', default='roberta', choices=['roberta', 'gpt2']) parser.add_argument('--model_name', default='roberta-large', type=str) parser.add_argument('--dump_checkpoint', default='serialization_dir/tf_roberta_048131723.pth', type=str) parser.add_argument('--vocab_transform', action='store_true') lowercase : Dict = parser.parse_args() if args.model_type == "roberta": lowercase : List[str] = RobertaForMaskedLM.from_pretrained(args.model_name) lowercase : List[str] = 'roberta' elif args.model_type == "gpt2": lowercase : Union[str, Any] = GPTaLMHeadModel.from_pretrained(args.model_name) lowercase : int = 'transformer' lowercase : Tuple = model.state_dict() lowercase : Any = {} # Embeddings # if args.model_type == "gpt2": for param_name in ["wte.weight", "wpe.weight"]: lowercase : Optional[Any] = state_dict[f'''{prefix}.{param_name}'''] else: for w in ["word_embeddings", "position_embeddings", "token_type_embeddings"]: lowercase : List[str] = f'''{prefix}.embeddings.{w}.weight''' lowercase : Optional[Any] = state_dict[param_name] for w in ["weight", "bias"]: lowercase : Tuple = f'''{prefix}.embeddings.LayerNorm.{w}''' lowercase : List[str] = state_dict[param_name] # Transformer Blocks # lowercase : str = 0 for teacher_idx in [0, 2, 4, 7, 9, 11]: if args.model_type == "gpt2": for layer in ["ln_1", "attn.c_attn", "attn.c_proj", "ln_2", "mlp.c_fc", "mlp.c_proj"]: for w in ["weight", "bias"]: lowercase : Tuple = state_dict[ f'''{prefix}.h.{teacher_idx}.{layer}.{w}''' ] lowercase : List[str] = state_dict[f'''{prefix}.h.{teacher_idx}.attn.bias'''] else: for layer in [ "attention.self.query", "attention.self.key", "attention.self.value", "attention.output.dense", "attention.output.LayerNorm", "intermediate.dense", "output.dense", "output.LayerNorm", ]: for w in ["weight", "bias"]: lowercase : Union[str, Any] = state_dict[ f'''{prefix}.encoder.layer.{teacher_idx}.{layer}.{w}''' ] std_idx += 1 # Language Modeling Head ###s if args.model_type == "roberta": for layer in ["lm_head.decoder.weight", "lm_head.bias"]: lowercase : int = state_dict[f'''{layer}'''] if args.vocab_transform: for w in ["weight", "bias"]: lowercase : str = state_dict[f'''lm_head.dense.{w}'''] lowercase : int = state_dict[f'''lm_head.layer_norm.{w}'''] elif args.model_type == "gpt2": for w in ["weight", "bias"]: lowercase : Any = state_dict[f'''{prefix}.ln_f.{w}'''] lowercase : Tuple = state_dict['lm_head.weight'] print(f'''N layers selected for distillation: {std_idx}''') print(f'''Number of params transferred for distillation: {len(compressed_sd.keys())}''') print(f'''Save transferred checkpoint to {args.dump_checkpoint}.''') torch.save(compressed_sd, args.dump_checkpoint)
634
"""simple docstring""" from __future__ import annotations import queue class lowercase__ : def __init__( self , SCREAMING_SNAKE_CASE) -> int: _lowerCamelCase : int = data _lowerCamelCase : List[str] = None _lowerCamelCase : Any = None def _snake_case ( ): """simple docstring""" print("""\n********Press N to stop entering at any point of time********\n""" ) _lowerCamelCase : Optional[int] = input("""Enter the value of the root node: """ ).strip().lower() _lowerCamelCase : queue.Queue = queue.Queue() _lowerCamelCase : Optional[int] = TreeNode(int(__snake_case ) ) q.put(__snake_case ) while not q.empty(): _lowerCamelCase : Tuple = q.get() _lowerCamelCase : Any = F'Enter the left node of {node_found.data}: ' _lowerCamelCase : Union[str, Any] = input(__snake_case ).strip().lower() or """n""" if check == "n": return tree_node _lowerCamelCase : Dict = TreeNode(int(__snake_case ) ) _lowerCamelCase : List[str] = left_node q.put(__snake_case ) _lowerCamelCase : Optional[int] = F'Enter the right node of {node_found.data}: ' _lowerCamelCase : Optional[Any] = input(__snake_case ).strip().lower() or """n""" if check == "n": return tree_node _lowerCamelCase : List[Any] = TreeNode(int(__snake_case ) ) _lowerCamelCase : List[Any] = right_node q.put(__snake_case ) raise def _snake_case ( __snake_case : TreeNode ): """simple docstring""" if not isinstance(__snake_case , __snake_case ) or not node: return print(node.data , end=""",""" ) pre_order(node.left ) pre_order(node.right ) def _snake_case ( __snake_case : TreeNode ): """simple docstring""" if not isinstance(__snake_case , __snake_case ) or not node: return in_order(node.left ) print(node.data , end=""",""" ) in_order(node.right ) def _snake_case ( __snake_case : TreeNode ): """simple docstring""" if not isinstance(__snake_case , __snake_case ) or not node: return post_order(node.left ) post_order(node.right ) print(node.data , end=""",""" ) def _snake_case ( __snake_case : TreeNode ): """simple docstring""" if not isinstance(__snake_case , __snake_case ) or not node: return _lowerCamelCase : queue.Queue = queue.Queue() q.put(__snake_case ) while not q.empty(): _lowerCamelCase : Any = q.get() print(node_dequeued.data , end=""",""" ) if node_dequeued.left: q.put(node_dequeued.left ) if node_dequeued.right: q.put(node_dequeued.right ) def _snake_case ( __snake_case : TreeNode ): """simple docstring""" if not isinstance(__snake_case , __snake_case ) or not node: return _lowerCamelCase : queue.Queue = queue.Queue() q.put(__snake_case ) while not q.empty(): _lowerCamelCase : Optional[Any] = [] while not q.empty(): _lowerCamelCase : Dict = q.get() print(node_dequeued.data , end=""",""" ) if node_dequeued.left: list_.append(node_dequeued.left ) if node_dequeued.right: list_.append(node_dequeued.right ) print() for node in list_: q.put(__snake_case ) def _snake_case ( __snake_case : TreeNode ): """simple docstring""" if not isinstance(__snake_case , __snake_case ) or not node: return _lowerCamelCase : list[TreeNode] = [] _lowerCamelCase : Optional[int] = node while n or stack: while n: # start from root node, find its left child print(n.data , end=""",""" ) stack.append(__snake_case ) _lowerCamelCase : Tuple = n.left # end of while means current node doesn't have left child _lowerCamelCase : Optional[Any] = stack.pop() # start to traverse its right child _lowerCamelCase : Dict = n.right def _snake_case ( __snake_case : TreeNode ): """simple docstring""" if not isinstance(__snake_case , __snake_case ) or not node: return _lowerCamelCase : list[TreeNode] = [] _lowerCamelCase : int = node while n or stack: while n: stack.append(__snake_case ) _lowerCamelCase : Any = n.left _lowerCamelCase : Optional[Any] = stack.pop() print(n.data , end=""",""" ) _lowerCamelCase : List[Any] = n.right def _snake_case ( __snake_case : TreeNode ): """simple docstring""" if not isinstance(__snake_case , __snake_case ) or not node: return _lowerCamelCase , _lowerCamelCase : Union[str, Any] = [], [] _lowerCamelCase : Optional[Any] = node stacka.append(__snake_case ) while stacka: # to find the reversed order of post order, store it in stack2 _lowerCamelCase : Union[str, Any] = stacka.pop() if n.left: stacka.append(n.left ) if n.right: stacka.append(n.right ) stacka.append(__snake_case ) while stacka: # pop up from stack2 will be the post order print(stacka.pop().data , end=""",""" ) def _snake_case ( __snake_case : str = "" , __snake_case : Any=50 , __snake_case : List[str]="*" ): """simple docstring""" if not s: return "\n" + width * char _lowerCamelCase , _lowerCamelCase : Optional[int] = divmod(width - len(__snake_case ) - 2 , 2 ) return F'{left * char} {s} {(left + extra) * char}' if __name__ == "__main__": import doctest doctest.testmod() print(prompt("""Binary Tree Traversals""")) UpperCAmelCase = build_tree() print(prompt("""Pre Order Traversal""")) pre_order(node) print(prompt() + """\n""") print(prompt("""In Order Traversal""")) in_order(node) print(prompt() + """\n""") print(prompt("""Post Order Traversal""")) post_order(node) print(prompt() + """\n""") print(prompt("""Level Order Traversal""")) level_order(node) print(prompt() + """\n""") print(prompt("""Actual Level Order Traversal""")) level_order_actual(node) print("""*""" * 50 + """\n""") print(prompt("""Pre Order Traversal - Iteration Version""")) pre_order_iter(node) print(prompt() + """\n""") print(prompt("""In Order Traversal - Iteration Version""")) in_order_iter(node) print(prompt() + """\n""") print(prompt("""Post Order Traversal - Iteration Version""")) post_order_iter(node) print(prompt())
88
0
'''simple docstring''' import json import pathlib import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ConditionalDetrImageProcessor class lowerCAmelCase ( unittest.TestCase): def __init__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=7 , __SCREAMING_SNAKE_CASE=3 , __SCREAMING_SNAKE_CASE=30 , __SCREAMING_SNAKE_CASE=400 , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE=[0.5, 0.5, 0.5] , __SCREAMING_SNAKE_CASE=[0.5, 0.5, 0.5] , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE=1 / 255 , __SCREAMING_SNAKE_CASE=True , ) -> Dict: '''simple docstring''' __snake_case = size if size is not None else {"""shortest_edge""": 18, """longest_edge""": 1333} __snake_case = parent __snake_case = batch_size __snake_case = num_channels __snake_case = min_resolution __snake_case = max_resolution __snake_case = do_resize __snake_case = size __snake_case = do_normalize __snake_case = image_mean __snake_case = image_std __snake_case = do_rescale __snake_case = rescale_factor __snake_case = do_pad def lowerCAmelCase ( self ) -> int: '''simple docstring''' return { "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_pad": self.do_pad, } def lowerCAmelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=False ) -> Any: '''simple docstring''' if not batched: __snake_case = image_inputs[0] if isinstance(__SCREAMING_SNAKE_CASE , Image.Image ): __snake_case = image.size else: __snake_case = image.shape[1], image.shape[2] if w < h: __snake_case = int(self.size['''shortest_edge'''] * h / w ) __snake_case = self.size["""shortest_edge"""] elif w > h: __snake_case = self.size["""shortest_edge"""] __snake_case = int(self.size['''shortest_edge'''] * w / h ) else: __snake_case = self.size["""shortest_edge"""] __snake_case = self.size["""shortest_edge"""] else: __snake_case = [] for image in image_inputs: __snake_case = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) __snake_case = max(__SCREAMING_SNAKE_CASE , key=lambda __SCREAMING_SNAKE_CASE : item[0] )[0] __snake_case = max(__SCREAMING_SNAKE_CASE , key=lambda __SCREAMING_SNAKE_CASE : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class lowerCAmelCase ( A_ , unittest.TestCase): __lowercase : Any = ConditionalDetrImageProcessor if is_vision_available() else None def lowerCAmelCase ( self ) -> Optional[Any]: '''simple docstring''' __snake_case = ConditionalDetrImageProcessingTester(self ) @property def lowerCAmelCase ( self ) -> str: '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def lowerCAmelCase ( self ) -> Dict: '''simple docstring''' __snake_case = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , '''image_mean''' ) ) self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , '''image_std''' ) ) self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , '''do_normalize''' ) ) self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , '''do_resize''' ) ) self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , '''size''' ) ) def lowerCAmelCase ( self ) -> int: '''simple docstring''' __snake_case = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'''shortest_edge''': 18, '''longest_edge''': 1333} ) self.assertEqual(image_processor.do_pad , __SCREAMING_SNAKE_CASE ) __snake_case = self.image_processing_class.from_dict( self.image_processor_dict , size=42 , max_size=84 , pad_and_return_pixel_mask=__SCREAMING_SNAKE_CASE ) self.assertEqual(image_processor.size , {'''shortest_edge''': 42, '''longest_edge''': 84} ) self.assertEqual(image_processor.do_pad , __SCREAMING_SNAKE_CASE ) def lowerCAmelCase ( self ) -> Tuple: '''simple docstring''' pass def lowerCAmelCase ( self ) -> Any: '''simple docstring''' __snake_case = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __snake_case = prepare_image_inputs(self.image_processor_tester , equal_resolution=__SCREAMING_SNAKE_CASE ) for image in image_inputs: self.assertIsInstance(__SCREAMING_SNAKE_CASE , Image.Image ) # Test not batched input __snake_case = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values __snake_case = self.image_processor_tester.get_expected_values(__SCREAMING_SNAKE_CASE ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __snake_case = self.image_processor_tester.get_expected_values(__SCREAMING_SNAKE_CASE , batched=__SCREAMING_SNAKE_CASE ) __snake_case = image_processing(__SCREAMING_SNAKE_CASE , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def lowerCAmelCase ( self ) -> int: '''simple docstring''' __snake_case = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __snake_case = prepare_image_inputs(self.image_processor_tester , equal_resolution=__SCREAMING_SNAKE_CASE , numpify=__SCREAMING_SNAKE_CASE ) for image in image_inputs: self.assertIsInstance(__SCREAMING_SNAKE_CASE , np.ndarray ) # Test not batched input __snake_case = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values __snake_case = self.image_processor_tester.get_expected_values(__SCREAMING_SNAKE_CASE ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __snake_case = image_processing(__SCREAMING_SNAKE_CASE , return_tensors='''pt''' ).pixel_values __snake_case = self.image_processor_tester.get_expected_values(__SCREAMING_SNAKE_CASE , batched=__SCREAMING_SNAKE_CASE ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def lowerCAmelCase ( self ) -> Optional[Any]: '''simple docstring''' __snake_case = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __snake_case = prepare_image_inputs(self.image_processor_tester , equal_resolution=__SCREAMING_SNAKE_CASE , torchify=__SCREAMING_SNAKE_CASE ) for image in image_inputs: self.assertIsInstance(__SCREAMING_SNAKE_CASE , torch.Tensor ) # Test not batched input __snake_case = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values __snake_case = self.image_processor_tester.get_expected_values(__SCREAMING_SNAKE_CASE ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __snake_case = image_processing(__SCREAMING_SNAKE_CASE , return_tensors='''pt''' ).pixel_values __snake_case = self.image_processor_tester.get_expected_values(__SCREAMING_SNAKE_CASE , batched=__SCREAMING_SNAKE_CASE ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) @slow def lowerCAmelCase ( self ) -> str: '''simple docstring''' __snake_case = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) with open('''./tests/fixtures/tests_samples/COCO/coco_annotations.txt''' , '''r''' ) as f: __snake_case = json.loads(f.read() ) __snake_case = {"""image_id""": 3_9769, """annotations""": target} # encode them __snake_case = ConditionalDetrImageProcessor.from_pretrained('''microsoft/conditional-detr-resnet-50''' ) __snake_case = image_processing(images=__SCREAMING_SNAKE_CASE , annotations=__SCREAMING_SNAKE_CASE , return_tensors='''pt''' ) # verify pixel values __snake_case = torch.Size([1, 3, 800, 1066] ) self.assertEqual(encoding['''pixel_values'''].shape , __SCREAMING_SNAKE_CASE ) __snake_case = torch.tensor([0.2_796, 0.3_138, 0.3_481] ) self.assertTrue(torch.allclose(encoding['''pixel_values'''][0, 0, 0, :3] , __SCREAMING_SNAKE_CASE , atol=1E-4 ) ) # verify area __snake_case = torch.tensor([5887.9600, 1_1250.2061, 48_9353.8438, 83_7122.7500, 14_7967.5156, 16_5732.3438] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''area'''] , __SCREAMING_SNAKE_CASE ) ) # verify boxes __snake_case = torch.Size([6, 4] ) self.assertEqual(encoding['''labels'''][0]['''boxes'''].shape , __SCREAMING_SNAKE_CASE ) __snake_case = torch.tensor([0.5_503, 0.2_765, 0.0_604, 0.2_215] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''boxes'''][0] , __SCREAMING_SNAKE_CASE , atol=1E-3 ) ) # verify image_id __snake_case = torch.tensor([3_9769] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''image_id'''] , __SCREAMING_SNAKE_CASE ) ) # verify is_crowd __snake_case = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''iscrowd'''] , __SCREAMING_SNAKE_CASE ) ) # verify class_labels __snake_case = torch.tensor([75, 75, 63, 65, 17, 17] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''class_labels'''] , __SCREAMING_SNAKE_CASE ) ) # verify orig_size __snake_case = torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''orig_size'''] , __SCREAMING_SNAKE_CASE ) ) # verify size __snake_case = torch.tensor([800, 1066] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''size'''] , __SCREAMING_SNAKE_CASE ) ) @slow def lowerCAmelCase ( self ) -> Optional[Any]: '''simple docstring''' __snake_case = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) with open('''./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt''' , '''r''' ) as f: __snake_case = json.loads(f.read() ) __snake_case = {"""file_name""": """000000039769.png""", """image_id""": 3_9769, """segments_info""": target} __snake_case = pathlib.Path('''./tests/fixtures/tests_samples/COCO/coco_panoptic''' ) # encode them __snake_case = ConditionalDetrImageProcessor(format='''coco_panoptic''' ) __snake_case = image_processing(images=__SCREAMING_SNAKE_CASE , annotations=__SCREAMING_SNAKE_CASE , masks_path=__SCREAMING_SNAKE_CASE , return_tensors='''pt''' ) # verify pixel values __snake_case = torch.Size([1, 3, 800, 1066] ) self.assertEqual(encoding['''pixel_values'''].shape , __SCREAMING_SNAKE_CASE ) __snake_case = torch.tensor([0.2_796, 0.3_138, 0.3_481] ) self.assertTrue(torch.allclose(encoding['''pixel_values'''][0, 0, 0, :3] , __SCREAMING_SNAKE_CASE , atol=1E-4 ) ) # verify area __snake_case = torch.tensor([14_7979.6875, 16_5527.0469, 48_4638.5938, 1_1292.9375, 5879.6562, 7634.1147] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''area'''] , __SCREAMING_SNAKE_CASE ) ) # verify boxes __snake_case = torch.Size([6, 4] ) self.assertEqual(encoding['''labels'''][0]['''boxes'''].shape , __SCREAMING_SNAKE_CASE ) __snake_case = torch.tensor([0.2_625, 0.5_437, 0.4_688, 0.8_625] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''boxes'''][0] , __SCREAMING_SNAKE_CASE , atol=1E-3 ) ) # verify image_id __snake_case = torch.tensor([3_9769] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''image_id'''] , __SCREAMING_SNAKE_CASE ) ) # verify is_crowd __snake_case = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''iscrowd'''] , __SCREAMING_SNAKE_CASE ) ) # verify class_labels __snake_case = torch.tensor([17, 17, 63, 75, 75, 93] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''class_labels'''] , __SCREAMING_SNAKE_CASE ) ) # verify masks __snake_case = 82_2873 self.assertEqual(encoding['''labels'''][0]['''masks'''].sum().item() , __SCREAMING_SNAKE_CASE ) # verify orig_size __snake_case = torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''orig_size'''] , __SCREAMING_SNAKE_CASE ) ) # verify size __snake_case = torch.tensor([800, 1066] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''size'''] , __SCREAMING_SNAKE_CASE ) )
24
"""simple docstring""" from __future__ import annotations import unittest from transformers import XGLMConfig, XGLMTokenizer, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers.models.xglm.modeling_tf_xglm import ( TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST, TFXGLMForCausalLM, TFXGLMModel, ) @require_tf class lowercase__ : __UpperCAmelCase = XGLMConfig __UpperCAmelCase = {} __UpperCAmelCase = '''gelu''' def __init__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=14 , SCREAMING_SNAKE_CASE=7 , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=99 , SCREAMING_SNAKE_CASE=32 , SCREAMING_SNAKE_CASE=2 , SCREAMING_SNAKE_CASE=4 , SCREAMING_SNAKE_CASE=37 , SCREAMING_SNAKE_CASE="gelu" , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=512 , SCREAMING_SNAKE_CASE=0.02 , ) -> List[str]: _lowerCamelCase : Optional[int] = parent _lowerCamelCase : int = batch_size _lowerCamelCase : str = seq_length _lowerCamelCase : Any = is_training _lowerCamelCase : int = use_input_mask _lowerCamelCase : Union[str, Any] = use_labels _lowerCamelCase : str = vocab_size _lowerCamelCase : List[str] = d_model _lowerCamelCase : List[Any] = num_hidden_layers _lowerCamelCase : Dict = num_attention_heads _lowerCamelCase : int = ffn_dim _lowerCamelCase : str = activation_function _lowerCamelCase : Optional[int] = activation_dropout _lowerCamelCase : Tuple = attention_dropout _lowerCamelCase : Tuple = max_position_embeddings _lowerCamelCase : Dict = initializer_range _lowerCamelCase : Optional[Any] = None _lowerCamelCase : Union[str, Any] = 0 _lowerCamelCase : List[Any] = 2 _lowerCamelCase : str = 1 def UpperCamelCase_ ( self) -> int: return XGLMConfig.from_pretrained("""facebook/xglm-564M""") def UpperCamelCase_ ( self) -> int: _lowerCamelCase : Union[str, Any] = tf.clip_by_value( ids_tensor([self.batch_size, self.seq_length] , self.vocab_size) , clip_value_min=0 , clip_value_max=3) _lowerCamelCase : str = None if self.use_input_mask: _lowerCamelCase : Union[str, Any] = random_attention_mask([self.batch_size, self.seq_length]) _lowerCamelCase : Tuple = self.get_config() _lowerCamelCase : Optional[int] = floats_tensor([self.num_hidden_layers, self.num_attention_heads] , 2) return ( config, input_ids, input_mask, head_mask, ) def UpperCamelCase_ ( self) -> Optional[int]: return XGLMConfig( vocab_size=self.vocab_size , d_model=self.hidden_size , num_layers=self.num_hidden_layers , attention_heads=self.num_attention_heads , ffn_dim=self.ffn_dim , activation_function=self.activation_function , activation_dropout=self.activation_dropout , attention_dropout=self.attention_dropout , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , use_cache=SCREAMING_SNAKE_CASE , bos_token_id=self.bos_token_id , eos_token_id=self.eos_token_id , pad_token_id=self.pad_token_id , return_dict=SCREAMING_SNAKE_CASE , ) def UpperCamelCase_ ( self) -> Optional[int]: _lowerCamelCase : List[Any] = self.prepare_config_and_inputs() ( ( _lowerCamelCase ) , ( _lowerCamelCase ) , ( _lowerCamelCase ) , ( _lowerCamelCase ) , ) : str = config_and_inputs _lowerCamelCase : Optional[Any] = { """input_ids""": input_ids, """head_mask""": head_mask, } return config, inputs_dict @require_tf class lowercase__ ( A_ ,A_ ,unittest.TestCase ): __UpperCAmelCase = (TFXGLMModel, TFXGLMForCausalLM) if is_tf_available() else () __UpperCAmelCase = (TFXGLMForCausalLM,) if is_tf_available() else () __UpperCAmelCase = ( {'''feature-extraction''': TFXGLMModel, '''text-generation''': TFXGLMForCausalLM} if is_tf_available() else {} ) __UpperCAmelCase = False __UpperCAmelCase = False __UpperCAmelCase = False def UpperCamelCase_ ( self) -> Optional[Any]: _lowerCamelCase : Optional[Any] = TFXGLMModelTester(self) _lowerCamelCase : str = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE , n_embd=37) def UpperCamelCase_ ( self) -> Dict: self.config_tester.run_common_tests() @slow def UpperCamelCase_ ( self) -> List[Any]: for model_name in TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _lowerCamelCase : Tuple = TFXGLMModel.from_pretrained(SCREAMING_SNAKE_CASE) self.assertIsNotNone(SCREAMING_SNAKE_CASE) @unittest.skip(reason="""Currently, model embeddings are going to undergo a major refactor.""") def UpperCamelCase_ ( self) -> List[Any]: super().test_resize_token_embeddings() @require_tf class lowercase__ ( unittest.TestCase ): @slow def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE=True) -> List[Any]: _lowerCamelCase : List[str] = TFXGLMForCausalLM.from_pretrained("""facebook/xglm-564M""") _lowerCamelCase : Union[str, Any] = tf.convert_to_tensor([[2, 268, 9865]] , dtype=tf.intaa) # The dog # </s> The dog is a very friendly dog. He is very affectionate and loves to play with other # fmt: off _lowerCamelCase : Dict = [2, 268, 9865, 67, 11, 1988, 5_7252, 9865, 5, 984, 67, 1988, 21_3838, 1658, 53, 7_0446, 33, 6657, 278, 1581] # fmt: on _lowerCamelCase : str = model.generate(SCREAMING_SNAKE_CASE , do_sample=SCREAMING_SNAKE_CASE , num_beams=1) if verify_outputs: self.assertListEqual(output_ids[0].numpy().tolist() , SCREAMING_SNAKE_CASE) @slow def UpperCamelCase_ ( self) -> int: _lowerCamelCase : int = XGLMTokenizer.from_pretrained("""facebook/xglm-564M""") _lowerCamelCase : Tuple = TFXGLMForCausalLM.from_pretrained("""facebook/xglm-564M""") tf.random.set_seed(0) _lowerCamelCase : Union[str, Any] = tokenizer("""Today is a nice day and""" , return_tensors="""tf""") _lowerCamelCase : Any = tokenized.input_ids # forces the generation to happen on CPU, to avoid GPU-related quirks (and assure same output regardless of the available devices) with tf.device(""":/CPU:0"""): _lowerCamelCase : Any = model.generate(SCREAMING_SNAKE_CASE , do_sample=SCREAMING_SNAKE_CASE , seed=[7, 0]) _lowerCamelCase : List[str] = tokenizer.decode(output_ids[0] , skip_special_tokens=SCREAMING_SNAKE_CASE) _lowerCamelCase : Any = ( """Today is a nice day and warm evening here over Southern Alberta!! Today when they closed schools due""" ) self.assertEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) @slow def UpperCamelCase_ ( self) -> List[Any]: _lowerCamelCase : Optional[Any] = TFXGLMForCausalLM.from_pretrained("""facebook/xglm-564M""") _lowerCamelCase : Any = XGLMTokenizer.from_pretrained("""facebook/xglm-564M""") _lowerCamelCase : List[Any] = """left""" # use different length sentences to test batching _lowerCamelCase : List[Any] = [ """This is an extremelly long sentence that only exists to test the ability of the model to cope with """ """left-padding, such as in batched generation. The output for the sequence below should be the same """ """regardless of whether left padding is applied or not. When""", """Hello, my dog is a little""", ] _lowerCamelCase : Union[str, Any] = tokenizer(SCREAMING_SNAKE_CASE , return_tensors="""tf""" , padding=SCREAMING_SNAKE_CASE) _lowerCamelCase : int = inputs["""input_ids"""] _lowerCamelCase : List[Any] = model.generate(input_ids=SCREAMING_SNAKE_CASE , attention_mask=inputs["""attention_mask"""] , max_new_tokens=12) _lowerCamelCase : List[str] = tokenizer(sentences[0] , return_tensors="""tf""").input_ids _lowerCamelCase : Optional[Any] = model.generate(input_ids=SCREAMING_SNAKE_CASE , max_new_tokens=12) _lowerCamelCase : Tuple = tokenizer(sentences[1] , return_tensors="""tf""").input_ids _lowerCamelCase : int = model.generate(input_ids=SCREAMING_SNAKE_CASE , max_new_tokens=12) _lowerCamelCase : Optional[int] = tokenizer.batch_decode(SCREAMING_SNAKE_CASE , skip_special_tokens=SCREAMING_SNAKE_CASE) _lowerCamelCase : Optional[Any] = tokenizer.decode(output_non_padded[0] , skip_special_tokens=SCREAMING_SNAKE_CASE) _lowerCamelCase : Union[str, Any] = tokenizer.decode(output_padded[0] , skip_special_tokens=SCREAMING_SNAKE_CASE) _lowerCamelCase : Tuple = [ """This is an extremelly long sentence that only exists to test the ability of the model to cope with """ """left-padding, such as in batched generation. The output for the sequence below should be the same """ """regardless of whether left padding is applied or not. When left padding is applied, the sequence will be """ """a single""", """Hello, my dog is a little bit of a shy one, but he is very friendly""", ] self.assertListEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) self.assertListEqual(SCREAMING_SNAKE_CASE , [non_padded_sentence, padded_sentence])
88
0
import os import unittest from transformers.models.bartpho.tokenization_bartpho import VOCAB_FILES_NAMES, BartphoTokenizer from transformers.testing_utils import get_tests_dir from ...test_tokenization_common import TokenizerTesterMixin _lowerCAmelCase : str = get_tests_dir("fixtures/test_sentencepiece_bpe.model") class __snake_case ( A_ , unittest.TestCase ): SCREAMING_SNAKE_CASE__ = BartphoTokenizer SCREAMING_SNAKE_CASE__ = False SCREAMING_SNAKE_CASE__ = True def SCREAMING_SNAKE_CASE_ ( self ): """simple docstring""" super().setUp() lowerCAmelCase__ = ["""▁This""", """▁is""", """▁a""", """▁t""", """est"""] lowerCAmelCase__ = dict(zip(a_ ,range(len(a_ ) ) ) ) lowerCAmelCase__ = {"""unk_token""": """<unk>"""} lowerCAmelCase__ = os.path.join(self.tmpdirname ,VOCAB_FILES_NAMES['monolingual_vocab_file'] ) with open(self.monolingual_vocab_file ,'w' ,encoding='utf-8' ) as fp: for token in vocab_tokens: fp.write(f'{token} {vocab_tokens[token]}\n' ) lowerCAmelCase__ = BartphoTokenizer(a_ ,self.monolingual_vocab_file ,**self.special_tokens_map ) tokenizer.save_pretrained(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self ,**a_ ): """simple docstring""" kwargs.update(self.special_tokens_map ) return BartphoTokenizer.from_pretrained(self.tmpdirname ,**a_ ) def SCREAMING_SNAKE_CASE_ ( self ,a_ ): """simple docstring""" lowerCAmelCase__ = """This is a là test""" lowerCAmelCase__ = """This is a<unk><unk> test""" return input_text, output_text def SCREAMING_SNAKE_CASE_ ( self ): """simple docstring""" lowerCAmelCase__ = BartphoTokenizer(a_ ,self.monolingual_vocab_file ,**self.special_tokens_map ) lowerCAmelCase__ = """This is a là test""" lowerCAmelCase__ = """▁This ▁is ▁a ▁l à ▁t est""".split() lowerCAmelCase__ = tokenizer.tokenize(a_ ) self.assertListEqual(a_ ,a_ ) lowerCAmelCase__ = tokens + [tokenizer.unk_token] lowerCAmelCase__ = [4, 5, 6, 3, 3, 7, 8, 3] self.assertListEqual(tokenizer.convert_tokens_to_ids(a_ ) ,a_ )
193
"""simple docstring""" from collections import defaultdict def _snake_case ( __snake_case : str , __snake_case : str ): """simple docstring""" _lowerCamelCase : Tuple = first_str.lower().strip() _lowerCamelCase : int = second_str.lower().strip() # Remove whitespace _lowerCamelCase : Any = first_str.replace(""" """ , """""" ) _lowerCamelCase : List[str] = second_str.replace(""" """ , """""" ) # Strings of different lengths are not anagrams if len(__snake_case ) != len(__snake_case ): return False # Default values for count should be 0 _lowerCamelCase : defaultdict[str, int] = defaultdict(__snake_case ) # For each character in input strings, # increment count in the corresponding for i in range(len(__snake_case ) ): count[first_str[i]] += 1 count[second_str[i]] -= 1 return all(_count == 0 for _count in count.values() ) if __name__ == "__main__": from doctest import testmod testmod() UpperCAmelCase = input("""Enter the first string """).strip() UpperCAmelCase = input("""Enter the second string """).strip() UpperCAmelCase = check_anagrams(input_a, input_b) print(f'''{input_a} and {input_b} are {"" if status else "not "}anagrams.''')
88
0
'''simple docstring''' from __future__ import annotations import random import unittest from transformers import TransfoXLConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TF_TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST, TFTransfoXLForSequenceClassification, TFTransfoXLLMHeadModel, TFTransfoXLModel, ) class __A : def __init__( self , UpperCamelCase_ , ): __UpperCAmelCase : Union[str, Any] = parent __UpperCAmelCase : str = 13 __UpperCAmelCase : Union[str, Any] = 7 __UpperCAmelCase : Optional[int] = 30 __UpperCAmelCase : Optional[int] = self.seq_length + self.mem_len __UpperCAmelCase : Dict = 15 __UpperCAmelCase : int = True __UpperCAmelCase : Union[str, Any] = True __UpperCAmelCase : List[Any] = 99 __UpperCAmelCase : Tuple = [10, 50, 80] __UpperCAmelCase : Tuple = 32 __UpperCAmelCase : int = 32 __UpperCAmelCase : Optional[Any] = 4 __UpperCAmelCase : Optional[Any] = 8 __UpperCAmelCase : List[Any] = 1_28 __UpperCAmelCase : Dict = 2 __UpperCAmelCase : str = 2 __UpperCAmelCase : Any = None __UpperCAmelCase : Union[str, Any] = 1 __UpperCAmelCase : int = 0 __UpperCAmelCase : Tuple = 3 __UpperCAmelCase : str = self.vocab_size - 1 __UpperCAmelCase : str = 0.0_1 def _snake_case ( self ): __UpperCAmelCase : Any = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __UpperCAmelCase : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __UpperCAmelCase : Dict = None if self.use_labels: __UpperCAmelCase : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __UpperCAmelCase : Optional[Any] = TransfoXLConfig( vocab_size=self.vocab_size , mem_len=self.mem_len , clamp_len=self.clamp_len , cutoffs=self.cutoffs , d_model=self.hidden_size , d_embed=self.d_embed , n_head=self.num_attention_heads , d_head=self.d_head , d_inner=self.d_inner , div_val=self.div_val , n_layer=self.num_hidden_layers , eos_token_id=self.eos_token_id , pad_token_id=self.vocab_size - 1 , init_range=self.init_range , num_labels=self.num_labels , ) return (config, input_ids_a, input_ids_a, lm_labels) def _snake_case ( self ): random.seed(self.seed ) tf.random.set_seed(self.seed ) def _snake_case ( self , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ): __UpperCAmelCase : str = TFTransfoXLModel(UpperCamelCase_ ) __UpperCAmelCase : Union[str, Any] = model(UpperCamelCase_ ).to_tuple() __UpperCAmelCase : int = {"""input_ids""": input_ids_a, """mems""": mems_a} __UpperCAmelCase : Optional[Any] = model(UpperCamelCase_ ).to_tuple() self.parent.assertEqual(hidden_states_a.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(hidden_states_a.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertListEqual( [mem.shape for mem in mems_a] , [(self.mem_len, self.batch_size, self.hidden_size)] * self.num_hidden_layers , ) self.parent.assertListEqual( [mem.shape for mem in mems_a] , [(self.mem_len, self.batch_size, self.hidden_size)] * self.num_hidden_layers , ) def _snake_case ( self , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ): __UpperCAmelCase : str = TFTransfoXLLMHeadModel(UpperCamelCase_ ) __UpperCAmelCase : Optional[Any] = model(UpperCamelCase_ ).to_tuple() __UpperCAmelCase : Tuple = {"""input_ids""": input_ids_a, """labels""": lm_labels} __UpperCAmelCase : Tuple = model(UpperCamelCase_ ).to_tuple() __UpperCAmelCase : int = model([input_ids_a, mems_a] ).to_tuple() __UpperCAmelCase : Optional[Any] = {"""input_ids""": input_ids_a, """mems""": mems_a, """labels""": lm_labels} __UpperCAmelCase : Optional[int] = model(UpperCamelCase_ ).to_tuple() self.parent.assertEqual(lm_logits_a.shape , (self.batch_size, self.seq_length, self.vocab_size) ) self.parent.assertListEqual( [mem.shape for mem in mems_a] , [(self.mem_len, self.batch_size, self.hidden_size)] * self.num_hidden_layers , ) self.parent.assertEqual(lm_logits_a.shape , (self.batch_size, self.seq_length, self.vocab_size) ) self.parent.assertListEqual( [mem.shape for mem in mems_a] , [(self.mem_len, self.batch_size, self.hidden_size)] * self.num_hidden_layers , ) def _snake_case ( self , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ): __UpperCAmelCase : Tuple = TFTransfoXLForSequenceClassification(UpperCamelCase_ ) __UpperCAmelCase : Any = model(UpperCamelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _snake_case ( self ): __UpperCAmelCase : str = self.prepare_config_and_inputs() (__UpperCAmelCase) : int = config_and_inputs __UpperCAmelCase : Optional[Any] = {"""input_ids""": input_ids_a} return config, inputs_dict @require_tf class __A (A_ , A_ , unittest.TestCase ): snake_case :Optional[int] = ( (TFTransfoXLModel, TFTransfoXLLMHeadModel, TFTransfoXLForSequenceClassification) if is_tf_available() else () ) snake_case :List[str] = () if is_tf_available() else () snake_case :List[Any] = ( { "feature-extraction": TFTransfoXLModel, "text-classification": TFTransfoXLForSequenceClassification, "text-generation": TFTransfoXLLMHeadModel, "zero-shot": TFTransfoXLForSequenceClassification, } if is_tf_available() else {} ) # TODO: add this test when TFTransfoXLLMHead has a linear output layer implemented snake_case :int = False snake_case :Optional[Any] = False snake_case :List[Any] = False snake_case :Any = False def _snake_case ( self , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ): if pipeline_test_casse_name == "TextGenerationPipelineTests": # Get `ValueError: AttributeError: 'NoneType' object has no attribute 'new_ones'` or `AssertionError`. # `TransfoXLConfig` was never used in pipeline tests: cannot create a simple # tokenizer. return True return False def _snake_case ( self ): __UpperCAmelCase : List[str] = TFTransfoXLModelTester(self ) __UpperCAmelCase : Any = ConfigTester(self , config_class=UpperCamelCase_ , d_embed=37 ) def _snake_case ( self ): self.config_tester.run_common_tests() def _snake_case ( self ): self.model_tester.set_seed() __UpperCAmelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_transfo_xl_model(*UpperCamelCase_ ) def _snake_case ( self ): self.model_tester.set_seed() __UpperCAmelCase : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_transfo_xl_lm_head(*UpperCamelCase_ ) def _snake_case ( self ): __UpperCAmelCase : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_transfo_xl_for_sequence_classification(*UpperCamelCase_ ) def _snake_case ( self ): __UpperCAmelCase : int = self.model_tester.prepare_config_and_inputs_for_common() __UpperCAmelCase : Any = [TFTransfoXLForSequenceClassification] for model_class in self.all_model_classes: __UpperCAmelCase : str = model_class(UpperCamelCase_ ) assert isinstance(model.get_input_embeddings() , tf.keras.layers.Layer ) if model_class in list_other_models_with_output_ebd: __UpperCAmelCase : Union[str, Any] = model.get_output_embeddings() assert isinstance(UpperCamelCase_ , tf.keras.layers.Layer ) __UpperCAmelCase : Tuple = model.get_bias() assert name is None else: __UpperCAmelCase : Dict = model.get_output_embeddings() assert x is None __UpperCAmelCase : List[str] = model.get_bias() assert name is None def _snake_case ( self ): # TODO JP: Make TransfoXL XLA compliant pass @slow def _snake_case ( self ): for model_name in TF_TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __UpperCAmelCase : Any = TFTransfoXLModel.from_pretrained(UpperCamelCase_ ) self.assertIsNotNone(UpperCamelCase_ ) @unittest.skip(reason="This model doesn't play well with fit() due to not returning a single loss." ) def _snake_case ( self ): pass @require_tf class __A (unittest.TestCase ): @unittest.skip("Skip test until #12651 is resolved." ) @slow def _snake_case ( self ): __UpperCAmelCase : Optional[int] = TFTransfoXLLMHeadModel.from_pretrained("transfo-xl-wt103" ) # fmt: off __UpperCAmelCase : int = tf.convert_to_tensor([[33,12_97,2,1,10_09,4,11_09,1_17_39,47_62,3_58,5,25,2_45,22,17_06,17,2_00_98,5,32_15,21,37,11_10,3,13,10_41,4,24,6_03,4_90,2,7_14_77,2_00_98,10_44_47,2,2_09_61,1,26_04,4,1,3_29,3,62_24,8_31,1_60_02,2,8,6_03,7_89_67,2_95_46,23,8_03,20,25,4_16,5,8,2_32,4,2_77,6,18_55,46_01,3,2_95_46,54,8,36_09,5,5_72_11,49,4,1,2_77,18,8,17_55,1_56_91,3,3_41,25,4_16,6_93,4_25_73,71,17,4_01,94,31,1_79_19,2,2_95_46,78_73,18,1,4_35,23,1_10_11,7_55,5,51_67,3,79_83,98,84,2,2_95_46,32_67,8,36_09,4,1,48_65,10_75,2,60_87,71,6,3_46,8,58_54,3,2_95_46,8_24,14_00,18_68,2,19,1_60,2,3_11,8,54_96,2,2_09_20,17,25,1_50_97,3,24,24,0]] , dtype=tf.intaa ) # noqa: E231 # fmt: on # In 1991 , the remains of Russian Tsar Nicholas II and his family # ( except for Alexei and Maria ) are discovered . # The voice of Nicholas's young son , Tsarevich Alexei Nikolaevich , narrates the # remainder of the story . 1883 Western Siberia , # a young Grigori Rasputin is asked by his father and a group of men to perform magic . # Rasputin has a vision and denounces one of the men as a horse thief . Although his # father initially slaps him for making such an accusation , Rasputin watches as the # man is chased outside and beaten . Twenty years later , Rasputin sees a vision of # the Virgin Mary , prompting him to become a priest . Rasputin quickly becomes famous , # with people , even a bishop , begging for his blessing . <eod> </s> <eos> # fmt: off __UpperCAmelCase : List[str] = [33,12_97,2,1,10_09,4,11_09,1_17_39,47_62,3_58,5,25,2_45,22,17_06,17,2_00_98,5,32_15,21,37,11_10,3,13,10_41,4,24,6_03,4_90,2,7_14_77,2_00_98,10_44_47,2,2_09_61,1,26_04,4,1,3_29,3,62_24,8_31,1_60_02,2,8,6_03,7_89_67,2_95_46,23,8_03,20,25,4_16,5,8,2_32,4,2_77,6,18_55,46_01,3,2_95_46,54,8,36_09,5,5_72_11,49,4,1,2_77,18,8,17_55,1_56_91,3,3_41,25,4_16,6_93,4_25_73,71,17,4_01,94,31,1_79_19,2,2_95_46,78_73,18,1,4_35,23,1_10_11,7_55,5,51_67,3,79_83,98,84,2,2_95_46,32_67,8,36_09,4,1,48_65,10_75,2,60_87,71,6,3_46,8,58_54,3,2_95_46,8_24,14_00,18_68,2,19,1_60,2,3_11,8,54_96,2,2_09_20,17,25,1_50_97,3,24,24,0,33,1,18_57,2,1,10_09,4,11_09,1_17_39,47_62,3_58,5,25,2_45,28,11_10,3,13,10_41,4,24,6_03,4_90,2,7_14_77,2_00_98,10_44_47,2,2_09_61,1,26_04,4,1,3_29,3,0] # noqa: E231 # fmt: on # In 1991, the remains of Russian Tsar Nicholas II and his family ( # except for Alexei and Maria ) are discovered. The voice of young son, # Tsarevich Alexei Nikolaevich, narrates the remainder of the story. # 1883 Western Siberia, a young Grigori Rasputin is asked by his father # and a group of men to perform magic. Rasputin has a vision and # denounces one of the men as a horse thief. Although his father initially # slaps him for making such an accusation, Rasputin watches as the man # is chased outside and beaten. Twenty years later, Rasputin sees a vision # of the Virgin Mary, prompting him to become a priest. # Rasputin quickly becomes famous, with people, even a bishop, begging for # his blessing. <unk> <unk> <eos> In the 1990s, the remains of Russian Tsar # Nicholas II and his family were discovered. The voice of <unk> young son, # Tsarevich Alexei Nikolaevich, narrates the remainder of the story.<eos> __UpperCAmelCase : Optional[int] = model.generate(UpperCamelCase_ , max_length=2_00 , do_sample=UpperCamelCase_ ) self.assertListEqual(output_ids[0].numpy().tolist() , UpperCamelCase_ )
168
"""simple docstring""" from __future__ import annotations from numpy import array, cos, cross, floataa, radians, sin from numpy.typing import NDArray def _snake_case ( __snake_case : float , __snake_case : float , __snake_case : bool = False ): """simple docstring""" if radian_mode: return [magnitude * cos(__snake_case ), magnitude * sin(__snake_case )] return [magnitude * cos(radians(__snake_case ) ), magnitude * sin(radians(__snake_case ) )] def _snake_case ( __snake_case : NDArray[floataa] , __snake_case : NDArray[floataa] , __snake_case : float = 10**-1 ): """simple docstring""" _lowerCamelCase : NDArray[floataa] = cross(__snake_case , __snake_case ) _lowerCamelCase : float = sum(__snake_case ) return abs(__snake_case ) < eps if __name__ == "__main__": # Test to check if it works UpperCAmelCase = array( [ polar_force(718.4, 180 - 30), polar_force(879.54, 45), polar_force(100, -90), ] ) UpperCAmelCase = array([[0, 0], [0, 0], [0, 0]]) assert in_static_equilibrium(forces, location) # Problem 1 in image_data/2D_problems.jpg UpperCAmelCase = array( [ polar_force(30 * 9.81, 15), polar_force(215, 180 - 45), polar_force(264, 90 - 30), ] ) UpperCAmelCase = array([[0, 0], [0, 0], [0, 0]]) assert in_static_equilibrium(forces, location) # Problem in image_data/2D_problems_1.jpg UpperCAmelCase = array([[0, -2000], [0, -1200], [0, 1_5600], [0, -1_2400]]) UpperCAmelCase = array([[0, 0], [6, 0], [10, 0], [12, 0]]) assert in_static_equilibrium(forces, location) import doctest doctest.testmod()
88
0
"""simple docstring""" from typing import Optional, Union import torch from torch import nn from ...configuration_utils import ConfigMixin, register_to_config from ...models.modeling_utils import ModelMixin class __lowerCAmelCase ( A_ , A_ ): '''simple docstring''' @register_to_config def __init__( self: Optional[int] , UpperCamelCase_: Any = 768 , ): super().__init__() UpperCamelCase_ =nn.Parameter(torch.zeros(1 , UpperCamelCase_ ) ) UpperCamelCase_ =nn.Parameter(torch.ones(1 , UpperCamelCase_ ) ) def UpperCamelCase__ ( self: Tuple , UpperCamelCase_: Optional[int] = None , UpperCamelCase_: Optional[Any] = None , ): UpperCamelCase_ =nn.Parameter(self.mean.to(UpperCamelCase_ ).to(UpperCamelCase_ ) ) UpperCamelCase_ =nn.Parameter(self.std.to(UpperCamelCase_ ).to(UpperCamelCase_ ) ) return self def UpperCamelCase__ ( self: int , UpperCamelCase_: List[str] ): UpperCamelCase_ =(embeds - self.mean) * 1.0 / self.std return embeds def UpperCamelCase__ ( self: List[Any] , UpperCamelCase_: Optional[Any] ): UpperCamelCase_ =(embeds * self.std) + self.mean return embeds
391
"""simple docstring""" import random def _snake_case ( __snake_case : List[Any] , __snake_case : List[Any] , __snake_case : int ): """simple docstring""" _lowerCamelCase : List[str] = a[left_index] _lowerCamelCase : Dict = left_index + 1 for j in range(left_index + 1 , __snake_case ): if a[j] < pivot: _lowerCamelCase , _lowerCamelCase : List[str] = a[i], a[j] i += 1 _lowerCamelCase , _lowerCamelCase : Optional[int] = a[i - 1], a[left_index] return i - 1 def _snake_case ( __snake_case : Tuple , __snake_case : List[str] , __snake_case : List[str] ): """simple docstring""" if left < right: _lowerCamelCase : Any = random.randint(__snake_case , right - 1 ) _lowerCamelCase , _lowerCamelCase : Optional[Any] = ( a[left], a[pivot], ) # switches the pivot with the left most bound _lowerCamelCase : List[str] = partition(__snake_case , __snake_case , __snake_case ) quick_sort_random( __snake_case , __snake_case , __snake_case ) # recursive quicksort to the left of the pivot point quick_sort_random( __snake_case , pivot_index + 1 , __snake_case ) # recursive quicksort to the right of the pivot point def _snake_case ( ): """simple docstring""" _lowerCamelCase : Union[str, Any] = input("""Enter numbers separated by a comma:\n""" ).strip() _lowerCamelCase : int = [int(__snake_case ) for item in user_input.split(""",""" )] quick_sort_random(__snake_case , 0 , len(__snake_case ) ) print(__snake_case ) if __name__ == "__main__": main()
88
0
from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices lowerCamelCase_ = logging.get_logger(__name__) lowerCamelCase_ = { "shi-labs/dinat-mini-in1k-224": "https://huggingface.co/shi-labs/dinat-mini-in1k-224/resolve/main/config.json", # See all Dinat models at https://huggingface.co/models?filter=dinat } class __a ( A_ , A_ ): """simple docstring""" _A : Union[str, Any] = "dinat" _A : Dict = { "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers", } def __init__( self : Union[str, Any] ,_UpperCamelCase : Any=4 ,_UpperCamelCase : List[str]=3 ,_UpperCamelCase : Optional[int]=6_4 ,_UpperCamelCase : int=[3, 4, 6, 5] ,_UpperCamelCase : str=[2, 4, 8, 1_6] ,_UpperCamelCase : Any=7 ,_UpperCamelCase : Optional[int]=[[1, 8, 1], [1, 4, 1, 4], [1, 2, 1, 2, 1, 2], [1, 1, 1, 1, 1]] ,_UpperCamelCase : int=3.0 ,_UpperCamelCase : List[Any]=True ,_UpperCamelCase : Optional[Any]=0.0 ,_UpperCamelCase : int=0.0 ,_UpperCamelCase : Dict=0.1 ,_UpperCamelCase : Any="gelu" ,_UpperCamelCase : List[str]=0.02 ,_UpperCamelCase : Dict=1e-5 ,_UpperCamelCase : List[str]=0.0 ,_UpperCamelCase : Optional[int]=None ,_UpperCamelCase : Union[str, Any]=None ,**_UpperCamelCase : List[Any] ,) -> Union[str, Any]: '''simple docstring''' super().__init__(**_UpperCamelCase ) SCREAMING_SNAKE_CASE__ =patch_size SCREAMING_SNAKE_CASE__ =num_channels SCREAMING_SNAKE_CASE__ =embed_dim SCREAMING_SNAKE_CASE__ =depths SCREAMING_SNAKE_CASE__ =len(_UpperCamelCase ) SCREAMING_SNAKE_CASE__ =num_heads SCREAMING_SNAKE_CASE__ =kernel_size SCREAMING_SNAKE_CASE__ =dilations SCREAMING_SNAKE_CASE__ =mlp_ratio SCREAMING_SNAKE_CASE__ =qkv_bias SCREAMING_SNAKE_CASE__ =hidden_dropout_prob SCREAMING_SNAKE_CASE__ =attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ =drop_path_rate SCREAMING_SNAKE_CASE__ =hidden_act SCREAMING_SNAKE_CASE__ =layer_norm_eps SCREAMING_SNAKE_CASE__ =initializer_range # we set the hidden_size attribute in order to make Dinat work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model SCREAMING_SNAKE_CASE__ =int(embed_dim * 2 ** (len(_UpperCamelCase ) - 1) ) SCREAMING_SNAKE_CASE__ =layer_scale_init_value SCREAMING_SNAKE_CASE__ =["""stem"""] + [f"""stage{idx}""" for idx in range(1 ,len(_UpperCamelCase ) + 1 )] SCREAMING_SNAKE_CASE__ =get_aligned_output_features_output_indices( out_features=_UpperCamelCase ,out_indices=_UpperCamelCase ,stage_names=self.stage_names )
151
"""simple docstring""" import itertools import os from collections import Counter, defaultdict from concurrent.futures import ThreadPoolExecutor, as_completed import numpy as np import datasets from .execute import check_correctness UpperCAmelCase = """\ @misc{chen2021evaluating, title={Evaluating Large Language Models Trained on Code}, author={Mark Chen and Jerry Tworek and Heewoo Jun and Qiming Yuan \ and Henrique Ponde de Oliveira Pinto and Jared Kaplan and Harri Edwards \ and Yuri Burda and Nicholas Joseph and Greg Brockman and Alex Ray \ and Raul Puri and Gretchen Krueger and Michael Petrov and Heidy Khlaaf \ and Girish Sastry and Pamela Mishkin and Brooke Chan and Scott Gray \ and Nick Ryder and Mikhail Pavlov and Alethea Power and Lukasz Kaiser \ and Mohammad Bavarian and Clemens Winter and Philippe Tillet \ and Felipe Petroski Such and Dave Cummings and Matthias Plappert \ and Fotios Chantzis and Elizabeth Barnes and Ariel Herbert-Voss \ and William Hebgen Guss and Alex Nichol and Alex Paino and Nikolas Tezak \ and Jie Tang and Igor Babuschkin and Suchir Balaji and Shantanu Jain \ and William Saunders and Christopher Hesse and Andrew N. Carr \ and Jan Leike and Josh Achiam and Vedant Misra and Evan Morikawa \ and Alec Radford and Matthew Knight and Miles Brundage and Mira Murati \ and Katie Mayer and Peter Welinder and Bob McGrew and Dario Amodei \ and Sam McCandlish and Ilya Sutskever and Wojciech Zaremba}, year={2021}, eprint={2107.03374}, archivePrefix={arXiv}, primaryClass={cs.LG} } """ UpperCAmelCase = """\ This metric implements the evaluation harness for the HumanEval problem solving dataset described in the paper \"Evaluating Large Language Models Trained on Code\" (https://arxiv.org/abs/2107.03374). """ UpperCAmelCase = """ Calculates how good are predictions given some references, using certain scores Args: predictions: list of candidates to evaluate. Each candidates should be a list of strings with several code candidates to solve the problem. references: a list with a test for each prediction. Each test should evaluate the correctness of a code candidate. k: number of code candidates to consider in the evaluation (Default: [1, 10, 100]) num_workers: number of workers used to evaluate the canidate programs (Default: 4). timeout: Returns: pass_at_k: dict with pass rates for each k results: dict with granular results of each unittest Examples: >>> code_eval = datasets.load_metric(\"code_eval\") >>> test_cases = [\"assert add(2,3)==5\"] >>> candidates = [[\"def add(a,b): return a*b\", \"def add(a, b): return a+b\"]] >>> pass_at_k, results = code_eval.compute(references=test_cases, predictions=candidates, k=[1, 2]) >>> print(pass_at_k) {'pass@1': 0.5, 'pass@2': 1.0} """ UpperCAmelCase = """ ################################################################################ !!!WARNING!!! ################################################################################ The \"code_eval\" metric executes untrusted model-generated code in Python. Although it is highly unlikely that model-generated code will do something overtly malicious in response to this test suite, model-generated code may act destructively due to a lack of model capability or alignment. Users are strongly encouraged to sandbox this evaluation suite so that it does not perform destructive actions on their host or network. For more information on how OpenAI sandboxes its code, see the paper \"Evaluating Large Language Models Trained on Code\" (https://arxiv.org/abs/2107.03374). Once you have read this disclaimer and taken appropriate precautions, set the environment variable HF_ALLOW_CODE_EVAL=\"1\". Within Python you can to this with: >>> import os >>> os.environ[\"HF_ALLOW_CODE_EVAL\"] = \"1\" ################################################################################\ """ UpperCAmelCase = """The MIT License Copyright (c) OpenAI (https://openai.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.""" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION ,_KWARGS_DESCRIPTION ) class lowercase__ ( datasets.Metric ): def UpperCamelCase_ ( self) -> str: return datasets.MetricInfo( # This is the description that will appear on the metrics page. description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": datasets.Sequence(datasets.Value("""string""")), """references""": datasets.Value("""string"""), }) , homepage="""https://github.com/openai/human-eval""" , codebase_urls=["""https://github.com/openai/human-eval"""] , reference_urls=["""https://github.com/openai/human-eval"""] , license=_LICENSE , ) def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=[1, 10, 100] , SCREAMING_SNAKE_CASE=4 , SCREAMING_SNAKE_CASE=3.0) -> Union[str, Any]: if os.getenv("""HF_ALLOW_CODE_EVAL""" , 0) != "1": raise ValueError(_WARNING) if os.name == "nt": raise NotImplementedError("""This metric is currently not supported on Windows.""") with ThreadPoolExecutor(max_workers=SCREAMING_SNAKE_CASE) as executor: _lowerCamelCase : Optional[int] = [] _lowerCamelCase : Optional[int] = Counter() _lowerCamelCase : Any = 0 _lowerCamelCase : List[Any] = defaultdict(SCREAMING_SNAKE_CASE) for task_id, (candidates, test_case) in enumerate(zip(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE)): for candidate in candidates: _lowerCamelCase : Any = candidate + """\n""" + test_case _lowerCamelCase : Union[str, Any] = (test_program, timeout, task_id, completion_id[task_id]) _lowerCamelCase : List[str] = executor.submit(SCREAMING_SNAKE_CASE , *SCREAMING_SNAKE_CASE) futures.append(SCREAMING_SNAKE_CASE) completion_id[task_id] += 1 n_samples += 1 for future in as_completed(SCREAMING_SNAKE_CASE): _lowerCamelCase : int = future.result() results[result["task_id"]].append((result["""completion_id"""], result)) _lowerCamelCase , _lowerCamelCase : List[Any] = [], [] for result in results.values(): result.sort() _lowerCamelCase : List[str] = [r[1]["""passed"""] for r in result] total.append(len(SCREAMING_SNAKE_CASE)) correct.append(sum(SCREAMING_SNAKE_CASE)) _lowerCamelCase : List[Any] = np.array(SCREAMING_SNAKE_CASE) _lowerCamelCase : Union[str, Any] = np.array(SCREAMING_SNAKE_CASE) _lowerCamelCase : Union[str, Any] = k _lowerCamelCase : Optional[Any] = {F'pass@{k}': estimate_pass_at_k(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE).mean() for k in ks if (total >= k).all()} return pass_at_k, results def _snake_case ( __snake_case : List[str] , __snake_case : List[str] , __snake_case : List[str] ): """simple docstring""" def estimator(__snake_case : int , __snake_case : int , __snake_case : int ) -> float: if n - c < k: return 1.0 return 1.0 - np.prod(1.0 - k / np.arange(n - c + 1 , n + 1 ) ) if isinstance(__snake_case , __snake_case ): _lowerCamelCase : Optional[int] = itertools.repeat(__snake_case , len(__snake_case ) ) else: assert len(__snake_case ) == len(__snake_case ) _lowerCamelCase : List[str] = iter(__snake_case ) return np.array([estimator(int(__snake_case ) , int(__snake_case ) , __snake_case ) for n, c in zip(__snake_case , __snake_case )] )
88
0
"""simple docstring""" import warnings from ...utils import logging from .image_processing_imagegpt import ImageGPTImageProcessor _UpperCamelCase : Optional[int] = logging.get_logger(__name__) class UpperCAmelCase_ ( A_): def __init__( self , *a , **a ) -> None: warnings.warn( 'The class ImageGPTFeatureExtractor is deprecated and will be removed in version 5 of Transformers.' ' Please use ImageGPTImageProcessor instead.' , a , ) super().__init__(*a , **a )
599
"""simple docstring""" from typing import Dict, List from nltk.translate import gleu_score import datasets from datasets import MetricInfo UpperCAmelCase = """\ @misc{wu2016googles, title={Google's Neural Machine Translation System: Bridging the Gap between Human and Machine Translation}, author={Yonghui Wu and Mike Schuster and Zhifeng Chen and Quoc V. Le and Mohammad Norouzi and Wolfgang Macherey and Maxim Krikun and Yuan Cao and Qin Gao and Klaus Macherey and Jeff Klingner and Apurva Shah and Melvin Johnson and Xiaobing Liu and Łukasz Kaiser and Stephan Gouws and Yoshikiyo Kato and Taku Kudo and Hideto Kazawa and Keith Stevens and George Kurian and Nishant Patil and Wei Wang and Cliff Young and Jason Smith and Jason Riesa and Alex Rudnick and Oriol Vinyals and Greg Corrado and Macduff Hughes and Jeffrey Dean}, year={2016}, eprint={1609.08144}, archivePrefix={arXiv}, primaryClass={cs.CL} } """ UpperCAmelCase = """\ The BLEU score has some undesirable properties when used for single sentences, as it was designed to be a corpus measure. We therefore use a slightly different score for our RL experiments which we call the 'GLEU score'. For the GLEU score, we record all sub-sequences of 1, 2, 3 or 4 tokens in output and target sequence (n-grams). We then compute a recall, which is the ratio of the number of matching n-grams to the number of total n-grams in the target (ground truth) sequence, and a precision, which is the ratio of the number of matching n-grams to the number of total n-grams in the generated output sequence. Then GLEU score is simply the minimum of recall and precision. This GLEU score's range is always between 0 (no matches) and 1 (all match) and it is symmetrical when switching output and target. According to our experiments, GLEU score correlates quite well with the BLEU metric on a corpus level but does not have its drawbacks for our per sentence reward objective. """ UpperCAmelCase = """\ Computes corpus-level Google BLEU (GLEU) score of translated segments against one or more references. Instead of averaging the sentence level GLEU scores (i.e. macro-average precision), Wu et al. (2016) sum up the matching tokens and the max of hypothesis and reference tokens for each sentence, then compute using the aggregate values. Args: predictions (list of str): list of translations to score. Each translation should be tokenized into a list of tokens. references (list of list of str): list of lists of references for each translation. Each reference should be tokenized into a list of tokens. min_len (int): The minimum order of n-gram this function should extract. Defaults to 1. max_len (int): The maximum order of n-gram this function should extract. Defaults to 4. Returns: 'google_bleu': google_bleu score Examples: Example 1: >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always', ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat'] >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which', ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never', ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat'] >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was', ... 'interested', 'in', 'world', 'history'] >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history', ... 'because', 'he', 'read', 'the', 'book'] >>> list_of_references = [[ref1a], [ref2a]] >>> hypotheses = [hyp1, hyp2] >>> google_bleu = datasets.load_metric(\"google_bleu\") >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references) >>> print(round(results[\"google_bleu\"], 2)) 0.44 Example 2: >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always', ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat'] >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which', ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never', ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat'] >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never', ... 'heed', 'the', 'cat', 'commands'] >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the', ... 'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions', ... 'of', 'the', 'cat'] >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was', ... 'interested', 'in', 'world', 'history'] >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history', ... 'because', 'he', 'read', 'the', 'book'] >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]] >>> hypotheses = [hyp1, hyp2] >>> google_bleu = datasets.load_metric(\"google_bleu\") >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references) >>> print(round(results[\"google_bleu\"], 2)) 0.61 Example 3: >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always', ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat'] >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which', ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never', ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat'] >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never', ... 'heed', 'the', 'cat', 'commands'] >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the', ... 'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions', ... 'of', 'the', 'cat'] >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was', ... 'interested', 'in', 'world', 'history'] >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history', ... 'because', 'he', 'read', 'the', 'book'] >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]] >>> hypotheses = [hyp1, hyp2] >>> google_bleu = datasets.load_metric(\"google_bleu\") >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references, min_len=2) >>> print(round(results[\"google_bleu\"], 2)) 0.53 Example 4: >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always', ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat'] >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which', ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never', ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat'] >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never', ... 'heed', 'the', 'cat', 'commands'] >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the', ... 'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions', ... 'of', 'the', 'cat'] >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was', ... 'interested', 'in', 'world', 'history'] >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history', ... 'because', 'he', 'read', 'the', 'book'] >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]] >>> hypotheses = [hyp1, hyp2] >>> google_bleu = datasets.load_metric(\"google_bleu\") >>> results = google_bleu.compute(predictions=hypotheses,references=list_of_references, min_len=2, max_len=6) >>> print(round(results[\"google_bleu\"], 2)) 0.4 """ @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION ,_KWARGS_DESCRIPTION ) class lowercase__ ( datasets.Metric ): def UpperCamelCase_ ( self) -> MetricInfo: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": datasets.Sequence(datasets.Value("""string""" , id="""token""") , id="""sequence"""), """references""": datasets.Sequence( datasets.Sequence(datasets.Value("""string""" , id="""token""") , id="""sequence""") , id="""references"""), }) , ) def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = 1 , SCREAMING_SNAKE_CASE = 4 , ) -> Dict[str, float]: return { "google_bleu": gleu_score.corpus_gleu( list_of_references=SCREAMING_SNAKE_CASE , hypotheses=SCREAMING_SNAKE_CASE , min_len=SCREAMING_SNAKE_CASE , max_len=SCREAMING_SNAKE_CASE) }
88
0
import torch from ..models.auto import AutoModelForSequenceClassification, AutoTokenizer from .base import PipelineTool class __lowerCAmelCase ( A_ ): _UpperCamelCase : Any = """facebook/bart-large-mnli""" _UpperCamelCase : Tuple = ( """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 : List[Any] = """text_classifier""" _UpperCamelCase : Any = AutoTokenizer _UpperCamelCase : List[str] = AutoModelForSequenceClassification _UpperCamelCase : Union[str, Any] = ["""text""", ["""text"""]] _UpperCamelCase : Dict = ["""text"""] def _snake_case ( self ) -> Union[str, Any]: """simple docstring""" super().setup() a__ : List[Any] = self.model.config a__ : Union[str, Any] = -1 for idx, label in config.idalabel.items(): if label.lower().startswith("entail" ): a__ : Tuple = int(snake_case ) if self.entailment_id == -1: raise ValueError("Could not determine the entailment ID from the model config, please pass it at init." ) def _snake_case ( self , snake_case , snake_case ) -> Any: """simple docstring""" a__ : Union[str, Any] = labels return self.pre_processor( [text] * len(snake_case ) , [F"""This example is {label}""" for label in labels] , return_tensors="pt" , padding="max_length" , ) def _snake_case ( self , snake_case ) -> Any: """simple docstring""" a__ : int = outputs.logits a__ : List[Any] = torch.argmax(logits[:, 2] ).item() return self._labels[label_id]
112
"""simple docstring""" def _snake_case ( __snake_case : str , __snake_case : str ): """simple docstring""" _lowerCamelCase : str = len(__snake_case ) _lowerCamelCase : Union[str, Any] = len(__snake_case ) _lowerCamelCase : int = [[False for _ in range(m + 1 )] for _ in range(n + 1 )] _lowerCamelCase : Union[str, Any] = True for i in range(__snake_case ): for j in range(m + 1 ): if dp[i][j]: if j < m and a[i].upper() == b[j]: _lowerCamelCase : Tuple = True if a[i].islower(): _lowerCamelCase : Tuple = True return dp[n][m] if __name__ == "__main__": import doctest doctest.testmod()
88
0
import torch from transformers import AutoModel class snake_case__ ( torch.nn.Module): '''simple docstring''' def __init__( self , a__="sayef/fsner-bert-base-uncased" ) -> str: '''simple docstring''' super(a__ , self ).__init__() __snake_case :Union[str, Any] = AutoModel.from_pretrained(a__ , return_dict=a__ ) __snake_case :List[str] = torch.nn.CosineSimilarity(3 , 1e-08 ) __snake_case :Optional[int] = torch.nn.Softmax(dim=1 ) def __lowercase ( self , **a__ ) -> str: '''simple docstring''' return self.bert(**a__ ).last_hidden_state def __lowercase ( self , a__ ) -> Optional[Any]: '''simple docstring''' return token_embeddings.sum(2 , keepdim=a__ ) def __lowercase ( self , a__ , a__ , a__=1 ) -> Union[str, Any]: '''simple docstring''' return self.softmax(T * self.cos(a__ , a__ ) ) def __lowercase ( self , a__ , a__ ) -> List[str]: '''simple docstring''' __snake_case :str = W_supports["""sizes"""].tolist() __snake_case :int = W_supports["""start_token_id"""].item() __snake_case :str = W_supports["""end_token_id"""].item() del W_supports["sizes"] del W_supports["start_token_id"] del W_supports["end_token_id"] __snake_case :List[str] = self.BERT(**a__ ) __snake_case :Optional[Any] = self.BERT(**a__ ) __snake_case :Any = None __snake_case :List[Any] = None __snake_case :Any = W_supports["""input_ids"""] == start_token_id __snake_case :Any = W_supports["""input_ids"""] == end_token_id for i, size in enumerate(a__ ): if i == 0: __snake_case :List[str] = 0 else: __snake_case :Dict = support_sizes[i - 1] __snake_case :Union[str, Any] = S[s : s + size][start_token_masks[s : s + size]] __snake_case :Any = S[s : s + size][end_token_masks[s : s + size]] __snake_case :Any = torch.matmul(q[i] , s_start.T ).sum(1 ).softmax(0 ) __snake_case :List[str] = torch.matmul(q[i] , s_end.T ).sum(1 ).softmax(0 ) if p_starts is not None: __snake_case :str = torch.vstack((p_starts, p_start) ) __snake_case :Optional[Any] = torch.vstack((p_ends, p_end) ) else: __snake_case :Optional[Any] = p_start __snake_case :int = p_end return p_starts, p_ends
455
"""simple docstring""" import warnings from ...utils import logging from .image_processing_imagegpt import ImageGPTImageProcessor UpperCAmelCase = logging.get_logger(__name__) class lowercase__ ( A_ ): def __init__( self , *SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE) -> None: warnings.warn( """The class ImageGPTFeatureExtractor is deprecated and will be removed in version 5 of Transformers.""" """ Please use ImageGPTImageProcessor instead.""" , SCREAMING_SNAKE_CASE , ) super().__init__(*SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE)
88
0
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging lowercase : str = logging.get_logger(__name__) lowercase : List[Any] = { """google/bigbird-roberta-base""": """https://huggingface.co/google/bigbird-roberta-base/resolve/main/config.json""", """google/bigbird-roberta-large""": """https://huggingface.co/google/bigbird-roberta-large/resolve/main/config.json""", """google/bigbird-base-trivia-itc""": """https://huggingface.co/google/bigbird-base-trivia-itc/resolve/main/config.json""", # See all BigBird models at https://huggingface.co/models?filter=big_bird } class A__ ( A_ ): """simple docstring""" __A : List[str] = '''big_bird''' def __init__( self , lowercase=5_0358 , lowercase=768 , lowercase=12 , lowercase=12 , lowercase=3072 , lowercase="gelu_new" , lowercase=0.1 , lowercase=0.1 , lowercase=4096 , lowercase=2 , lowercase=0.02 , lowercase=1e-12 , lowercase=True , lowercase=0 , lowercase=1 , lowercase=2 , lowercase=66 , lowercase="block_sparse" , lowercase=True , lowercase=False , lowercase=64 , lowercase=3 , lowercase=None , **lowercase , ) -> Union[str, Any]: '''simple docstring''' super().__init__( pad_token_id=lowercase , bos_token_id=lowercase , eos_token_id=lowercase , sep_token_id=lowercase , **lowercase , ) a__ : Optional[Any] = vocab_size a__ : Dict = max_position_embeddings a__ : int = hidden_size a__ : Any = num_hidden_layers a__ : Optional[int] = num_attention_heads a__ : int = intermediate_size a__ : int = hidden_act a__ : Union[str, Any] = hidden_dropout_prob a__ : Optional[Any] = attention_probs_dropout_prob a__ : str = initializer_range a__ : Optional[int] = type_vocab_size a__ : Optional[int] = layer_norm_eps a__ : Optional[Any] = use_cache a__ : Any = rescale_embeddings a__ : Optional[int] = attention_type a__ : Optional[int] = use_bias a__ : List[Any] = block_size a__ : str = num_random_blocks a__ : Any = classifier_dropout class A__ ( A_ ): """simple docstring""" @property def __lowercase ( self) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' if self.task == "multiple-choice": a__ : str = {0: """batch""", 1: """choice""", 2: """sequence"""} else: a__ : Optional[Any] = {0: """batch""", 1: """sequence"""} return OrderedDict( [ ('input_ids', dynamic_axis), ('attention_mask', dynamic_axis), ])
302
"""simple docstring""" from math import isqrt, loga def _snake_case ( __snake_case : int ): """simple docstring""" _lowerCamelCase : List[str] = [True] * max_number for i in range(2 , isqrt(max_number - 1 ) + 1 ): if is_prime[i]: for j in range(i**2 , __snake_case , __snake_case ): _lowerCamelCase : Optional[int] = False return [i for i in range(2 , __snake_case ) if is_prime[i]] def _snake_case ( __snake_case : int = 800800 , __snake_case : int = 800800 ): """simple docstring""" _lowerCamelCase : Union[str, Any] = degree * loga(__snake_case ) _lowerCamelCase : Union[str, Any] = int(__snake_case ) _lowerCamelCase : Dict = calculate_prime_numbers(__snake_case ) _lowerCamelCase : Optional[int] = 0 _lowerCamelCase : Any = 0 _lowerCamelCase : Any = len(__snake_case ) - 1 while left < right: while ( prime_numbers[right] * loga(prime_numbers[left] ) + prime_numbers[left] * loga(prime_numbers[right] ) > upper_bound ): right -= 1 hybrid_integers_count += right - left left += 1 return hybrid_integers_count if __name__ == "__main__": print(f'''{solution() = }''')
88
0
from __future__ import annotations def UpperCamelCase ( snake_case__ : list[int] , snake_case__ : int ) -> Optional[Any]: UpperCamelCase : Optional[Any] = 0 UpperCamelCase : Union[str, Any] = len(__snake_case ) - 1 while i < j: if nums[i] + nums[j] == target: return [i, j] elif nums[i] + nums[j] < target: UpperCamelCase : Tuple = i + 1 else: UpperCamelCase : Optional[int] = j - 1 return [] if __name__ == "__main__": import doctest doctest.testmod() print(F"""{two_pointer([2, 7, 11, 15], 9) = }""")
40
"""simple docstring""" import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, StableDiffusionSAGPipeline, UNetaDConditionModel, ) from diffusers.utils import slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class lowercase__ ( A_ ,A_ ,unittest.TestCase ): __UpperCAmelCase = StableDiffusionSAGPipeline __UpperCAmelCase = TEXT_TO_IMAGE_PARAMS __UpperCAmelCase = TEXT_TO_IMAGE_BATCH_PARAMS __UpperCAmelCase = TEXT_TO_IMAGE_IMAGE_PARAMS __UpperCAmelCase = TEXT_TO_IMAGE_IMAGE_PARAMS __UpperCAmelCase = False def UpperCamelCase_ ( self) -> Optional[Any]: torch.manual_seed(0) _lowerCamelCase : Dict = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , cross_attention_dim=32 , ) _lowerCamelCase : int = DDIMScheduler( beta_start=0.0_00_85 , beta_end=0.0_12 , beta_schedule="""scaled_linear""" , clip_sample=SCREAMING_SNAKE_CASE , set_alpha_to_one=SCREAMING_SNAKE_CASE , ) torch.manual_seed(0) _lowerCamelCase : Tuple = 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 , ) torch.manual_seed(0) _lowerCamelCase : Tuple = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) _lowerCamelCase : List[Any] = CLIPTextModel(SCREAMING_SNAKE_CASE) _lowerCamelCase : Tuple = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""") _lowerCamelCase : List[Any] = { """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """safety_checker""": None, """feature_extractor""": None, } return components def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=0) -> List[Any]: if str(SCREAMING_SNAKE_CASE).startswith("""mps"""): _lowerCamelCase : List[str] = torch.manual_seed(SCREAMING_SNAKE_CASE) else: _lowerCamelCase : List[str] = torch.Generator(device=SCREAMING_SNAKE_CASE).manual_seed(SCREAMING_SNAKE_CASE) _lowerCamelCase : List[Any] = { """prompt""": """.""", """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 1.0, """sag_scale""": 1.0, """output_type""": """numpy""", } return inputs def UpperCamelCase_ ( self) -> Tuple: super().test_inference_batch_single_identical(expected_max_diff=3e-3) @slow @require_torch_gpu class lowercase__ ( unittest.TestCase ): def UpperCamelCase_ ( self) -> Union[str, Any]: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCamelCase_ ( self) -> Optional[Any]: _lowerCamelCase : Any = StableDiffusionSAGPipeline.from_pretrained("""CompVis/stable-diffusion-v1-4""") _lowerCamelCase : Union[str, Any] = sag_pipe.to(SCREAMING_SNAKE_CASE) sag_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE) _lowerCamelCase : Optional[int] = """.""" _lowerCamelCase : int = torch.manual_seed(0) _lowerCamelCase : Tuple = sag_pipe( [prompt] , generator=SCREAMING_SNAKE_CASE , guidance_scale=7.5 , sag_scale=1.0 , num_inference_steps=20 , output_type="""np""") _lowerCamelCase : Dict = output.images _lowerCamelCase : Tuple = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) _lowerCamelCase : Optional[Any] = np.array([0.15_68, 0.17_38, 0.16_95, 0.16_93, 0.15_07, 0.17_05, 0.15_47, 0.17_51, 0.19_49]) assert np.abs(image_slice.flatten() - expected_slice).max() < 5e-2 def UpperCamelCase_ ( self) -> List[str]: _lowerCamelCase : Optional[Any] = StableDiffusionSAGPipeline.from_pretrained("""stabilityai/stable-diffusion-2-1-base""") _lowerCamelCase : Dict = sag_pipe.to(SCREAMING_SNAKE_CASE) sag_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE) _lowerCamelCase : Union[str, Any] = """.""" _lowerCamelCase : List[str] = torch.manual_seed(0) _lowerCamelCase : int = sag_pipe( [prompt] , generator=SCREAMING_SNAKE_CASE , guidance_scale=7.5 , sag_scale=1.0 , num_inference_steps=20 , output_type="""np""") _lowerCamelCase : Any = output.images _lowerCamelCase : List[str] = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) _lowerCamelCase : Any = np.array([0.34_59, 0.28_76, 0.25_37, 0.30_02, 0.26_71, 0.21_60, 0.30_26, 0.22_62, 0.23_71]) assert np.abs(image_slice.flatten() - expected_slice).max() < 5e-2 def UpperCamelCase_ ( self) -> List[str]: _lowerCamelCase : int = StableDiffusionSAGPipeline.from_pretrained("""stabilityai/stable-diffusion-2-1-base""") _lowerCamelCase : Optional[Any] = sag_pipe.to(SCREAMING_SNAKE_CASE) sag_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE) _lowerCamelCase : Dict = """.""" _lowerCamelCase : Union[str, Any] = torch.manual_seed(0) _lowerCamelCase : Optional[int] = sag_pipe( [prompt] , width=768 , height=512 , generator=SCREAMING_SNAKE_CASE , guidance_scale=7.5 , sag_scale=1.0 , num_inference_steps=20 , output_type="""np""" , ) _lowerCamelCase : Union[str, Any] = output.images assert image.shape == (1, 512, 768, 3)
88
0
'''simple docstring''' import warnings from ...utils import logging from .image_processing_clip import CLIPImageProcessor lowercase : Union[str, Any] = logging.get_logger(__name__) class A ( A_ ): def __init__( self , *SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) -> None: """simple docstring""" warnings.warn( '''The class CLIPFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please''' ''' use CLIPImageProcessor instead.''' , SCREAMING_SNAKE_CASE , ) super().__init__(*SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE )
634
"""simple docstring""" import inspect import unittest import numpy as np from tests.test_modeling_common import floats_tensor from transformers import MaskaFormerConfig, is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MaskaFormerForUniversalSegmentation, MaskaFormerModel if is_vision_available(): from transformers import MaskaFormerImageProcessor if is_vision_available(): from PIL import Image class lowercase__ : def __init__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=2 , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=False , SCREAMING_SNAKE_CASE=10 , SCREAMING_SNAKE_CASE=3 , SCREAMING_SNAKE_CASE=32 * 8 , SCREAMING_SNAKE_CASE=32 * 8 , SCREAMING_SNAKE_CASE=4 , SCREAMING_SNAKE_CASE=64 , ) -> Optional[int]: _lowerCamelCase : List[str] = parent _lowerCamelCase : List[Any] = batch_size _lowerCamelCase : Tuple = is_training _lowerCamelCase : Tuple = use_auxiliary_loss _lowerCamelCase : Any = num_queries _lowerCamelCase : List[str] = num_channels _lowerCamelCase : List[str] = min_size _lowerCamelCase : Tuple = max_size _lowerCamelCase : str = num_labels _lowerCamelCase : Any = hidden_dim _lowerCamelCase : Dict = hidden_dim def UpperCamelCase_ ( self) -> List[str]: _lowerCamelCase : Union[str, Any] = floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size]).to( SCREAMING_SNAKE_CASE) _lowerCamelCase : List[Any] = torch.ones([self.batch_size, self.min_size, self.max_size] , device=SCREAMING_SNAKE_CASE) _lowerCamelCase : Union[str, Any] = ( torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size] , device=SCREAMING_SNAKE_CASE) > 0.5 ).float() _lowerCamelCase : Dict = (torch.rand((self.batch_size, self.num_labels) , device=SCREAMING_SNAKE_CASE) > 0.5).long() _lowerCamelCase : Optional[int] = self.get_config() return config, pixel_values, pixel_mask, mask_labels, class_labels def UpperCamelCase_ ( self) -> str: _lowerCamelCase : List[str] = MaskaFormerConfig( hidden_size=self.hidden_dim , ) _lowerCamelCase : Any = self.num_queries _lowerCamelCase : int = self.num_labels _lowerCamelCase : int = [1, 1, 1, 1] _lowerCamelCase : Any = self.num_channels _lowerCamelCase : Optional[Any] = 64 _lowerCamelCase : str = 128 _lowerCamelCase : Optional[Any] = self.hidden_dim _lowerCamelCase : Any = self.hidden_dim _lowerCamelCase : List[Any] = self.hidden_dim return config def UpperCamelCase_ ( self) -> Any: _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase : List[str] = self.prepare_config_and_inputs() _lowerCamelCase : str = {"""pixel_values""": pixel_values, """pixel_mask""": pixel_mask} return config, inputs_dict def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) -> Optional[int]: _lowerCamelCase : str = output.encoder_hidden_states _lowerCamelCase : int = output.pixel_decoder_hidden_states _lowerCamelCase : Optional[int] = output.transformer_decoder_hidden_states self.parent.assertTrue(len(SCREAMING_SNAKE_CASE) , len(config.backbone_config.depths)) self.parent.assertTrue(len(SCREAMING_SNAKE_CASE) , len(config.backbone_config.depths)) self.parent.assertTrue(len(SCREAMING_SNAKE_CASE) , config.decoder_layers) def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=False) -> List[str]: with torch.no_grad(): _lowerCamelCase : Optional[int] = MaskaFormerModel(config=SCREAMING_SNAKE_CASE) model.to(SCREAMING_SNAKE_CASE) model.eval() _lowerCamelCase : Optional[int] = model(pixel_values=SCREAMING_SNAKE_CASE , pixel_mask=SCREAMING_SNAKE_CASE) _lowerCamelCase : List[str] = model(SCREAMING_SNAKE_CASE , output_hidden_states=SCREAMING_SNAKE_CASE) self.parent.assertEqual( output.transformer_decoder_last_hidden_state.shape , (self.batch_size, self.num_queries, self.hidden_dim) , ) # let's ensure the other two hidden state exists self.parent.assertTrue(output.pixel_decoder_last_hidden_state is not None) self.parent.assertTrue(output.encoder_last_hidden_state is not None) if output_hidden_states: self.check_output_hidden_state(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) -> str: _lowerCamelCase : str = MaskaFormerForUniversalSegmentation(config=SCREAMING_SNAKE_CASE) model.to(SCREAMING_SNAKE_CASE) model.eval() def comm_check_on_output(SCREAMING_SNAKE_CASE): # let's still check that all the required stuff is there self.parent.assertTrue(result.transformer_decoder_last_hidden_state is not None) self.parent.assertTrue(result.pixel_decoder_last_hidden_state is not None) self.parent.assertTrue(result.encoder_last_hidden_state is not None) # okay, now we need to check the logits shape # due to the encoder compression, masks have a //4 spatial size self.parent.assertEqual( result.masks_queries_logits.shape , (self.batch_size, self.num_queries, self.min_size // 4, self.max_size // 4) , ) # + 1 for null class self.parent.assertEqual( result.class_queries_logits.shape , (self.batch_size, self.num_queries, self.num_labels + 1)) with torch.no_grad(): _lowerCamelCase : List[Any] = model(pixel_values=SCREAMING_SNAKE_CASE , pixel_mask=SCREAMING_SNAKE_CASE) _lowerCamelCase : List[Any] = model(SCREAMING_SNAKE_CASE) comm_check_on_output(SCREAMING_SNAKE_CASE) _lowerCamelCase : Optional[Any] = model( pixel_values=SCREAMING_SNAKE_CASE , pixel_mask=SCREAMING_SNAKE_CASE , mask_labels=SCREAMING_SNAKE_CASE , class_labels=SCREAMING_SNAKE_CASE) comm_check_on_output(SCREAMING_SNAKE_CASE) self.parent.assertTrue(result.loss is not None) self.parent.assertEqual(result.loss.shape , torch.Size([1])) @require_torch class lowercase__ ( A_ ,A_ ,unittest.TestCase ): __UpperCAmelCase = (MaskaFormerModel, MaskaFormerForUniversalSegmentation) if is_torch_available() else () __UpperCAmelCase = {'''feature-extraction''': MaskaFormerModel} if is_torch_available() else {} __UpperCAmelCase = False __UpperCAmelCase = False __UpperCAmelCase = False __UpperCAmelCase = False def UpperCamelCase_ ( self) -> Dict: _lowerCamelCase : Optional[int] = MaskaFormerModelTester(self) _lowerCamelCase : Union[str, Any] = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE , has_text_modality=SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self) -> List[str]: self.config_tester.run_common_tests() def UpperCamelCase_ ( self) -> int: _lowerCamelCase , _lowerCamelCase : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskaformer_model(SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE , output_hidden_states=SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self) -> Tuple: _lowerCamelCase : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_maskaformer_instance_segmentation_head_model(*SCREAMING_SNAKE_CASE) @unittest.skip(reason="""Mask2Former does not use inputs_embeds""") def UpperCamelCase_ ( self) -> Optional[int]: pass @unittest.skip(reason="""Mask2Former does not have a get_input_embeddings method""") def UpperCamelCase_ ( self) -> Tuple: pass @unittest.skip(reason="""Mask2Former is not a generative model""") def UpperCamelCase_ ( self) -> List[Any]: pass @unittest.skip(reason="""Mask2Former does not use token embeddings""") def UpperCamelCase_ ( self) -> Any: pass @require_torch_multi_gpu @unittest.skip( reason="""Mask2Former has some layers using `add_module` which doesn't work well with `nn.DataParallel`""") def UpperCamelCase_ ( self) -> Dict: pass @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""") def UpperCamelCase_ ( self) -> Optional[int]: pass def UpperCamelCase_ ( self) -> Optional[Any]: _lowerCamelCase , _lowerCamelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _lowerCamelCase : Dict = model_class(SCREAMING_SNAKE_CASE) _lowerCamelCase : Any = inspect.signature(model.forward) # signature.parameters is an OrderedDict => so arg_names order is deterministic _lowerCamelCase : str = [*signature.parameters.keys()] _lowerCamelCase : int = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , SCREAMING_SNAKE_CASE) @slow def UpperCamelCase_ ( self) -> Optional[int]: for model_name in ["facebook/mask2former-swin-small-coco-instance"]: _lowerCamelCase : Optional[int] = MaskaFormerModel.from_pretrained(SCREAMING_SNAKE_CASE) self.assertIsNotNone(SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self) -> Optional[Any]: _lowerCamelCase : Dict = (self.model_tester.min_size,) * 2 _lowerCamelCase : str = { """pixel_values""": torch.randn((2, 3, *size) , device=SCREAMING_SNAKE_CASE), """mask_labels""": torch.randn((2, 10, *size) , device=SCREAMING_SNAKE_CASE), """class_labels""": torch.zeros(2 , 10 , device=SCREAMING_SNAKE_CASE).long(), } _lowerCamelCase : List[str] = self.model_tester.get_config() _lowerCamelCase : Tuple = MaskaFormerForUniversalSegmentation(SCREAMING_SNAKE_CASE).to(SCREAMING_SNAKE_CASE) _lowerCamelCase : Union[str, Any] = model(**SCREAMING_SNAKE_CASE) self.assertTrue(outputs.loss is not None) def UpperCamelCase_ ( self) -> Tuple: _lowerCamelCase , _lowerCamelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskaformer_model(SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE , output_hidden_states=SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self) -> Optional[int]: _lowerCamelCase , _lowerCamelCase : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _lowerCamelCase : str = model_class(SCREAMING_SNAKE_CASE).to(SCREAMING_SNAKE_CASE) _lowerCamelCase : Union[str, Any] = model(**SCREAMING_SNAKE_CASE , output_attentions=SCREAMING_SNAKE_CASE) self.assertTrue(outputs.attentions is not None) def UpperCamelCase_ ( self) -> Optional[Any]: if not self.model_tester.is_training: return _lowerCamelCase : Any = self.all_model_classes[1] _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs() _lowerCamelCase : List[Any] = model_class(SCREAMING_SNAKE_CASE) model.to(SCREAMING_SNAKE_CASE) model.train() _lowerCamelCase : int = model(SCREAMING_SNAKE_CASE , mask_labels=SCREAMING_SNAKE_CASE , class_labels=SCREAMING_SNAKE_CASE).loss loss.backward() def UpperCamelCase_ ( self) -> Optional[Any]: _lowerCamelCase : Any = self.all_model_classes[1] _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase : int = self.model_tester.prepare_config_and_inputs() _lowerCamelCase : int = True _lowerCamelCase : Optional[Any] = True _lowerCamelCase : str = model_class(SCREAMING_SNAKE_CASE).to(SCREAMING_SNAKE_CASE) model.train() _lowerCamelCase : List[Any] = model(SCREAMING_SNAKE_CASE , mask_labels=SCREAMING_SNAKE_CASE , class_labels=SCREAMING_SNAKE_CASE) _lowerCamelCase : Tuple = outputs.encoder_hidden_states[0] encoder_hidden_states.retain_grad() _lowerCamelCase : int = outputs.pixel_decoder_hidden_states[0] pixel_decoder_hidden_states.retain_grad() _lowerCamelCase : str = outputs.transformer_decoder_hidden_states[0] transformer_decoder_hidden_states.retain_grad() _lowerCamelCase : Optional[int] = outputs.attentions[0] attentions.retain_grad() outputs.loss.backward(retain_graph=SCREAMING_SNAKE_CASE) self.assertIsNotNone(encoder_hidden_states.grad) self.assertIsNotNone(pixel_decoder_hidden_states.grad) self.assertIsNotNone(transformer_decoder_hidden_states.grad) self.assertIsNotNone(attentions.grad) UpperCAmelCase = 1e-4 def _snake_case ( ): """simple docstring""" _lowerCamelCase : List[str] = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_vision @slow class lowercase__ ( unittest.TestCase ): @cached_property def UpperCamelCase_ ( self) -> int: return "facebook/mask2former-swin-small-coco-instance" @cached_property def UpperCamelCase_ ( self) -> Union[str, Any]: return MaskaFormerImageProcessor.from_pretrained(self.model_checkpoints) if is_vision_available() else None def UpperCamelCase_ ( self) -> Optional[Any]: _lowerCamelCase : Tuple = MaskaFormerModel.from_pretrained(self.model_checkpoints).to(SCREAMING_SNAKE_CASE) _lowerCamelCase : str = self.default_image_processor _lowerCamelCase : List[str] = prepare_img() _lowerCamelCase : Union[str, Any] = image_processor(SCREAMING_SNAKE_CASE , return_tensors="""pt""").to(SCREAMING_SNAKE_CASE) _lowerCamelCase : Union[str, Any] = inputs["""pixel_values"""].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0) # check size self.assertEqual(SCREAMING_SNAKE_CASE , (1, 3, 384, 384)) with torch.no_grad(): _lowerCamelCase : Dict = model(**SCREAMING_SNAKE_CASE) _lowerCamelCase : List[Any] = torch.tensor( [[-0.27_90, -1.07_17, -1.16_68], [-0.51_28, -0.31_28, -0.49_87], [-0.58_32, 0.19_71, -0.01_97]]).to(SCREAMING_SNAKE_CASE) self.assertTrue( torch.allclose( outputs.encoder_last_hidden_state[0, 0, :3, :3] , SCREAMING_SNAKE_CASE , atol=SCREAMING_SNAKE_CASE)) _lowerCamelCase : Any = torch.tensor( [[0.89_73, 1.18_47, 1.17_76], [1.19_34, 1.50_40, 1.51_28], [1.11_53, 1.44_86, 1.49_51]]).to(SCREAMING_SNAKE_CASE) self.assertTrue( torch.allclose( outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3] , SCREAMING_SNAKE_CASE , atol=SCREAMING_SNAKE_CASE)) _lowerCamelCase : Dict = torch.tensor( [[2.11_52, 1.70_00, -0.86_03], [1.58_08, 1.80_04, -0.93_53], [1.60_43, 1.74_95, -0.59_99]]).to(SCREAMING_SNAKE_CASE) self.assertTrue( torch.allclose( outputs.transformer_decoder_last_hidden_state[0, :3, :3] , SCREAMING_SNAKE_CASE , atol=SCREAMING_SNAKE_CASE)) def UpperCamelCase_ ( self) -> Any: _lowerCamelCase : Optional[Any] = MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints).to(SCREAMING_SNAKE_CASE).eval() _lowerCamelCase : Optional[Any] = self.default_image_processor _lowerCamelCase : Any = prepare_img() _lowerCamelCase : Dict = image_processor(SCREAMING_SNAKE_CASE , return_tensors="""pt""").to(SCREAMING_SNAKE_CASE) _lowerCamelCase : Union[str, Any] = inputs["""pixel_values"""].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0) # check size self.assertEqual(SCREAMING_SNAKE_CASE , (1, 3, 384, 384)) with torch.no_grad(): _lowerCamelCase : List[str] = model(**SCREAMING_SNAKE_CASE) # masks_queries_logits _lowerCamelCase : str = outputs.masks_queries_logits self.assertEqual( masks_queries_logits.shape , (1, model.config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4)) _lowerCamelCase : Any = [ [-8.78_39, -9.00_56, -8.81_21], [-7.41_04, -7.03_13, -6.54_01], [-6.61_05, -6.34_27, -6.46_75], ] _lowerCamelCase : List[Any] = torch.tensor(SCREAMING_SNAKE_CASE).to(SCREAMING_SNAKE_CASE) self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , SCREAMING_SNAKE_CASE , atol=SCREAMING_SNAKE_CASE)) # class_queries_logits _lowerCamelCase : List[str] = outputs.class_queries_logits self.assertEqual(class_queries_logits.shape , (1, model.config.num_queries, model.config.num_labels + 1)) _lowerCamelCase : Optional[Any] = torch.tensor( [ [1.83_24, -8.08_35, -4.19_22], [0.84_50, -9.00_50, -3.60_53], [0.30_45, -7.72_93, -3.02_75], ]).to(SCREAMING_SNAKE_CASE) self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , SCREAMING_SNAKE_CASE , atol=SCREAMING_SNAKE_CASE)) def UpperCamelCase_ ( self) -> int: _lowerCamelCase : Tuple = MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints).to(SCREAMING_SNAKE_CASE).eval() _lowerCamelCase : str = self.default_image_processor _lowerCamelCase : Tuple = image_processor( [np.zeros((3, 800, 1333)), np.zeros((3, 800, 1333))] , segmentation_maps=[np.zeros((384, 384)).astype(np.floataa), np.zeros((384, 384)).astype(np.floataa)] , return_tensors="""pt""" , ) _lowerCamelCase : Optional[Any] = inputs["""pixel_values"""].to(SCREAMING_SNAKE_CASE) _lowerCamelCase : Any = [el.to(SCREAMING_SNAKE_CASE) for el in inputs["""mask_labels"""]] _lowerCamelCase : Union[str, Any] = [el.to(SCREAMING_SNAKE_CASE) for el in inputs["""class_labels"""]] with torch.no_grad(): _lowerCamelCase : Any = model(**SCREAMING_SNAKE_CASE) self.assertTrue(outputs.loss is not None)
88
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available UpperCAmelCase_ : Optional[Any] = { '''configuration_bloom''': ['''BLOOM_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''BloomConfig''', '''BloomOnnxConfig'''], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ : Any = ['''BloomTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ : int = [ '''BLOOM_PRETRAINED_MODEL_ARCHIVE_LIST''', '''BloomForCausalLM''', '''BloomModel''', '''BloomPreTrainedModel''', '''BloomForSequenceClassification''', '''BloomForTokenClassification''', '''BloomForQuestionAnswering''', ] if TYPE_CHECKING: from .configuration_bloom import BLOOM_PRETRAINED_CONFIG_ARCHIVE_MAP, BloomConfig, BloomOnnxConfig try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_bloom_fast import BloomTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_bloom import ( BLOOM_PRETRAINED_MODEL_ARCHIVE_LIST, BloomForCausalLM, BloomForQuestionAnswering, BloomForSequenceClassification, BloomForTokenClassification, BloomModel, BloomPreTrainedModel, ) else: import sys UpperCAmelCase_ : Tuple = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
24
"""simple docstring""" from collections import OrderedDict from ...utils import logging from .auto_factory import _BaseAutoModelClass, _LazyAutoMapping, auto_class_update from .configuration_auto import CONFIG_MAPPING_NAMES UpperCAmelCase = logging.get_logger(__name__) UpperCAmelCase = OrderedDict( [ # Base model mapping ("""albert""", """FlaxAlbertModel"""), ("""bart""", """FlaxBartModel"""), ("""beit""", """FlaxBeitModel"""), ("""bert""", """FlaxBertModel"""), ("""big_bird""", """FlaxBigBirdModel"""), ("""blenderbot""", """FlaxBlenderbotModel"""), ("""blenderbot-small""", """FlaxBlenderbotSmallModel"""), ("""clip""", """FlaxCLIPModel"""), ("""distilbert""", """FlaxDistilBertModel"""), ("""electra""", """FlaxElectraModel"""), ("""gpt-sw3""", """FlaxGPT2Model"""), ("""gpt2""", """FlaxGPT2Model"""), ("""gpt_neo""", """FlaxGPTNeoModel"""), ("""gptj""", """FlaxGPTJModel"""), ("""longt5""", """FlaxLongT5Model"""), ("""marian""", """FlaxMarianModel"""), ("""mbart""", """FlaxMBartModel"""), ("""mt5""", """FlaxMT5Model"""), ("""opt""", """FlaxOPTModel"""), ("""pegasus""", """FlaxPegasusModel"""), ("""regnet""", """FlaxRegNetModel"""), ("""resnet""", """FlaxResNetModel"""), ("""roberta""", """FlaxRobertaModel"""), ("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormModel"""), ("""roformer""", """FlaxRoFormerModel"""), ("""t5""", """FlaxT5Model"""), ("""vision-text-dual-encoder""", """FlaxVisionTextDualEncoderModel"""), ("""vit""", """FlaxViTModel"""), ("""wav2vec2""", """FlaxWav2Vec2Model"""), ("""whisper""", """FlaxWhisperModel"""), ("""xglm""", """FlaxXGLMModel"""), ("""xlm-roberta""", """FlaxXLMRobertaModel"""), ] ) UpperCAmelCase = OrderedDict( [ # Model for pre-training mapping ("""albert""", """FlaxAlbertForPreTraining"""), ("""bart""", """FlaxBartForConditionalGeneration"""), ("""bert""", """FlaxBertForPreTraining"""), ("""big_bird""", """FlaxBigBirdForPreTraining"""), ("""electra""", """FlaxElectraForPreTraining"""), ("""longt5""", """FlaxLongT5ForConditionalGeneration"""), ("""mbart""", """FlaxMBartForConditionalGeneration"""), ("""mt5""", """FlaxMT5ForConditionalGeneration"""), ("""roberta""", """FlaxRobertaForMaskedLM"""), ("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormForMaskedLM"""), ("""roformer""", """FlaxRoFormerForMaskedLM"""), ("""t5""", """FlaxT5ForConditionalGeneration"""), ("""wav2vec2""", """FlaxWav2Vec2ForPreTraining"""), ("""whisper""", """FlaxWhisperForConditionalGeneration"""), ("""xlm-roberta""", """FlaxXLMRobertaForMaskedLM"""), ] ) UpperCAmelCase = OrderedDict( [ # Model for Masked LM mapping ("""albert""", """FlaxAlbertForMaskedLM"""), ("""bart""", """FlaxBartForConditionalGeneration"""), ("""bert""", """FlaxBertForMaskedLM"""), ("""big_bird""", """FlaxBigBirdForMaskedLM"""), ("""distilbert""", """FlaxDistilBertForMaskedLM"""), ("""electra""", """FlaxElectraForMaskedLM"""), ("""mbart""", """FlaxMBartForConditionalGeneration"""), ("""roberta""", """FlaxRobertaForMaskedLM"""), ("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormForMaskedLM"""), ("""roformer""", """FlaxRoFormerForMaskedLM"""), ("""xlm-roberta""", """FlaxXLMRobertaForMaskedLM"""), ] ) UpperCAmelCase = OrderedDict( [ # Model for Seq2Seq Causal LM mapping ("""bart""", """FlaxBartForConditionalGeneration"""), ("""blenderbot""", """FlaxBlenderbotForConditionalGeneration"""), ("""blenderbot-small""", """FlaxBlenderbotSmallForConditionalGeneration"""), ("""encoder-decoder""", """FlaxEncoderDecoderModel"""), ("""longt5""", """FlaxLongT5ForConditionalGeneration"""), ("""marian""", """FlaxMarianMTModel"""), ("""mbart""", """FlaxMBartForConditionalGeneration"""), ("""mt5""", """FlaxMT5ForConditionalGeneration"""), ("""pegasus""", """FlaxPegasusForConditionalGeneration"""), ("""t5""", """FlaxT5ForConditionalGeneration"""), ] ) UpperCAmelCase = OrderedDict( [ # Model for Image-classsification ("""beit""", """FlaxBeitForImageClassification"""), ("""regnet""", """FlaxRegNetForImageClassification"""), ("""resnet""", """FlaxResNetForImageClassification"""), ("""vit""", """FlaxViTForImageClassification"""), ] ) UpperCAmelCase = OrderedDict( [ ("""vision-encoder-decoder""", """FlaxVisionEncoderDecoderModel"""), ] ) UpperCAmelCase = OrderedDict( [ # Model for Causal LM mapping ("""bart""", """FlaxBartForCausalLM"""), ("""bert""", """FlaxBertForCausalLM"""), ("""big_bird""", """FlaxBigBirdForCausalLM"""), ("""electra""", """FlaxElectraForCausalLM"""), ("""gpt-sw3""", """FlaxGPT2LMHeadModel"""), ("""gpt2""", """FlaxGPT2LMHeadModel"""), ("""gpt_neo""", """FlaxGPTNeoForCausalLM"""), ("""gptj""", """FlaxGPTJForCausalLM"""), ("""opt""", """FlaxOPTForCausalLM"""), ("""roberta""", """FlaxRobertaForCausalLM"""), ("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormForCausalLM"""), ("""xglm""", """FlaxXGLMForCausalLM"""), ("""xlm-roberta""", """FlaxXLMRobertaForCausalLM"""), ] ) UpperCAmelCase = OrderedDict( [ # Model for Sequence Classification mapping ("""albert""", """FlaxAlbertForSequenceClassification"""), ("""bart""", """FlaxBartForSequenceClassification"""), ("""bert""", """FlaxBertForSequenceClassification"""), ("""big_bird""", """FlaxBigBirdForSequenceClassification"""), ("""distilbert""", """FlaxDistilBertForSequenceClassification"""), ("""electra""", """FlaxElectraForSequenceClassification"""), ("""mbart""", """FlaxMBartForSequenceClassification"""), ("""roberta""", """FlaxRobertaForSequenceClassification"""), ("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormForSequenceClassification"""), ("""roformer""", """FlaxRoFormerForSequenceClassification"""), ("""xlm-roberta""", """FlaxXLMRobertaForSequenceClassification"""), ] ) UpperCAmelCase = OrderedDict( [ # Model for Question Answering mapping ("""albert""", """FlaxAlbertForQuestionAnswering"""), ("""bart""", """FlaxBartForQuestionAnswering"""), ("""bert""", """FlaxBertForQuestionAnswering"""), ("""big_bird""", """FlaxBigBirdForQuestionAnswering"""), ("""distilbert""", """FlaxDistilBertForQuestionAnswering"""), ("""electra""", """FlaxElectraForQuestionAnswering"""), ("""mbart""", """FlaxMBartForQuestionAnswering"""), ("""roberta""", """FlaxRobertaForQuestionAnswering"""), ("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormForQuestionAnswering"""), ("""roformer""", """FlaxRoFormerForQuestionAnswering"""), ("""xlm-roberta""", """FlaxXLMRobertaForQuestionAnswering"""), ] ) UpperCAmelCase = OrderedDict( [ # Model for Token Classification mapping ("""albert""", """FlaxAlbertForTokenClassification"""), ("""bert""", """FlaxBertForTokenClassification"""), ("""big_bird""", """FlaxBigBirdForTokenClassification"""), ("""distilbert""", """FlaxDistilBertForTokenClassification"""), ("""electra""", """FlaxElectraForTokenClassification"""), ("""roberta""", """FlaxRobertaForTokenClassification"""), ("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormForTokenClassification"""), ("""roformer""", """FlaxRoFormerForTokenClassification"""), ("""xlm-roberta""", """FlaxXLMRobertaForTokenClassification"""), ] ) UpperCAmelCase = OrderedDict( [ # Model for Multiple Choice mapping ("""albert""", """FlaxAlbertForMultipleChoice"""), ("""bert""", """FlaxBertForMultipleChoice"""), ("""big_bird""", """FlaxBigBirdForMultipleChoice"""), ("""distilbert""", """FlaxDistilBertForMultipleChoice"""), ("""electra""", """FlaxElectraForMultipleChoice"""), ("""roberta""", """FlaxRobertaForMultipleChoice"""), ("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormForMultipleChoice"""), ("""roformer""", """FlaxRoFormerForMultipleChoice"""), ("""xlm-roberta""", """FlaxXLMRobertaForMultipleChoice"""), ] ) UpperCAmelCase = OrderedDict( [ ("""bert""", """FlaxBertForNextSentencePrediction"""), ] ) UpperCAmelCase = OrderedDict( [ ("""speech-encoder-decoder""", """FlaxSpeechEncoderDecoderModel"""), ("""whisper""", """FlaxWhisperForConditionalGeneration"""), ] ) UpperCAmelCase = OrderedDict( [ ("""whisper""", """FlaxWhisperForAudioClassification"""), ] ) UpperCAmelCase = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_MAPPING_NAMES) UpperCAmelCase = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_PRETRAINING_MAPPING_NAMES) UpperCAmelCase = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MASKED_LM_MAPPING_NAMES) UpperCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES ) UpperCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES ) UpperCAmelCase = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES) UpperCAmelCase = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_CAUSAL_LM_MAPPING_NAMES) UpperCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES ) UpperCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES ) UpperCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES ) UpperCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES ) UpperCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING_NAMES ) UpperCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES ) UpperCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES ) class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_MAPPING UpperCAmelCase = auto_class_update(FlaxAutoModel) class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_PRETRAINING_MAPPING UpperCAmelCase = auto_class_update(FlaxAutoModelForPreTraining, head_doc="""pretraining""") class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_CAUSAL_LM_MAPPING UpperCAmelCase = auto_class_update(FlaxAutoModelForCausalLM, head_doc="""causal language modeling""") class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_MASKED_LM_MAPPING UpperCAmelCase = auto_class_update(FlaxAutoModelForMaskedLM, head_doc="""masked language modeling""") class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING UpperCAmelCase = auto_class_update( FlaxAutoModelForSeqaSeqLM, head_doc="""sequence-to-sequence language modeling""", checkpoint_for_example="""t5-base""" ) class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING UpperCAmelCase = auto_class_update( FlaxAutoModelForSequenceClassification, head_doc="""sequence classification""" ) class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING UpperCAmelCase = auto_class_update(FlaxAutoModelForQuestionAnswering, head_doc="""question answering""") class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING UpperCAmelCase = auto_class_update( FlaxAutoModelForTokenClassification, head_doc="""token classification""" ) class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING UpperCAmelCase = auto_class_update(FlaxAutoModelForMultipleChoice, head_doc="""multiple choice""") class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING UpperCAmelCase = auto_class_update( FlaxAutoModelForNextSentencePrediction, head_doc="""next sentence prediction""" ) class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING UpperCAmelCase = auto_class_update( FlaxAutoModelForImageClassification, head_doc="""image classification""" ) class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING UpperCAmelCase = auto_class_update(FlaxAutoModelForVisionaSeq, head_doc="""vision-to-text modeling""") class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING UpperCAmelCase = auto_class_update( FlaxAutoModelForSpeechSeqaSeq, head_doc="""sequence-to-sequence speech-to-text modeling""" )
88
0
from __future__ import annotations def UpperCAmelCase_ ( snake_case__ , snake_case__ = None ) -> Optional[int]: """simple docstring""" lowerCAmelCase__ = word_bank or [] # create a table lowerCAmelCase__ = len(__snake_case ) + 1 lowerCAmelCase__ = [] for _ in range(__snake_case ): table.append([] ) # seed value lowerCAmelCase__ = [[]] # because empty string has empty combination # iterate through the indices for i in range(__snake_case ): # condition if table[i] != []: for word in word_bank: # slice condition if target[i : i + len(__snake_case )] == word: lowerCAmelCase__ = [ [word, *way] for way in table[i] ] # adds the word to every combination the current position holds # now,push that combination to the table[i+len(word)] table[i + len(__snake_case )] += new_combinations # combinations are in reverse order so reverse for better output for combination in table[len(__snake_case )]: combination.reverse() return table[len(__snake_case )] if __name__ == "__main__": print(all_construct("jwajalapa", ["jwa", "j", "w", "a", "la", "lapa"])) print(all_construct("rajamati", ["s", "raj", "amat", "raja", "ma", "i", "t"])) print( all_construct( "hexagonosaurus", ["h", "ex", "hex", "ag", "ago", "ru", "auru", "rus", "go", "no", "o", "s"], ) )
193
"""simple docstring""" # limitations under the License. # NOTE: This file is deprecated and will be removed in a future version. # It only exists so that temporarely `from diffusers.pipelines import DiffusionPipeline` works from .pipelines import DiffusionPipeline, ImagePipelineOutput # noqa: F401 from .utils import deprecate deprecate( """pipelines_utils""", """0.22.0""", """Importing `DiffusionPipeline` or `ImagePipelineOutput` from diffusers.pipeline_utils is deprecated. Please import from diffusers.pipelines.pipeline_utils instead.""", standard_warn=False, stacklevel=3, )
88
0
'''simple docstring''' from __future__ import annotations import unittest from transformers import XGLMConfig, XGLMTokenizer, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers.models.xglm.modeling_tf_xglm import ( TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST, TFXGLMForCausalLM, TFXGLMModel, ) @require_tf class __A : snake_case :Optional[Any] = XGLMConfig snake_case :Tuple = {} snake_case :Any = "gelu" def __init__( self , UpperCamelCase_ , UpperCamelCase_=14 , UpperCamelCase_=7 , UpperCamelCase_=True , UpperCamelCase_=True , UpperCamelCase_=True , UpperCamelCase_=99 , UpperCamelCase_=32 , UpperCamelCase_=2 , UpperCamelCase_=4 , UpperCamelCase_=37 , UpperCamelCase_="gelu" , UpperCamelCase_=0.1 , UpperCamelCase_=0.1 , UpperCamelCase_=5_12 , UpperCamelCase_=0.0_2 , ): __UpperCAmelCase : Optional[int] = parent __UpperCAmelCase : int = batch_size __UpperCAmelCase : str = seq_length __UpperCAmelCase : Any = is_training __UpperCAmelCase : int = use_input_mask __UpperCAmelCase : Union[str, Any] = use_labels __UpperCAmelCase : str = vocab_size __UpperCAmelCase : List[str] = d_model __UpperCAmelCase : List[Any] = num_hidden_layers __UpperCAmelCase : Dict = num_attention_heads __UpperCAmelCase : int = ffn_dim __UpperCAmelCase : str = activation_function __UpperCAmelCase : Optional[int] = activation_dropout __UpperCAmelCase : Tuple = attention_dropout __UpperCAmelCase : Tuple = max_position_embeddings __UpperCAmelCase : Dict = initializer_range __UpperCAmelCase : Optional[Any] = None __UpperCAmelCase : Union[str, Any] = 0 __UpperCAmelCase : List[Any] = 2 __UpperCAmelCase : str = 1 def _snake_case ( self ): return XGLMConfig.from_pretrained("facebook/xglm-564M" ) def _snake_case ( self ): __UpperCAmelCase : Union[str, Any] = tf.clip_by_value( ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) , clip_value_min=0 , clip_value_max=3 ) __UpperCAmelCase : str = None if self.use_input_mask: __UpperCAmelCase : Union[str, Any] = random_attention_mask([self.batch_size, self.seq_length] ) __UpperCAmelCase : Tuple = self.get_config() __UpperCAmelCase : Optional[int] = floats_tensor([self.num_hidden_layers, self.num_attention_heads] , 2 ) return ( config, input_ids, input_mask, head_mask, ) def _snake_case ( self ): return XGLMConfig( vocab_size=self.vocab_size , d_model=self.hidden_size , num_layers=self.num_hidden_layers , attention_heads=self.num_attention_heads , ffn_dim=self.ffn_dim , activation_function=self.activation_function , activation_dropout=self.activation_dropout , attention_dropout=self.attention_dropout , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , use_cache=UpperCamelCase_ , bos_token_id=self.bos_token_id , eos_token_id=self.eos_token_id , pad_token_id=self.pad_token_id , return_dict=UpperCamelCase_ , ) def _snake_case ( self ): __UpperCAmelCase : List[Any] = self.prepare_config_and_inputs() ( __UpperCAmelCase ) : str = config_and_inputs __UpperCAmelCase : Optional[Any] = { """input_ids""": input_ids, """head_mask""": head_mask, } return config, inputs_dict @require_tf class __A (A_ , A_ , unittest.TestCase ): snake_case :Tuple = (TFXGLMModel, TFXGLMForCausalLM) if is_tf_available() else () snake_case :str = (TFXGLMForCausalLM,) if is_tf_available() else () snake_case :Dict = ( {"feature-extraction": TFXGLMModel, "text-generation": TFXGLMForCausalLM} if is_tf_available() else {} ) snake_case :Optional[Any] = False snake_case :int = False snake_case :Tuple = False def _snake_case ( self ): __UpperCAmelCase : Optional[Any] = TFXGLMModelTester(self ) __UpperCAmelCase : str = ConfigTester(self , config_class=UpperCamelCase_ , n_embd=37 ) def _snake_case ( self ): self.config_tester.run_common_tests() @slow def _snake_case ( self ): for model_name in TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __UpperCAmelCase : Tuple = TFXGLMModel.from_pretrained(UpperCamelCase_ ) self.assertIsNotNone(UpperCamelCase_ ) @unittest.skip(reason="Currently, model embeddings are going to undergo a major refactor." ) def _snake_case ( self ): super().test_resize_token_embeddings() @require_tf class __A (unittest.TestCase ): @slow def _snake_case ( self , UpperCamelCase_=True ): __UpperCAmelCase : List[str] = TFXGLMForCausalLM.from_pretrained("facebook/xglm-564M" ) __UpperCAmelCase : Union[str, Any] = tf.convert_to_tensor([[2, 2_68, 98_65]] , dtype=tf.intaa ) # The dog # </s> The dog is a very friendly dog. He is very affectionate and loves to play with other # fmt: off __UpperCAmelCase : Dict = [2, 2_68, 98_65, 67, 11, 19_88, 5_72_52, 98_65, 5, 9_84, 67, 19_88, 21_38_38, 16_58, 53, 7_04_46, 33, 66_57, 2_78, 15_81] # fmt: on __UpperCAmelCase : str = model.generate(UpperCamelCase_ , do_sample=UpperCamelCase_ , num_beams=1 ) if verify_outputs: self.assertListEqual(output_ids[0].numpy().tolist() , UpperCamelCase_ ) @slow def _snake_case ( self ): __UpperCAmelCase : int = XGLMTokenizer.from_pretrained("facebook/xglm-564M" ) __UpperCAmelCase : Tuple = TFXGLMForCausalLM.from_pretrained("facebook/xglm-564M" ) tf.random.set_seed(0 ) __UpperCAmelCase : Union[str, Any] = tokenizer("Today is a nice day and" , return_tensors="tf" ) __UpperCAmelCase : Any = tokenized.input_ids # forces the generation to happen on CPU, to avoid GPU-related quirks (and assure same output regardless of the available devices) with tf.device(":/CPU:0" ): __UpperCAmelCase : Any = model.generate(UpperCamelCase_ , do_sample=UpperCamelCase_ , seed=[7, 0] ) __UpperCAmelCase : List[str] = tokenizer.decode(output_ids[0] , skip_special_tokens=UpperCamelCase_ ) __UpperCAmelCase : Any = ( """Today is a nice day and warm evening here over Southern Alberta!! Today when they closed schools due""" ) self.assertEqual(UpperCamelCase_ , UpperCamelCase_ ) @slow def _snake_case ( self ): __UpperCAmelCase : Optional[Any] = TFXGLMForCausalLM.from_pretrained("facebook/xglm-564M" ) __UpperCAmelCase : Any = XGLMTokenizer.from_pretrained("facebook/xglm-564M" ) __UpperCAmelCase : List[Any] = """left""" # use different length sentences to test batching __UpperCAmelCase : List[Any] = [ """This is an extremelly long sentence that only exists to test the ability of the model to cope with """ """left-padding, such as in batched generation. The output for the sequence below should be the same """ """regardless of whether left padding is applied or not. When""", """Hello, my dog is a little""", ] __UpperCAmelCase : Union[str, Any] = tokenizer(UpperCamelCase_ , return_tensors="tf" , padding=UpperCamelCase_ ) __UpperCAmelCase : int = inputs["""input_ids"""] __UpperCAmelCase : List[Any] = model.generate(input_ids=UpperCamelCase_ , attention_mask=inputs["attention_mask"] , max_new_tokens=12 ) __UpperCAmelCase : List[str] = tokenizer(sentences[0] , return_tensors="tf" ).input_ids __UpperCAmelCase : Optional[Any] = model.generate(input_ids=UpperCamelCase_ , max_new_tokens=12 ) __UpperCAmelCase : Tuple = tokenizer(sentences[1] , return_tensors="tf" ).input_ids __UpperCAmelCase : int = model.generate(input_ids=UpperCamelCase_ , max_new_tokens=12 ) __UpperCAmelCase : Optional[int] = tokenizer.batch_decode(UpperCamelCase_ , skip_special_tokens=UpperCamelCase_ ) __UpperCAmelCase : Optional[Any] = tokenizer.decode(output_non_padded[0] , skip_special_tokens=UpperCamelCase_ ) __UpperCAmelCase : Union[str, Any] = tokenizer.decode(output_padded[0] , skip_special_tokens=UpperCamelCase_ ) __UpperCAmelCase : Tuple = [ """This is an extremelly long sentence that only exists to test the ability of the model to cope with """ """left-padding, such as in batched generation. The output for the sequence below should be the same """ """regardless of whether left padding is applied or not. When left padding is applied, the sequence will be """ """a single""", """Hello, my dog is a little bit of a shy one, but he is very friendly""", ] self.assertListEqual(UpperCamelCase_ , UpperCamelCase_ ) self.assertListEqual(UpperCamelCase_ , [non_padded_sentence, padded_sentence] )
168
"""simple docstring""" def _snake_case ( __snake_case : list[list[int]] , __snake_case : int , __snake_case : int , __snake_case : list[int] ): """simple docstring""" 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 _snake_case ( __snake_case : list[list[int]] , __snake_case : list[int] , __snake_case : int ): """simple docstring""" if curr_ind == len(__snake_case ): # 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(__snake_case ) ): if valid_connection(__snake_case , __snake_case , __snake_case , __snake_case ): # Insert current vertex into path as next transition _lowerCamelCase : List[str] = next_ver # Validate created path if util_hamilton_cycle(__snake_case , __snake_case , curr_ind + 1 ): return True # Backtrack _lowerCamelCase : Tuple = -1 return False def _snake_case ( __snake_case : list[list[int]] , __snake_case : int = 0 ): """simple docstring""" _lowerCamelCase : Any = [-1] * (len(__snake_case ) + 1) # initialize start and end of path with starting index _lowerCamelCase : Optional[int] = start_index # evaluate and if we find answer return path either return empty array return path if util_hamilton_cycle(__snake_case , __snake_case , 1 ) else []
88
0
"""simple docstring""" import json import os import subprocess import unittest from ast import literal_eval import pytest from parameterized import parameterized, parameterized_class from . import is_sagemaker_available if is_sagemaker_available(): from sagemaker import Session, TrainingJobAnalytics from sagemaker.huggingface import HuggingFace @pytest.mark.skipif( literal_eval(os.getenv("TEST_SAGEMAKER" , "False" ) ) is not True , reason="Skipping test because should only be run when releasing minor transformers version" , ) @pytest.mark.usefixtures("sm_env" ) @parameterized_class( [ { "framework": "pytorch", "script": "run_glue.py", "model_name_or_path": "distilbert-base-cased", "instance_type": "ml.p3.16xlarge", "results": {"train_runtime": 6_50, "eval_accuracy": 0.7, "eval_loss": 0.6}, }, { "framework": "pytorch", "script": "run_ddp.py", "model_name_or_path": "distilbert-base-cased", "instance_type": "ml.p3.16xlarge", "results": {"train_runtime": 6_00, "eval_accuracy": 0.7, "eval_loss": 0.6}, }, { "framework": "tensorflow", "script": "run_tf_dist.py", "model_name_or_path": "distilbert-base-cased", "instance_type": "ml.p3.16xlarge", "results": {"train_runtime": 6_00, "eval_accuracy": 0.6, "eval_loss": 0.7}, }, ] ) class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' def UpperCamelCase__ ( self: List[Any] ): if self.framework == "pytorch": subprocess.run( f"""cp ./examples/pytorch/text-classification/run_glue.py {self.env.test_path}/run_glue.py""".split() , encoding="utf-8" , check=UpperCamelCase_ , ) assert hasattr(self , "env" ) def UpperCamelCase__ ( self: str , UpperCamelCase_: List[Any] ): UpperCamelCase_ =f"""{self.env.base_job_name}-{instance_count}-{"ddp" if "ddp" in self.script else "smd"}""" # distributed data settings UpperCamelCase_ ={"""smdistributed""": {"""dataparallel""": {"""enabled""": True}}} if self.script != """run_ddp.py""" else None # creates estimator return HuggingFace( entry_point=self.script , source_dir=self.env.test_path , role=self.env.role , image_uri=self.env.image_uri , base_job_name=UpperCamelCase_ , instance_count=UpperCamelCase_ , instance_type=self.instance_type , debugger_hook_config=UpperCamelCase_ , hyperparameters={**self.env.distributed_hyperparameters, "model_name_or_path": self.model_name_or_path} , metric_definitions=self.env.metric_definitions , distribution=UpperCamelCase_ , py_version="py36" , ) def UpperCamelCase__ ( self: int , UpperCamelCase_: List[Any] ): TrainingJobAnalytics(UpperCamelCase_ ).export_csv(f"""{self.env.test_path}/{job_name}_metrics.csv""" ) @parameterized.expand([(2,)] ) def UpperCamelCase__ ( self: Any , UpperCamelCase_: str ): # create estimator UpperCamelCase_ =self.create_estimator(UpperCamelCase_ ) # run training estimator.fit() # result dataframe UpperCamelCase_ =TrainingJobAnalytics(estimator.latest_training_job.name ).dataframe() # extract kpis UpperCamelCase_ =list(result_metrics_df[result_metrics_df.metric_name == "eval_accuracy"]["value"] ) UpperCamelCase_ =list(result_metrics_df[result_metrics_df.metric_name == "eval_loss"]["value"] ) # get train time from SageMaker job, this includes starting, preprocessing, stopping UpperCamelCase_ =( Session().describe_training_job(estimator.latest_training_job.name ).get("TrainingTimeInSeconds" , 99_9999 ) ) # assert kpis assert train_runtime <= self.results["train_runtime"] assert all(t >= self.results["eval_accuracy"] for t in eval_accuracy ) assert all(t <= self.results["eval_loss"] for t in eval_loss ) # dump tests result into json file to share in PR with open(f"""{estimator.latest_training_job.name}.json""" , "w" ) as outfile: json.dump({"train_time": train_runtime, "eval_accuracy": eval_accuracy, "eval_loss": eval_loss} , UpperCamelCase_ )
391
"""simple docstring""" import mpmath # for roots of unity import numpy as np class lowercase__ : def __init__( self , SCREAMING_SNAKE_CASE=None , SCREAMING_SNAKE_CASE=None) -> Tuple: # Input as list _lowerCamelCase : Any = list(poly_a or [0])[:] _lowerCamelCase : Optional[Any] = list(poly_b or [0])[:] # Remove leading zero coefficients while self.polyA[-1] == 0: self.polyA.pop() _lowerCamelCase : int = len(self.polyA) while self.polyB[-1] == 0: self.polyB.pop() _lowerCamelCase : Union[str, Any] = len(self.polyB) # Add 0 to make lengths equal a power of 2 _lowerCamelCase : List[Any] = int( 2 ** np.ceil(np.loga(len(self.polyA) + len(self.polyB) - 1))) while len(self.polyA) < self.c_max_length: self.polyA.append(0) while len(self.polyB) < self.c_max_length: self.polyB.append(0) # A complex root used for the fourier transform _lowerCamelCase : Optional[Any] = complex(mpmath.root(x=1 , n=self.c_max_length , k=1)) # The product _lowerCamelCase : int = self.__multiply() def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE) -> List[str]: _lowerCamelCase : Dict = [[x] for x in self.polyA] if which == """A""" else [[x] for x in self.polyB] # Corner case if len(SCREAMING_SNAKE_CASE) <= 1: return dft[0] # _lowerCamelCase : str = self.c_max_length // 2 while next_ncol > 0: _lowerCamelCase : Dict = [[] for i in range(SCREAMING_SNAKE_CASE)] _lowerCamelCase : Tuple = self.root**next_ncol # First half of next step _lowerCamelCase : int = 1 for j in range(self.c_max_length // (next_ncol * 2)): for i in range(SCREAMING_SNAKE_CASE): new_dft[i].append(dft[i][j] + current_root * dft[i + next_ncol][j]) current_root *= root # Second half of next step _lowerCamelCase : Optional[int] = 1 for j in range(self.c_max_length // (next_ncol * 2)): for i in range(SCREAMING_SNAKE_CASE): new_dft[i].append(dft[i][j] - current_root * dft[i + next_ncol][j]) current_root *= root # Update _lowerCamelCase : Union[str, Any] = new_dft _lowerCamelCase : List[str] = next_ncol // 2 return dft[0] def UpperCamelCase_ ( self) -> str: _lowerCamelCase : Optional[Any] = self.__dft("""A""") _lowerCamelCase : List[str] = self.__dft("""B""") _lowerCamelCase : List[Any] = [[dft_a[i] * dft_b[i] for i in range(self.c_max_length)]] del dft_a del dft_b # Corner Case if len(inverce_c[0]) <= 1: return inverce_c[0] # Inverse DFT _lowerCamelCase : List[str] = 2 while next_ncol <= self.c_max_length: _lowerCamelCase : Any = [[] for i in range(SCREAMING_SNAKE_CASE)] _lowerCamelCase : List[Any] = self.root ** (next_ncol // 2) _lowerCamelCase : str = 1 # First half of next step for j in range(self.c_max_length // next_ncol): for i in range(next_ncol // 2): # Even positions new_inverse_c[i].append( ( inverce_c[i][j] + inverce_c[i][j + self.c_max_length // next_ncol] ) / 2) # Odd positions new_inverse_c[i + next_ncol // 2].append( ( inverce_c[i][j] - inverce_c[i][j + self.c_max_length // next_ncol] ) / (2 * current_root)) current_root *= root # Update _lowerCamelCase : Any = new_inverse_c next_ncol *= 2 # Unpack _lowerCamelCase : Optional[Any] = [round(x[0].real , 8) + round(x[0].imag , 8) * 1j for x in inverce_c] # Remove leading 0's while inverce_c[-1] == 0: inverce_c.pop() return inverce_c def __str__( self) -> Any: _lowerCamelCase : Dict = """A = """ + """ + """.join( F'{coef}*x^{i}' for coef, i in enumerate(self.polyA[: self.len_A])) _lowerCamelCase : List[Any] = """B = """ + """ + """.join( F'{coef}*x^{i}' for coef, i in enumerate(self.polyB[: self.len_B])) _lowerCamelCase : int = """A*B = """ + """ + """.join( F'{coef}*x^{i}' for coef, i in enumerate(self.product)) return F'{a}\n{b}\n{c}' # Unit tests if __name__ == "__main__": import doctest doctest.testmod()
88
0
import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, DDIMScheduler, LDMTextToImagePipeline, UNetaDConditionModel from diffusers.utils.testing_utils import ( enable_full_determinism, load_numpy, nightly, require_torch_gpu, slow, torch_device, ) from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class __a ( A_ , unittest.TestCase ): """simple docstring""" _A : Dict = LDMTextToImagePipeline _A : Optional[int] = TEXT_TO_IMAGE_PARAMS - { "negative_prompt", "negative_prompt_embeds", "cross_attention_kwargs", "prompt_embeds", } _A : Dict = PipelineTesterMixin.required_optional_params - { "num_images_per_prompt", "callback", "callback_steps", } _A : List[str] = TEXT_TO_IMAGE_BATCH_PARAMS _A : Union[str, Any] = False def __A ( self : Dict ) -> List[str]: '''simple docstring''' torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ =UNetaDConditionModel( block_out_channels=(3_2, 6_4) ,layers_per_block=2 ,sample_size=3_2 ,in_channels=4 ,out_channels=4 ,down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") ,up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") ,cross_attention_dim=3_2 ,) SCREAMING_SNAKE_CASE__ =DDIMScheduler( beta_start=0.0_0085 ,beta_end=0.012 ,beta_schedule="""scaled_linear""" ,clip_sample=_UpperCamelCase ,set_alpha_to_one=_UpperCamelCase ,) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ =AutoencoderKL( block_out_channels=(3_2, 6_4) ,in_channels=3 ,out_channels=3 ,down_block_types=("""DownEncoderBlock2D""", """DownEncoderBlock2D""") ,up_block_types=("""UpDecoderBlock2D""", """UpDecoderBlock2D""") ,latent_channels=4 ,) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ =CLIPTextConfig( bos_token_id=0 ,eos_token_id=2 ,hidden_size=3_2 ,intermediate_size=3_7 ,layer_norm_eps=1e-05 ,num_attention_heads=4 ,num_hidden_layers=5 ,pad_token_id=1 ,vocab_size=1_0_0_0 ,) SCREAMING_SNAKE_CASE__ =CLIPTextModel(_UpperCamelCase ) SCREAMING_SNAKE_CASE__ =CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) SCREAMING_SNAKE_CASE__ ={ """unet""": unet, """scheduler""": scheduler, """vqvae""": vae, """bert""": text_encoder, """tokenizer""": tokenizer, } return components def __A ( self : str ,_UpperCamelCase : Tuple ,_UpperCamelCase : Optional[Any]=0 ) -> str: '''simple docstring''' if str(_UpperCamelCase ).startswith("""mps""" ): SCREAMING_SNAKE_CASE__ =torch.manual_seed(_UpperCamelCase ) else: SCREAMING_SNAKE_CASE__ =torch.Generator(device=_UpperCamelCase ).manual_seed(_UpperCamelCase ) SCREAMING_SNAKE_CASE__ ={ """prompt""": """A painting of a squirrel eating a burger""", """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 6.0, """output_type""": """numpy""", } return inputs def __A ( self : Tuple ) -> List[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE__ ="""cpu""" # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE__ =self.get_dummy_components() SCREAMING_SNAKE_CASE__ =LDMTextToImagePipeline(**_UpperCamelCase ) pipe.to(_UpperCamelCase ) pipe.set_progress_bar_config(disable=_UpperCamelCase ) SCREAMING_SNAKE_CASE__ =self.get_dummy_inputs(_UpperCamelCase ) SCREAMING_SNAKE_CASE__ =pipe(**_UpperCamelCase ).images SCREAMING_SNAKE_CASE__ =image[0, -3:, -3:, -1] assert image.shape == (1, 1_6, 1_6, 3) SCREAMING_SNAKE_CASE__ =np.array([0.6101, 0.6156, 0.5622, 0.4895, 0.6661, 0.3804, 0.5748, 0.6136, 0.5014] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 @slow @require_torch_gpu class __a ( unittest.TestCase ): """simple docstring""" def __A ( self : Optional[Any] ) -> str: '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def __A ( self : Any ,_UpperCamelCase : Any ,_UpperCamelCase : Any=torch.floataa ,_UpperCamelCase : Optional[Any]=0 ) -> List[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE__ =torch.manual_seed(_UpperCamelCase ) SCREAMING_SNAKE_CASE__ =np.random.RandomState(_UpperCamelCase ).standard_normal((1, 4, 3_2, 3_2) ) SCREAMING_SNAKE_CASE__ =torch.from_numpy(_UpperCamelCase ).to(device=_UpperCamelCase ,dtype=_UpperCamelCase ) SCREAMING_SNAKE_CASE__ ={ """prompt""": """A painting of a squirrel eating a burger""", """latents""": latents, """generator""": generator, """num_inference_steps""": 3, """guidance_scale""": 6.0, """output_type""": """numpy""", } return inputs def __A ( self : Tuple ) -> Union[str, Any]: '''simple docstring''' SCREAMING_SNAKE_CASE__ =LDMTextToImagePipeline.from_pretrained("""CompVis/ldm-text2im-large-256""" ).to(_UpperCamelCase ) pipe.set_progress_bar_config(disable=_UpperCamelCase ) SCREAMING_SNAKE_CASE__ =self.get_inputs(_UpperCamelCase ) SCREAMING_SNAKE_CASE__ =pipe(**_UpperCamelCase ).images SCREAMING_SNAKE_CASE__ =image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 2_5_6, 2_5_6, 3) SCREAMING_SNAKE_CASE__ =np.array([0.5_1825, 0.5_2850, 0.5_2543, 0.5_4258, 0.5_2304, 0.5_2569, 0.5_4363, 0.5_5276, 0.5_6878] ) SCREAMING_SNAKE_CASE__ =np.abs(expected_slice - image_slice ).max() assert max_diff < 1e-3 @nightly @require_torch_gpu class __a ( unittest.TestCase ): """simple docstring""" def __A ( self : Any ) -> Optional[int]: '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def __A ( self : List[Any] ,_UpperCamelCase : Union[str, Any] ,_UpperCamelCase : Tuple=torch.floataa ,_UpperCamelCase : Union[str, Any]=0 ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE__ =torch.manual_seed(_UpperCamelCase ) SCREAMING_SNAKE_CASE__ =np.random.RandomState(_UpperCamelCase ).standard_normal((1, 4, 3_2, 3_2) ) SCREAMING_SNAKE_CASE__ =torch.from_numpy(_UpperCamelCase ).to(device=_UpperCamelCase ,dtype=_UpperCamelCase ) SCREAMING_SNAKE_CASE__ ={ """prompt""": """A painting of a squirrel eating a burger""", """latents""": latents, """generator""": generator, """num_inference_steps""": 5_0, """guidance_scale""": 6.0, """output_type""": """numpy""", } return inputs def __A ( self : int ) -> Optional[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE__ =LDMTextToImagePipeline.from_pretrained("""CompVis/ldm-text2im-large-256""" ).to(_UpperCamelCase ) pipe.set_progress_bar_config(disable=_UpperCamelCase ) SCREAMING_SNAKE_CASE__ =self.get_inputs(_UpperCamelCase ) SCREAMING_SNAKE_CASE__ =pipe(**_UpperCamelCase ).images[0] SCREAMING_SNAKE_CASE__ =load_numpy( """https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/ldm_text2img/ldm_large_256_ddim.npy""" ) SCREAMING_SNAKE_CASE__ =np.abs(expected_image - image ).max() assert max_diff < 1e-3
151
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) UpperCAmelCase = { """configuration_vision_encoder_decoder""": ["""VisionEncoderDecoderConfig""", """VisionEncoderDecoderOnnxConfig"""] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase = ["""VisionEncoderDecoderModel"""] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase = ["""TFVisionEncoderDecoderModel"""] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase = ["""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 UpperCAmelCase = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
88
0
"""simple docstring""" from transformers import BertTokenizerFast from .custom_tokenization import CustomTokenizer class UpperCAmelCase_ ( A_): lowerCamelCase__ : Optional[int] = CustomTokenizer pass
599
"""simple docstring""" from datetime import datetime import matplotlib.pyplot as plt import torch def _snake_case ( __snake_case : List[str] ): """simple docstring""" for param in module.parameters(): _lowerCamelCase : Optional[Any] = False def _snake_case ( ): """simple docstring""" _lowerCamelCase : Any = """cuda""" if torch.cuda.is_available() else """cpu""" if torch.backends.mps.is_available() and torch.backends.mps.is_built(): _lowerCamelCase : Any = """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 _snake_case ( __snake_case : Union[str, Any] ): """simple docstring""" _lowerCamelCase : int = plt.imshow(__snake_case ) fig.axes.get_xaxis().set_visible(__snake_case ) fig.axes.get_yaxis().set_visible(__snake_case ) plt.show() def _snake_case ( ): """simple docstring""" _lowerCamelCase : Tuple = datetime.now() _lowerCamelCase : Optional[Any] = current_time.strftime("""%H:%M:%S""" ) return timestamp
88
0
from __future__ import annotations from numpy import array, cos, cross, floataa, radians, sin from numpy.typing import NDArray def _A ( lowerCamelCase , lowerCamelCase , lowerCamelCase = False ): if radian_mode: return [magnitude * cos(__snake_case ), magnitude * sin(__snake_case )] return [magnitude * cos(radians(__snake_case ) ), magnitude * sin(radians(__snake_case ) )] def _A ( lowerCamelCase , lowerCamelCase , lowerCamelCase = 10**-1 ): a__ : NDArray[floataa] = cross(__snake_case , __snake_case ) a__ : float = sum(__snake_case ) return abs(__snake_case ) < eps if __name__ == "__main__": # Test to check if it works SCREAMING_SNAKE_CASE__ : List[Any] = array( [ polar_force(718.4, 1_8_0 - 3_0), polar_force(879.54, 4_5), polar_force(1_0_0, -9_0), ] ) SCREAMING_SNAKE_CASE__ : List[Any] = array([[0, 0], [0, 0], [0, 0]]) assert in_static_equilibrium(forces, location) # Problem 1 in image_data/2D_problems.jpg SCREAMING_SNAKE_CASE__ : int = array( [ polar_force(3_0 * 9.81, 1_5), polar_force(2_1_5, 1_8_0 - 4_5), polar_force(2_6_4, 9_0 - 3_0), ] ) SCREAMING_SNAKE_CASE__ : Tuple = array([[0, 0], [0, 0], [0, 0]]) assert in_static_equilibrium(forces, location) # Problem in image_data/2D_problems_1.jpg SCREAMING_SNAKE_CASE__ : List[str] = array([[0, -2_0_0_0], [0, -1_2_0_0], [0, 1_5_6_0_0], [0, -1_2_4_0_0]]) SCREAMING_SNAKE_CASE__ : str = array([[0, 0], [6, 0], [1_0, 0], [1_2, 0]]) assert in_static_equilibrium(forces, location) import doctest doctest.testmod()
112
"""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 UpperCAmelCase = 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 lowercase__ : __UpperCAmelCase = field( default='''cifar10''' ,metadata={'''help''': '''Name of a dataset from the datasets package'''} ) __UpperCAmelCase = field( default=A_ ,metadata={'''help''': '''The configuration name of the dataset to use (via the datasets library).'''} ) __UpperCAmelCase = field( default=A_ ,metadata={'''help''': '''The column name of the images in the files.'''} ) __UpperCAmelCase = field(default=A_ ,metadata={'''help''': '''A folder containing the training data.'''} ) __UpperCAmelCase = field(default=A_ ,metadata={'''help''': '''A folder containing the validation data.'''} ) __UpperCAmelCase = field( default=0.1_5 ,metadata={'''help''': '''Percent to split off of train for validation.'''} ) __UpperCAmelCase = field( default=A_ ,metadata={ '''help''': ( '''For debugging purposes or quicker training, truncate the number of training examples to this ''' '''value if set.''' ) } ,) __UpperCAmelCase = field( default=A_ ,metadata={ '''help''': ( '''For debugging purposes or quicker training, truncate the number of evaluation examples to this ''' '''value if set.''' ) } ,) def UpperCamelCase_ ( self) -> Any: _lowerCamelCase : Any = {} if self.train_dir is not None: _lowerCamelCase : int = self.train_dir if self.validation_dir is not None: _lowerCamelCase : Tuple = self.validation_dir _lowerCamelCase : Optional[int] = data_files if data_files else None @dataclass class lowercase__ : __UpperCAmelCase = field( default=A_ ,metadata={ '''help''': ( '''The model checkpoint for weights initialization.Don\'t set if you want to train a model from scratch.''' ) } ,) __UpperCAmelCase = field( default=A_ ,metadata={'''help''': '''Pretrained config name or path if not the same as model_name_or_path'''} ) __UpperCAmelCase = field( default=A_ ,metadata={ '''help''': ( '''Override some existing default config settings when a model is trained from scratch. Example: ''' '''n_embd=10,resid_pdrop=0.2,scale_attn_weights=false,summary_type=cls_index''' ) } ,) __UpperCAmelCase = field( default=A_ ,metadata={'''help''': '''Where do you want to store the pretrained models downloaded from s3'''} ) __UpperCAmelCase = field( default='''main''' ,metadata={'''help''': '''The specific model version to use (can be a branch name, tag name or commit id).'''} ,) __UpperCAmelCase = field(default=A_ ,metadata={'''help''': '''Name or path of preprocessor config.'''} ) __UpperCAmelCase = field( default=A_ ,metadata={ '''help''': ( '''Will use the token generated when running `huggingface-cli login` (necessary to use this script ''' '''with private models).''' ) } ,) __UpperCAmelCase = field( default=0.7_5 ,metadata={'''help''': '''The ratio of the number of masked tokens in the input sequence.'''} ) __UpperCAmelCase = field( default=A_ ,metadata={'''help''': '''Whether or not to train with normalized pixel values as target.'''} ) @dataclass class lowercase__ ( A_ ): __UpperCAmelCase = field( default=1e-3 ,metadata={'''help''': '''Base learning rate: absolute_lr = base_lr * total_batch_size / 256.'''} ) def _snake_case ( __snake_case : Optional[Any] ): """simple docstring""" _lowerCamelCase : int = torch.stack([example["""pixel_values"""] for example in examples] ) return {"pixel_values": pixel_values} def _snake_case ( ): """simple docstring""" _lowerCamelCase : Tuple = 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. _lowerCamelCase , _lowerCamelCase , _lowerCamelCase : Union[str, Any] = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: _lowerCamelCase , _lowerCamelCase , _lowerCamelCase : Dict = 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""" , __snake_case , __snake_case ) # Setup logging logging.basicConfig( format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""" , datefmt="""%m/%d/%Y %H:%M:%S""" , handlers=[logging.StreamHandler(sys.stdout )] , ) if training_args.should_log: # The default of training_args.log_level is passive, so we set log level at info here to have that default. transformers.utils.logging.set_verbosity_info() _lowerCamelCase : Union[str, Any] = training_args.get_process_log_level() logger.setLevel(__snake_case ) transformers.utils.logging.set_verbosity(__snake_case ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Log on each process the small summary: logger.warning( F'Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}' + F'distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}' ) logger.info(F'Training/evaluation parameters {training_args}' ) # Detecting last checkpoint. _lowerCamelCase : List[Any] = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: _lowerCamelCase : Optional[int] = 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. _lowerCamelCase : Optional[Any] = 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. _lowerCamelCase : Tuple = None if """validation""" in ds.keys() else data_args.train_val_split if isinstance(data_args.train_val_split , __snake_case ) and data_args.train_val_split > 0.0: _lowerCamelCase : List[str] = ds["""train"""].train_test_split(data_args.train_val_split ) _lowerCamelCase : Union[str, Any] = split["""train"""] _lowerCamelCase : Optional[int] = 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. _lowerCamelCase : 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: _lowerCamelCase : Dict = ViTMAEConfig.from_pretrained(model_args.config_name , **__snake_case ) elif model_args.model_name_or_path: _lowerCamelCase : Union[str, Any] = ViTMAEConfig.from_pretrained(model_args.model_name_or_path , **__snake_case ) else: _lowerCamelCase : Optional[Any] = 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: _lowerCamelCase : str = ViTImageProcessor.from_pretrained(model_args.image_processor_name , **__snake_case ) elif model_args.model_name_or_path: _lowerCamelCase : Dict = ViTImageProcessor.from_pretrained(model_args.model_name_or_path , **__snake_case ) else: _lowerCamelCase : Union[str, Any] = ViTImageProcessor() # create model if model_args.model_name_or_path: _lowerCamelCase : List[Any] = ViTMAEForPreTraining.from_pretrained( model_args.model_name_or_path , from_tf=bool(""".ckpt""" in model_args.model_name_or_path ) , config=__snake_case , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) else: logger.info("""Training new model from scratch""" ) _lowerCamelCase : Union[str, Any] = ViTMAEForPreTraining(__snake_case ) if training_args.do_train: _lowerCamelCase : List[Any] = ds["""train"""].column_names else: _lowerCamelCase : Union[str, Any] = ds["""validation"""].column_names if data_args.image_column_name is not None: _lowerCamelCase : str = data_args.image_column_name elif "image" in column_names: _lowerCamelCase : Optional[Any] = """image""" elif "img" in column_names: _lowerCamelCase : List[Any] = """img""" else: _lowerCamelCase : str = 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: _lowerCamelCase : Dict = image_processor.size["""shortest_edge"""] else: _lowerCamelCase : List[Any] = (image_processor.size["""height"""], image_processor.size["""width"""]) _lowerCamelCase : Tuple = Compose( [ Lambda(lambda __snake_case : img.convert("""RGB""" ) if img.mode != "RGB" else img ), RandomResizedCrop(__snake_case , scale=(0.2, 1.0) , interpolation=InterpolationMode.BICUBIC ), RandomHorizontalFlip(), ToTensor(), Normalize(mean=image_processor.image_mean , std=image_processor.image_std ), ] ) def preprocess_images(__snake_case : Optional[Any] ): _lowerCamelCase : Dict = [transforms(__snake_case ) 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: _lowerCamelCase : int = ds["""train"""].shuffle(seed=training_args.seed ).select(range(data_args.max_train_samples ) ) # Set the training transforms ds["train"].set_transform(__snake_case ) 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: _lowerCamelCase : Union[str, Any] = ( ds["""validation"""].shuffle(seed=training_args.seed ).select(range(data_args.max_eval_samples ) ) ) # Set the validation transforms ds["validation"].set_transform(__snake_case ) # Compute absolute learning rate _lowerCamelCase : Optional[Any] = ( training_args.train_batch_size * training_args.gradient_accumulation_steps * training_args.world_size ) if training_args.base_learning_rate is not None: _lowerCamelCase : Tuple = training_args.base_learning_rate * total_train_batch_size / 256 # Initialize our trainer _lowerCamelCase : Optional[Any] = Trainer( model=__snake_case , args=__snake_case , train_dataset=ds["""train"""] if training_args.do_train else None , eval_dataset=ds["""validation"""] if training_args.do_eval else None , tokenizer=__snake_case , data_collator=__snake_case , ) # Training if training_args.do_train: _lowerCamelCase : Any = None if training_args.resume_from_checkpoint is not None: _lowerCamelCase : List[Any] = training_args.resume_from_checkpoint elif last_checkpoint is not None: _lowerCamelCase : Union[str, Any] = last_checkpoint _lowerCamelCase : Optional[Any] = trainer.train(resume_from_checkpoint=__snake_case ) trainer.save_model() trainer.log_metrics("""train""" , train_result.metrics ) trainer.save_metrics("""train""" , train_result.metrics ) trainer.save_state() # Evaluation if training_args.do_eval: _lowerCamelCase : int = trainer.evaluate() trainer.log_metrics("""eval""" , __snake_case ) trainer.save_metrics("""eval""" , __snake_case ) # Write model card and (optionally) push to hub _lowerCamelCase : Optional[Any] = { """tasks""": """masked-auto-encoding""", """dataset""": data_args.dataset_name, """tags""": ["""masked-auto-encoding"""], } if training_args.push_to_hub: trainer.push_to_hub(**__snake_case ) else: trainer.create_model_card(**__snake_case ) def _snake_case ( __snake_case : Dict ): """simple docstring""" main() if __name__ == "__main__": main()
88
0
import argparse import json from collections import OrderedDict from functools import partial from pathlib import Path import timm import torch from huggingface_hub import hf_hub_download from transformers import LevitConfig, LevitForImageClassificationWithTeacher, LevitImageProcessor from transformers.utils import logging logging.set_verbosity_info() lowerCamelCase__ = logging.get_logger() def UpperCamelCase ( snake_case__ : int ,snake_case__ : str ,snake_case__ : LevitConfig ,snake_case__ : Path ,snake_case__ : bool = True ): '''simple docstring''' print(f'''Converting {name}...''' ) with torch.no_grad(): if hidden_sizes == 128: if name[-1] == "S": __snake_case :List[str] = timm.create_model("""levit_128s""" ,pretrained=__snake_case ) else: __snake_case :Any = timm.create_model("""levit_128""" ,pretrained=__snake_case ) if hidden_sizes == 192: __snake_case :str = timm.create_model("""levit_192""" ,pretrained=__snake_case ) if hidden_sizes == 256: __snake_case :Tuple = timm.create_model("""levit_256""" ,pretrained=__snake_case ) if hidden_sizes == 384: __snake_case :List[Any] = timm.create_model("""levit_384""" ,pretrained=__snake_case ) from_model.eval() __snake_case :List[Any] = LevitForImageClassificationWithTeacher(__snake_case ).eval() __snake_case :Union[str, Any] = OrderedDict() __snake_case :Union[str, Any] = from_model.state_dict() __snake_case :List[Any] = list(from_model.state_dict().keys() ) __snake_case :Any = list(our_model.state_dict().keys() ) print(len(__snake_case ) ,len(__snake_case ) ) for i in range(len(__snake_case ) ): __snake_case :Optional[int] = weights[og_keys[i]] our_model.load_state_dict(__snake_case ) __snake_case :Dict = torch.randn((2, 3, 224, 224) ) __snake_case :Optional[int] = from_model(__snake_case ) __snake_case :Optional[int] = our_model(__snake_case ).logits assert torch.allclose(__snake_case ,__snake_case ), "The model logits don't match the original one." __snake_case :str = name print(__snake_case ) if push_to_hub: our_model.save_pretrained(save_directory / checkpoint_name ) __snake_case :Optional[int] = LevitImageProcessor() image_processor.save_pretrained(save_directory / checkpoint_name ) print(f'''Pushed {checkpoint_name}''' ) def UpperCamelCase ( snake_case__ : Path ,snake_case__ : str = None ,snake_case__ : bool = True ): '''simple docstring''' __snake_case :str = """imagenet-1k-id2label.json""" __snake_case :Optional[Any] = 1000 __snake_case :Any = (1, num_labels) __snake_case :int = """huggingface/label-files""" __snake_case :Union[str, Any] = num_labels __snake_case :int = json.load(open(hf_hub_download(__snake_case ,__snake_case ,repo_type="""dataset""" ) ,"""r""" ) ) __snake_case :List[str] = {int(__snake_case ): v for k, v in idalabel.items()} __snake_case :str = idalabel __snake_case :Optional[int] = {v: k for k, v in idalabel.items()} __snake_case :int = partial(__snake_case ,num_labels=__snake_case ,idalabel=__snake_case ,labelaid=__snake_case ) __snake_case :Optional[Any] = { """levit-128S""": 128, """levit-128""": 128, """levit-192""": 192, """levit-256""": 256, """levit-384""": 384, } __snake_case :Optional[Any] = { """levit-128S""": ImageNetPreTrainedConfig( hidden_sizes=[128, 256, 384] ,num_attention_heads=[4, 6, 8] ,depths=[2, 3, 4] ,key_dim=[16, 16, 16] ,drop_path_rate=0 ,), """levit-128""": ImageNetPreTrainedConfig( hidden_sizes=[128, 256, 384] ,num_attention_heads=[4, 8, 12] ,depths=[4, 4, 4] ,key_dim=[16, 16, 16] ,drop_path_rate=0 ,), """levit-192""": ImageNetPreTrainedConfig( hidden_sizes=[192, 288, 384] ,num_attention_heads=[3, 5, 6] ,depths=[4, 4, 4] ,key_dim=[32, 32, 32] ,drop_path_rate=0 ,), """levit-256""": ImageNetPreTrainedConfig( hidden_sizes=[256, 384, 512] ,num_attention_heads=[4, 6, 8] ,depths=[4, 4, 4] ,key_dim=[32, 32, 32] ,drop_path_rate=0 ,), """levit-384""": ImageNetPreTrainedConfig( hidden_sizes=[384, 512, 768] ,num_attention_heads=[6, 9, 12] ,depths=[4, 4, 4] ,key_dim=[32, 32, 32] ,drop_path_rate=0.1 ,), } if model_name: convert_weight_and_push( names_to_hidden_sizes[model_name] ,__snake_case ,names_to_config[model_name] ,__snake_case ,__snake_case ) else: for model_name, config in names_to_config.items(): convert_weight_and_push(names_to_hidden_sizes[model_name] ,__snake_case ,__snake_case ,__snake_case ,__snake_case ) return config, expected_shape if __name__ == "__main__": lowerCamelCase__ = 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 Levit* architecture,""", ) parser.add_argument( """--pytorch_dump_folder_path""", default="""levit-dump-folder/""", type=Path, required=False, help="""Path to the output PyTorch model directory.""", ) parser.add_argument("""--push_to_hub""", action="""store_true""", help="""Push model and image processor to the hub""") parser.add_argument( """--no-push_to_hub""", dest="""push_to_hub""", action="""store_false""", help="""Do not push model and image processor to the hub""", ) lowerCamelCase__ = parser.parse_args() lowerCamelCase__ = 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)
455
"""simple docstring""" import numpy as np def _snake_case ( __snake_case : np.ndarray ): """simple docstring""" return 1 / (1 + np.exp(-vector )) def _snake_case ( __snake_case : np.ndarray ): """simple docstring""" return vector * sigmoid(__snake_case ) if __name__ == "__main__": import doctest doctest.testmod()
88
0
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging lowercase : Union[str, Any] = logging.get_logger(__name__) lowercase : str = { """facebook/xlm-roberta-xl""": """https://huggingface.co/facebook/xlm-roberta-xl/resolve/main/config.json""", """facebook/xlm-roberta-xxl""": """https://huggingface.co/facebook/xlm-roberta-xxl/resolve/main/config.json""", # See all XLM-RoBERTa-XL models at https://huggingface.co/models?filter=xlm-roberta-xl } class A__ ( A_ ): """simple docstring""" __A : Any = '''xlm-roberta-xl''' def __init__( self , lowercase=25_0880 , lowercase=2560 , lowercase=36 , lowercase=32 , lowercase=1_0240 , lowercase="gelu" , lowercase=0.1 , lowercase=0.1 , lowercase=514 , lowercase=1 , lowercase=0.02 , lowercase=1e-05 , lowercase=1 , lowercase=0 , lowercase=2 , lowercase="absolute" , lowercase=True , lowercase=None , **lowercase , ) -> Optional[int]: '''simple docstring''' super().__init__(pad_token_id=lowercase , bos_token_id=lowercase , eos_token_id=lowercase , **lowercase) a__ : List[str] = vocab_size a__ : List[Any] = hidden_size a__ : Any = num_hidden_layers a__ : Any = num_attention_heads a__ : Optional[int] = hidden_act a__ : List[Any] = intermediate_size a__ : Dict = hidden_dropout_prob a__ : Tuple = attention_probs_dropout_prob a__ : List[Any] = max_position_embeddings a__ : int = type_vocab_size a__ : Tuple = initializer_range a__ : Union[str, Any] = layer_norm_eps a__ : Optional[int] = position_embedding_type a__ : Optional[int] = use_cache a__ : List[str] = classifier_dropout class A__ ( A_ ): """simple docstring""" @property def __lowercase ( self) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' if self.task == "multiple-choice": a__ : int = {0: """batch""", 1: """choice""", 2: """sequence"""} else: a__ : Optional[int] = {0: """batch""", 1: """sequence"""} return OrderedDict( [ ('input_ids', dynamic_axis), ('attention_mask', dynamic_axis), ])
302
"""simple docstring""" from transformers import HfArgumentParser, TensorFlowBenchmark, TensorFlowBenchmarkArguments def _snake_case ( ): """simple docstring""" _lowerCamelCase : Any = HfArgumentParser(__snake_case ) _lowerCamelCase : int = parser.parse_args_into_dataclasses()[0] _lowerCamelCase : Dict = TensorFlowBenchmark(args=__snake_case ) try: _lowerCamelCase : Optional[int] = parser.parse_args_into_dataclasses()[0] except ValueError as e: _lowerCamelCase : Union[str, Any] = """Arg --no_{0} is no longer used, please use --no-{0} instead.""" _lowerCamelCase : List[str] = """ """.join(str(__snake_case ).split(""" """ )[:-1] ) _lowerCamelCase : Dict = """""" _lowerCamelCase : List[Any] = eval(str(__snake_case ).split(""" """ )[-1] ) _lowerCamelCase : Tuple = [] for arg in depreciated_args: # arg[2:] removes '--' if arg[2:] in TensorFlowBenchmark.deprecated_args: # arg[5:] removes '--no_' full_error_msg += arg_error_msg.format(arg[5:] ) else: wrong_args.append(__snake_case ) if len(__snake_case ) > 0: _lowerCamelCase : Tuple = full_error_msg + begin_error_msg + str(__snake_case ) raise ValueError(__snake_case ) benchmark.run() if __name__ == "__main__": main()
88
0
from argparse import ArgumentParser from .env import EnvironmentCommand def UpperCamelCase ( ) -> Optional[Any]: UpperCamelCase : Optional[Any] = ArgumentParser('Diffusers CLI tool' , usage='diffusers-cli <command> [<args>]' ) UpperCamelCase : Dict = parser.add_subparsers(help='diffusers-cli command helpers' ) # Register commands EnvironmentCommand.register_subcommand(__snake_case ) # Let's go UpperCamelCase : Any = parser.parse_args() if not hasattr(__snake_case , 'func' ): parser.print_help() exit(1 ) # Run UpperCamelCase : List[str] = args.func(__snake_case ) service.run() if __name__ == "__main__": main()
40
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging UpperCAmelCase = logging.get_logger(__name__) UpperCAmelCase = { """kssteven/ibert-roberta-base""": """https://huggingface.co/kssteven/ibert-roberta-base/resolve/main/config.json""", """kssteven/ibert-roberta-large""": """https://huggingface.co/kssteven/ibert-roberta-large/resolve/main/config.json""", """kssteven/ibert-roberta-large-mnli""": ( """https://huggingface.co/kssteven/ibert-roberta-large-mnli/resolve/main/config.json""" ), } class lowercase__ ( A_ ): __UpperCAmelCase = '''ibert''' def __init__( self , SCREAMING_SNAKE_CASE=3_0522 , SCREAMING_SNAKE_CASE=768 , SCREAMING_SNAKE_CASE=12 , SCREAMING_SNAKE_CASE=12 , SCREAMING_SNAKE_CASE=3072 , SCREAMING_SNAKE_CASE="gelu" , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=512 , SCREAMING_SNAKE_CASE=2 , SCREAMING_SNAKE_CASE=0.02 , SCREAMING_SNAKE_CASE=1e-1_2 , SCREAMING_SNAKE_CASE=1 , SCREAMING_SNAKE_CASE=0 , SCREAMING_SNAKE_CASE=2 , SCREAMING_SNAKE_CASE="absolute" , SCREAMING_SNAKE_CASE=False , SCREAMING_SNAKE_CASE="none" , **SCREAMING_SNAKE_CASE , ) -> Any: super().__init__(pad_token_id=SCREAMING_SNAKE_CASE , bos_token_id=SCREAMING_SNAKE_CASE , eos_token_id=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE) _lowerCamelCase : Optional[int] = vocab_size _lowerCamelCase : Dict = hidden_size _lowerCamelCase : List[str] = num_hidden_layers _lowerCamelCase : int = num_attention_heads _lowerCamelCase : Tuple = hidden_act _lowerCamelCase : str = intermediate_size _lowerCamelCase : Union[str, Any] = hidden_dropout_prob _lowerCamelCase : Tuple = attention_probs_dropout_prob _lowerCamelCase : Any = max_position_embeddings _lowerCamelCase : Dict = type_vocab_size _lowerCamelCase : List[Any] = initializer_range _lowerCamelCase : Dict = layer_norm_eps _lowerCamelCase : List[Any] = position_embedding_type _lowerCamelCase : Any = quant_mode _lowerCamelCase : List[str] = force_dequant class lowercase__ ( A_ ): @property def UpperCamelCase_ ( self) -> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": _lowerCamelCase : Dict = {0: """batch""", 1: """choice""", 2: """sequence"""} else: _lowerCamelCase : Optional[int] = {0: """batch""", 1: """sequence"""} return OrderedDict( [ ("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ])
88
0
'''simple docstring''' import gc import unittest from transformers import MODEL_FOR_MASKED_LM_MAPPING, TF_MODEL_FOR_MASKED_LM_MAPPING, FillMaskPipeline, pipeline from transformers.pipelines import PipelineException from transformers.testing_utils import ( is_pipeline_test, is_torch_available, nested_simplify, require_tf, require_torch, require_torch_gpu, slow, ) from .test_pipelines_common import ANY @is_pipeline_test class A ( unittest.TestCase ): __magic_name__ = MODEL_FOR_MASKED_LM_MAPPING __magic_name__ = TF_MODEL_FOR_MASKED_LM_MAPPING def __lowerCAmelCase ( self ) -> Tuple: """simple docstring""" super().tearDown() # clean-up as much as possible GPU memory occupied by PyTorch gc.collect() if is_torch_available(): import torch torch.cuda.empty_cache() @require_tf def __lowerCAmelCase ( self ) -> Union[str, Any]: """simple docstring""" A : int = pipeline(task='''fill-mask''' , model='''sshleifer/tiny-distilroberta-base''' , top_k=2 , framework='''tf''' ) A : List[Any] = unmasker('''My name is <mask>''' ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE , decimals=6 ) , [ {'''sequence''': '''My name is grouped''', '''score''': 2.1e-05, '''token''': 38015, '''token_str''': ''' grouped'''}, {'''sequence''': '''My name is accuser''', '''score''': 2.1e-05, '''token''': 25506, '''token_str''': ''' accuser'''}, ] , ) A : Union[str, Any] = unmasker('''The largest city in France is <mask>''' ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE , decimals=6 ) , [ { '''sequence''': '''The largest city in France is grouped''', '''score''': 2.1e-05, '''token''': 38015, '''token_str''': ''' grouped''', }, { '''sequence''': '''The largest city in France is accuser''', '''score''': 2.1e-05, '''token''': 25506, '''token_str''': ''' accuser''', }, ] , ) A : Optional[int] = unmasker('''My name is <mask>''' , targets=[''' Patrick''', ''' Clara''', ''' Teven'''] , top_k=3 ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE , decimals=6 ) , [ {'''sequence''': '''My name is Clara''', '''score''': 2e-05, '''token''': 13606, '''token_str''': ''' Clara'''}, {'''sequence''': '''My name is Patrick''', '''score''': 2e-05, '''token''': 3499, '''token_str''': ''' Patrick'''}, {'''sequence''': '''My name is Te''', '''score''': 1.9e-05, '''token''': 2941, '''token_str''': ''' Te'''}, ] , ) @require_torch def __lowerCAmelCase ( self ) -> Optional[Any]: """simple docstring""" A : Any = pipeline(task='''fill-mask''' , model='''sshleifer/tiny-distilroberta-base''' , top_k=2 , framework='''pt''' ) A : Dict = unmasker('''My name is <mask>''' ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE , decimals=6 ) , [ {'''sequence''': '''My name is Maul''', '''score''': 2.2e-05, '''token''': 35676, '''token_str''': ''' Maul'''}, {'''sequence''': '''My name isELS''', '''score''': 2.2e-05, '''token''': 16416, '''token_str''': '''ELS'''}, ] , ) A : Tuple = unmasker('''The largest city in France is <mask>''' ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE , decimals=6 ) , [ { '''sequence''': '''The largest city in France is Maul''', '''score''': 2.2e-05, '''token''': 35676, '''token_str''': ''' Maul''', }, {'''sequence''': '''The largest city in France isELS''', '''score''': 2.2e-05, '''token''': 16416, '''token_str''': '''ELS'''}, ] , ) A : Dict = unmasker('''My name is <mask>''' , targets=[''' Patrick''', ''' Clara''', ''' Teven'''] , top_k=3 ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE , decimals=6 ) , [ {'''sequence''': '''My name is Patrick''', '''score''': 2.1e-05, '''token''': 3499, '''token_str''': ''' Patrick'''}, {'''sequence''': '''My name is Te''', '''score''': 2e-05, '''token''': 2941, '''token_str''': ''' Te'''}, {'''sequence''': '''My name is Clara''', '''score''': 2e-05, '''token''': 13606, '''token_str''': ''' Clara'''}, ] , ) A : Union[str, Any] = unmasker('''My name is <mask> <mask>''' , top_k=2 ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE , decimals=6 ) , [ [ { '''score''': 2.2e-05, '''token''': 35676, '''token_str''': ''' Maul''', '''sequence''': '''<s>My name is Maul<mask></s>''', }, {'''score''': 2.2e-05, '''token''': 16416, '''token_str''': '''ELS''', '''sequence''': '''<s>My name isELS<mask></s>'''}, ], [ { '''score''': 2.2e-05, '''token''': 35676, '''token_str''': ''' Maul''', '''sequence''': '''<s>My name is<mask> Maul</s>''', }, {'''score''': 2.2e-05, '''token''': 16416, '''token_str''': '''ELS''', '''sequence''': '''<s>My name is<mask>ELS</s>'''}, ], ] , ) @require_torch_gpu def __lowerCAmelCase ( self ) -> str: """simple docstring""" A : Optional[int] = pipeline('''fill-mask''' , model='''hf-internal-testing/tiny-random-distilbert''' , device=0 , framework='''pt''' ) # convert model to fp16 pipe.model.half() A : List[str] = pipe('''Paris is the [MASK] of France.''' ) # We actually don't care about the result, we just want to make sure # it works, meaning the float16 tensor got casted back to float32 # for postprocessing. self.assertIsInstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) @slow @require_torch def __lowerCAmelCase ( self ) -> Optional[int]: """simple docstring""" A : Any = pipeline(task='''fill-mask''' , model='''distilroberta-base''' , top_k=2 , framework='''pt''' ) self.run_large_test(SCREAMING_SNAKE_CASE ) @slow @require_tf def __lowerCAmelCase ( self ) -> Dict: """simple docstring""" A : Tuple = pipeline(task='''fill-mask''' , model='''distilroberta-base''' , top_k=2 , framework='''tf''' ) self.run_large_test(SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE ) -> Tuple: """simple docstring""" A : Optional[int] = unmasker('''My name is <mask>''' ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE ) , [ {'''sequence''': '''My name is John''', '''score''': 0.008, '''token''': 610, '''token_str''': ''' John'''}, {'''sequence''': '''My name is Chris''', '''score''': 0.007, '''token''': 1573, '''token_str''': ''' Chris'''}, ] , ) A : Tuple = unmasker('''The largest city in France is <mask>''' ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE ) , [ { '''sequence''': '''The largest city in France is Paris''', '''score''': 0.251, '''token''': 2201, '''token_str''': ''' Paris''', }, { '''sequence''': '''The largest city in France is Lyon''', '''score''': 0.214, '''token''': 12790, '''token_str''': ''' Lyon''', }, ] , ) A : int = unmasker('''My name is <mask>''' , targets=[''' Patrick''', ''' Clara''', ''' Teven'''] , top_k=3 ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE ) , [ {'''sequence''': '''My name is Patrick''', '''score''': 0.005, '''token''': 3499, '''token_str''': ''' Patrick'''}, {'''sequence''': '''My name is Clara''', '''score''': 0.000, '''token''': 13606, '''token_str''': ''' Clara'''}, {'''sequence''': '''My name is Te''', '''score''': 0.000, '''token''': 2941, '''token_str''': ''' Te'''}, ] , ) @require_torch def __lowerCAmelCase ( self ) -> List[str]: """simple docstring""" A : int = pipeline(task='''fill-mask''' , model='''sshleifer/tiny-distilroberta-base''' , framework='''pt''' ) A : int = None A : int = None self.run_pipeline_test(SCREAMING_SNAKE_CASE , [] ) @require_tf def __lowerCAmelCase ( self ) -> int: """simple docstring""" A : Union[str, Any] = pipeline(task='''fill-mask''' , model='''sshleifer/tiny-distilroberta-base''' , framework='''tf''' ) A : Dict = None A : int = None self.run_pipeline_test(SCREAMING_SNAKE_CASE , [] ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Optional[int]: """simple docstring""" if tokenizer is None or tokenizer.mask_token_id is None: self.skipTest('''The provided tokenizer has no mask token, (probably reformer or wav2vec2)''' ) A : List[Any] = FillMaskPipeline(model=SCREAMING_SNAKE_CASE , tokenizer=SCREAMING_SNAKE_CASE ) A : List[str] = [ F'This is another {tokenizer.mask_token} test', ] return fill_masker, examples def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Any: """simple docstring""" A : Dict = fill_masker.tokenizer A : Union[str, Any] = fill_masker.model A : int = fill_masker( F'This is a {tokenizer.mask_token}' , ) self.assertEqual( SCREAMING_SNAKE_CASE , [ {'''sequence''': ANY(SCREAMING_SNAKE_CASE ), '''score''': ANY(SCREAMING_SNAKE_CASE ), '''token''': ANY(SCREAMING_SNAKE_CASE ), '''token_str''': ANY(SCREAMING_SNAKE_CASE )}, {'''sequence''': ANY(SCREAMING_SNAKE_CASE ), '''score''': ANY(SCREAMING_SNAKE_CASE ), '''token''': ANY(SCREAMING_SNAKE_CASE ), '''token_str''': ANY(SCREAMING_SNAKE_CASE )}, {'''sequence''': ANY(SCREAMING_SNAKE_CASE ), '''score''': ANY(SCREAMING_SNAKE_CASE ), '''token''': ANY(SCREAMING_SNAKE_CASE ), '''token_str''': ANY(SCREAMING_SNAKE_CASE )}, {'''sequence''': ANY(SCREAMING_SNAKE_CASE ), '''score''': ANY(SCREAMING_SNAKE_CASE ), '''token''': ANY(SCREAMING_SNAKE_CASE ), '''token_str''': ANY(SCREAMING_SNAKE_CASE )}, {'''sequence''': ANY(SCREAMING_SNAKE_CASE ), '''score''': ANY(SCREAMING_SNAKE_CASE ), '''token''': ANY(SCREAMING_SNAKE_CASE ), '''token_str''': ANY(SCREAMING_SNAKE_CASE )}, ] , ) A : Optional[int] = fill_masker([F'This is a {tokenizer.mask_token}'] ) self.assertEqual( SCREAMING_SNAKE_CASE , [ {'''sequence''': ANY(SCREAMING_SNAKE_CASE ), '''score''': ANY(SCREAMING_SNAKE_CASE ), '''token''': ANY(SCREAMING_SNAKE_CASE ), '''token_str''': ANY(SCREAMING_SNAKE_CASE )}, {'''sequence''': ANY(SCREAMING_SNAKE_CASE ), '''score''': ANY(SCREAMING_SNAKE_CASE ), '''token''': ANY(SCREAMING_SNAKE_CASE ), '''token_str''': ANY(SCREAMING_SNAKE_CASE )}, {'''sequence''': ANY(SCREAMING_SNAKE_CASE ), '''score''': ANY(SCREAMING_SNAKE_CASE ), '''token''': ANY(SCREAMING_SNAKE_CASE ), '''token_str''': ANY(SCREAMING_SNAKE_CASE )}, {'''sequence''': ANY(SCREAMING_SNAKE_CASE ), '''score''': ANY(SCREAMING_SNAKE_CASE ), '''token''': ANY(SCREAMING_SNAKE_CASE ), '''token_str''': ANY(SCREAMING_SNAKE_CASE )}, {'''sequence''': ANY(SCREAMING_SNAKE_CASE ), '''score''': ANY(SCREAMING_SNAKE_CASE ), '''token''': ANY(SCREAMING_SNAKE_CASE ), '''token_str''': ANY(SCREAMING_SNAKE_CASE )}, ] , ) A : Optional[int] = fill_masker([F'This is a {tokenizer.mask_token}', F'Another {tokenizer.mask_token} great test.'] ) self.assertEqual( SCREAMING_SNAKE_CASE , [ [ {'''sequence''': ANY(SCREAMING_SNAKE_CASE ), '''score''': ANY(SCREAMING_SNAKE_CASE ), '''token''': ANY(SCREAMING_SNAKE_CASE ), '''token_str''': ANY(SCREAMING_SNAKE_CASE )}, {'''sequence''': ANY(SCREAMING_SNAKE_CASE ), '''score''': ANY(SCREAMING_SNAKE_CASE ), '''token''': ANY(SCREAMING_SNAKE_CASE ), '''token_str''': ANY(SCREAMING_SNAKE_CASE )}, {'''sequence''': ANY(SCREAMING_SNAKE_CASE ), '''score''': ANY(SCREAMING_SNAKE_CASE ), '''token''': ANY(SCREAMING_SNAKE_CASE ), '''token_str''': ANY(SCREAMING_SNAKE_CASE )}, {'''sequence''': ANY(SCREAMING_SNAKE_CASE ), '''score''': ANY(SCREAMING_SNAKE_CASE ), '''token''': ANY(SCREAMING_SNAKE_CASE ), '''token_str''': ANY(SCREAMING_SNAKE_CASE )}, {'''sequence''': ANY(SCREAMING_SNAKE_CASE ), '''score''': ANY(SCREAMING_SNAKE_CASE ), '''token''': ANY(SCREAMING_SNAKE_CASE ), '''token_str''': ANY(SCREAMING_SNAKE_CASE )}, ], [ {'''sequence''': ANY(SCREAMING_SNAKE_CASE ), '''score''': ANY(SCREAMING_SNAKE_CASE ), '''token''': ANY(SCREAMING_SNAKE_CASE ), '''token_str''': ANY(SCREAMING_SNAKE_CASE )}, {'''sequence''': ANY(SCREAMING_SNAKE_CASE ), '''score''': ANY(SCREAMING_SNAKE_CASE ), '''token''': ANY(SCREAMING_SNAKE_CASE ), '''token_str''': ANY(SCREAMING_SNAKE_CASE )}, {'''sequence''': ANY(SCREAMING_SNAKE_CASE ), '''score''': ANY(SCREAMING_SNAKE_CASE ), '''token''': ANY(SCREAMING_SNAKE_CASE ), '''token_str''': ANY(SCREAMING_SNAKE_CASE )}, {'''sequence''': ANY(SCREAMING_SNAKE_CASE ), '''score''': ANY(SCREAMING_SNAKE_CASE ), '''token''': ANY(SCREAMING_SNAKE_CASE ), '''token_str''': ANY(SCREAMING_SNAKE_CASE )}, {'''sequence''': ANY(SCREAMING_SNAKE_CASE ), '''score''': ANY(SCREAMING_SNAKE_CASE ), '''token''': ANY(SCREAMING_SNAKE_CASE ), '''token_str''': ANY(SCREAMING_SNAKE_CASE )}, ], ] , ) with self.assertRaises(SCREAMING_SNAKE_CASE ): fill_masker([None] ) # No mask_token is not supported with self.assertRaises(SCREAMING_SNAKE_CASE ): fill_masker('''This is''' ) self.run_test_top_k(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) self.run_test_targets(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) self.run_test_top_k_targets(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) self.fill_mask_with_duplicate_targets_and_top_k(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) self.fill_mask_with_multiple_masks(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Optional[Any]: """simple docstring""" A : List[str] = tokenizer.get_vocab() A : Union[str, Any] = sorted(vocab.keys() )[:2] # Pipeline argument A : int = FillMaskPipeline(model=SCREAMING_SNAKE_CASE , tokenizer=SCREAMING_SNAKE_CASE , targets=SCREAMING_SNAKE_CASE ) A : Optional[Any] = fill_masker(F'This is a {tokenizer.mask_token}' ) self.assertEqual( SCREAMING_SNAKE_CASE , [ {'''sequence''': ANY(SCREAMING_SNAKE_CASE ), '''score''': ANY(SCREAMING_SNAKE_CASE ), '''token''': ANY(SCREAMING_SNAKE_CASE ), '''token_str''': ANY(SCREAMING_SNAKE_CASE )}, {'''sequence''': ANY(SCREAMING_SNAKE_CASE ), '''score''': ANY(SCREAMING_SNAKE_CASE ), '''token''': ANY(SCREAMING_SNAKE_CASE ), '''token_str''': ANY(SCREAMING_SNAKE_CASE )}, ] , ) A : Optional[int] = {vocab[el] for el in targets} self.assertEqual({el['''token'''] for el in outputs} , SCREAMING_SNAKE_CASE ) A : Optional[Any] = [tokenizer.decode([x] ) for x in target_ids] self.assertEqual({el['''token_str'''] for el in outputs} , set(SCREAMING_SNAKE_CASE ) ) # Call argument A : int = FillMaskPipeline(model=SCREAMING_SNAKE_CASE , tokenizer=SCREAMING_SNAKE_CASE ) A : Optional[Any] = fill_masker(F'This is a {tokenizer.mask_token}' , targets=SCREAMING_SNAKE_CASE ) self.assertEqual( SCREAMING_SNAKE_CASE , [ {'''sequence''': ANY(SCREAMING_SNAKE_CASE ), '''score''': ANY(SCREAMING_SNAKE_CASE ), '''token''': ANY(SCREAMING_SNAKE_CASE ), '''token_str''': ANY(SCREAMING_SNAKE_CASE )}, {'''sequence''': ANY(SCREAMING_SNAKE_CASE ), '''score''': ANY(SCREAMING_SNAKE_CASE ), '''token''': ANY(SCREAMING_SNAKE_CASE ), '''token_str''': ANY(SCREAMING_SNAKE_CASE )}, ] , ) A : Dict = {vocab[el] for el in targets} self.assertEqual({el['''token'''] for el in outputs} , SCREAMING_SNAKE_CASE ) A : Union[str, Any] = [tokenizer.decode([x] ) for x in target_ids] self.assertEqual({el['''token_str'''] for el in outputs} , set(SCREAMING_SNAKE_CASE ) ) # Score equivalence A : List[str] = fill_masker(F'This is a {tokenizer.mask_token}' , targets=SCREAMING_SNAKE_CASE ) A : Dict = [top_mask["""token_str"""] for top_mask in outputs] A : Dict = [top_mask["""score"""] for top_mask in outputs] # For some BPE tokenizers, `</w>` is removed during decoding, so `token_str` won't be the same as in `targets`. if set(SCREAMING_SNAKE_CASE ) == set(SCREAMING_SNAKE_CASE ): A : Optional[int] = fill_masker(F'This is a {tokenizer.mask_token}' , targets=SCREAMING_SNAKE_CASE ) A : List[str] = [top_mask["""score"""] for top_mask in unmasked_targets] self.assertEqual(nested_simplify(SCREAMING_SNAKE_CASE ) , nested_simplify(SCREAMING_SNAKE_CASE ) ) # Raises with invalid with self.assertRaises(SCREAMING_SNAKE_CASE ): A : str = fill_masker(F'This is a {tokenizer.mask_token}' , targets=[] ) # For some tokenizers, `""` is actually in the vocabulary and the expected error won't raised if "" not in tokenizer.get_vocab(): with self.assertRaises(SCREAMING_SNAKE_CASE ): A : Union[str, Any] = fill_masker(F'This is a {tokenizer.mask_token}' , targets=[''''''] ) with self.assertRaises(SCREAMING_SNAKE_CASE ): A : List[str] = fill_masker(F'This is a {tokenizer.mask_token}' , targets='''''' ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> List[Any]: """simple docstring""" A : List[str] = FillMaskPipeline(model=SCREAMING_SNAKE_CASE , tokenizer=SCREAMING_SNAKE_CASE , top_k=2 ) A : Any = fill_masker(F'This is a {tokenizer.mask_token}' ) self.assertEqual( SCREAMING_SNAKE_CASE , [ {'''sequence''': ANY(SCREAMING_SNAKE_CASE ), '''score''': ANY(SCREAMING_SNAKE_CASE ), '''token''': ANY(SCREAMING_SNAKE_CASE ), '''token_str''': ANY(SCREAMING_SNAKE_CASE )}, {'''sequence''': ANY(SCREAMING_SNAKE_CASE ), '''score''': ANY(SCREAMING_SNAKE_CASE ), '''token''': ANY(SCREAMING_SNAKE_CASE ), '''token_str''': ANY(SCREAMING_SNAKE_CASE )}, ] , ) A : List[str] = FillMaskPipeline(model=SCREAMING_SNAKE_CASE , tokenizer=SCREAMING_SNAKE_CASE ) A : int = fill_masker(F'This is a {tokenizer.mask_token}' , top_k=2 ) self.assertEqual( SCREAMING_SNAKE_CASE , [ {'''sequence''': ANY(SCREAMING_SNAKE_CASE ), '''score''': ANY(SCREAMING_SNAKE_CASE ), '''token''': ANY(SCREAMING_SNAKE_CASE ), '''token_str''': ANY(SCREAMING_SNAKE_CASE )}, {'''sequence''': ANY(SCREAMING_SNAKE_CASE ), '''score''': ANY(SCREAMING_SNAKE_CASE ), '''token''': ANY(SCREAMING_SNAKE_CASE ), '''token_str''': ANY(SCREAMING_SNAKE_CASE )}, ] , ) self.assertEqual(nested_simplify(SCREAMING_SNAKE_CASE ) , nested_simplify(SCREAMING_SNAKE_CASE ) ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> str: """simple docstring""" A : Optional[int] = tokenizer.get_vocab() A : str = FillMaskPipeline(model=SCREAMING_SNAKE_CASE , tokenizer=SCREAMING_SNAKE_CASE ) # top_k=2, ntargets=3 A : List[str] = sorted(vocab.keys() )[:3] A : Optional[int] = fill_masker(F'This is a {tokenizer.mask_token}' , top_k=2 , targets=SCREAMING_SNAKE_CASE ) # If we use the most probably targets, and filter differently, we should still # have the same results A : Optional[Any] = [el["""token_str"""] for el in sorted(SCREAMING_SNAKE_CASE , key=lambda SCREAMING_SNAKE_CASE : x["score"] , reverse=SCREAMING_SNAKE_CASE )] # For some BPE tokenizers, `</w>` is removed during decoding, so `token_str` won't be the same as in `targets`. if set(SCREAMING_SNAKE_CASE ).issubset(SCREAMING_SNAKE_CASE ): A : Any = fill_masker(F'This is a {tokenizer.mask_token}' , top_k=3 , targets=SCREAMING_SNAKE_CASE ) # They should yield exactly the same result self.assertEqual(nested_simplify(SCREAMING_SNAKE_CASE ) , nested_simplify(SCREAMING_SNAKE_CASE ) ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Any: """simple docstring""" A : Tuple = FillMaskPipeline(model=SCREAMING_SNAKE_CASE , tokenizer=SCREAMING_SNAKE_CASE ) A : List[Any] = tokenizer.get_vocab() # String duplicates + id duplicates A : List[Any] = sorted(vocab.keys() )[:3] A : str = [targets[0], targets[1], targets[0], targets[2], targets[1]] A : Union[str, Any] = fill_masker(F'My name is {tokenizer.mask_token}' , targets=SCREAMING_SNAKE_CASE , top_k=10 ) # The target list contains duplicates, so we can't output more # than them self.assertEqual(len(SCREAMING_SNAKE_CASE ) , 3 ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> List[Any]: """simple docstring""" A : Optional[int] = FillMaskPipeline(model=SCREAMING_SNAKE_CASE , tokenizer=SCREAMING_SNAKE_CASE ) A : Optional[int] = fill_masker( F'This is a {tokenizer.mask_token} {tokenizer.mask_token} {tokenizer.mask_token}' , top_k=2 ) self.assertEqual( SCREAMING_SNAKE_CASE , [ [ {'''sequence''': ANY(SCREAMING_SNAKE_CASE ), '''score''': ANY(SCREAMING_SNAKE_CASE ), '''token''': ANY(SCREAMING_SNAKE_CASE ), '''token_str''': ANY(SCREAMING_SNAKE_CASE )}, {'''sequence''': ANY(SCREAMING_SNAKE_CASE ), '''score''': ANY(SCREAMING_SNAKE_CASE ), '''token''': ANY(SCREAMING_SNAKE_CASE ), '''token_str''': ANY(SCREAMING_SNAKE_CASE )}, ], [ {'''sequence''': ANY(SCREAMING_SNAKE_CASE ), '''score''': ANY(SCREAMING_SNAKE_CASE ), '''token''': ANY(SCREAMING_SNAKE_CASE ), '''token_str''': ANY(SCREAMING_SNAKE_CASE )}, {'''sequence''': ANY(SCREAMING_SNAKE_CASE ), '''score''': ANY(SCREAMING_SNAKE_CASE ), '''token''': ANY(SCREAMING_SNAKE_CASE ), '''token_str''': ANY(SCREAMING_SNAKE_CASE )}, ], [ {'''sequence''': ANY(SCREAMING_SNAKE_CASE ), '''score''': ANY(SCREAMING_SNAKE_CASE ), '''token''': ANY(SCREAMING_SNAKE_CASE ), '''token_str''': ANY(SCREAMING_SNAKE_CASE )}, {'''sequence''': ANY(SCREAMING_SNAKE_CASE ), '''score''': ANY(SCREAMING_SNAKE_CASE ), '''token''': ANY(SCREAMING_SNAKE_CASE ), '''token_str''': ANY(SCREAMING_SNAKE_CASE )}, ], ] , )
634
"""simple docstring""" from __future__ import annotations import queue class lowercase__ : def __init__( self , SCREAMING_SNAKE_CASE) -> int: _lowerCamelCase : int = data _lowerCamelCase : List[str] = None _lowerCamelCase : Any = None def _snake_case ( ): """simple docstring""" print("""\n********Press N to stop entering at any point of time********\n""" ) _lowerCamelCase : Optional[int] = input("""Enter the value of the root node: """ ).strip().lower() _lowerCamelCase : queue.Queue = queue.Queue() _lowerCamelCase : Optional[int] = TreeNode(int(__snake_case ) ) q.put(__snake_case ) while not q.empty(): _lowerCamelCase : Tuple = q.get() _lowerCamelCase : Any = F'Enter the left node of {node_found.data}: ' _lowerCamelCase : Union[str, Any] = input(__snake_case ).strip().lower() or """n""" if check == "n": return tree_node _lowerCamelCase : Dict = TreeNode(int(__snake_case ) ) _lowerCamelCase : List[str] = left_node q.put(__snake_case ) _lowerCamelCase : Optional[int] = F'Enter the right node of {node_found.data}: ' _lowerCamelCase : Optional[Any] = input(__snake_case ).strip().lower() or """n""" if check == "n": return tree_node _lowerCamelCase : List[Any] = TreeNode(int(__snake_case ) ) _lowerCamelCase : List[Any] = right_node q.put(__snake_case ) raise def _snake_case ( __snake_case : TreeNode ): """simple docstring""" if not isinstance(__snake_case , __snake_case ) or not node: return print(node.data , end=""",""" ) pre_order(node.left ) pre_order(node.right ) def _snake_case ( __snake_case : TreeNode ): """simple docstring""" if not isinstance(__snake_case , __snake_case ) or not node: return in_order(node.left ) print(node.data , end=""",""" ) in_order(node.right ) def _snake_case ( __snake_case : TreeNode ): """simple docstring""" if not isinstance(__snake_case , __snake_case ) or not node: return post_order(node.left ) post_order(node.right ) print(node.data , end=""",""" ) def _snake_case ( __snake_case : TreeNode ): """simple docstring""" if not isinstance(__snake_case , __snake_case ) or not node: return _lowerCamelCase : queue.Queue = queue.Queue() q.put(__snake_case ) while not q.empty(): _lowerCamelCase : Any = q.get() print(node_dequeued.data , end=""",""" ) if node_dequeued.left: q.put(node_dequeued.left ) if node_dequeued.right: q.put(node_dequeued.right ) def _snake_case ( __snake_case : TreeNode ): """simple docstring""" if not isinstance(__snake_case , __snake_case ) or not node: return _lowerCamelCase : queue.Queue = queue.Queue() q.put(__snake_case ) while not q.empty(): _lowerCamelCase : Optional[Any] = [] while not q.empty(): _lowerCamelCase : Dict = q.get() print(node_dequeued.data , end=""",""" ) if node_dequeued.left: list_.append(node_dequeued.left ) if node_dequeued.right: list_.append(node_dequeued.right ) print() for node in list_: q.put(__snake_case ) def _snake_case ( __snake_case : TreeNode ): """simple docstring""" if not isinstance(__snake_case , __snake_case ) or not node: return _lowerCamelCase : list[TreeNode] = [] _lowerCamelCase : Optional[int] = node while n or stack: while n: # start from root node, find its left child print(n.data , end=""",""" ) stack.append(__snake_case ) _lowerCamelCase : Tuple = n.left # end of while means current node doesn't have left child _lowerCamelCase : Optional[Any] = stack.pop() # start to traverse its right child _lowerCamelCase : Dict = n.right def _snake_case ( __snake_case : TreeNode ): """simple docstring""" if not isinstance(__snake_case , __snake_case ) or not node: return _lowerCamelCase : list[TreeNode] = [] _lowerCamelCase : int = node while n or stack: while n: stack.append(__snake_case ) _lowerCamelCase : Any = n.left _lowerCamelCase : Optional[Any] = stack.pop() print(n.data , end=""",""" ) _lowerCamelCase : List[Any] = n.right def _snake_case ( __snake_case : TreeNode ): """simple docstring""" if not isinstance(__snake_case , __snake_case ) or not node: return _lowerCamelCase , _lowerCamelCase : Union[str, Any] = [], [] _lowerCamelCase : Optional[Any] = node stacka.append(__snake_case ) while stacka: # to find the reversed order of post order, store it in stack2 _lowerCamelCase : Union[str, Any] = stacka.pop() if n.left: stacka.append(n.left ) if n.right: stacka.append(n.right ) stacka.append(__snake_case ) while stacka: # pop up from stack2 will be the post order print(stacka.pop().data , end=""",""" ) def _snake_case ( __snake_case : str = "" , __snake_case : Any=50 , __snake_case : List[str]="*" ): """simple docstring""" if not s: return "\n" + width * char _lowerCamelCase , _lowerCamelCase : Optional[int] = divmod(width - len(__snake_case ) - 2 , 2 ) return F'{left * char} {s} {(left + extra) * char}' if __name__ == "__main__": import doctest doctest.testmod() print(prompt("""Binary Tree Traversals""")) UpperCAmelCase = build_tree() print(prompt("""Pre Order Traversal""")) pre_order(node) print(prompt() + """\n""") print(prompt("""In Order Traversal""")) in_order(node) print(prompt() + """\n""") print(prompt("""Post Order Traversal""")) post_order(node) print(prompt() + """\n""") print(prompt("""Level Order Traversal""")) level_order(node) print(prompt() + """\n""") print(prompt("""Actual Level Order Traversal""")) level_order_actual(node) print("""*""" * 50 + """\n""") print(prompt("""Pre Order Traversal - Iteration Version""")) pre_order_iter(node) print(prompt() + """\n""") print(prompt("""In Order Traversal - Iteration Version""")) in_order_iter(node) print(prompt() + """\n""") print(prompt("""Post Order Traversal - Iteration Version""")) post_order_iter(node) print(prompt())
88
0
'''simple docstring''' import re import subprocess import sys UpperCAmelCase_ : List[Any] = subprocess.check_output('''git merge-base main HEAD'''.split()).decode('''utf-8''') UpperCAmelCase_ : List[Any] = ( subprocess.check_output(F"""git diff --diff-filter=d --name-only {fork_point_sha}""".split()).decode('''utf-8''').split() ) UpperCAmelCase_ : List[Any] = '''|'''.join(sys.argv[1:]) UpperCAmelCase_ : Dict = re.compile(RF"""^({joined_dirs}).*?\.py$""") UpperCAmelCase_ : Tuple = [x for x in modified_files if regex.match(x)] print(''' '''.join(relevant_modified_files), end='''''')
24
"""simple docstring""" from __future__ import annotations import unittest from transformers import XGLMConfig, XGLMTokenizer, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers.models.xglm.modeling_tf_xglm import ( TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST, TFXGLMForCausalLM, TFXGLMModel, ) @require_tf class lowercase__ : __UpperCAmelCase = XGLMConfig __UpperCAmelCase = {} __UpperCAmelCase = '''gelu''' def __init__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=14 , SCREAMING_SNAKE_CASE=7 , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=99 , SCREAMING_SNAKE_CASE=32 , SCREAMING_SNAKE_CASE=2 , SCREAMING_SNAKE_CASE=4 , SCREAMING_SNAKE_CASE=37 , SCREAMING_SNAKE_CASE="gelu" , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=512 , SCREAMING_SNAKE_CASE=0.02 , ) -> List[str]: _lowerCamelCase : Optional[int] = parent _lowerCamelCase : int = batch_size _lowerCamelCase : str = seq_length _lowerCamelCase : Any = is_training _lowerCamelCase : int = use_input_mask _lowerCamelCase : Union[str, Any] = use_labels _lowerCamelCase : str = vocab_size _lowerCamelCase : List[str] = d_model _lowerCamelCase : List[Any] = num_hidden_layers _lowerCamelCase : Dict = num_attention_heads _lowerCamelCase : int = ffn_dim _lowerCamelCase : str = activation_function _lowerCamelCase : Optional[int] = activation_dropout _lowerCamelCase : Tuple = attention_dropout _lowerCamelCase : Tuple = max_position_embeddings _lowerCamelCase : Dict = initializer_range _lowerCamelCase : Optional[Any] = None _lowerCamelCase : Union[str, Any] = 0 _lowerCamelCase : List[Any] = 2 _lowerCamelCase : str = 1 def UpperCamelCase_ ( self) -> int: return XGLMConfig.from_pretrained("""facebook/xglm-564M""") def UpperCamelCase_ ( self) -> int: _lowerCamelCase : Union[str, Any] = tf.clip_by_value( ids_tensor([self.batch_size, self.seq_length] , self.vocab_size) , clip_value_min=0 , clip_value_max=3) _lowerCamelCase : str = None if self.use_input_mask: _lowerCamelCase : Union[str, Any] = random_attention_mask([self.batch_size, self.seq_length]) _lowerCamelCase : Tuple = self.get_config() _lowerCamelCase : Optional[int] = floats_tensor([self.num_hidden_layers, self.num_attention_heads] , 2) return ( config, input_ids, input_mask, head_mask, ) def UpperCamelCase_ ( self) -> Optional[int]: return XGLMConfig( vocab_size=self.vocab_size , d_model=self.hidden_size , num_layers=self.num_hidden_layers , attention_heads=self.num_attention_heads , ffn_dim=self.ffn_dim , activation_function=self.activation_function , activation_dropout=self.activation_dropout , attention_dropout=self.attention_dropout , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , use_cache=SCREAMING_SNAKE_CASE , bos_token_id=self.bos_token_id , eos_token_id=self.eos_token_id , pad_token_id=self.pad_token_id , return_dict=SCREAMING_SNAKE_CASE , ) def UpperCamelCase_ ( self) -> Optional[int]: _lowerCamelCase : List[Any] = self.prepare_config_and_inputs() ( ( _lowerCamelCase ) , ( _lowerCamelCase ) , ( _lowerCamelCase ) , ( _lowerCamelCase ) , ) : str = config_and_inputs _lowerCamelCase : Optional[Any] = { """input_ids""": input_ids, """head_mask""": head_mask, } return config, inputs_dict @require_tf class lowercase__ ( A_ ,A_ ,unittest.TestCase ): __UpperCAmelCase = (TFXGLMModel, TFXGLMForCausalLM) if is_tf_available() else () __UpperCAmelCase = (TFXGLMForCausalLM,) if is_tf_available() else () __UpperCAmelCase = ( {'''feature-extraction''': TFXGLMModel, '''text-generation''': TFXGLMForCausalLM} if is_tf_available() else {} ) __UpperCAmelCase = False __UpperCAmelCase = False __UpperCAmelCase = False def UpperCamelCase_ ( self) -> Optional[Any]: _lowerCamelCase : Optional[Any] = TFXGLMModelTester(self) _lowerCamelCase : str = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE , n_embd=37) def UpperCamelCase_ ( self) -> Dict: self.config_tester.run_common_tests() @slow def UpperCamelCase_ ( self) -> List[Any]: for model_name in TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _lowerCamelCase : Tuple = TFXGLMModel.from_pretrained(SCREAMING_SNAKE_CASE) self.assertIsNotNone(SCREAMING_SNAKE_CASE) @unittest.skip(reason="""Currently, model embeddings are going to undergo a major refactor.""") def UpperCamelCase_ ( self) -> List[Any]: super().test_resize_token_embeddings() @require_tf class lowercase__ ( unittest.TestCase ): @slow def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE=True) -> List[Any]: _lowerCamelCase : List[str] = TFXGLMForCausalLM.from_pretrained("""facebook/xglm-564M""") _lowerCamelCase : Union[str, Any] = tf.convert_to_tensor([[2, 268, 9865]] , dtype=tf.intaa) # The dog # </s> The dog is a very friendly dog. He is very affectionate and loves to play with other # fmt: off _lowerCamelCase : Dict = [2, 268, 9865, 67, 11, 1988, 5_7252, 9865, 5, 984, 67, 1988, 21_3838, 1658, 53, 7_0446, 33, 6657, 278, 1581] # fmt: on _lowerCamelCase : str = model.generate(SCREAMING_SNAKE_CASE , do_sample=SCREAMING_SNAKE_CASE , num_beams=1) if verify_outputs: self.assertListEqual(output_ids[0].numpy().tolist() , SCREAMING_SNAKE_CASE) @slow def UpperCamelCase_ ( self) -> int: _lowerCamelCase : int = XGLMTokenizer.from_pretrained("""facebook/xglm-564M""") _lowerCamelCase : Tuple = TFXGLMForCausalLM.from_pretrained("""facebook/xglm-564M""") tf.random.set_seed(0) _lowerCamelCase : Union[str, Any] = tokenizer("""Today is a nice day and""" , return_tensors="""tf""") _lowerCamelCase : Any = tokenized.input_ids # forces the generation to happen on CPU, to avoid GPU-related quirks (and assure same output regardless of the available devices) with tf.device(""":/CPU:0"""): _lowerCamelCase : Any = model.generate(SCREAMING_SNAKE_CASE , do_sample=SCREAMING_SNAKE_CASE , seed=[7, 0]) _lowerCamelCase : List[str] = tokenizer.decode(output_ids[0] , skip_special_tokens=SCREAMING_SNAKE_CASE) _lowerCamelCase : Any = ( """Today is a nice day and warm evening here over Southern Alberta!! Today when they closed schools due""" ) self.assertEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) @slow def UpperCamelCase_ ( self) -> List[Any]: _lowerCamelCase : Optional[Any] = TFXGLMForCausalLM.from_pretrained("""facebook/xglm-564M""") _lowerCamelCase : Any = XGLMTokenizer.from_pretrained("""facebook/xglm-564M""") _lowerCamelCase : List[Any] = """left""" # use different length sentences to test batching _lowerCamelCase : List[Any] = [ """This is an extremelly long sentence that only exists to test the ability of the model to cope with """ """left-padding, such as in batched generation. The output for the sequence below should be the same """ """regardless of whether left padding is applied or not. When""", """Hello, my dog is a little""", ] _lowerCamelCase : Union[str, Any] = tokenizer(SCREAMING_SNAKE_CASE , return_tensors="""tf""" , padding=SCREAMING_SNAKE_CASE) _lowerCamelCase : int = inputs["""input_ids"""] _lowerCamelCase : List[Any] = model.generate(input_ids=SCREAMING_SNAKE_CASE , attention_mask=inputs["""attention_mask"""] , max_new_tokens=12) _lowerCamelCase : List[str] = tokenizer(sentences[0] , return_tensors="""tf""").input_ids _lowerCamelCase : Optional[Any] = model.generate(input_ids=SCREAMING_SNAKE_CASE , max_new_tokens=12) _lowerCamelCase : Tuple = tokenizer(sentences[1] , return_tensors="""tf""").input_ids _lowerCamelCase : int = model.generate(input_ids=SCREAMING_SNAKE_CASE , max_new_tokens=12) _lowerCamelCase : Optional[int] = tokenizer.batch_decode(SCREAMING_SNAKE_CASE , skip_special_tokens=SCREAMING_SNAKE_CASE) _lowerCamelCase : Optional[Any] = tokenizer.decode(output_non_padded[0] , skip_special_tokens=SCREAMING_SNAKE_CASE) _lowerCamelCase : Union[str, Any] = tokenizer.decode(output_padded[0] , skip_special_tokens=SCREAMING_SNAKE_CASE) _lowerCamelCase : Tuple = [ """This is an extremelly long sentence that only exists to test the ability of the model to cope with """ """left-padding, such as in batched generation. The output for the sequence below should be the same """ """regardless of whether left padding is applied or not. When left padding is applied, the sequence will be """ """a single""", """Hello, my dog is a little bit of a shy one, but he is very friendly""", ] self.assertListEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) self.assertListEqual(SCREAMING_SNAKE_CASE , [non_padded_sentence, padded_sentence])
88
0
import argparse import os from . import ( ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, BART_PRETRAINED_MODEL_ARCHIVE_LIST, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, CAMEMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP, DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST, ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP, FLAUBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP, LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST, LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP, OPENAI_GPT_PRETRAINED_CONFIG_ARCHIVE_MAP, ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, T5_PRETRAINED_CONFIG_ARCHIVE_MAP, TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP, WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP, XLM_PRETRAINED_CONFIG_ARCHIVE_MAP, XLM_ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP, AlbertConfig, BartConfig, BertConfig, CamembertConfig, CTRLConfig, DistilBertConfig, DPRConfig, ElectraConfig, FlaubertConfig, GPTaConfig, LayoutLMConfig, LxmertConfig, OpenAIGPTConfig, RobertaConfig, TaConfig, TFAlbertForPreTraining, TFBartForConditionalGeneration, TFBartForSequenceClassification, TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification, TFCamembertForMaskedLM, TFCTRLLMHeadModel, TFDistilBertForMaskedLM, TFDistilBertForQuestionAnswering, TFDPRContextEncoder, TFDPRQuestionEncoder, TFDPRReader, TFElectraForPreTraining, TFFlaubertWithLMHeadModel, TFGPTaLMHeadModel, TFLayoutLMForMaskedLM, TFLxmertForPreTraining, TFLxmertVisualFeatureEncoder, TFOpenAIGPTLMHeadModel, TFRobertaForCausalLM, TFRobertaForMaskedLM, TFRobertaForSequenceClassification, TFTaForConditionalGeneration, TFTransfoXLLMHeadModel, TFWavaVecaModel, TFXLMRobertaForMaskedLM, TFXLMWithLMHeadModel, TFXLNetLMHeadModel, TransfoXLConfig, WavaVecaConfig, WavaVecaModel, XLMConfig, XLMRobertaConfig, XLNetConfig, is_torch_available, load_pytorch_checkpoint_in_tfa_model, ) from .utils import CONFIG_NAME, WEIGHTS_NAME, cached_file, logging if is_torch_available(): import numpy as np import torch from . import ( AlbertForPreTraining, BartForConditionalGeneration, BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification, CamembertForMaskedLM, CTRLLMHeadModel, DistilBertForMaskedLM, DistilBertForQuestionAnswering, DPRContextEncoder, DPRQuestionEncoder, DPRReader, ElectraForPreTraining, FlaubertWithLMHeadModel, GPTaLMHeadModel, LayoutLMForMaskedLM, LxmertForPreTraining, LxmertVisualFeatureEncoder, OpenAIGPTLMHeadModel, RobertaForMaskedLM, RobertaForSequenceClassification, TaForConditionalGeneration, TransfoXLLMHeadModel, XLMRobertaForMaskedLM, XLMWithLMHeadModel, XLNetLMHeadModel, ) logging.set_verbosity_info() _lowerCAmelCase : Any = { "bart": ( BartConfig, TFBartForConditionalGeneration, TFBartForSequenceClassification, BartForConditionalGeneration, BART_PRETRAINED_MODEL_ARCHIVE_LIST, ), "bert": ( BertConfig, TFBertForPreTraining, BertForPreTraining, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "bert-large-uncased-whole-word-masking-finetuned-squad": ( BertConfig, TFBertForQuestionAnswering, BertForQuestionAnswering, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "bert-large-cased-whole-word-masking-finetuned-squad": ( BertConfig, TFBertForQuestionAnswering, BertForQuestionAnswering, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "bert-base-cased-finetuned-mrpc": ( BertConfig, TFBertForSequenceClassification, BertForSequenceClassification, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "dpr": ( DPRConfig, TFDPRQuestionEncoder, TFDPRContextEncoder, TFDPRReader, DPRQuestionEncoder, DPRContextEncoder, DPRReader, DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST, ), "gpt2": ( GPTaConfig, TFGPTaLMHeadModel, GPTaLMHeadModel, GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "xlnet": ( XLNetConfig, TFXLNetLMHeadModel, XLNetLMHeadModel, XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "xlm": ( XLMConfig, TFXLMWithLMHeadModel, XLMWithLMHeadModel, XLM_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "xlm-roberta": ( XLMRobertaConfig, TFXLMRobertaForMaskedLM, XLMRobertaForMaskedLM, XLM_ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "transfo-xl": ( TransfoXLConfig, TFTransfoXLLMHeadModel, TransfoXLLMHeadModel, TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "openai-gpt": ( OpenAIGPTConfig, TFOpenAIGPTLMHeadModel, OpenAIGPTLMHeadModel, OPENAI_GPT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "roberta": ( RobertaConfig, TFRobertaForCausalLM, TFRobertaForMaskedLM, RobertaForMaskedLM, ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "layoutlm": ( LayoutLMConfig, TFLayoutLMForMaskedLM, LayoutLMForMaskedLM, LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST, ), "roberta-large-mnli": ( RobertaConfig, TFRobertaForSequenceClassification, RobertaForSequenceClassification, ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "camembert": ( CamembertConfig, TFCamembertForMaskedLM, CamembertForMaskedLM, CAMEMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "flaubert": ( FlaubertConfig, TFFlaubertWithLMHeadModel, FlaubertWithLMHeadModel, FLAUBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "distilbert": ( DistilBertConfig, TFDistilBertForMaskedLM, DistilBertForMaskedLM, DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "distilbert-base-distilled-squad": ( DistilBertConfig, TFDistilBertForQuestionAnswering, DistilBertForQuestionAnswering, DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "lxmert": ( LxmertConfig, TFLxmertForPreTraining, LxmertForPreTraining, LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "lxmert-visual-feature-encoder": ( LxmertConfig, TFLxmertVisualFeatureEncoder, LxmertVisualFeatureEncoder, LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "ctrl": ( CTRLConfig, TFCTRLLMHeadModel, CTRLLMHeadModel, CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "albert": ( AlbertConfig, TFAlbertForPreTraining, AlbertForPreTraining, ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "t5": ( TaConfig, TFTaForConditionalGeneration, TaForConditionalGeneration, T5_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "electra": ( ElectraConfig, TFElectraForPreTraining, ElectraForPreTraining, ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "wav2vec2": ( WavaVecaConfig, TFWavaVecaModel, WavaVecaModel, WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP, ), } def UpperCAmelCase_ ( snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__=False , snake_case__=True ) -> int: """simple docstring""" if model_type not in MODEL_CLASSES: raise ValueError(f'Unrecognized model type, should be one of {list(MODEL_CLASSES.keys() )}.' ) lowerCAmelCase__ = MODEL_CLASSES[model_type] # Initialise TF model if config_file in aws_config_map: lowerCAmelCase__ = cached_file(__snake_case , __snake_case , force_download=not use_cached_models ) lowerCAmelCase__ = config_class.from_json_file(__snake_case ) lowerCAmelCase__ = True lowerCAmelCase__ = True print(f'Building TensorFlow model from configuration: {config}' ) lowerCAmelCase__ = model_class(__snake_case ) # Load weights from tf checkpoint if pytorch_checkpoint_path in aws_config_map.keys(): lowerCAmelCase__ = cached_file( __snake_case , __snake_case , force_download=not use_cached_models ) # Load PyTorch checkpoint in tf2 model: lowerCAmelCase__ = load_pytorch_checkpoint_in_tfa_model(__snake_case , __snake_case ) if compare_with_pt_model: lowerCAmelCase__ = tf_model(tf_model.dummy_inputs , training=__snake_case ) # build the network lowerCAmelCase__ = torch.load(__snake_case , map_location='cpu' ) lowerCAmelCase__ = pt_model_class.from_pretrained( pretrained_model_name_or_path=__snake_case , config=__snake_case , state_dict=__snake_case ) with torch.no_grad(): lowerCAmelCase__ = pt_model(**pt_model.dummy_inputs ) lowerCAmelCase__ = pto[0].numpy() lowerCAmelCase__ = tfo[0].numpy() lowerCAmelCase__ = np.amax(np.abs(np_pt - np_tf ) ) print(f'Max absolute difference between models outputs {diff}' ) assert diff <= 2E-2, f'Error, model absolute difference is >2e-2: {diff}' # Save pytorch-model print(f'Save TensorFlow model to {tf_dump_path}' ) tf_model.save_weights(__snake_case , save_format='h5' ) def UpperCAmelCase_ ( snake_case__ , snake_case__ , snake_case__=None , snake_case__=None , snake_case__=False , snake_case__=False , snake_case__=False , snake_case__=False , ) -> str: """simple docstring""" if args_model_type is None: lowerCAmelCase__ = list(MODEL_CLASSES.keys() ) else: lowerCAmelCase__ = [args_model_type] for j, model_type in enumerate(__snake_case , start=1 ): print('=' * 100 ) print(f' Converting model type {j}/{len(__snake_case )}: {model_type}' ) print('=' * 100 ) if model_type not in MODEL_CLASSES: raise ValueError(f'Unrecognized model type {model_type}, should be one of {list(MODEL_CLASSES.keys() )}.' ) lowerCAmelCase__ = MODEL_CLASSES[model_type] if model_shortcut_names_or_path is None: lowerCAmelCase__ = list(aws_model_maps.keys() ) if config_shortcut_names_or_path is None: lowerCAmelCase__ = model_shortcut_names_or_path for i, (model_shortcut_name, config_shortcut_name) in enumerate( zip(__snake_case , __snake_case ) , start=1 ): print('-' * 100 ) if "-squad" in model_shortcut_name or "-mrpc" in model_shortcut_name or "-mnli" in model_shortcut_name: if not only_convert_finetuned_models: print(f' Skipping finetuned checkpoint {model_shortcut_name}' ) continue lowerCAmelCase__ = model_shortcut_name elif only_convert_finetuned_models: print(f' Skipping not finetuned checkpoint {model_shortcut_name}' ) continue print( f' Converting checkpoint {i}/{len(__snake_case )}: {model_shortcut_name} - model_type {model_type}' ) print('-' * 100 ) if config_shortcut_name in aws_config_map: lowerCAmelCase__ = cached_file(__snake_case , __snake_case , force_download=not use_cached_models ) else: lowerCAmelCase__ = config_shortcut_name if model_shortcut_name in aws_model_maps: lowerCAmelCase__ = cached_file(__snake_case , __snake_case , force_download=not use_cached_models ) else: lowerCAmelCase__ = model_shortcut_name if os.path.isfile(__snake_case ): lowerCAmelCase__ = """converted_model""" convert_pt_checkpoint_to_tf( model_type=__snake_case , pytorch_checkpoint_path=__snake_case , config_file=__snake_case , tf_dump_path=os.path.join(__snake_case , model_shortcut_name + '-tf_model.h5' ) , compare_with_pt_model=__snake_case , ) if remove_cached_files: os.remove(__snake_case ) os.remove(__snake_case ) if __name__ == "__main__": _lowerCAmelCase : str = argparse.ArgumentParser() # Required parameters parser.add_argument( "--tf_dump_path", default=None, type=str, required=True, help="Path to the output Tensorflow dump file." ) parser.add_argument( "--model_type", default=None, type=str, help=( f"""Model type selected in the list of {list(MODEL_CLASSES.keys())}. If not given, will download and """ "convert all the models from AWS." ), ) parser.add_argument( "--pytorch_checkpoint_path", default=None, type=str, help=( "Path to the PyTorch checkpoint path or shortcut name to download from AWS. " "If not given, will download and convert all the checkpoints from AWS." ), ) parser.add_argument( "--config_file", default=None, type=str, help=( "The config json file corresponding to the pre-trained model. \n" "This specifies the model architecture. If not given and " "--pytorch_checkpoint_path is not given or is a shortcut name " "use the configuration associated to the shortcut name on the AWS" ), ) parser.add_argument( "--compare_with_pt_model", action="store_true", help="Compare Tensorflow and PyTorch model predictions." ) parser.add_argument( "--use_cached_models", action="store_true", help="Use cached models if possible instead of updating to latest checkpoint versions.", ) parser.add_argument( "--remove_cached_files", action="store_true", help="Remove pytorch models after conversion (save memory when converting in batches).", ) parser.add_argument("--only_convert_finetuned_models", action="store_true", help="Only convert finetuned models.") _lowerCAmelCase : Any = parser.parse_args() # if args.pytorch_checkpoint_path is not None: # convert_pt_checkpoint_to_tf(args.model_type.lower(), # args.pytorch_checkpoint_path, # args.config_file if args.config_file is not None else args.pytorch_checkpoint_path, # args.tf_dump_path, # compare_with_pt_model=args.compare_with_pt_model, # use_cached_models=args.use_cached_models) # else: convert_all_pt_checkpoints_to_tf( args.model_type.lower() if args.model_type is not None else None, args.tf_dump_path, model_shortcut_names_or_path=[args.pytorch_checkpoint_path] if args.pytorch_checkpoint_path is not None else None, config_shortcut_names_or_path=[args.config_file] if args.config_file is not None else None, compare_with_pt_model=args.compare_with_pt_model, use_cached_models=args.use_cached_models, remove_cached_files=args.remove_cached_files, only_convert_finetuned_models=args.only_convert_finetuned_models, )
193
"""simple docstring""" from collections import defaultdict def _snake_case ( __snake_case : str , __snake_case : str ): """simple docstring""" _lowerCamelCase : Tuple = first_str.lower().strip() _lowerCamelCase : int = second_str.lower().strip() # Remove whitespace _lowerCamelCase : Any = first_str.replace(""" """ , """""" ) _lowerCamelCase : List[str] = second_str.replace(""" """ , """""" ) # Strings of different lengths are not anagrams if len(__snake_case ) != len(__snake_case ): return False # Default values for count should be 0 _lowerCamelCase : defaultdict[str, int] = defaultdict(__snake_case ) # For each character in input strings, # increment count in the corresponding for i in range(len(__snake_case ) ): count[first_str[i]] += 1 count[second_str[i]] -= 1 return all(_count == 0 for _count in count.values() ) if __name__ == "__main__": from doctest import testmod testmod() UpperCAmelCase = input("""Enter the first string """).strip() UpperCAmelCase = input("""Enter the second string """).strip() UpperCAmelCase = check_anagrams(input_a, input_b) print(f'''{input_a} and {input_b} are {"" if status else "not "}anagrams.''')
88
0
'''simple docstring''' import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import MgpstrTokenizer from transformers.models.mgp_str.tokenization_mgp_str import VOCAB_FILES_NAMES from transformers.testing_utils import require_torch, require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_torch_available, is_vision_available if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import MgpstrProcessor, ViTImageProcessor @require_torch @require_vision class __A (unittest.TestCase ): snake_case :List[str] = ViTImageProcessor if is_vision_available() else None @property def _snake_case ( self ): return self.image_processor_tester.prepare_image_processor_dict() def _snake_case ( self ): __UpperCAmelCase : List[str] = (3, 32, 1_28) __UpperCAmelCase : List[Any] = tempfile.mkdtemp() # fmt: off __UpperCAmelCase : Optional[int] = ["""[GO]""", """[s]""", """0""", """1""", """2""", """3""", """4""", """5""", """6""", """7""", """8""", """9""", """a""", """b""", """c""", """d""", """e""", """f""", """g""", """h""", """i""", """j""", """k""", """l""", """m""", """n""", """o""", """p""", """q""", """r""", """s""", """t""", """u""", """v""", """w""", """x""", """y""", """z"""] # fmt: on __UpperCAmelCase : Dict = dict(zip(UpperCamelCase_ , range(len(UpperCamelCase_ ) ) ) ) __UpperCAmelCase : int = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as fp: fp.write(json.dumps(UpperCamelCase_ ) + "\n" ) __UpperCAmelCase : Any = { """do_normalize""": False, """do_resize""": True, """image_processor_type""": """ViTImageProcessor""", """resample""": 3, """size""": {"""height""": 32, """width""": 1_28}, } __UpperCAmelCase : Union[str, Any] = os.path.join(self.tmpdirname , UpperCamelCase_ ) with open(self.image_processor_file , "w" , encoding="utf-8" ) as fp: json.dump(UpperCamelCase_ , UpperCamelCase_ ) def _snake_case ( self , **UpperCamelCase_ ): return MgpstrTokenizer.from_pretrained(self.tmpdirname , **UpperCamelCase_ ) def _snake_case ( self , **UpperCamelCase_ ): return ViTImageProcessor.from_pretrained(self.tmpdirname , **UpperCamelCase_ ) def _snake_case ( self ): shutil.rmtree(self.tmpdirname ) def _snake_case ( self ): __UpperCAmelCase : Optional[int] = np.random.randint(2_55 , size=(3, 30, 4_00) , dtype=np.uinta ) __UpperCAmelCase : Union[str, Any] = Image.fromarray(np.moveaxis(UpperCamelCase_ , 0 , -1 ) ) return image_input def _snake_case ( self ): __UpperCAmelCase : Optional[Any] = self.get_tokenizer() __UpperCAmelCase : Dict = self.get_image_processor() __UpperCAmelCase : Tuple = MgpstrProcessor(tokenizer=UpperCamelCase_ , image_processor=UpperCamelCase_ ) processor.save_pretrained(self.tmpdirname ) __UpperCAmelCase : Dict = MgpstrProcessor.from_pretrained(self.tmpdirname , use_fast=UpperCamelCase_ ) self.assertEqual(processor.char_tokenizer.get_vocab() , tokenizer.get_vocab() ) self.assertIsInstance(processor.char_tokenizer , UpperCamelCase_ ) self.assertEqual(processor.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor.image_processor , UpperCamelCase_ ) def _snake_case ( self ): __UpperCAmelCase : Optional[int] = self.get_tokenizer() __UpperCAmelCase : Any = self.get_image_processor() __UpperCAmelCase : List[Any] = MgpstrProcessor(tokenizer=UpperCamelCase_ , image_processor=UpperCamelCase_ ) processor.save_pretrained(self.tmpdirname ) __UpperCAmelCase : Optional[int] = self.get_tokenizer(bos_token="(BOS)" , eos_token="(EOS)" ) __UpperCAmelCase : Optional[Any] = self.get_image_processor(do_normalize=UpperCamelCase_ , padding_value=1.0 ) __UpperCAmelCase : Any = MgpstrProcessor.from_pretrained( self.tmpdirname , bos_token="(BOS)" , eos_token="(EOS)" , do_normalize=UpperCamelCase_ , padding_value=1.0 ) self.assertEqual(processor.char_tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.char_tokenizer , UpperCamelCase_ ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , UpperCamelCase_ ) def _snake_case ( self ): __UpperCAmelCase : Optional[int] = self.get_image_processor() __UpperCAmelCase : Union[str, Any] = self.get_tokenizer() __UpperCAmelCase : Optional[int] = MgpstrProcessor(tokenizer=UpperCamelCase_ , image_processor=UpperCamelCase_ ) __UpperCAmelCase : List[Any] = self.prepare_image_inputs() __UpperCAmelCase : Optional[Any] = image_processor(UpperCamelCase_ , return_tensors="np" ) __UpperCAmelCase : Tuple = processor(images=UpperCamelCase_ , return_tensors="np" ) for key in input_image_proc.keys(): self.assertAlmostEqual(input_image_proc[key].sum() , input_processor[key].sum() , delta=1E-2 ) def _snake_case ( self ): __UpperCAmelCase : Dict = self.get_image_processor() __UpperCAmelCase : str = self.get_tokenizer() __UpperCAmelCase : Dict = MgpstrProcessor(tokenizer=UpperCamelCase_ , image_processor=UpperCamelCase_ ) __UpperCAmelCase : int = """test""" __UpperCAmelCase : Union[str, Any] = processor(text=UpperCamelCase_ ) __UpperCAmelCase : List[Any] = tokenizer(UpperCamelCase_ ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def _snake_case ( self ): __UpperCAmelCase : Optional[int] = self.get_image_processor() __UpperCAmelCase : Optional[int] = self.get_tokenizer() __UpperCAmelCase : Any = MgpstrProcessor(tokenizer=UpperCamelCase_ , image_processor=UpperCamelCase_ ) __UpperCAmelCase : List[str] = """test""" __UpperCAmelCase : Dict = self.prepare_image_inputs() __UpperCAmelCase : Tuple = processor(text=UpperCamelCase_ , images=UpperCamelCase_ ) self.assertListEqual(list(inputs.keys() ) , ["pixel_values", "labels"] ) # test if it raises when no input is passed with pytest.raises(UpperCamelCase_ ): processor() def _snake_case ( self ): __UpperCAmelCase : Tuple = self.get_image_processor() __UpperCAmelCase : Union[str, Any] = self.get_tokenizer() __UpperCAmelCase : Union[str, Any] = MgpstrProcessor(tokenizer=UpperCamelCase_ , image_processor=UpperCamelCase_ ) __UpperCAmelCase : Optional[Any] = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9], [3, 4, 3, 1, 1, 8, 9]] __UpperCAmelCase : Dict = processor.char_decode(UpperCamelCase_ ) __UpperCAmelCase : Optional[int] = tokenizer.batch_decode(UpperCamelCase_ ) __UpperCAmelCase : Optional[int] = [seq.replace(" " , "" ) for seq in decoded_tok] self.assertListEqual(UpperCamelCase_ , UpperCamelCase_ ) def _snake_case ( self ): __UpperCAmelCase : Optional[int] = self.get_image_processor() __UpperCAmelCase : Dict = self.get_tokenizer() __UpperCAmelCase : int = MgpstrProcessor(tokenizer=UpperCamelCase_ , image_processor=UpperCamelCase_ ) __UpperCAmelCase : str = None __UpperCAmelCase : List[str] = self.prepare_image_inputs() __UpperCAmelCase : List[Any] = processor(text=UpperCamelCase_ , images=UpperCamelCase_ ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names ) def _snake_case ( self ): __UpperCAmelCase : Optional[Any] = self.get_image_processor() __UpperCAmelCase : Optional[Any] = self.get_tokenizer() __UpperCAmelCase : int = MgpstrProcessor(tokenizer=UpperCamelCase_ , image_processor=UpperCamelCase_ ) __UpperCAmelCase : Union[str, Any] = torch.randn(1 , 27 , 38 ) __UpperCAmelCase : int = torch.randn(1 , 27 , 5_02_57 ) __UpperCAmelCase : Dict = torch.randn(1 , 27 , 3_05_22 ) __UpperCAmelCase : Union[str, Any] = processor.batch_decode([char_input, bpe_input, wp_input] ) self.assertListEqual(list(results.keys() ) , ["generated_text", "scores", "char_preds", "bpe_preds", "wp_preds"] )
168
"""simple docstring""" from __future__ import annotations from numpy import array, cos, cross, floataa, radians, sin from numpy.typing import NDArray def _snake_case ( __snake_case : float , __snake_case : float , __snake_case : bool = False ): """simple docstring""" if radian_mode: return [magnitude * cos(__snake_case ), magnitude * sin(__snake_case )] return [magnitude * cos(radians(__snake_case ) ), magnitude * sin(radians(__snake_case ) )] def _snake_case ( __snake_case : NDArray[floataa] , __snake_case : NDArray[floataa] , __snake_case : float = 10**-1 ): """simple docstring""" _lowerCamelCase : NDArray[floataa] = cross(__snake_case , __snake_case ) _lowerCamelCase : float = sum(__snake_case ) return abs(__snake_case ) < eps if __name__ == "__main__": # Test to check if it works UpperCAmelCase = array( [ polar_force(718.4, 180 - 30), polar_force(879.54, 45), polar_force(100, -90), ] ) UpperCAmelCase = array([[0, 0], [0, 0], [0, 0]]) assert in_static_equilibrium(forces, location) # Problem 1 in image_data/2D_problems.jpg UpperCAmelCase = array( [ polar_force(30 * 9.81, 15), polar_force(215, 180 - 45), polar_force(264, 90 - 30), ] ) UpperCAmelCase = array([[0, 0], [0, 0], [0, 0]]) assert in_static_equilibrium(forces, location) # Problem in image_data/2D_problems_1.jpg UpperCAmelCase = array([[0, -2000], [0, -1200], [0, 1_5600], [0, -1_2400]]) UpperCAmelCase = array([[0, 0], [6, 0], [10, 0], [12, 0]]) assert in_static_equilibrium(forces, location) import doctest doctest.testmod()
88
0
"""simple docstring""" from typing import Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature from ...image_transforms import get_image_size, pad, rescale, to_channel_dimension_format from ...image_utils import ChannelDimension, ImageInput, make_list_of_images, to_numpy_array, valid_images from ...utils import TensorType, logging A_ = logging.get_logger(__name__) class __lowerCAmelCase ( A_ ): '''simple docstring''' __lowerCamelCase : List[str] = ["pixel_values"] def __init__( self: Tuple , UpperCamelCase_: Optional[Any] = True , UpperCamelCase_: Dict = 1 / 255 , UpperCamelCase_: Any = True , UpperCamelCase_: Union[str, Any] = 8 , **UpperCamelCase_: Optional[Any] , ): super().__init__(**UpperCamelCase_ ) UpperCamelCase_ =do_rescale UpperCamelCase_ =rescale_factor UpperCamelCase_ =do_pad UpperCamelCase_ =pad_size def UpperCamelCase__ ( self: Union[str, Any] , UpperCamelCase_: Tuple , UpperCamelCase_: Optional[Any] , UpperCamelCase_: Dict = None , **UpperCamelCase_: str ): return rescale(UpperCamelCase_ , scale=UpperCamelCase_ , data_format=UpperCamelCase_ , **UpperCamelCase_ ) def UpperCamelCase__ ( self: Union[str, Any] , UpperCamelCase_: List[Any] , UpperCamelCase_: Optional[Any] , UpperCamelCase_: Dict = None ): UpperCamelCase_ =get_image_size(UpperCamelCase_ ) UpperCamelCase_ =(old_height // size + 1) * size - old_height UpperCamelCase_ =(old_width // size + 1) * size - old_width return pad(UpperCamelCase_ , ((0, pad_height), (0, pad_width)) , mode="symmetric" , data_format=UpperCamelCase_ ) def UpperCamelCase__ ( self: str , UpperCamelCase_: Any , UpperCamelCase_: Tuple = None , UpperCamelCase_: int = None , UpperCamelCase_: Tuple = None , UpperCamelCase_: Optional[int] = None , UpperCamelCase_: int = None , UpperCamelCase_: Dict = ChannelDimension.FIRST , **UpperCamelCase_: Union[str, Any] , ): UpperCamelCase_ =do_rescale if do_rescale is not None else self.do_rescale UpperCamelCase_ =rescale_factor if rescale_factor is not None else self.rescale_factor UpperCamelCase_ =do_pad if do_pad is not None else self.do_pad UpperCamelCase_ =pad_size if pad_size is not None else self.pad_size UpperCamelCase_ =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_rescale and rescale_factor is None: raise ValueError("Rescale factor must be specified if do_rescale is True." ) # All transformations expect numpy arrays. UpperCamelCase_ =[to_numpy_array(UpperCamelCase_ ) for image in images] if do_rescale: UpperCamelCase_ =[self.rescale(image=UpperCamelCase_ , scale=UpperCamelCase_ ) for image in images] if do_pad: UpperCamelCase_ =[self.pad(UpperCamelCase_ , size=UpperCamelCase_ ) for image in images] UpperCamelCase_ =[to_channel_dimension_format(UpperCamelCase_ , UpperCamelCase_ ) for image in images] UpperCamelCase_ ={"""pixel_values""": images} return BatchFeature(data=UpperCamelCase_ , tensor_type=UpperCamelCase_ )
391
"""simple docstring""" import random def _snake_case ( __snake_case : List[Any] , __snake_case : List[Any] , __snake_case : int ): """simple docstring""" _lowerCamelCase : List[str] = a[left_index] _lowerCamelCase : Dict = left_index + 1 for j in range(left_index + 1 , __snake_case ): if a[j] < pivot: _lowerCamelCase , _lowerCamelCase : List[str] = a[i], a[j] i += 1 _lowerCamelCase , _lowerCamelCase : Optional[int] = a[i - 1], a[left_index] return i - 1 def _snake_case ( __snake_case : Tuple , __snake_case : List[str] , __snake_case : List[str] ): """simple docstring""" if left < right: _lowerCamelCase : Any = random.randint(__snake_case , right - 1 ) _lowerCamelCase , _lowerCamelCase : Optional[Any] = ( a[left], a[pivot], ) # switches the pivot with the left most bound _lowerCamelCase : List[str] = partition(__snake_case , __snake_case , __snake_case ) quick_sort_random( __snake_case , __snake_case , __snake_case ) # recursive quicksort to the left of the pivot point quick_sort_random( __snake_case , pivot_index + 1 , __snake_case ) # recursive quicksort to the right of the pivot point def _snake_case ( ): """simple docstring""" _lowerCamelCase : Union[str, Any] = input("""Enter numbers separated by a comma:\n""" ).strip() _lowerCamelCase : int = [int(__snake_case ) for item in user_input.split(""",""" )] quick_sort_random(__snake_case , 0 , len(__snake_case ) ) print(__snake_case ) if __name__ == "__main__": main()
88
0
from __future__ import annotations def UpperCAmelCase_ ( __UpperCamelCase, __UpperCamelCase ): SCREAMING_SNAKE_CASE__ =[] create_all_state(1, __snake_case, __snake_case, [], __snake_case ) return result def UpperCAmelCase_ ( __UpperCamelCase, __UpperCamelCase, __UpperCamelCase, __UpperCamelCase, __UpperCamelCase, ): if level == 0: total_list.append(current_list[:] ) return for i in range(__snake_case, total_number - level + 2 ): current_list.append(__snake_case ) create_all_state(i + 1, __snake_case, level - 1, __snake_case, __snake_case ) current_list.pop() def UpperCAmelCase_ ( __UpperCamelCase ): for i in total_list: print(*__snake_case ) if __name__ == "__main__": lowerCamelCase_ = 4 lowerCamelCase_ = 2 lowerCamelCase_ = generate_all_combinations(n, k) print_all_state(total_list)
151
"""simple docstring""" import itertools import os from collections import Counter, defaultdict from concurrent.futures import ThreadPoolExecutor, as_completed import numpy as np import datasets from .execute import check_correctness UpperCAmelCase = """\ @misc{chen2021evaluating, title={Evaluating Large Language Models Trained on Code}, author={Mark Chen and Jerry Tworek and Heewoo Jun and Qiming Yuan \ and Henrique Ponde de Oliveira Pinto and Jared Kaplan and Harri Edwards \ and Yuri Burda and Nicholas Joseph and Greg Brockman and Alex Ray \ and Raul Puri and Gretchen Krueger and Michael Petrov and Heidy Khlaaf \ and Girish Sastry and Pamela Mishkin and Brooke Chan and Scott Gray \ and Nick Ryder and Mikhail Pavlov and Alethea Power and Lukasz Kaiser \ and Mohammad Bavarian and Clemens Winter and Philippe Tillet \ and Felipe Petroski Such and Dave Cummings and Matthias Plappert \ and Fotios Chantzis and Elizabeth Barnes and Ariel Herbert-Voss \ and William Hebgen Guss and Alex Nichol and Alex Paino and Nikolas Tezak \ and Jie Tang and Igor Babuschkin and Suchir Balaji and Shantanu Jain \ and William Saunders and Christopher Hesse and Andrew N. Carr \ and Jan Leike and Josh Achiam and Vedant Misra and Evan Morikawa \ and Alec Radford and Matthew Knight and Miles Brundage and Mira Murati \ and Katie Mayer and Peter Welinder and Bob McGrew and Dario Amodei \ and Sam McCandlish and Ilya Sutskever and Wojciech Zaremba}, year={2021}, eprint={2107.03374}, archivePrefix={arXiv}, primaryClass={cs.LG} } """ UpperCAmelCase = """\ This metric implements the evaluation harness for the HumanEval problem solving dataset described in the paper \"Evaluating Large Language Models Trained on Code\" (https://arxiv.org/abs/2107.03374). """ UpperCAmelCase = """ Calculates how good are predictions given some references, using certain scores Args: predictions: list of candidates to evaluate. Each candidates should be a list of strings with several code candidates to solve the problem. references: a list with a test for each prediction. Each test should evaluate the correctness of a code candidate. k: number of code candidates to consider in the evaluation (Default: [1, 10, 100]) num_workers: number of workers used to evaluate the canidate programs (Default: 4). timeout: Returns: pass_at_k: dict with pass rates for each k results: dict with granular results of each unittest Examples: >>> code_eval = datasets.load_metric(\"code_eval\") >>> test_cases = [\"assert add(2,3)==5\"] >>> candidates = [[\"def add(a,b): return a*b\", \"def add(a, b): return a+b\"]] >>> pass_at_k, results = code_eval.compute(references=test_cases, predictions=candidates, k=[1, 2]) >>> print(pass_at_k) {'pass@1': 0.5, 'pass@2': 1.0} """ UpperCAmelCase = """ ################################################################################ !!!WARNING!!! ################################################################################ The \"code_eval\" metric executes untrusted model-generated code in Python. Although it is highly unlikely that model-generated code will do something overtly malicious in response to this test suite, model-generated code may act destructively due to a lack of model capability or alignment. Users are strongly encouraged to sandbox this evaluation suite so that it does not perform destructive actions on their host or network. For more information on how OpenAI sandboxes its code, see the paper \"Evaluating Large Language Models Trained on Code\" (https://arxiv.org/abs/2107.03374). Once you have read this disclaimer and taken appropriate precautions, set the environment variable HF_ALLOW_CODE_EVAL=\"1\". Within Python you can to this with: >>> import os >>> os.environ[\"HF_ALLOW_CODE_EVAL\"] = \"1\" ################################################################################\ """ UpperCAmelCase = """The MIT License Copyright (c) OpenAI (https://openai.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.""" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION ,_KWARGS_DESCRIPTION ) class lowercase__ ( datasets.Metric ): def UpperCamelCase_ ( self) -> str: return datasets.MetricInfo( # This is the description that will appear on the metrics page. description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": datasets.Sequence(datasets.Value("""string""")), """references""": datasets.Value("""string"""), }) , homepage="""https://github.com/openai/human-eval""" , codebase_urls=["""https://github.com/openai/human-eval"""] , reference_urls=["""https://github.com/openai/human-eval"""] , license=_LICENSE , ) def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=[1, 10, 100] , SCREAMING_SNAKE_CASE=4 , SCREAMING_SNAKE_CASE=3.0) -> Union[str, Any]: if os.getenv("""HF_ALLOW_CODE_EVAL""" , 0) != "1": raise ValueError(_WARNING) if os.name == "nt": raise NotImplementedError("""This metric is currently not supported on Windows.""") with ThreadPoolExecutor(max_workers=SCREAMING_SNAKE_CASE) as executor: _lowerCamelCase : Optional[int] = [] _lowerCamelCase : Optional[int] = Counter() _lowerCamelCase : Any = 0 _lowerCamelCase : List[Any] = defaultdict(SCREAMING_SNAKE_CASE) for task_id, (candidates, test_case) in enumerate(zip(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE)): for candidate in candidates: _lowerCamelCase : Any = candidate + """\n""" + test_case _lowerCamelCase : Union[str, Any] = (test_program, timeout, task_id, completion_id[task_id]) _lowerCamelCase : List[str] = executor.submit(SCREAMING_SNAKE_CASE , *SCREAMING_SNAKE_CASE) futures.append(SCREAMING_SNAKE_CASE) completion_id[task_id] += 1 n_samples += 1 for future in as_completed(SCREAMING_SNAKE_CASE): _lowerCamelCase : int = future.result() results[result["task_id"]].append((result["""completion_id"""], result)) _lowerCamelCase , _lowerCamelCase : List[Any] = [], [] for result in results.values(): result.sort() _lowerCamelCase : List[str] = [r[1]["""passed"""] for r in result] total.append(len(SCREAMING_SNAKE_CASE)) correct.append(sum(SCREAMING_SNAKE_CASE)) _lowerCamelCase : List[Any] = np.array(SCREAMING_SNAKE_CASE) _lowerCamelCase : Union[str, Any] = np.array(SCREAMING_SNAKE_CASE) _lowerCamelCase : Union[str, Any] = k _lowerCamelCase : Optional[Any] = {F'pass@{k}': estimate_pass_at_k(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE).mean() for k in ks if (total >= k).all()} return pass_at_k, results def _snake_case ( __snake_case : List[str] , __snake_case : List[str] , __snake_case : List[str] ): """simple docstring""" def estimator(__snake_case : int , __snake_case : int , __snake_case : int ) -> float: if n - c < k: return 1.0 return 1.0 - np.prod(1.0 - k / np.arange(n - c + 1 , n + 1 ) ) if isinstance(__snake_case , __snake_case ): _lowerCamelCase : Optional[int] = itertools.repeat(__snake_case , len(__snake_case ) ) else: assert len(__snake_case ) == len(__snake_case ) _lowerCamelCase : List[str] = iter(__snake_case ) return np.array([estimator(int(__snake_case ) , int(__snake_case ) , __snake_case ) for n, c in zip(__snake_case , __snake_case )] )
88
0
"""simple docstring""" from typing import List, Optional, Union from ...image_utils import ImageInput from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class UpperCAmelCase_ ( A_): lowerCamelCase__ : List[Any] = ["image_processor", "tokenizer"] lowerCamelCase__ : Optional[Any] = "BlipImageProcessor" lowerCamelCase__ : List[str] = ("BertTokenizer", "BertTokenizerFast") def __init__( self , a , a ) -> List[str]: lowercase__ : Dict = False super().__init__(a , a ) lowercase__ : Optional[Any] = self.image_processor def __call__( self , a = None , a = None , a = True , a = False , a = None , a = None , a = 0 , a = None , a = None , a = False , a = False , a = False , a = False , a = False , a = True , a = None , **a , ) -> BatchEncoding: if images is None and text is None: raise ValueError('You have to specify either images or text.' ) # Get only text if images is None: lowercase__ : Any = self.tokenizer lowercase__ : str = self.tokenizer( text=a , add_special_tokens=a , padding=a , truncation=a , max_length=a , stride=a , pad_to_multiple_of=a , return_attention_mask=a , return_overflowing_tokens=a , return_special_tokens_mask=a , return_offsets_mapping=a , return_token_type_ids=a , return_length=a , verbose=a , return_tensors=a , **a , ) return text_encoding # add pixel_values lowercase__ : Dict = self.image_processor(a , return_tensors=a ) if text is not None: lowercase__ : Optional[Any] = self.tokenizer( text=a , add_special_tokens=a , padding=a , truncation=a , max_length=a , stride=a , pad_to_multiple_of=a , return_attention_mask=a , return_overflowing_tokens=a , return_special_tokens_mask=a , return_offsets_mapping=a , return_token_type_ids=a , return_length=a , verbose=a , return_tensors=a , **a , ) else: lowercase__ : List[Any] = None if text_encoding is not None: encoding_image_processor.update(a ) return encoding_image_processor def _UpperCAmelCase ( self , *a , **a ) -> Optional[int]: return self.tokenizer.batch_decode(*a , **a ) def _UpperCAmelCase ( self , *a , **a ) -> Optional[int]: return self.tokenizer.decode(*a , **a ) @property def _UpperCAmelCase ( self ) -> Tuple: lowercase__ : str = self.tokenizer.model_input_names lowercase__ : Optional[Any] = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
599
"""simple docstring""" from typing import Dict, List from nltk.translate import gleu_score import datasets from datasets import MetricInfo UpperCAmelCase = """\ @misc{wu2016googles, title={Google's Neural Machine Translation System: Bridging the Gap between Human and Machine Translation}, author={Yonghui Wu and Mike Schuster and Zhifeng Chen and Quoc V. Le and Mohammad Norouzi and Wolfgang Macherey and Maxim Krikun and Yuan Cao and Qin Gao and Klaus Macherey and Jeff Klingner and Apurva Shah and Melvin Johnson and Xiaobing Liu and Łukasz Kaiser and Stephan Gouws and Yoshikiyo Kato and Taku Kudo and Hideto Kazawa and Keith Stevens and George Kurian and Nishant Patil and Wei Wang and Cliff Young and Jason Smith and Jason Riesa and Alex Rudnick and Oriol Vinyals and Greg Corrado and Macduff Hughes and Jeffrey Dean}, year={2016}, eprint={1609.08144}, archivePrefix={arXiv}, primaryClass={cs.CL} } """ UpperCAmelCase = """\ The BLEU score has some undesirable properties when used for single sentences, as it was designed to be a corpus measure. We therefore use a slightly different score for our RL experiments which we call the 'GLEU score'. For the GLEU score, we record all sub-sequences of 1, 2, 3 or 4 tokens in output and target sequence (n-grams). We then compute a recall, which is the ratio of the number of matching n-grams to the number of total n-grams in the target (ground truth) sequence, and a precision, which is the ratio of the number of matching n-grams to the number of total n-grams in the generated output sequence. Then GLEU score is simply the minimum of recall and precision. This GLEU score's range is always between 0 (no matches) and 1 (all match) and it is symmetrical when switching output and target. According to our experiments, GLEU score correlates quite well with the BLEU metric on a corpus level but does not have its drawbacks for our per sentence reward objective. """ UpperCAmelCase = """\ Computes corpus-level Google BLEU (GLEU) score of translated segments against one or more references. Instead of averaging the sentence level GLEU scores (i.e. macro-average precision), Wu et al. (2016) sum up the matching tokens and the max of hypothesis and reference tokens for each sentence, then compute using the aggregate values. Args: predictions (list of str): list of translations to score. Each translation should be tokenized into a list of tokens. references (list of list of str): list of lists of references for each translation. Each reference should be tokenized into a list of tokens. min_len (int): The minimum order of n-gram this function should extract. Defaults to 1. max_len (int): The maximum order of n-gram this function should extract. Defaults to 4. Returns: 'google_bleu': google_bleu score Examples: Example 1: >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always', ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat'] >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which', ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never', ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat'] >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was', ... 'interested', 'in', 'world', 'history'] >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history', ... 'because', 'he', 'read', 'the', 'book'] >>> list_of_references = [[ref1a], [ref2a]] >>> hypotheses = [hyp1, hyp2] >>> google_bleu = datasets.load_metric(\"google_bleu\") >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references) >>> print(round(results[\"google_bleu\"], 2)) 0.44 Example 2: >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always', ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat'] >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which', ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never', ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat'] >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never', ... 'heed', 'the', 'cat', 'commands'] >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the', ... 'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions', ... 'of', 'the', 'cat'] >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was', ... 'interested', 'in', 'world', 'history'] >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history', ... 'because', 'he', 'read', 'the', 'book'] >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]] >>> hypotheses = [hyp1, hyp2] >>> google_bleu = datasets.load_metric(\"google_bleu\") >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references) >>> print(round(results[\"google_bleu\"], 2)) 0.61 Example 3: >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always', ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat'] >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which', ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never', ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat'] >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never', ... 'heed', 'the', 'cat', 'commands'] >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the', ... 'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions', ... 'of', 'the', 'cat'] >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was', ... 'interested', 'in', 'world', 'history'] >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history', ... 'because', 'he', 'read', 'the', 'book'] >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]] >>> hypotheses = [hyp1, hyp2] >>> google_bleu = datasets.load_metric(\"google_bleu\") >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references, min_len=2) >>> print(round(results[\"google_bleu\"], 2)) 0.53 Example 4: >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always', ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat'] >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which', ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never', ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat'] >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never', ... 'heed', 'the', 'cat', 'commands'] >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the', ... 'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions', ... 'of', 'the', 'cat'] >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was', ... 'interested', 'in', 'world', 'history'] >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history', ... 'because', 'he', 'read', 'the', 'book'] >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]] >>> hypotheses = [hyp1, hyp2] >>> google_bleu = datasets.load_metric(\"google_bleu\") >>> results = google_bleu.compute(predictions=hypotheses,references=list_of_references, min_len=2, max_len=6) >>> print(round(results[\"google_bleu\"], 2)) 0.4 """ @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION ,_KWARGS_DESCRIPTION ) class lowercase__ ( datasets.Metric ): def UpperCamelCase_ ( self) -> MetricInfo: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": datasets.Sequence(datasets.Value("""string""" , id="""token""") , id="""sequence"""), """references""": datasets.Sequence( datasets.Sequence(datasets.Value("""string""" , id="""token""") , id="""sequence""") , id="""references"""), }) , ) def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = 1 , SCREAMING_SNAKE_CASE = 4 , ) -> Dict[str, float]: return { "google_bleu": gleu_score.corpus_gleu( list_of_references=SCREAMING_SNAKE_CASE , hypotheses=SCREAMING_SNAKE_CASE , min_len=SCREAMING_SNAKE_CASE , max_len=SCREAMING_SNAKE_CASE) }
88
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available SCREAMING_SNAKE_CASE__ : Dict = { """configuration_squeezebert""": [ """SQUEEZEBERT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """SqueezeBertConfig""", """SqueezeBertOnnxConfig""", ], """tokenization_squeezebert""": ["""SqueezeBertTokenizer"""], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : List[Any] = ["""SqueezeBertTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : str = [ """SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST""", """SqueezeBertForMaskedLM""", """SqueezeBertForMultipleChoice""", """SqueezeBertForQuestionAnswering""", """SqueezeBertForSequenceClassification""", """SqueezeBertForTokenClassification""", """SqueezeBertModel""", """SqueezeBertModule""", """SqueezeBertPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_squeezebert import ( SQUEEZEBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, SqueezeBertConfig, SqueezeBertOnnxConfig, ) from .tokenization_squeezebert import SqueezeBertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_squeezebert_fast import SqueezeBertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_squeezebert import ( SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST, SqueezeBertForMaskedLM, SqueezeBertForMultipleChoice, SqueezeBertForQuestionAnswering, SqueezeBertForSequenceClassification, SqueezeBertForTokenClassification, SqueezeBertModel, SqueezeBertModule, SqueezeBertPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE__ : Optional[Any] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
112
"""simple docstring""" def _snake_case ( __snake_case : str , __snake_case : str ): """simple docstring""" _lowerCamelCase : str = len(__snake_case ) _lowerCamelCase : Union[str, Any] = len(__snake_case ) _lowerCamelCase : int = [[False for _ in range(m + 1 )] for _ in range(n + 1 )] _lowerCamelCase : Union[str, Any] = True for i in range(__snake_case ): for j in range(m + 1 ): if dp[i][j]: if j < m and a[i].upper() == b[j]: _lowerCamelCase : Tuple = True if a[i].islower(): _lowerCamelCase : Tuple = True return dp[n][m] if __name__ == "__main__": import doctest doctest.testmod()
88
0
from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase__ = logging.get_logger(__name__) lowerCamelCase__ = { """microsoft/markuplm-base""": """https://huggingface.co/microsoft/markuplm-base/resolve/main/config.json""", """microsoft/markuplm-large""": """https://huggingface.co/microsoft/markuplm-large/resolve/main/config.json""", } class snake_case__ ( A_): '''simple docstring''' lowerCamelCase : str = "markuplm" def __init__( self , a__=3_05_22 , a__=7_68 , a__=12 , a__=12 , a__=30_72 , a__="gelu" , a__=0.1 , a__=0.1 , a__=5_12 , a__=2 , a__=0.02 , a__=1e-12 , a__=0 , a__=0 , a__=2 , a__=2_56 , a__=10_24 , a__=2_16 , a__=10_01 , a__=32 , a__=50 , a__="absolute" , a__=True , a__=None , **a__ , ) -> int: '''simple docstring''' super().__init__( pad_token_id=a__ , bos_token_id=a__ , eos_token_id=a__ , **a__ , ) __snake_case :str = vocab_size __snake_case :Union[str, Any] = hidden_size __snake_case :List[Any] = num_hidden_layers __snake_case :Any = num_attention_heads __snake_case :Union[str, Any] = hidden_act __snake_case :Optional[int] = intermediate_size __snake_case :Optional[int] = hidden_dropout_prob __snake_case :Union[str, Any] = attention_probs_dropout_prob __snake_case :List[Any] = max_position_embeddings __snake_case :Optional[int] = type_vocab_size __snake_case :int = initializer_range __snake_case :Tuple = layer_norm_eps __snake_case :str = position_embedding_type __snake_case :List[Any] = use_cache __snake_case :Tuple = classifier_dropout # additional properties __snake_case :Tuple = max_depth __snake_case :List[Any] = max_xpath_tag_unit_embeddings __snake_case :Optional[int] = max_xpath_subs_unit_embeddings __snake_case :Tuple = tag_pad_id __snake_case :int = subs_pad_id __snake_case :Optional[int] = xpath_unit_hidden_size
455
"""simple docstring""" import warnings from ...utils import logging from .image_processing_imagegpt import ImageGPTImageProcessor UpperCAmelCase = logging.get_logger(__name__) class lowercase__ ( A_ ): def __init__( self , *SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE) -> None: warnings.warn( """The class ImageGPTFeatureExtractor is deprecated and will be removed in version 5 of Transformers.""" """ Please use ImageGPTImageProcessor instead.""" , SCREAMING_SNAKE_CASE , ) super().__init__(*SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE)
88
0
from __future__ import annotations from sys import maxsize from typing import Generic, TypeVar lowercase : List[str] = TypeVar("""T""") def A_ ( A__ ) -> Tuple: return (position - 1) // 2 def A_ ( A__ ) -> Union[str, Any]: return (2 * position) + 1 def A_ ( A__ ) -> int: return (2 * position) + 2 class A__ ( Generic[T] ): """simple docstring""" def __init__( self) -> None: '''simple docstring''' a__ : list[tuple[T, int]] = [] a__ : dict[T, int] = {} a__ : int = 0 def __len__( self) -> int: '''simple docstring''' return self.elements def __repr__( self) -> str: '''simple docstring''' return str(self.heap) def __lowercase ( self) -> bool: '''simple docstring''' return self.elements == 0 def __lowercase ( self , lowercase , lowercase) -> None: '''simple docstring''' self.heap.append((elem, weight)) a__ : Any = self.elements self.elements += 1 self._bubble_up(lowercase) def __lowercase ( self) -> T: '''simple docstring''' if self.elements > 1: self._swap_nodes(0 , self.elements - 1) a__ : Dict = self.heap.pop() del self.position_map[elem] self.elements -= 1 if self.elements > 0: a__ : Tuple = self.heap[0] self._bubble_down(lowercase) return elem def __lowercase ( self , lowercase , lowercase) -> None: '''simple docstring''' a__ : List[Any] = self.position_map[elem] a__ : Tuple = (elem, weight) if position > 0: a__ : List[str] = get_parent_position(lowercase) a__ : int = self.heap[parent_position] if parent_weight > weight: self._bubble_up(lowercase) else: self._bubble_down(lowercase) else: self._bubble_down(lowercase) def __lowercase ( self , lowercase) -> None: '''simple docstring''' a__ : int = self.position_map[elem] if curr_pos == 0: return None a__ : List[Any] = get_parent_position(lowercase) a__ : Dict = self.heap[curr_pos] a__ : List[Any] = self.heap[parent_position] if parent_weight > weight: self._swap_nodes(lowercase , lowercase) return self._bubble_up(lowercase) return None def __lowercase ( self , lowercase) -> None: '''simple docstring''' a__ : int = self.position_map[elem] a__ : Dict = self.heap[curr_pos] a__ : str = get_child_left_position(lowercase) a__ : int = get_child_right_position(lowercase) if child_left_position < self.elements and child_right_position < self.elements: a__ : Optional[Any] = self.heap[child_left_position] a__ : Dict = self.heap[child_right_position] if child_right_weight < child_left_weight and child_right_weight < weight: self._swap_nodes(lowercase , lowercase) return self._bubble_down(lowercase) if child_left_position < self.elements: a__ : Dict = self.heap[child_left_position] if child_left_weight < weight: self._swap_nodes(lowercase , lowercase) return self._bubble_down(lowercase) else: return None if child_right_position < self.elements: a__ : int = self.heap[child_right_position] if child_right_weight < weight: self._swap_nodes(lowercase , lowercase) return self._bubble_down(lowercase) return None def __lowercase ( self , lowercase , lowercase) -> None: '''simple docstring''' a__ : List[str] = self.heap[nodea_pos][0] a__ : Dict = self.heap[nodea_pos][0] a__ : List[Any] = ( self.heap[nodea_pos], self.heap[nodea_pos], ) a__ : Optional[Any] = nodea_pos a__ : int = nodea_pos class A__ ( Generic[T] ): """simple docstring""" def __init__( self) -> None: '''simple docstring''' a__ : dict[T, dict[T, int]] = {} a__ : int = 0 def __repr__( self) -> str: '''simple docstring''' return str(self.connections) def __len__( self) -> int: '''simple docstring''' return self.nodes def __lowercase ( self , lowercase) -> None: '''simple docstring''' if node not in self.connections: a__ : int = {} self.nodes += 1 def __lowercase ( self , lowercase , lowercase , lowercase) -> None: '''simple docstring''' self.add_node(lowercase) self.add_node(lowercase) a__ : List[Any] = weight a__ : int = weight def A_ ( A__ , ) -> Optional[int]: a__ : dict[T, int] = {node: maxsize for node in graph.connections} a__ : dict[T, T | None] = {node: None for node in graph.connections} a__ : MinPriorityQueue[T] = MinPriorityQueue() for node, weight in dist.items(): priority_queue.push(__snake_case , __snake_case ) if priority_queue.is_empty(): return dist, parent # initialization a__ : List[str] = priority_queue.extract_min() a__ : str = 0 for neighbour in graph.connections[node]: if dist[neighbour] > dist[node] + graph.connections[node][neighbour]: a__ : List[Any] = dist[node] + graph.connections[node][neighbour] priority_queue.update_key(__snake_case , dist[neighbour] ) a__ : Tuple = node # running prim's algorithm while not priority_queue.is_empty(): a__ : List[Any] = priority_queue.extract_min() for neighbour in graph.connections[node]: if dist[neighbour] > dist[node] + graph.connections[node][neighbour]: a__ : Tuple = dist[node] + graph.connections[node][neighbour] priority_queue.update_key(__snake_case , dist[neighbour] ) a__ : List[str] = node return dist, parent
302
"""simple docstring""" from math import isqrt, loga def _snake_case ( __snake_case : int ): """simple docstring""" _lowerCamelCase : List[str] = [True] * max_number for i in range(2 , isqrt(max_number - 1 ) + 1 ): if is_prime[i]: for j in range(i**2 , __snake_case , __snake_case ): _lowerCamelCase : Optional[int] = False return [i for i in range(2 , __snake_case ) if is_prime[i]] def _snake_case ( __snake_case : int = 800800 , __snake_case : int = 800800 ): """simple docstring""" _lowerCamelCase : Union[str, Any] = degree * loga(__snake_case ) _lowerCamelCase : Union[str, Any] = int(__snake_case ) _lowerCamelCase : Dict = calculate_prime_numbers(__snake_case ) _lowerCamelCase : Optional[int] = 0 _lowerCamelCase : Any = 0 _lowerCamelCase : Any = len(__snake_case ) - 1 while left < right: while ( prime_numbers[right] * loga(prime_numbers[left] ) + prime_numbers[left] * loga(prime_numbers[right] ) > upper_bound ): right -= 1 hybrid_integers_count += right - left left += 1 return hybrid_integers_count if __name__ == "__main__": print(f'''{solution() = }''')
88
0
from __future__ import annotations def UpperCamelCase ( snake_case__ : list[list[int]] ) -> int: UpperCamelCase : Dict = len(__snake_case ) # We need to create solution object to save path. UpperCamelCase : int = [[0 for _ in range(__snake_case )] for _ in range(__snake_case )] UpperCamelCase : str = run_maze(__snake_case , 0 , 0 , __snake_case ) if solved: print('\n'.join(str(__snake_case ) for row in solutions ) ) else: print('No solution exists!' ) return solved def UpperCamelCase ( snake_case__ : list[list[int]] , snake_case__ : int , snake_case__ : int , snake_case__ : list[list[int]] ) -> Dict: UpperCamelCase : Optional[Any] = len(__snake_case ) # Final check point. if i == j == (size - 1): UpperCamelCase : List[str] = 1 return True UpperCamelCase : List[Any] = (not i < 0) and (not j < 0) # Check lower bounds UpperCamelCase : Union[str, Any] = (i < size) and (j < size) # Check upper bounds if lower_flag and upper_flag: # check for already visited and block points. UpperCamelCase : List[str] = (not solutions[i][j]) and (not maze[i][j]) if block_flag: # check visited UpperCamelCase : Union[str, Any] = 1 # check for directions if ( run_maze(__snake_case , i + 1 , __snake_case , __snake_case ) or run_maze(__snake_case , __snake_case , j + 1 , __snake_case ) or run_maze(__snake_case , i - 1 , __snake_case , __snake_case ) or run_maze(__snake_case , __snake_case , j - 1 , __snake_case ) ): return True UpperCamelCase : str = 0 return False return False if __name__ == "__main__": import doctest doctest.testmod()
40
"""simple docstring""" import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, StableDiffusionSAGPipeline, UNetaDConditionModel, ) from diffusers.utils import slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class lowercase__ ( A_ ,A_ ,unittest.TestCase ): __UpperCAmelCase = StableDiffusionSAGPipeline __UpperCAmelCase = TEXT_TO_IMAGE_PARAMS __UpperCAmelCase = TEXT_TO_IMAGE_BATCH_PARAMS __UpperCAmelCase = TEXT_TO_IMAGE_IMAGE_PARAMS __UpperCAmelCase = TEXT_TO_IMAGE_IMAGE_PARAMS __UpperCAmelCase = False def UpperCamelCase_ ( self) -> Optional[Any]: torch.manual_seed(0) _lowerCamelCase : Dict = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , cross_attention_dim=32 , ) _lowerCamelCase : int = DDIMScheduler( beta_start=0.0_00_85 , beta_end=0.0_12 , beta_schedule="""scaled_linear""" , clip_sample=SCREAMING_SNAKE_CASE , set_alpha_to_one=SCREAMING_SNAKE_CASE , ) torch.manual_seed(0) _lowerCamelCase : Tuple = 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 , ) torch.manual_seed(0) _lowerCamelCase : Tuple = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) _lowerCamelCase : List[Any] = CLIPTextModel(SCREAMING_SNAKE_CASE) _lowerCamelCase : Tuple = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""") _lowerCamelCase : List[Any] = { """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """safety_checker""": None, """feature_extractor""": None, } return components def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=0) -> List[Any]: if str(SCREAMING_SNAKE_CASE).startswith("""mps"""): _lowerCamelCase : List[str] = torch.manual_seed(SCREAMING_SNAKE_CASE) else: _lowerCamelCase : List[str] = torch.Generator(device=SCREAMING_SNAKE_CASE).manual_seed(SCREAMING_SNAKE_CASE) _lowerCamelCase : List[Any] = { """prompt""": """.""", """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 1.0, """sag_scale""": 1.0, """output_type""": """numpy""", } return inputs def UpperCamelCase_ ( self) -> Tuple: super().test_inference_batch_single_identical(expected_max_diff=3e-3) @slow @require_torch_gpu class lowercase__ ( unittest.TestCase ): def UpperCamelCase_ ( self) -> Union[str, Any]: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCamelCase_ ( self) -> Optional[Any]: _lowerCamelCase : Any = StableDiffusionSAGPipeline.from_pretrained("""CompVis/stable-diffusion-v1-4""") _lowerCamelCase : Union[str, Any] = sag_pipe.to(SCREAMING_SNAKE_CASE) sag_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE) _lowerCamelCase : Optional[int] = """.""" _lowerCamelCase : int = torch.manual_seed(0) _lowerCamelCase : Tuple = sag_pipe( [prompt] , generator=SCREAMING_SNAKE_CASE , guidance_scale=7.5 , sag_scale=1.0 , num_inference_steps=20 , output_type="""np""") _lowerCamelCase : Dict = output.images _lowerCamelCase : Tuple = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) _lowerCamelCase : Optional[Any] = np.array([0.15_68, 0.17_38, 0.16_95, 0.16_93, 0.15_07, 0.17_05, 0.15_47, 0.17_51, 0.19_49]) assert np.abs(image_slice.flatten() - expected_slice).max() < 5e-2 def UpperCamelCase_ ( self) -> List[str]: _lowerCamelCase : Optional[Any] = StableDiffusionSAGPipeline.from_pretrained("""stabilityai/stable-diffusion-2-1-base""") _lowerCamelCase : Dict = sag_pipe.to(SCREAMING_SNAKE_CASE) sag_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE) _lowerCamelCase : Union[str, Any] = """.""" _lowerCamelCase : List[str] = torch.manual_seed(0) _lowerCamelCase : int = sag_pipe( [prompt] , generator=SCREAMING_SNAKE_CASE , guidance_scale=7.5 , sag_scale=1.0 , num_inference_steps=20 , output_type="""np""") _lowerCamelCase : Any = output.images _lowerCamelCase : List[str] = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) _lowerCamelCase : Any = np.array([0.34_59, 0.28_76, 0.25_37, 0.30_02, 0.26_71, 0.21_60, 0.30_26, 0.22_62, 0.23_71]) assert np.abs(image_slice.flatten() - expected_slice).max() < 5e-2 def UpperCamelCase_ ( self) -> List[str]: _lowerCamelCase : int = StableDiffusionSAGPipeline.from_pretrained("""stabilityai/stable-diffusion-2-1-base""") _lowerCamelCase : Optional[Any] = sag_pipe.to(SCREAMING_SNAKE_CASE) sag_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE) _lowerCamelCase : Dict = """.""" _lowerCamelCase : Union[str, Any] = torch.manual_seed(0) _lowerCamelCase : Optional[int] = sag_pipe( [prompt] , width=768 , height=512 , generator=SCREAMING_SNAKE_CASE , guidance_scale=7.5 , sag_scale=1.0 , num_inference_steps=20 , output_type="""np""" , ) _lowerCamelCase : Union[str, Any] = output.images assert image.shape == (1, 512, 768, 3)
88
0
'''simple docstring''' import argparse import os import re lowercase : int = 'src/transformers' # Pattern that looks at the indentation in a line. lowercase : Any = re.compile(R'^(\s*)\S') # Pattern that matches `"key":" and puts `key` in group 0. lowercase : str = re.compile(R'^\s*\"([^\"]+)\":') # Pattern that matches `_import_structure["key"]` and puts `key` in group 0. lowercase : List[Any] = re.compile(R'^\s*_import_structure\[\"([^\"]+)\"\]') # Pattern that matches `"key",` and puts `key` in group 0. lowercase : int = re.compile(R'^\s*\"([^\"]+)\",\s*$') # Pattern that matches any `[stuff]` and puts `stuff` in group 0. lowercase : Union[str, Any] = re.compile(R'\[([^\]]+)\]') def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' A : Tuple = _re_indent.search(__snake_case ) return "" if search is None else search.groups()[0] def lowerCAmelCase_ ( snake_case__ , snake_case__="" , snake_case__=None , snake_case__=None ): '''simple docstring''' A : List[str] = 0 A : Tuple = code.split('''\n''' ) if start_prompt is not None: while not lines[index].startswith(__snake_case ): index += 1 A : Union[str, Any] = ["""\n""".join(lines[:index] )] else: A : Any = [] # We split into blocks until we get to the `end_prompt` (or the end of the block). A : Optional[int] = [lines[index]] index += 1 while index < len(__snake_case ) and (end_prompt is None or not lines[index].startswith(__snake_case )): if len(lines[index] ) > 0 and get_indent(lines[index] ) == indent_level: if len(__snake_case ) > 0 and get_indent(current_block[-1] ).startswith(indent_level + ''' ''' ): current_block.append(lines[index] ) blocks.append('''\n'''.join(__snake_case ) ) if index < len(__snake_case ) - 1: A : Optional[int] = [lines[index + 1]] index += 1 else: A : int = [] else: blocks.append('''\n'''.join(__snake_case ) ) A : Dict = [lines[index]] else: current_block.append(lines[index] ) index += 1 # Adds current block if it's nonempty. if len(__snake_case ) > 0: blocks.append('''\n'''.join(__snake_case ) ) # Add final block after end_prompt if provided. if end_prompt is not None and index < len(__snake_case ): blocks.append('''\n'''.join(lines[index:] ) ) return blocks def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' def _inner(snake_case__ ): return key(__snake_case ).lower().replace('''_''' , '''''' ) return _inner def lowerCAmelCase_ ( snake_case__ , snake_case__=None ): '''simple docstring''' def noop(snake_case__ ): return x if key is None: A : Dict = noop # Constants are all uppercase, they go first. A : List[Any] = [obj for obj in objects if key(__snake_case ).isupper()] # Classes are not all uppercase but start with a capital, they go second. A : Any = [obj for obj in objects if key(__snake_case )[0].isupper() and not key(__snake_case ).isupper()] # Functions begin with a lowercase, they go last. A : Union[str, Any] = [obj for obj in objects if not key(__snake_case )[0].isupper()] A : List[Any] = ignore_underscore(__snake_case ) return sorted(__snake_case , key=__snake_case ) + sorted(__snake_case , key=__snake_case ) + sorted(__snake_case , key=__snake_case ) def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' def _replace(snake_case__ ): A : Any = match.groups()[0] if "," not in imports: return F'[{imports}]' A : Optional[Any] = [part.strip().replace('''\"''' , '''''' ) for part in imports.split(''',''' )] # We will have a final empty element if the line finished with a comma. if len(keys[-1] ) == 0: A : Dict = keys[:-1] return "[" + ", ".join([F'"{k}"' for k in sort_objects(__snake_case )] ) + "]" A : Tuple = import_statement.split('''\n''' ) if len(__snake_case ) > 3: # Here we have to sort internal imports that are on several lines (one per name): # key: [ # "object1", # "object2", # ... # ] # We may have to ignore one or two lines on each side. A : Union[str, Any] = 2 if lines[1].strip() == """[""" else 1 A : Optional[Any] = [(i, _re_strip_line.search(__snake_case ).groups()[0]) for i, line in enumerate(lines[idx:-idx] )] A : Optional[Any] = sort_objects(__snake_case , key=lambda snake_case__ : x[1] ) A : str = [lines[x[0] + idx] for x in sorted_indices] return "\n".join(lines[:idx] + sorted_lines + lines[-idx:] ) elif len(__snake_case ) == 3: # Here we have to sort internal imports that are on one separate line: # key: [ # "object1", "object2", ... # ] if _re_bracket_content.search(lines[1] ) is not None: A : str = _re_bracket_content.sub(_replace , lines[1] ) else: A : Optional[Any] = [part.strip().replace('''\"''' , '''''' ) for part in lines[1].split(''',''' )] # We will have a final empty element if the line finished with a comma. if len(keys[-1] ) == 0: A : str = keys[:-1] A : Optional[int] = get_indent(lines[1] ) + """, """.join([F'"{k}"' for k in sort_objects(__snake_case )] ) return "\n".join(__snake_case ) else: # Finally we have to deal with imports fitting on one line A : Optional[Any] = _re_bracket_content.sub(_replace , __snake_case ) return import_statement def lowerCAmelCase_ ( snake_case__ , snake_case__=True ): '''simple docstring''' with open(__snake_case , encoding='''utf-8''' ) as f: A : Any = f.read() if "_import_structure" not in code: return # Blocks of indent level 0 A : Optional[int] = split_code_in_indented_blocks( __snake_case , start_prompt='''_import_structure = {''' , end_prompt='''if TYPE_CHECKING:''' ) # We ignore block 0 (everything untils start_prompt) and the last block (everything after end_prompt). for block_idx in range(1 , len(__snake_case ) - 1 ): # Check if the block contains some `_import_structure`s thingy to sort. A : Union[str, Any] = main_blocks[block_idx] A : List[Any] = block.split('''\n''' ) # Get to the start of the imports. A : List[str] = 0 while line_idx < len(__snake_case ) and "_import_structure" not in block_lines[line_idx]: # Skip dummy import blocks if "import dummy" in block_lines[line_idx]: A : Tuple = len(__snake_case ) else: line_idx += 1 if line_idx >= len(__snake_case ): continue # Ignore beginning and last line: they don't contain anything. A : List[str] = """\n""".join(block_lines[line_idx:-1] ) A : Union[str, Any] = get_indent(block_lines[1] ) # Slit the internal block into blocks of indent level 1. A : Optional[int] = split_code_in_indented_blocks(__snake_case , indent_level=__snake_case ) # We have two categories of import key: list or _import_structure[key].append/extend A : List[str] = _re_direct_key if """_import_structure = {""" in block_lines[0] else _re_indirect_key # Grab the keys, but there is a trap: some lines are empty or just comments. A : List[Any] = [(pattern.search(__snake_case ).groups()[0] if pattern.search(__snake_case ) is not None else None) for b in internal_blocks] # We only sort the lines with a key. A : Union[str, Any] = [(i, key) for i, key in enumerate(__snake_case ) if key is not None] A : Optional[Any] = [x[0] for x in sorted(__snake_case , key=lambda snake_case__ : x[1] )] # We reorder the blocks by leaving empty lines/comments as they were and reorder the rest. A : Tuple = 0 A : Dict = [] for i in range(len(__snake_case ) ): if keys[i] is None: reorderded_blocks.append(internal_blocks[i] ) else: A : Any = sort_objects_in_import(internal_blocks[sorted_indices[count]] ) reorderded_blocks.append(__snake_case ) count += 1 # And we put our main block back together with its first and last line. A : Tuple = """\n""".join(block_lines[:line_idx] + reorderded_blocks + [block_lines[-1]] ) if code != "\n".join(__snake_case ): if check_only: return True else: print(F'Overwriting {file}.' ) with open(__snake_case , '''w''' , encoding='''utf-8''' ) as f: f.write('''\n'''.join(__snake_case ) ) def lowerCAmelCase_ ( snake_case__=True ): '''simple docstring''' A : Dict = [] for root, _, files in os.walk(__snake_case ): if "__init__.py" in files: A : int = sort_imports(os.path.join(__snake_case , '''__init__.py''' ) , check_only=__snake_case ) if result: A : str = [os.path.join(__snake_case , '''__init__.py''' )] if len(__snake_case ) > 0: raise ValueError(F'Would overwrite {len(__snake_case )} files, run `make style`.' ) if __name__ == "__main__": lowercase : List[Any] = argparse.ArgumentParser() parser.add_argument('--check_only', action='store_true', help='Whether to only check or fix style.') lowercase : List[str] = parser.parse_args() sort_imports_in_all_inits(check_only=args.check_only)
634
"""simple docstring""" import inspect import unittest import numpy as np from tests.test_modeling_common import floats_tensor from transformers import MaskaFormerConfig, is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MaskaFormerForUniversalSegmentation, MaskaFormerModel if is_vision_available(): from transformers import MaskaFormerImageProcessor if is_vision_available(): from PIL import Image class lowercase__ : def __init__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=2 , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=False , SCREAMING_SNAKE_CASE=10 , SCREAMING_SNAKE_CASE=3 , SCREAMING_SNAKE_CASE=32 * 8 , SCREAMING_SNAKE_CASE=32 * 8 , SCREAMING_SNAKE_CASE=4 , SCREAMING_SNAKE_CASE=64 , ) -> Optional[int]: _lowerCamelCase : List[str] = parent _lowerCamelCase : List[Any] = batch_size _lowerCamelCase : Tuple = is_training _lowerCamelCase : Tuple = use_auxiliary_loss _lowerCamelCase : Any = num_queries _lowerCamelCase : List[str] = num_channels _lowerCamelCase : List[str] = min_size _lowerCamelCase : Tuple = max_size _lowerCamelCase : str = num_labels _lowerCamelCase : Any = hidden_dim _lowerCamelCase : Dict = hidden_dim def UpperCamelCase_ ( self) -> List[str]: _lowerCamelCase : Union[str, Any] = floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size]).to( SCREAMING_SNAKE_CASE) _lowerCamelCase : List[Any] = torch.ones([self.batch_size, self.min_size, self.max_size] , device=SCREAMING_SNAKE_CASE) _lowerCamelCase : Union[str, Any] = ( torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size] , device=SCREAMING_SNAKE_CASE) > 0.5 ).float() _lowerCamelCase : Dict = (torch.rand((self.batch_size, self.num_labels) , device=SCREAMING_SNAKE_CASE) > 0.5).long() _lowerCamelCase : Optional[int] = self.get_config() return config, pixel_values, pixel_mask, mask_labels, class_labels def UpperCamelCase_ ( self) -> str: _lowerCamelCase : List[str] = MaskaFormerConfig( hidden_size=self.hidden_dim , ) _lowerCamelCase : Any = self.num_queries _lowerCamelCase : int = self.num_labels _lowerCamelCase : int = [1, 1, 1, 1] _lowerCamelCase : Any = self.num_channels _lowerCamelCase : Optional[Any] = 64 _lowerCamelCase : str = 128 _lowerCamelCase : Optional[Any] = self.hidden_dim _lowerCamelCase : Any = self.hidden_dim _lowerCamelCase : List[Any] = self.hidden_dim return config def UpperCamelCase_ ( self) -> Any: _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase : List[str] = self.prepare_config_and_inputs() _lowerCamelCase : str = {"""pixel_values""": pixel_values, """pixel_mask""": pixel_mask} return config, inputs_dict def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) -> Optional[int]: _lowerCamelCase : str = output.encoder_hidden_states _lowerCamelCase : int = output.pixel_decoder_hidden_states _lowerCamelCase : Optional[int] = output.transformer_decoder_hidden_states self.parent.assertTrue(len(SCREAMING_SNAKE_CASE) , len(config.backbone_config.depths)) self.parent.assertTrue(len(SCREAMING_SNAKE_CASE) , len(config.backbone_config.depths)) self.parent.assertTrue(len(SCREAMING_SNAKE_CASE) , config.decoder_layers) def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=False) -> List[str]: with torch.no_grad(): _lowerCamelCase : Optional[int] = MaskaFormerModel(config=SCREAMING_SNAKE_CASE) model.to(SCREAMING_SNAKE_CASE) model.eval() _lowerCamelCase : Optional[int] = model(pixel_values=SCREAMING_SNAKE_CASE , pixel_mask=SCREAMING_SNAKE_CASE) _lowerCamelCase : List[str] = model(SCREAMING_SNAKE_CASE , output_hidden_states=SCREAMING_SNAKE_CASE) self.parent.assertEqual( output.transformer_decoder_last_hidden_state.shape , (self.batch_size, self.num_queries, self.hidden_dim) , ) # let's ensure the other two hidden state exists self.parent.assertTrue(output.pixel_decoder_last_hidden_state is not None) self.parent.assertTrue(output.encoder_last_hidden_state is not None) if output_hidden_states: self.check_output_hidden_state(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) -> str: _lowerCamelCase : str = MaskaFormerForUniversalSegmentation(config=SCREAMING_SNAKE_CASE) model.to(SCREAMING_SNAKE_CASE) model.eval() def comm_check_on_output(SCREAMING_SNAKE_CASE): # let's still check that all the required stuff is there self.parent.assertTrue(result.transformer_decoder_last_hidden_state is not None) self.parent.assertTrue(result.pixel_decoder_last_hidden_state is not None) self.parent.assertTrue(result.encoder_last_hidden_state is not None) # okay, now we need to check the logits shape # due to the encoder compression, masks have a //4 spatial size self.parent.assertEqual( result.masks_queries_logits.shape , (self.batch_size, self.num_queries, self.min_size // 4, self.max_size // 4) , ) # + 1 for null class self.parent.assertEqual( result.class_queries_logits.shape , (self.batch_size, self.num_queries, self.num_labels + 1)) with torch.no_grad(): _lowerCamelCase : List[Any] = model(pixel_values=SCREAMING_SNAKE_CASE , pixel_mask=SCREAMING_SNAKE_CASE) _lowerCamelCase : List[Any] = model(SCREAMING_SNAKE_CASE) comm_check_on_output(SCREAMING_SNAKE_CASE) _lowerCamelCase : Optional[Any] = model( pixel_values=SCREAMING_SNAKE_CASE , pixel_mask=SCREAMING_SNAKE_CASE , mask_labels=SCREAMING_SNAKE_CASE , class_labels=SCREAMING_SNAKE_CASE) comm_check_on_output(SCREAMING_SNAKE_CASE) self.parent.assertTrue(result.loss is not None) self.parent.assertEqual(result.loss.shape , torch.Size([1])) @require_torch class lowercase__ ( A_ ,A_ ,unittest.TestCase ): __UpperCAmelCase = (MaskaFormerModel, MaskaFormerForUniversalSegmentation) if is_torch_available() else () __UpperCAmelCase = {'''feature-extraction''': MaskaFormerModel} if is_torch_available() else {} __UpperCAmelCase = False __UpperCAmelCase = False __UpperCAmelCase = False __UpperCAmelCase = False def UpperCamelCase_ ( self) -> Dict: _lowerCamelCase : Optional[int] = MaskaFormerModelTester(self) _lowerCamelCase : Union[str, Any] = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE , has_text_modality=SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self) -> List[str]: self.config_tester.run_common_tests() def UpperCamelCase_ ( self) -> int: _lowerCamelCase , _lowerCamelCase : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskaformer_model(SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE , output_hidden_states=SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self) -> Tuple: _lowerCamelCase : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_maskaformer_instance_segmentation_head_model(*SCREAMING_SNAKE_CASE) @unittest.skip(reason="""Mask2Former does not use inputs_embeds""") def UpperCamelCase_ ( self) -> Optional[int]: pass @unittest.skip(reason="""Mask2Former does not have a get_input_embeddings method""") def UpperCamelCase_ ( self) -> Tuple: pass @unittest.skip(reason="""Mask2Former is not a generative model""") def UpperCamelCase_ ( self) -> List[Any]: pass @unittest.skip(reason="""Mask2Former does not use token embeddings""") def UpperCamelCase_ ( self) -> Any: pass @require_torch_multi_gpu @unittest.skip( reason="""Mask2Former has some layers using `add_module` which doesn't work well with `nn.DataParallel`""") def UpperCamelCase_ ( self) -> Dict: pass @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""") def UpperCamelCase_ ( self) -> Optional[int]: pass def UpperCamelCase_ ( self) -> Optional[Any]: _lowerCamelCase , _lowerCamelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _lowerCamelCase : Dict = model_class(SCREAMING_SNAKE_CASE) _lowerCamelCase : Any = inspect.signature(model.forward) # signature.parameters is an OrderedDict => so arg_names order is deterministic _lowerCamelCase : str = [*signature.parameters.keys()] _lowerCamelCase : int = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , SCREAMING_SNAKE_CASE) @slow def UpperCamelCase_ ( self) -> Optional[int]: for model_name in ["facebook/mask2former-swin-small-coco-instance"]: _lowerCamelCase : Optional[int] = MaskaFormerModel.from_pretrained(SCREAMING_SNAKE_CASE) self.assertIsNotNone(SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self) -> Optional[Any]: _lowerCamelCase : Dict = (self.model_tester.min_size,) * 2 _lowerCamelCase : str = { """pixel_values""": torch.randn((2, 3, *size) , device=SCREAMING_SNAKE_CASE), """mask_labels""": torch.randn((2, 10, *size) , device=SCREAMING_SNAKE_CASE), """class_labels""": torch.zeros(2 , 10 , device=SCREAMING_SNAKE_CASE).long(), } _lowerCamelCase : List[str] = self.model_tester.get_config() _lowerCamelCase : Tuple = MaskaFormerForUniversalSegmentation(SCREAMING_SNAKE_CASE).to(SCREAMING_SNAKE_CASE) _lowerCamelCase : Union[str, Any] = model(**SCREAMING_SNAKE_CASE) self.assertTrue(outputs.loss is not None) def UpperCamelCase_ ( self) -> Tuple: _lowerCamelCase , _lowerCamelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskaformer_model(SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE , output_hidden_states=SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self) -> Optional[int]: _lowerCamelCase , _lowerCamelCase : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _lowerCamelCase : str = model_class(SCREAMING_SNAKE_CASE).to(SCREAMING_SNAKE_CASE) _lowerCamelCase : Union[str, Any] = model(**SCREAMING_SNAKE_CASE , output_attentions=SCREAMING_SNAKE_CASE) self.assertTrue(outputs.attentions is not None) def UpperCamelCase_ ( self) -> Optional[Any]: if not self.model_tester.is_training: return _lowerCamelCase : Any = self.all_model_classes[1] _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs() _lowerCamelCase : List[Any] = model_class(SCREAMING_SNAKE_CASE) model.to(SCREAMING_SNAKE_CASE) model.train() _lowerCamelCase : int = model(SCREAMING_SNAKE_CASE , mask_labels=SCREAMING_SNAKE_CASE , class_labels=SCREAMING_SNAKE_CASE).loss loss.backward() def UpperCamelCase_ ( self) -> Optional[Any]: _lowerCamelCase : Any = self.all_model_classes[1] _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase : int = self.model_tester.prepare_config_and_inputs() _lowerCamelCase : int = True _lowerCamelCase : Optional[Any] = True _lowerCamelCase : str = model_class(SCREAMING_SNAKE_CASE).to(SCREAMING_SNAKE_CASE) model.train() _lowerCamelCase : List[Any] = model(SCREAMING_SNAKE_CASE , mask_labels=SCREAMING_SNAKE_CASE , class_labels=SCREAMING_SNAKE_CASE) _lowerCamelCase : Tuple = outputs.encoder_hidden_states[0] encoder_hidden_states.retain_grad() _lowerCamelCase : int = outputs.pixel_decoder_hidden_states[0] pixel_decoder_hidden_states.retain_grad() _lowerCamelCase : str = outputs.transformer_decoder_hidden_states[0] transformer_decoder_hidden_states.retain_grad() _lowerCamelCase : Optional[int] = outputs.attentions[0] attentions.retain_grad() outputs.loss.backward(retain_graph=SCREAMING_SNAKE_CASE) self.assertIsNotNone(encoder_hidden_states.grad) self.assertIsNotNone(pixel_decoder_hidden_states.grad) self.assertIsNotNone(transformer_decoder_hidden_states.grad) self.assertIsNotNone(attentions.grad) UpperCAmelCase = 1e-4 def _snake_case ( ): """simple docstring""" _lowerCamelCase : List[str] = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_vision @slow class lowercase__ ( unittest.TestCase ): @cached_property def UpperCamelCase_ ( self) -> int: return "facebook/mask2former-swin-small-coco-instance" @cached_property def UpperCamelCase_ ( self) -> Union[str, Any]: return MaskaFormerImageProcessor.from_pretrained(self.model_checkpoints) if is_vision_available() else None def UpperCamelCase_ ( self) -> Optional[Any]: _lowerCamelCase : Tuple = MaskaFormerModel.from_pretrained(self.model_checkpoints).to(SCREAMING_SNAKE_CASE) _lowerCamelCase : str = self.default_image_processor _lowerCamelCase : List[str] = prepare_img() _lowerCamelCase : Union[str, Any] = image_processor(SCREAMING_SNAKE_CASE , return_tensors="""pt""").to(SCREAMING_SNAKE_CASE) _lowerCamelCase : Union[str, Any] = inputs["""pixel_values"""].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0) # check size self.assertEqual(SCREAMING_SNAKE_CASE , (1, 3, 384, 384)) with torch.no_grad(): _lowerCamelCase : Dict = model(**SCREAMING_SNAKE_CASE) _lowerCamelCase : List[Any] = torch.tensor( [[-0.27_90, -1.07_17, -1.16_68], [-0.51_28, -0.31_28, -0.49_87], [-0.58_32, 0.19_71, -0.01_97]]).to(SCREAMING_SNAKE_CASE) self.assertTrue( torch.allclose( outputs.encoder_last_hidden_state[0, 0, :3, :3] , SCREAMING_SNAKE_CASE , atol=SCREAMING_SNAKE_CASE)) _lowerCamelCase : Any = torch.tensor( [[0.89_73, 1.18_47, 1.17_76], [1.19_34, 1.50_40, 1.51_28], [1.11_53, 1.44_86, 1.49_51]]).to(SCREAMING_SNAKE_CASE) self.assertTrue( torch.allclose( outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3] , SCREAMING_SNAKE_CASE , atol=SCREAMING_SNAKE_CASE)) _lowerCamelCase : Dict = torch.tensor( [[2.11_52, 1.70_00, -0.86_03], [1.58_08, 1.80_04, -0.93_53], [1.60_43, 1.74_95, -0.59_99]]).to(SCREAMING_SNAKE_CASE) self.assertTrue( torch.allclose( outputs.transformer_decoder_last_hidden_state[0, :3, :3] , SCREAMING_SNAKE_CASE , atol=SCREAMING_SNAKE_CASE)) def UpperCamelCase_ ( self) -> Any: _lowerCamelCase : Optional[Any] = MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints).to(SCREAMING_SNAKE_CASE).eval() _lowerCamelCase : Optional[Any] = self.default_image_processor _lowerCamelCase : Any = prepare_img() _lowerCamelCase : Dict = image_processor(SCREAMING_SNAKE_CASE , return_tensors="""pt""").to(SCREAMING_SNAKE_CASE) _lowerCamelCase : Union[str, Any] = inputs["""pixel_values"""].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0) # check size self.assertEqual(SCREAMING_SNAKE_CASE , (1, 3, 384, 384)) with torch.no_grad(): _lowerCamelCase : List[str] = model(**SCREAMING_SNAKE_CASE) # masks_queries_logits _lowerCamelCase : str = outputs.masks_queries_logits self.assertEqual( masks_queries_logits.shape , (1, model.config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4)) _lowerCamelCase : Any = [ [-8.78_39, -9.00_56, -8.81_21], [-7.41_04, -7.03_13, -6.54_01], [-6.61_05, -6.34_27, -6.46_75], ] _lowerCamelCase : List[Any] = torch.tensor(SCREAMING_SNAKE_CASE).to(SCREAMING_SNAKE_CASE) self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , SCREAMING_SNAKE_CASE , atol=SCREAMING_SNAKE_CASE)) # class_queries_logits _lowerCamelCase : List[str] = outputs.class_queries_logits self.assertEqual(class_queries_logits.shape , (1, model.config.num_queries, model.config.num_labels + 1)) _lowerCamelCase : Optional[Any] = torch.tensor( [ [1.83_24, -8.08_35, -4.19_22], [0.84_50, -9.00_50, -3.60_53], [0.30_45, -7.72_93, -3.02_75], ]).to(SCREAMING_SNAKE_CASE) self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , SCREAMING_SNAKE_CASE , atol=SCREAMING_SNAKE_CASE)) def UpperCamelCase_ ( self) -> int: _lowerCamelCase : Tuple = MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints).to(SCREAMING_SNAKE_CASE).eval() _lowerCamelCase : str = self.default_image_processor _lowerCamelCase : Tuple = image_processor( [np.zeros((3, 800, 1333)), np.zeros((3, 800, 1333))] , segmentation_maps=[np.zeros((384, 384)).astype(np.floataa), np.zeros((384, 384)).astype(np.floataa)] , return_tensors="""pt""" , ) _lowerCamelCase : Optional[Any] = inputs["""pixel_values"""].to(SCREAMING_SNAKE_CASE) _lowerCamelCase : Any = [el.to(SCREAMING_SNAKE_CASE) for el in inputs["""mask_labels"""]] _lowerCamelCase : Union[str, Any] = [el.to(SCREAMING_SNAKE_CASE) for el in inputs["""class_labels"""]] with torch.no_grad(): _lowerCamelCase : Any = model(**SCREAMING_SNAKE_CASE) self.assertTrue(outputs.loss is not None)
88
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) UpperCAmelCase_ : Optional[int] = { '''configuration_vision_encoder_decoder''': ['''VisionEncoderDecoderConfig''', '''VisionEncoderDecoderOnnxConfig'''] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ : Optional[Any] = ['''VisionEncoderDecoderModel'''] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ : Union[str, Any] = ['''TFVisionEncoderDecoderModel'''] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ : Tuple = ['''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 UpperCAmelCase_ : Union[str, Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
24
"""simple docstring""" from collections import OrderedDict from ...utils import logging from .auto_factory import _BaseAutoModelClass, _LazyAutoMapping, auto_class_update from .configuration_auto import CONFIG_MAPPING_NAMES UpperCAmelCase = logging.get_logger(__name__) UpperCAmelCase = OrderedDict( [ # Base model mapping ("""albert""", """FlaxAlbertModel"""), ("""bart""", """FlaxBartModel"""), ("""beit""", """FlaxBeitModel"""), ("""bert""", """FlaxBertModel"""), ("""big_bird""", """FlaxBigBirdModel"""), ("""blenderbot""", """FlaxBlenderbotModel"""), ("""blenderbot-small""", """FlaxBlenderbotSmallModel"""), ("""clip""", """FlaxCLIPModel"""), ("""distilbert""", """FlaxDistilBertModel"""), ("""electra""", """FlaxElectraModel"""), ("""gpt-sw3""", """FlaxGPT2Model"""), ("""gpt2""", """FlaxGPT2Model"""), ("""gpt_neo""", """FlaxGPTNeoModel"""), ("""gptj""", """FlaxGPTJModel"""), ("""longt5""", """FlaxLongT5Model"""), ("""marian""", """FlaxMarianModel"""), ("""mbart""", """FlaxMBartModel"""), ("""mt5""", """FlaxMT5Model"""), ("""opt""", """FlaxOPTModel"""), ("""pegasus""", """FlaxPegasusModel"""), ("""regnet""", """FlaxRegNetModel"""), ("""resnet""", """FlaxResNetModel"""), ("""roberta""", """FlaxRobertaModel"""), ("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormModel"""), ("""roformer""", """FlaxRoFormerModel"""), ("""t5""", """FlaxT5Model"""), ("""vision-text-dual-encoder""", """FlaxVisionTextDualEncoderModel"""), ("""vit""", """FlaxViTModel"""), ("""wav2vec2""", """FlaxWav2Vec2Model"""), ("""whisper""", """FlaxWhisperModel"""), ("""xglm""", """FlaxXGLMModel"""), ("""xlm-roberta""", """FlaxXLMRobertaModel"""), ] ) UpperCAmelCase = OrderedDict( [ # Model for pre-training mapping ("""albert""", """FlaxAlbertForPreTraining"""), ("""bart""", """FlaxBartForConditionalGeneration"""), ("""bert""", """FlaxBertForPreTraining"""), ("""big_bird""", """FlaxBigBirdForPreTraining"""), ("""electra""", """FlaxElectraForPreTraining"""), ("""longt5""", """FlaxLongT5ForConditionalGeneration"""), ("""mbart""", """FlaxMBartForConditionalGeneration"""), ("""mt5""", """FlaxMT5ForConditionalGeneration"""), ("""roberta""", """FlaxRobertaForMaskedLM"""), ("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormForMaskedLM"""), ("""roformer""", """FlaxRoFormerForMaskedLM"""), ("""t5""", """FlaxT5ForConditionalGeneration"""), ("""wav2vec2""", """FlaxWav2Vec2ForPreTraining"""), ("""whisper""", """FlaxWhisperForConditionalGeneration"""), ("""xlm-roberta""", """FlaxXLMRobertaForMaskedLM"""), ] ) UpperCAmelCase = OrderedDict( [ # Model for Masked LM mapping ("""albert""", """FlaxAlbertForMaskedLM"""), ("""bart""", """FlaxBartForConditionalGeneration"""), ("""bert""", """FlaxBertForMaskedLM"""), ("""big_bird""", """FlaxBigBirdForMaskedLM"""), ("""distilbert""", """FlaxDistilBertForMaskedLM"""), ("""electra""", """FlaxElectraForMaskedLM"""), ("""mbart""", """FlaxMBartForConditionalGeneration"""), ("""roberta""", """FlaxRobertaForMaskedLM"""), ("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormForMaskedLM"""), ("""roformer""", """FlaxRoFormerForMaskedLM"""), ("""xlm-roberta""", """FlaxXLMRobertaForMaskedLM"""), ] ) UpperCAmelCase = OrderedDict( [ # Model for Seq2Seq Causal LM mapping ("""bart""", """FlaxBartForConditionalGeneration"""), ("""blenderbot""", """FlaxBlenderbotForConditionalGeneration"""), ("""blenderbot-small""", """FlaxBlenderbotSmallForConditionalGeneration"""), ("""encoder-decoder""", """FlaxEncoderDecoderModel"""), ("""longt5""", """FlaxLongT5ForConditionalGeneration"""), ("""marian""", """FlaxMarianMTModel"""), ("""mbart""", """FlaxMBartForConditionalGeneration"""), ("""mt5""", """FlaxMT5ForConditionalGeneration"""), ("""pegasus""", """FlaxPegasusForConditionalGeneration"""), ("""t5""", """FlaxT5ForConditionalGeneration"""), ] ) UpperCAmelCase = OrderedDict( [ # Model for Image-classsification ("""beit""", """FlaxBeitForImageClassification"""), ("""regnet""", """FlaxRegNetForImageClassification"""), ("""resnet""", """FlaxResNetForImageClassification"""), ("""vit""", """FlaxViTForImageClassification"""), ] ) UpperCAmelCase = OrderedDict( [ ("""vision-encoder-decoder""", """FlaxVisionEncoderDecoderModel"""), ] ) UpperCAmelCase = OrderedDict( [ # Model for Causal LM mapping ("""bart""", """FlaxBartForCausalLM"""), ("""bert""", """FlaxBertForCausalLM"""), ("""big_bird""", """FlaxBigBirdForCausalLM"""), ("""electra""", """FlaxElectraForCausalLM"""), ("""gpt-sw3""", """FlaxGPT2LMHeadModel"""), ("""gpt2""", """FlaxGPT2LMHeadModel"""), ("""gpt_neo""", """FlaxGPTNeoForCausalLM"""), ("""gptj""", """FlaxGPTJForCausalLM"""), ("""opt""", """FlaxOPTForCausalLM"""), ("""roberta""", """FlaxRobertaForCausalLM"""), ("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormForCausalLM"""), ("""xglm""", """FlaxXGLMForCausalLM"""), ("""xlm-roberta""", """FlaxXLMRobertaForCausalLM"""), ] ) UpperCAmelCase = OrderedDict( [ # Model for Sequence Classification mapping ("""albert""", """FlaxAlbertForSequenceClassification"""), ("""bart""", """FlaxBartForSequenceClassification"""), ("""bert""", """FlaxBertForSequenceClassification"""), ("""big_bird""", """FlaxBigBirdForSequenceClassification"""), ("""distilbert""", """FlaxDistilBertForSequenceClassification"""), ("""electra""", """FlaxElectraForSequenceClassification"""), ("""mbart""", """FlaxMBartForSequenceClassification"""), ("""roberta""", """FlaxRobertaForSequenceClassification"""), ("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormForSequenceClassification"""), ("""roformer""", """FlaxRoFormerForSequenceClassification"""), ("""xlm-roberta""", """FlaxXLMRobertaForSequenceClassification"""), ] ) UpperCAmelCase = OrderedDict( [ # Model for Question Answering mapping ("""albert""", """FlaxAlbertForQuestionAnswering"""), ("""bart""", """FlaxBartForQuestionAnswering"""), ("""bert""", """FlaxBertForQuestionAnswering"""), ("""big_bird""", """FlaxBigBirdForQuestionAnswering"""), ("""distilbert""", """FlaxDistilBertForQuestionAnswering"""), ("""electra""", """FlaxElectraForQuestionAnswering"""), ("""mbart""", """FlaxMBartForQuestionAnswering"""), ("""roberta""", """FlaxRobertaForQuestionAnswering"""), ("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormForQuestionAnswering"""), ("""roformer""", """FlaxRoFormerForQuestionAnswering"""), ("""xlm-roberta""", """FlaxXLMRobertaForQuestionAnswering"""), ] ) UpperCAmelCase = OrderedDict( [ # Model for Token Classification mapping ("""albert""", """FlaxAlbertForTokenClassification"""), ("""bert""", """FlaxBertForTokenClassification"""), ("""big_bird""", """FlaxBigBirdForTokenClassification"""), ("""distilbert""", """FlaxDistilBertForTokenClassification"""), ("""electra""", """FlaxElectraForTokenClassification"""), ("""roberta""", """FlaxRobertaForTokenClassification"""), ("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormForTokenClassification"""), ("""roformer""", """FlaxRoFormerForTokenClassification"""), ("""xlm-roberta""", """FlaxXLMRobertaForTokenClassification"""), ] ) UpperCAmelCase = OrderedDict( [ # Model for Multiple Choice mapping ("""albert""", """FlaxAlbertForMultipleChoice"""), ("""bert""", """FlaxBertForMultipleChoice"""), ("""big_bird""", """FlaxBigBirdForMultipleChoice"""), ("""distilbert""", """FlaxDistilBertForMultipleChoice"""), ("""electra""", """FlaxElectraForMultipleChoice"""), ("""roberta""", """FlaxRobertaForMultipleChoice"""), ("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormForMultipleChoice"""), ("""roformer""", """FlaxRoFormerForMultipleChoice"""), ("""xlm-roberta""", """FlaxXLMRobertaForMultipleChoice"""), ] ) UpperCAmelCase = OrderedDict( [ ("""bert""", """FlaxBertForNextSentencePrediction"""), ] ) UpperCAmelCase = OrderedDict( [ ("""speech-encoder-decoder""", """FlaxSpeechEncoderDecoderModel"""), ("""whisper""", """FlaxWhisperForConditionalGeneration"""), ] ) UpperCAmelCase = OrderedDict( [ ("""whisper""", """FlaxWhisperForAudioClassification"""), ] ) UpperCAmelCase = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_MAPPING_NAMES) UpperCAmelCase = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_PRETRAINING_MAPPING_NAMES) UpperCAmelCase = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MASKED_LM_MAPPING_NAMES) UpperCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES ) UpperCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES ) UpperCAmelCase = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES) UpperCAmelCase = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_CAUSAL_LM_MAPPING_NAMES) UpperCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES ) UpperCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES ) UpperCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES ) UpperCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES ) UpperCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING_NAMES ) UpperCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES ) UpperCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES ) class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_MAPPING UpperCAmelCase = auto_class_update(FlaxAutoModel) class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_PRETRAINING_MAPPING UpperCAmelCase = auto_class_update(FlaxAutoModelForPreTraining, head_doc="""pretraining""") class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_CAUSAL_LM_MAPPING UpperCAmelCase = auto_class_update(FlaxAutoModelForCausalLM, head_doc="""causal language modeling""") class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_MASKED_LM_MAPPING UpperCAmelCase = auto_class_update(FlaxAutoModelForMaskedLM, head_doc="""masked language modeling""") class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING UpperCAmelCase = auto_class_update( FlaxAutoModelForSeqaSeqLM, head_doc="""sequence-to-sequence language modeling""", checkpoint_for_example="""t5-base""" ) class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING UpperCAmelCase = auto_class_update( FlaxAutoModelForSequenceClassification, head_doc="""sequence classification""" ) class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING UpperCAmelCase = auto_class_update(FlaxAutoModelForQuestionAnswering, head_doc="""question answering""") class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING UpperCAmelCase = auto_class_update( FlaxAutoModelForTokenClassification, head_doc="""token classification""" ) class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING UpperCAmelCase = auto_class_update(FlaxAutoModelForMultipleChoice, head_doc="""multiple choice""") class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING UpperCAmelCase = auto_class_update( FlaxAutoModelForNextSentencePrediction, head_doc="""next sentence prediction""" ) class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING UpperCAmelCase = auto_class_update( FlaxAutoModelForImageClassification, head_doc="""image classification""" ) class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING UpperCAmelCase = auto_class_update(FlaxAutoModelForVisionaSeq, head_doc="""vision-to-text modeling""") class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING UpperCAmelCase = auto_class_update( FlaxAutoModelForSpeechSeqaSeq, head_doc="""sequence-to-sequence speech-to-text modeling""" )
88
0
from math import pi, sqrt def UpperCAmelCase_ ( snake_case__ ) -> int: """simple docstring""" if num <= 0: raise ValueError('math domain error' ) if num > 171.5: raise OverflowError('math range error' ) elif num - int(__snake_case ) not in (0, 0.5): raise NotImplementedError('num must be an integer or a half-integer' ) elif num == 0.5: return sqrt(__snake_case ) else: return 1.0 if num == 1 else (num - 1) * gamma(num - 1 ) def UpperCAmelCase_ ( ) -> str: """simple docstring""" assert gamma(0.5 ) == sqrt(__snake_case ) assert gamma(1 ) == 1.0 assert gamma(2 ) == 1.0 if __name__ == "__main__": from doctest import testmod testmod() _lowerCAmelCase : Dict = 1.0 while num: _lowerCAmelCase : Union[str, Any] = float(input("Gamma of: ")) print(f"""gamma({num}) = {gamma(num)}""") print("\nEnter 0 to exit...")
193
"""simple docstring""" # limitations under the License. # NOTE: This file is deprecated and will be removed in a future version. # It only exists so that temporarely `from diffusers.pipelines import DiffusionPipeline` works from .pipelines import DiffusionPipeline, ImagePipelineOutput # noqa: F401 from .utils import deprecate deprecate( """pipelines_utils""", """0.22.0""", """Importing `DiffusionPipeline` or `ImagePipelineOutput` from diffusers.pipeline_utils is deprecated. Please import from diffusers.pipelines.pipeline_utils instead.""", standard_warn=False, stacklevel=3, )
88
0
'''simple docstring''' import json from typing import List, Optional, Tuple from tokenizers import normalizers from tokenizers.pre_tokenizers import BertPreTokenizer, PreTokenizer from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_roformer import RoFormerTokenizer from .tokenization_utils import JiebaPreTokenizer _a : List[Any] = logging.get_logger(__name__) _a : Union[str, Any] = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"} _a : int = { "vocab_file": { "junnyu/roformer_chinese_small": "https://huggingface.co/junnyu/roformer_chinese_small/resolve/main/vocab.txt", "junnyu/roformer_chinese_base": "https://huggingface.co/junnyu/roformer_chinese_base/resolve/main/vocab.txt", "junnyu/roformer_chinese_char_small": ( "https://huggingface.co/junnyu/roformer_chinese_char_small/resolve/main/vocab.txt" ), "junnyu/roformer_chinese_char_base": ( "https://huggingface.co/junnyu/roformer_chinese_char_base/resolve/main/vocab.txt" ), "junnyu/roformer_small_discriminator": ( "https://huggingface.co/junnyu/roformer_small_discriminator/resolve/main/vocab.txt" ), "junnyu/roformer_small_generator": ( "https://huggingface.co/junnyu/roformer_small_generator/resolve/main/vocab.txt" ), } } _a : Union[str, Any] = { "junnyu/roformer_chinese_small": 1536, "junnyu/roformer_chinese_base": 1536, "junnyu/roformer_chinese_char_small": 512, "junnyu/roformer_chinese_char_base": 512, "junnyu/roformer_small_discriminator": 128, "junnyu/roformer_small_generator": 128, } _a : Optional[int] = { "junnyu/roformer_chinese_small": {"do_lower_case": True}, "junnyu/roformer_chinese_base": {"do_lower_case": True}, "junnyu/roformer_chinese_char_small": {"do_lower_case": True}, "junnyu/roformer_chinese_char_base": {"do_lower_case": True}, "junnyu/roformer_small_discriminator": {"do_lower_case": True}, "junnyu/roformer_small_generator": {"do_lower_case": True}, } class __A (A_ ): snake_case :Any = VOCAB_FILES_NAMES snake_case :List[Any] = PRETRAINED_VOCAB_FILES_MAP snake_case :Optional[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES snake_case :Optional[Any] = PRETRAINED_INIT_CONFIGURATION snake_case :Dict = RoFormerTokenizer def __init__( self , UpperCamelCase_=None , UpperCamelCase_=None , UpperCamelCase_=True , UpperCamelCase_="[UNK]" , UpperCamelCase_="[SEP]" , UpperCamelCase_="[PAD]" , UpperCamelCase_="[CLS]" , UpperCamelCase_="[MASK]" , UpperCamelCase_=True , UpperCamelCase_=None , **UpperCamelCase_ , ): super().__init__( UpperCamelCase_ , tokenizer_file=UpperCamelCase_ , do_lower_case=UpperCamelCase_ , unk_token=UpperCamelCase_ , sep_token=UpperCamelCase_ , pad_token=UpperCamelCase_ , cls_token=UpperCamelCase_ , mask_token=UpperCamelCase_ , tokenize_chinese_chars=UpperCamelCase_ , strip_accents=UpperCamelCase_ , **UpperCamelCase_ , ) __UpperCAmelCase : Tuple = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( pre_tok_state.get("lowercase" , UpperCamelCase_ ) != do_lower_case or pre_tok_state.get("strip_accents" , UpperCamelCase_ ) != strip_accents ): __UpperCAmelCase : str = getattr(UpperCamelCase_ , pre_tok_state.pop("type" ) ) __UpperCAmelCase : List[str] = do_lower_case __UpperCAmelCase : str = strip_accents __UpperCAmelCase : Optional[Any] = pre_tok_class(**UpperCamelCase_ ) __UpperCAmelCase : Any = do_lower_case def __getstate__( self ): __UpperCAmelCase : Any = self.__dict__.copy() __UpperCAmelCase : Dict = BertPreTokenizer() return state def __setstate__( self , UpperCamelCase_ ): __UpperCAmelCase : Tuple = d __UpperCAmelCase : List[Any] = self.__dict__["""_tokenizer"""].get_vocab() __UpperCAmelCase : Optional[int] = PreTokenizer.custom(JiebaPreTokenizer(UpperCamelCase_ ) ) def _snake_case ( self , UpperCamelCase_ , UpperCamelCase_=None ): __UpperCAmelCase : List[Any] = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def _snake_case ( self , UpperCamelCase_ , UpperCamelCase_ = None ): __UpperCAmelCase : List[Any] = [self.sep_token_id] __UpperCAmelCase : Optional[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 _snake_case ( self , UpperCamelCase_ , UpperCamelCase_ = None ): __UpperCAmelCase : Dict = self._tokenizer.model.save(UpperCamelCase_ , name=UpperCamelCase_ ) return tuple(UpperCamelCase_ ) def _snake_case ( self , UpperCamelCase_ , UpperCamelCase_=None , UpperCamelCase_=None , UpperCamelCase_=False , **UpperCamelCase_ , ): __UpperCAmelCase : List[Any] = BertPreTokenizer() return super().save_pretrained(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , **UpperCamelCase_ )
168
"""simple docstring""" def _snake_case ( __snake_case : list[list[int]] , __snake_case : int , __snake_case : int , __snake_case : list[int] ): """simple docstring""" 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 _snake_case ( __snake_case : list[list[int]] , __snake_case : list[int] , __snake_case : int ): """simple docstring""" if curr_ind == len(__snake_case ): # 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(__snake_case ) ): if valid_connection(__snake_case , __snake_case , __snake_case , __snake_case ): # Insert current vertex into path as next transition _lowerCamelCase : List[str] = next_ver # Validate created path if util_hamilton_cycle(__snake_case , __snake_case , curr_ind + 1 ): return True # Backtrack _lowerCamelCase : Tuple = -1 return False def _snake_case ( __snake_case : list[list[int]] , __snake_case : int = 0 ): """simple docstring""" _lowerCamelCase : Any = [-1] * (len(__snake_case ) + 1) # initialize start and end of path with starting index _lowerCamelCase : Optional[int] = start_index # evaluate and if we find answer return path either return empty array return path if util_hamilton_cycle(__snake_case , __snake_case , 1 ) else []
88
0
"""simple docstring""" import inspect import unittest import numpy as np from tests.test_modeling_common import floats_tensor from transformers import MaskaFormerConfig, is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MaskaFormerForUniversalSegmentation, MaskaFormerModel if is_vision_available(): from transformers import MaskaFormerImageProcessor if is_vision_available(): from PIL import Image class __lowerCAmelCase : '''simple docstring''' def __init__( self: List[Any] , UpperCamelCase_: Optional[int] , UpperCamelCase_: Any=2 , UpperCamelCase_: Tuple=True , UpperCamelCase_: Optional[Any]=False , UpperCamelCase_: Any=10 , UpperCamelCase_: Dict=3 , UpperCamelCase_: List[Any]=32 * 8 , UpperCamelCase_: Dict=32 * 8 , UpperCamelCase_: Dict=4 , UpperCamelCase_: Tuple=64 , ): UpperCamelCase_ =parent UpperCamelCase_ =batch_size UpperCamelCase_ =is_training UpperCamelCase_ =use_auxiliary_loss UpperCamelCase_ =num_queries UpperCamelCase_ =num_channels UpperCamelCase_ =min_size UpperCamelCase_ =max_size UpperCamelCase_ =num_labels UpperCamelCase_ =hidden_dim UpperCamelCase_ =hidden_dim def UpperCamelCase__ ( self: Optional[int] ): UpperCamelCase_ =floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size] ).to( UpperCamelCase_ ) UpperCamelCase_ =torch.ones([self.batch_size, self.min_size, self.max_size] , device=UpperCamelCase_ ) UpperCamelCase_ =( torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size] , device=UpperCamelCase_ ) > 0.5 ).float() UpperCamelCase_ =(torch.rand((self.batch_size, self.num_labels) , device=UpperCamelCase_ ) > 0.5).long() UpperCamelCase_ =self.get_config() return config, pixel_values, pixel_mask, mask_labels, class_labels def UpperCamelCase__ ( self: Tuple ): UpperCamelCase_ =MaskaFormerConfig( hidden_size=self.hidden_dim , ) UpperCamelCase_ =self.num_queries UpperCamelCase_ =self.num_labels UpperCamelCase_ =[1, 1, 1, 1] UpperCamelCase_ =self.num_channels UpperCamelCase_ =64 UpperCamelCase_ =128 UpperCamelCase_ =self.hidden_dim UpperCamelCase_ =self.hidden_dim UpperCamelCase_ =self.hidden_dim return config def UpperCamelCase__ ( self: List[Any] ): UpperCamelCase_ =self.prepare_config_and_inputs() UpperCamelCase_ ={"""pixel_values""": pixel_values, """pixel_mask""": pixel_mask} return config, inputs_dict def UpperCamelCase__ ( self: Tuple , UpperCamelCase_: Optional[int] , UpperCamelCase_: Union[str, Any] ): UpperCamelCase_ =output.encoder_hidden_states UpperCamelCase_ =output.pixel_decoder_hidden_states UpperCamelCase_ =output.transformer_decoder_hidden_states self.parent.assertTrue(len(UpperCamelCase_ ) , len(config.backbone_config.depths ) ) self.parent.assertTrue(len(UpperCamelCase_ ) , len(config.backbone_config.depths ) ) self.parent.assertTrue(len(UpperCamelCase_ ) , config.decoder_layers ) def UpperCamelCase__ ( self: Optional[int] , UpperCamelCase_: Union[str, Any] , UpperCamelCase_: List[str] , UpperCamelCase_: Any , UpperCamelCase_: str=False ): with torch.no_grad(): UpperCamelCase_ =MaskaFormerModel(config=UpperCamelCase_ ) model.to(UpperCamelCase_ ) model.eval() UpperCamelCase_ =model(pixel_values=UpperCamelCase_ , pixel_mask=UpperCamelCase_ ) UpperCamelCase_ =model(UpperCamelCase_ , output_hidden_states=UpperCamelCase_ ) self.parent.assertEqual( output.transformer_decoder_last_hidden_state.shape , (self.batch_size, self.num_queries, self.hidden_dim) , ) # let's ensure the other two hidden state exists self.parent.assertTrue(output.pixel_decoder_last_hidden_state is not None ) self.parent.assertTrue(output.encoder_last_hidden_state is not None ) if output_hidden_states: self.check_output_hidden_state(UpperCamelCase_ , UpperCamelCase_ ) def UpperCamelCase__ ( self: Optional[int] , UpperCamelCase_: Optional[int] , UpperCamelCase_: str , UpperCamelCase_: Any , UpperCamelCase_: List[str] , UpperCamelCase_: int ): UpperCamelCase_ =MaskaFormerForUniversalSegmentation(config=UpperCamelCase_ ) model.to(UpperCamelCase_ ) model.eval() def comm_check_on_output(UpperCamelCase_: Optional[int] ): # let's still check that all the required stuff is there self.parent.assertTrue(result.transformer_decoder_last_hidden_state is not None ) self.parent.assertTrue(result.pixel_decoder_last_hidden_state is not None ) self.parent.assertTrue(result.encoder_last_hidden_state is not None ) # okay, now we need to check the logits shape # due to the encoder compression, masks have a //4 spatial size self.parent.assertEqual( result.masks_queries_logits.shape , (self.batch_size, self.num_queries, self.min_size // 4, self.max_size // 4) , ) # + 1 for null class self.parent.assertEqual( result.class_queries_logits.shape , (self.batch_size, self.num_queries, self.num_labels + 1) ) with torch.no_grad(): UpperCamelCase_ =model(pixel_values=UpperCamelCase_ , pixel_mask=UpperCamelCase_ ) UpperCamelCase_ =model(UpperCamelCase_ ) comm_check_on_output(UpperCamelCase_ ) UpperCamelCase_ =model( pixel_values=UpperCamelCase_ , pixel_mask=UpperCamelCase_ , mask_labels=UpperCamelCase_ , class_labels=UpperCamelCase_ ) comm_check_on_output(UpperCamelCase_ ) self.parent.assertTrue(result.loss is not None ) self.parent.assertEqual(result.loss.shape , torch.Size([1] ) ) @require_torch class __lowerCAmelCase ( A_ , A_ , unittest.TestCase ): '''simple docstring''' __lowerCamelCase : Union[str, Any] = (MaskaFormerModel, MaskaFormerForUniversalSegmentation) if is_torch_available() else () __lowerCamelCase : Optional[int] = {"feature-extraction": MaskaFormerModel} if is_torch_available() else {} __lowerCamelCase : List[str] = False __lowerCamelCase : int = False __lowerCamelCase : Tuple = False __lowerCamelCase : str = False def UpperCamelCase__ ( self: int ): UpperCamelCase_ =MaskaFormerModelTester(self ) UpperCamelCase_ =ConfigTester(self , config_class=UpperCamelCase_ , has_text_modality=UpperCamelCase_ ) def UpperCamelCase__ ( self: Any ): self.config_tester.run_common_tests() def UpperCamelCase__ ( self: List[Any] ): UpperCamelCase_ =self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskaformer_model(UpperCamelCase_ , **UpperCamelCase_ , output_hidden_states=UpperCamelCase_ ) def UpperCamelCase__ ( self: Dict ): UpperCamelCase_ =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_maskaformer_instance_segmentation_head_model(*UpperCamelCase_ ) @unittest.skip(reason="Mask2Former does not use inputs_embeds" ) def UpperCamelCase__ ( self: List[str] ): pass @unittest.skip(reason="Mask2Former does not have a get_input_embeddings method" ) def UpperCamelCase__ ( self: Any ): pass @unittest.skip(reason="Mask2Former is not a generative model" ) def UpperCamelCase__ ( self: int ): pass @unittest.skip(reason="Mask2Former does not use token embeddings" ) def UpperCamelCase__ ( self: Optional[Any] ): pass @require_torch_multi_gpu @unittest.skip( reason="Mask2Former has some layers using `add_module` which doesn't work well with `nn.DataParallel`" ) def UpperCamelCase__ ( self: int ): pass @unittest.skip("Will be fixed soon by reducing the size of the model used for common tests." ) def UpperCamelCase__ ( self: Tuple ): pass def UpperCamelCase__ ( self: Tuple ): UpperCamelCase_ =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase_ =model_class(UpperCamelCase_ ) UpperCamelCase_ =inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic UpperCamelCase_ =[*signature.parameters.keys()] UpperCamelCase_ =["""pixel_values"""] self.assertListEqual(arg_names[:1] , UpperCamelCase_ ) @slow def UpperCamelCase__ ( self: Optional[int] ): for model_name in ["facebook/mask2former-swin-small-coco-instance"]: UpperCamelCase_ =MaskaFormerModel.from_pretrained(UpperCamelCase_ ) self.assertIsNotNone(UpperCamelCase_ ) def UpperCamelCase__ ( self: Optional[Any] ): UpperCamelCase_ =(self.model_tester.min_size,) * 2 UpperCamelCase_ ={ """pixel_values""": torch.randn((2, 3, *size) , device=UpperCamelCase_ ), """mask_labels""": torch.randn((2, 10, *size) , device=UpperCamelCase_ ), """class_labels""": torch.zeros(2 , 10 , device=UpperCamelCase_ ).long(), } UpperCamelCase_ =self.model_tester.get_config() UpperCamelCase_ =MaskaFormerForUniversalSegmentation(UpperCamelCase_ ).to(UpperCamelCase_ ) UpperCamelCase_ =model(**UpperCamelCase_ ) self.assertTrue(outputs.loss is not None ) def UpperCamelCase__ ( self: str ): UpperCamelCase_ =self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskaformer_model(UpperCamelCase_ , **UpperCamelCase_ , output_hidden_states=UpperCamelCase_ ) def UpperCamelCase__ ( self: Optional[Any] ): UpperCamelCase_ =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase_ =model_class(UpperCamelCase_ ).to(UpperCamelCase_ ) UpperCamelCase_ =model(**UpperCamelCase_ , output_attentions=UpperCamelCase_ ) self.assertTrue(outputs.attentions is not None ) def UpperCamelCase__ ( self: Union[str, Any] ): if not self.model_tester.is_training: return UpperCamelCase_ =self.all_model_classes[1] UpperCamelCase_ =self.model_tester.prepare_config_and_inputs() UpperCamelCase_ =model_class(UpperCamelCase_ ) model.to(UpperCamelCase_ ) model.train() UpperCamelCase_ =model(UpperCamelCase_ , mask_labels=UpperCamelCase_ , class_labels=UpperCamelCase_ ).loss loss.backward() def UpperCamelCase__ ( self: str ): UpperCamelCase_ =self.all_model_classes[1] UpperCamelCase_ =self.model_tester.prepare_config_and_inputs() UpperCamelCase_ =True UpperCamelCase_ =True UpperCamelCase_ =model_class(UpperCamelCase_ ).to(UpperCamelCase_ ) model.train() UpperCamelCase_ =model(UpperCamelCase_ , mask_labels=UpperCamelCase_ , class_labels=UpperCamelCase_ ) UpperCamelCase_ =outputs.encoder_hidden_states[0] encoder_hidden_states.retain_grad() UpperCamelCase_ =outputs.pixel_decoder_hidden_states[0] pixel_decoder_hidden_states.retain_grad() UpperCamelCase_ =outputs.transformer_decoder_hidden_states[0] transformer_decoder_hidden_states.retain_grad() UpperCamelCase_ =outputs.attentions[0] attentions.retain_grad() outputs.loss.backward(retain_graph=UpperCamelCase_ ) self.assertIsNotNone(encoder_hidden_states.grad ) self.assertIsNotNone(pixel_decoder_hidden_states.grad ) self.assertIsNotNone(transformer_decoder_hidden_states.grad ) self.assertIsNotNone(attentions.grad ) A_ = 1e-4 def _UpperCamelCase ( ): UpperCamelCase_ =Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_vision @slow class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' @cached_property def UpperCamelCase__ ( self: List[Any] ): return "facebook/mask2former-swin-small-coco-instance" @cached_property def UpperCamelCase__ ( self: int ): return MaskaFormerImageProcessor.from_pretrained(self.model_checkpoints ) if is_vision_available() else None def UpperCamelCase__ ( self: Tuple ): UpperCamelCase_ =MaskaFormerModel.from_pretrained(self.model_checkpoints ).to(UpperCamelCase_ ) UpperCamelCase_ =self.default_image_processor UpperCamelCase_ =prepare_img() UpperCamelCase_ =image_processor(UpperCamelCase_ , return_tensors="pt" ).to(UpperCamelCase_ ) UpperCamelCase_ =inputs["""pixel_values"""].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 ) # check size self.assertEqual(UpperCamelCase_ , (1, 3, 384, 384) ) with torch.no_grad(): UpperCamelCase_ =model(**UpperCamelCase_ ) UpperCamelCase_ =torch.tensor( [[-0.2790, -1.0717, -1.1668], [-0.5128, -0.3128, -0.4987], [-0.5832, 0.1971, -0.0197]] ).to(UpperCamelCase_ ) self.assertTrue( torch.allclose( outputs.encoder_last_hidden_state[0, 0, :3, :3] , UpperCamelCase_ , atol=UpperCamelCase_ ) ) UpperCamelCase_ =torch.tensor( [[0.8973, 1.1847, 1.1776], [1.1934, 1.5040, 1.5128], [1.1153, 1.4486, 1.4951]] ).to(UpperCamelCase_ ) self.assertTrue( torch.allclose( outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3] , UpperCamelCase_ , atol=UpperCamelCase_ ) ) UpperCamelCase_ =torch.tensor( [[2.1152, 1.7000, -0.8603], [1.5808, 1.8004, -0.9353], [1.6043, 1.7495, -0.5999]] ).to(UpperCamelCase_ ) self.assertTrue( torch.allclose( outputs.transformer_decoder_last_hidden_state[0, :3, :3] , UpperCamelCase_ , atol=UpperCamelCase_ ) ) def UpperCamelCase__ ( self: Optional[int] ): UpperCamelCase_ =MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints ).to(UpperCamelCase_ ).eval() UpperCamelCase_ =self.default_image_processor UpperCamelCase_ =prepare_img() UpperCamelCase_ =image_processor(UpperCamelCase_ , return_tensors="pt" ).to(UpperCamelCase_ ) UpperCamelCase_ =inputs["""pixel_values"""].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 ) # check size self.assertEqual(UpperCamelCase_ , (1, 3, 384, 384) ) with torch.no_grad(): UpperCamelCase_ =model(**UpperCamelCase_ ) # masks_queries_logits UpperCamelCase_ =outputs.masks_queries_logits self.assertEqual( masks_queries_logits.shape , (1, model.config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) ) UpperCamelCase_ =[ [-8.7839, -9.0056, -8.8121], [-7.4104, -7.0313, -6.5401], [-6.6105, -6.3427, -6.4675], ] UpperCamelCase_ =torch.tensor(UpperCamelCase_ ).to(UpperCamelCase_ ) self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , UpperCamelCase_ , atol=UpperCamelCase_ ) ) # class_queries_logits UpperCamelCase_ =outputs.class_queries_logits self.assertEqual(class_queries_logits.shape , (1, model.config.num_queries, model.config.num_labels + 1) ) UpperCamelCase_ =torch.tensor( [ [1.8324, -8.0835, -4.1922], [0.8450, -9.0050, -3.6053], [0.3045, -7.7293, -3.0275], ] ).to(UpperCamelCase_ ) self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , UpperCamelCase_ , atol=UpperCamelCase_ ) ) def UpperCamelCase__ ( self: str ): UpperCamelCase_ =MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints ).to(UpperCamelCase_ ).eval() UpperCamelCase_ =self.default_image_processor UpperCamelCase_ =image_processor( [np.zeros((3, 800, 1333) ), np.zeros((3, 800, 1333) )] , segmentation_maps=[np.zeros((384, 384) ).astype(np.floataa ), np.zeros((384, 384) ).astype(np.floataa )] , return_tensors="pt" , ) UpperCamelCase_ =inputs["""pixel_values"""].to(UpperCamelCase_ ) UpperCamelCase_ =[el.to(UpperCamelCase_ ) for el in inputs["""mask_labels"""]] UpperCamelCase_ =[el.to(UpperCamelCase_ ) for el in inputs["""class_labels"""]] with torch.no_grad(): UpperCamelCase_ =model(**UpperCamelCase_ ) self.assertTrue(outputs.loss is not None )
391
"""simple docstring""" import mpmath # for roots of unity import numpy as np class lowercase__ : def __init__( self , SCREAMING_SNAKE_CASE=None , SCREAMING_SNAKE_CASE=None) -> Tuple: # Input as list _lowerCamelCase : Any = list(poly_a or [0])[:] _lowerCamelCase : Optional[Any] = list(poly_b or [0])[:] # Remove leading zero coefficients while self.polyA[-1] == 0: self.polyA.pop() _lowerCamelCase : int = len(self.polyA) while self.polyB[-1] == 0: self.polyB.pop() _lowerCamelCase : Union[str, Any] = len(self.polyB) # Add 0 to make lengths equal a power of 2 _lowerCamelCase : List[Any] = int( 2 ** np.ceil(np.loga(len(self.polyA) + len(self.polyB) - 1))) while len(self.polyA) < self.c_max_length: self.polyA.append(0) while len(self.polyB) < self.c_max_length: self.polyB.append(0) # A complex root used for the fourier transform _lowerCamelCase : Optional[Any] = complex(mpmath.root(x=1 , n=self.c_max_length , k=1)) # The product _lowerCamelCase : int = self.__multiply() def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE) -> List[str]: _lowerCamelCase : Dict = [[x] for x in self.polyA] if which == """A""" else [[x] for x in self.polyB] # Corner case if len(SCREAMING_SNAKE_CASE) <= 1: return dft[0] # _lowerCamelCase : str = self.c_max_length // 2 while next_ncol > 0: _lowerCamelCase : Dict = [[] for i in range(SCREAMING_SNAKE_CASE)] _lowerCamelCase : Tuple = self.root**next_ncol # First half of next step _lowerCamelCase : int = 1 for j in range(self.c_max_length // (next_ncol * 2)): for i in range(SCREAMING_SNAKE_CASE): new_dft[i].append(dft[i][j] + current_root * dft[i + next_ncol][j]) current_root *= root # Second half of next step _lowerCamelCase : Optional[int] = 1 for j in range(self.c_max_length // (next_ncol * 2)): for i in range(SCREAMING_SNAKE_CASE): new_dft[i].append(dft[i][j] - current_root * dft[i + next_ncol][j]) current_root *= root # Update _lowerCamelCase : Union[str, Any] = new_dft _lowerCamelCase : List[str] = next_ncol // 2 return dft[0] def UpperCamelCase_ ( self) -> str: _lowerCamelCase : Optional[Any] = self.__dft("""A""") _lowerCamelCase : List[str] = self.__dft("""B""") _lowerCamelCase : List[Any] = [[dft_a[i] * dft_b[i] for i in range(self.c_max_length)]] del dft_a del dft_b # Corner Case if len(inverce_c[0]) <= 1: return inverce_c[0] # Inverse DFT _lowerCamelCase : List[str] = 2 while next_ncol <= self.c_max_length: _lowerCamelCase : Any = [[] for i in range(SCREAMING_SNAKE_CASE)] _lowerCamelCase : List[Any] = self.root ** (next_ncol // 2) _lowerCamelCase : str = 1 # First half of next step for j in range(self.c_max_length // next_ncol): for i in range(next_ncol // 2): # Even positions new_inverse_c[i].append( ( inverce_c[i][j] + inverce_c[i][j + self.c_max_length // next_ncol] ) / 2) # Odd positions new_inverse_c[i + next_ncol // 2].append( ( inverce_c[i][j] - inverce_c[i][j + self.c_max_length // next_ncol] ) / (2 * current_root)) current_root *= root # Update _lowerCamelCase : Any = new_inverse_c next_ncol *= 2 # Unpack _lowerCamelCase : Optional[Any] = [round(x[0].real , 8) + round(x[0].imag , 8) * 1j for x in inverce_c] # Remove leading 0's while inverce_c[-1] == 0: inverce_c.pop() return inverce_c def __str__( self) -> Any: _lowerCamelCase : Dict = """A = """ + """ + """.join( F'{coef}*x^{i}' for coef, i in enumerate(self.polyA[: self.len_A])) _lowerCamelCase : List[Any] = """B = """ + """ + """.join( F'{coef}*x^{i}' for coef, i in enumerate(self.polyB[: self.len_B])) _lowerCamelCase : int = """A*B = """ + """ + """.join( F'{coef}*x^{i}' for coef, i in enumerate(self.product)) return F'{a}\n{b}\n{c}' # Unit tests if __name__ == "__main__": import doctest doctest.testmod()
88
0
def UpperCAmelCase_ ( __UpperCamelCase ): return str(__snake_case ) == str(__snake_case )[::-1] def UpperCAmelCase_ ( __UpperCamelCase ): return int(__snake_case ) + int(str(__snake_case )[::-1] ) def UpperCAmelCase_ ( __UpperCamelCase = 10_000 ): SCREAMING_SNAKE_CASE__ =[] for num in range(1, __snake_case ): SCREAMING_SNAKE_CASE__ =0 SCREAMING_SNAKE_CASE__ =num while iterations < 50: SCREAMING_SNAKE_CASE__ =sum_reverse(__snake_case ) iterations += 1 if is_palindrome(__snake_case ): break else: lychrel_nums.append(__snake_case ) return len(__snake_case ) if __name__ == "__main__": print(f"""{solution() = }""")
151
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) UpperCAmelCase = { """configuration_vision_encoder_decoder""": ["""VisionEncoderDecoderConfig""", """VisionEncoderDecoderOnnxConfig"""] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase = ["""VisionEncoderDecoderModel"""] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase = ["""TFVisionEncoderDecoderModel"""] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase = ["""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 UpperCAmelCase = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
88
0
"""simple docstring""" import warnings from ...utils import logging from .image_processing_deformable_detr import DeformableDetrImageProcessor _UpperCamelCase : str = logging.get_logger(__name__) class UpperCAmelCase_ ( A_): def __init__( self , *a , **a ) -> None: warnings.warn( 'The class DeformableDetrFeatureExtractor is deprecated and will be removed in version 5 of Transformers.' ' Please use DeformableDetrImageProcessor instead.' , a , ) super().__init__(*a , **a )
599
"""simple docstring""" from datetime import datetime import matplotlib.pyplot as plt import torch def _snake_case ( __snake_case : List[str] ): """simple docstring""" for param in module.parameters(): _lowerCamelCase : Optional[Any] = False def _snake_case ( ): """simple docstring""" _lowerCamelCase : Any = """cuda""" if torch.cuda.is_available() else """cpu""" if torch.backends.mps.is_available() and torch.backends.mps.is_built(): _lowerCamelCase : Any = """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 _snake_case ( __snake_case : Union[str, Any] ): """simple docstring""" _lowerCamelCase : int = plt.imshow(__snake_case ) fig.axes.get_xaxis().set_visible(__snake_case ) fig.axes.get_yaxis().set_visible(__snake_case ) plt.show() def _snake_case ( ): """simple docstring""" _lowerCamelCase : Tuple = datetime.now() _lowerCamelCase : Optional[Any] = current_time.strftime("""%H:%M:%S""" ) return timestamp
88
0
import argparse import shlex import runhouse as rh if __name__ == "__main__": # Refer to https://runhouse-docs.readthedocs-hosted.com/en/latest/api/python/cluster.html#hardware-setup for cloud access # setup instructions, if using on-demand hardware # If user passes --user <user> --host <host> --key_path <key_path> <example> <args>, fill them in as BYO cluster # If user passes --instance <instance> --provider <provider> <example> <args>, fill them in as on-demand cluster # Throw an error if user passes both BYO and on-demand cluster args # Otherwise, use default values SCREAMING_SNAKE_CASE__ : Dict = argparse.ArgumentParser() parser.add_argument("""--user""", type=str, default="""ubuntu""") parser.add_argument("""--host""", type=str, default="""localhost""") parser.add_argument("""--key_path""", type=str, default=None) parser.add_argument("""--instance""", type=str, default="""V100:1""") parser.add_argument("""--provider""", type=str, default="""cheapest""") parser.add_argument("""--use_spot""", type=bool, default=False) parser.add_argument("""--example""", type=str, default="""pytorch/text-generation/run_generation.py""") SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] = parser.parse_known_args() if args.host != "localhost": if args.instance != "V100:1" or args.provider != "cheapest": raise ValueError("""Cannot specify both BYO and on-demand cluster args""") SCREAMING_SNAKE_CASE__ : Tuple = rh.cluster( name="""rh-cluster""", ips=[args.host], ssh_creds={"""ssh_user""": args.user, """ssh_private_key""": args.key_path} ) else: SCREAMING_SNAKE_CASE__ : Dict = rh.cluster( name="""rh-cluster""", instance_type=args.instance, provider=args.provider, use_spot=args.use_spot ) SCREAMING_SNAKE_CASE__ : Tuple = args.example.rsplit("""/""", 1)[0] # Set up remote environment cluster.install_packages(["""pip:./"""]) # Installs transformers from local source # Note transformers is copied into the home directory on the remote machine, so we can install from there cluster.run([f'pip install -r transformers/examples/{example_dir}/requirements.txt']) cluster.run(["""pip install torch --upgrade --extra-index-url https://download.pytorch.org/whl/cu117"""]) # Run example. You can bypass the CLI wrapper and paste your own code here. cluster.run([f'python transformers/examples/{args.example} {" ".join(shlex.quote(arg) for arg in unknown)}']) # Alternatively, we can just import and run a training function (especially if there's no wrapper CLI): # from my_script... import train # reqs = ['pip:./', 'torch', 'datasets', 'accelerate', 'evaluate', 'tqdm', 'scipy', 'scikit-learn', 'tensorboard'] # launch_train_gpu = rh.function(fn=train, # system=gpu, # reqs=reqs, # name='train_bert_glue') # # We can pass in arguments just like we would to a function: # launch_train_gpu(num_epochs = 3, lr = 2e-5, seed = 42, batch_size = 16 # stream_logs=True)
112
"""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 UpperCAmelCase = 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 lowercase__ : __UpperCAmelCase = field( default='''cifar10''' ,metadata={'''help''': '''Name of a dataset from the datasets package'''} ) __UpperCAmelCase = field( default=A_ ,metadata={'''help''': '''The configuration name of the dataset to use (via the datasets library).'''} ) __UpperCAmelCase = field( default=A_ ,metadata={'''help''': '''The column name of the images in the files.'''} ) __UpperCAmelCase = field(default=A_ ,metadata={'''help''': '''A folder containing the training data.'''} ) __UpperCAmelCase = field(default=A_ ,metadata={'''help''': '''A folder containing the validation data.'''} ) __UpperCAmelCase = field( default=0.1_5 ,metadata={'''help''': '''Percent to split off of train for validation.'''} ) __UpperCAmelCase = field( default=A_ ,metadata={ '''help''': ( '''For debugging purposes or quicker training, truncate the number of training examples to this ''' '''value if set.''' ) } ,) __UpperCAmelCase = field( default=A_ ,metadata={ '''help''': ( '''For debugging purposes or quicker training, truncate the number of evaluation examples to this ''' '''value if set.''' ) } ,) def UpperCamelCase_ ( self) -> Any: _lowerCamelCase : Any = {} if self.train_dir is not None: _lowerCamelCase : int = self.train_dir if self.validation_dir is not None: _lowerCamelCase : Tuple = self.validation_dir _lowerCamelCase : Optional[int] = data_files if data_files else None @dataclass class lowercase__ : __UpperCAmelCase = field( default=A_ ,metadata={ '''help''': ( '''The model checkpoint for weights initialization.Don\'t set if you want to train a model from scratch.''' ) } ,) __UpperCAmelCase = field( default=A_ ,metadata={'''help''': '''Pretrained config name or path if not the same as model_name_or_path'''} ) __UpperCAmelCase = field( default=A_ ,metadata={ '''help''': ( '''Override some existing default config settings when a model is trained from scratch. Example: ''' '''n_embd=10,resid_pdrop=0.2,scale_attn_weights=false,summary_type=cls_index''' ) } ,) __UpperCAmelCase = field( default=A_ ,metadata={'''help''': '''Where do you want to store the pretrained models downloaded from s3'''} ) __UpperCAmelCase = field( default='''main''' ,metadata={'''help''': '''The specific model version to use (can be a branch name, tag name or commit id).'''} ,) __UpperCAmelCase = field(default=A_ ,metadata={'''help''': '''Name or path of preprocessor config.'''} ) __UpperCAmelCase = field( default=A_ ,metadata={ '''help''': ( '''Will use the token generated when running `huggingface-cli login` (necessary to use this script ''' '''with private models).''' ) } ,) __UpperCAmelCase = field( default=0.7_5 ,metadata={'''help''': '''The ratio of the number of masked tokens in the input sequence.'''} ) __UpperCAmelCase = field( default=A_ ,metadata={'''help''': '''Whether or not to train with normalized pixel values as target.'''} ) @dataclass class lowercase__ ( A_ ): __UpperCAmelCase = field( default=1e-3 ,metadata={'''help''': '''Base learning rate: absolute_lr = base_lr * total_batch_size / 256.'''} ) def _snake_case ( __snake_case : Optional[Any] ): """simple docstring""" _lowerCamelCase : int = torch.stack([example["""pixel_values"""] for example in examples] ) return {"pixel_values": pixel_values} def _snake_case ( ): """simple docstring""" _lowerCamelCase : Tuple = 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. _lowerCamelCase , _lowerCamelCase , _lowerCamelCase : Union[str, Any] = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: _lowerCamelCase , _lowerCamelCase , _lowerCamelCase : Dict = 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""" , __snake_case , __snake_case ) # Setup logging logging.basicConfig( format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""" , datefmt="""%m/%d/%Y %H:%M:%S""" , handlers=[logging.StreamHandler(sys.stdout )] , ) if training_args.should_log: # The default of training_args.log_level is passive, so we set log level at info here to have that default. transformers.utils.logging.set_verbosity_info() _lowerCamelCase : Union[str, Any] = training_args.get_process_log_level() logger.setLevel(__snake_case ) transformers.utils.logging.set_verbosity(__snake_case ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Log on each process the small summary: logger.warning( F'Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}' + F'distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}' ) logger.info(F'Training/evaluation parameters {training_args}' ) # Detecting last checkpoint. _lowerCamelCase : List[Any] = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: _lowerCamelCase : Optional[int] = 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. _lowerCamelCase : Optional[Any] = 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. _lowerCamelCase : Tuple = None if """validation""" in ds.keys() else data_args.train_val_split if isinstance(data_args.train_val_split , __snake_case ) and data_args.train_val_split > 0.0: _lowerCamelCase : List[str] = ds["""train"""].train_test_split(data_args.train_val_split ) _lowerCamelCase : Union[str, Any] = split["""train"""] _lowerCamelCase : Optional[int] = 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. _lowerCamelCase : 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: _lowerCamelCase : Dict = ViTMAEConfig.from_pretrained(model_args.config_name , **__snake_case ) elif model_args.model_name_or_path: _lowerCamelCase : Union[str, Any] = ViTMAEConfig.from_pretrained(model_args.model_name_or_path , **__snake_case ) else: _lowerCamelCase : Optional[Any] = 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: _lowerCamelCase : str = ViTImageProcessor.from_pretrained(model_args.image_processor_name , **__snake_case ) elif model_args.model_name_or_path: _lowerCamelCase : Dict = ViTImageProcessor.from_pretrained(model_args.model_name_or_path , **__snake_case ) else: _lowerCamelCase : Union[str, Any] = ViTImageProcessor() # create model if model_args.model_name_or_path: _lowerCamelCase : List[Any] = ViTMAEForPreTraining.from_pretrained( model_args.model_name_or_path , from_tf=bool(""".ckpt""" in model_args.model_name_or_path ) , config=__snake_case , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) else: logger.info("""Training new model from scratch""" ) _lowerCamelCase : Union[str, Any] = ViTMAEForPreTraining(__snake_case ) if training_args.do_train: _lowerCamelCase : List[Any] = ds["""train"""].column_names else: _lowerCamelCase : Union[str, Any] = ds["""validation"""].column_names if data_args.image_column_name is not None: _lowerCamelCase : str = data_args.image_column_name elif "image" in column_names: _lowerCamelCase : Optional[Any] = """image""" elif "img" in column_names: _lowerCamelCase : List[Any] = """img""" else: _lowerCamelCase : str = 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: _lowerCamelCase : Dict = image_processor.size["""shortest_edge"""] else: _lowerCamelCase : List[Any] = (image_processor.size["""height"""], image_processor.size["""width"""]) _lowerCamelCase : Tuple = Compose( [ Lambda(lambda __snake_case : img.convert("""RGB""" ) if img.mode != "RGB" else img ), RandomResizedCrop(__snake_case , scale=(0.2, 1.0) , interpolation=InterpolationMode.BICUBIC ), RandomHorizontalFlip(), ToTensor(), Normalize(mean=image_processor.image_mean , std=image_processor.image_std ), ] ) def preprocess_images(__snake_case : Optional[Any] ): _lowerCamelCase : Dict = [transforms(__snake_case ) 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: _lowerCamelCase : int = ds["""train"""].shuffle(seed=training_args.seed ).select(range(data_args.max_train_samples ) ) # Set the training transforms ds["train"].set_transform(__snake_case ) 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: _lowerCamelCase : Union[str, Any] = ( ds["""validation"""].shuffle(seed=training_args.seed ).select(range(data_args.max_eval_samples ) ) ) # Set the validation transforms ds["validation"].set_transform(__snake_case ) # Compute absolute learning rate _lowerCamelCase : Optional[Any] = ( training_args.train_batch_size * training_args.gradient_accumulation_steps * training_args.world_size ) if training_args.base_learning_rate is not None: _lowerCamelCase : Tuple = training_args.base_learning_rate * total_train_batch_size / 256 # Initialize our trainer _lowerCamelCase : Optional[Any] = Trainer( model=__snake_case , args=__snake_case , train_dataset=ds["""train"""] if training_args.do_train else None , eval_dataset=ds["""validation"""] if training_args.do_eval else None , tokenizer=__snake_case , data_collator=__snake_case , ) # Training if training_args.do_train: _lowerCamelCase : Any = None if training_args.resume_from_checkpoint is not None: _lowerCamelCase : List[Any] = training_args.resume_from_checkpoint elif last_checkpoint is not None: _lowerCamelCase : Union[str, Any] = last_checkpoint _lowerCamelCase : Optional[Any] = trainer.train(resume_from_checkpoint=__snake_case ) trainer.save_model() trainer.log_metrics("""train""" , train_result.metrics ) trainer.save_metrics("""train""" , train_result.metrics ) trainer.save_state() # Evaluation if training_args.do_eval: _lowerCamelCase : int = trainer.evaluate() trainer.log_metrics("""eval""" , __snake_case ) trainer.save_metrics("""eval""" , __snake_case ) # Write model card and (optionally) push to hub _lowerCamelCase : Optional[Any] = { """tasks""": """masked-auto-encoding""", """dataset""": data_args.dataset_name, """tags""": ["""masked-auto-encoding"""], } if training_args.push_to_hub: trainer.push_to_hub(**__snake_case ) else: trainer.create_model_card(**__snake_case ) def _snake_case ( __snake_case : Dict ): """simple docstring""" main() if __name__ == "__main__": main()
88
0
import os from huggingface_hub.constants import HUGGINGFACE_HUB_CACHE, hf_cache_home lowerCamelCase__ = HUGGINGFACE_HUB_CACHE lowerCamelCase__ = """config.json""" lowerCamelCase__ = """diffusion_pytorch_model.bin""" lowerCamelCase__ = """diffusion_flax_model.msgpack""" lowerCamelCase__ = """model.onnx""" lowerCamelCase__ = """diffusion_pytorch_model.safetensors""" lowerCamelCase__ = """weights.pb""" lowerCamelCase__ = """https://huggingface.co""" lowerCamelCase__ = default_cache_path lowerCamelCase__ = """diffusers_modules""" lowerCamelCase__ = os.getenv("""HF_MODULES_CACHE""", os.path.join(hf_cache_home, """modules""")) lowerCamelCase__ = ["""fp16""", """non-ema"""] lowerCamelCase__ = """.self_attn"""
455
"""simple docstring""" import numpy as np def _snake_case ( __snake_case : np.ndarray ): """simple docstring""" return 1 / (1 + np.exp(-vector )) def _snake_case ( __snake_case : np.ndarray ): """simple docstring""" return vector * sigmoid(__snake_case ) if __name__ == "__main__": import doctest doctest.testmod()
88
0
import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, StableDiffusionAttendAndExcitePipeline, UNetaDConditionModel, ) from diffusers.utils import load_numpy, skip_mps, slow from diffusers.utils.testing_utils import require_torch_gpu from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin lowercase : Tuple = False @skip_mps class A__ ( A_ , A_ , A_ , unittest.TestCase ): """simple docstring""" __A : Any = StableDiffusionAttendAndExcitePipeline __A : Dict = False __A : int = TEXT_TO_IMAGE_PARAMS __A : Union[str, Any] = TEXT_TO_IMAGE_BATCH_PARAMS.union({'''token_indices'''} ) __A : str = TEXT_TO_IMAGE_IMAGE_PARAMS __A : str = TEXT_TO_IMAGE_IMAGE_PARAMS @classmethod def __lowercase ( cls) -> List[Any]: '''simple docstring''' super().setUpClass() torch.use_deterministic_algorithms(lowercase) @classmethod def __lowercase ( cls) -> Optional[Any]: '''simple docstring''' super().tearDownClass() torch.use_deterministic_algorithms(lowercase) def __lowercase ( self) -> Dict: '''simple docstring''' torch.manual_seed(0) a__ : Optional[int] = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=1 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D') , up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D') , cross_attention_dim=32 , attention_head_dim=(2, 4) , use_linear_projection=lowercase , ) a__ : int = DDIMScheduler( beta_start=0.0_00_85 , beta_end=0.0_12 , beta_schedule='scaled_linear' , clip_sample=lowercase , set_alpha_to_one=lowercase , ) torch.manual_seed(0) a__ : 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__ : Dict = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , hidden_act='gelu' , projection_dim=512 , ) a__ : Dict = CLIPTextModel(lowercase) a__ : int = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip') a__ : Dict = { """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """safety_checker""": None, """feature_extractor""": None, } return components def __lowercase ( self , lowercase , lowercase=0) -> Any: '''simple docstring''' if str(lowercase).startswith('mps'): a__ : Tuple = torch.manual_seed(lowercase) else: a__ : Any = torch.Generator(device=lowercase).manual_seed(lowercase) a__ : Union[str, Any] = { """prompt""": """a cat and a frog""", """token_indices""": [2, 5], """generator""": generator, """num_inference_steps""": 1, """guidance_scale""": 6.0, """output_type""": """numpy""", """max_iter_to_alter""": 2, """thresholds""": {0: 0.7}, } return inputs def __lowercase ( self) -> List[Any]: '''simple docstring''' a__ : Dict = """cpu""" a__ : Tuple = self.get_dummy_components() a__ : Tuple = self.pipeline_class(**lowercase) pipe.to(lowercase) pipe.set_progress_bar_config(disable=lowercase) a__ : List[Any] = self.get_dummy_inputs(lowercase) a__ : List[Any] = pipe(**lowercase).images a__ : List[str] = image[0, -3:, -3:, -1] self.assertEqual(image.shape , (1, 64, 64, 3)) a__ : int = np.array( [0.63_90_53_64, 0.62_89_73_07, 0.48_59_90_17, 0.5_13_36_24, 0.5_55_00_48, 0.45_76_95_16, 0.50_32_69_73, 0.5_02_31_39, 0.45_38_44_96]) a__ : Any = np.abs(image_slice.flatten() - expected_slice).max() self.assertLessEqual(lowercase , 1e-3) def __lowercase ( self) -> List[str]: '''simple docstring''' super().test_cpu_offload_forward_pass(expected_max_diff=5e-4) def __lowercase ( self) -> Optional[Any]: '''simple docstring''' self._test_inference_batch_consistent(batch_sizes=[1, 2]) def __lowercase ( self) -> Optional[Any]: '''simple docstring''' self._test_inference_batch_single_identical(batch_size=2 , expected_max_diff=7e-4) def __lowercase ( self) -> Tuple: '''simple docstring''' super().test_dict_tuple_outputs_equivalent(expected_max_difference=3e-3) def __lowercase ( self) -> str: '''simple docstring''' super().test_pt_np_pil_outputs_equivalent(expected_max_diff=5e-4) def __lowercase ( self) -> str: '''simple docstring''' super().test_save_load_local(expected_max_difference=5e-4) def __lowercase ( self) -> int: '''simple docstring''' super().test_save_load_optional_components(expected_max_difference=4e-4) @require_torch_gpu @slow class A__ ( unittest.TestCase ): """simple docstring""" @classmethod def __lowercase ( cls) -> Any: '''simple docstring''' super().setUpClass() torch.use_deterministic_algorithms(lowercase) @classmethod def __lowercase ( cls) -> str: '''simple docstring''' super().tearDownClass() torch.use_deterministic_algorithms(lowercase) def __lowercase ( self) -> Union[str, Any]: '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def __lowercase ( self) -> Dict: '''simple docstring''' a__ : Dict = torch.manual_seed(51) a__ : str = StableDiffusionAttendAndExcitePipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , safety_checker=lowercase , torch_dtype=torch.floataa) pipe.to('cuda') a__ : List[str] = """a painting of an elephant with glasses""" a__ : Optional[Any] = [5, 7] a__ : List[Any] = pipe( prompt=lowercase , token_indices=lowercase , guidance_scale=7.5 , generator=lowercase , num_inference_steps=5 , max_iter_to_alter=5 , output_type='numpy' , ).images[0] a__ : Tuple = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/attend-and-excite/elephant_glasses.npy') assert np.abs((expected_image - image).max()) < 5e-1
302
"""simple docstring""" from transformers import HfArgumentParser, TensorFlowBenchmark, TensorFlowBenchmarkArguments def _snake_case ( ): """simple docstring""" _lowerCamelCase : Any = HfArgumentParser(__snake_case ) _lowerCamelCase : int = parser.parse_args_into_dataclasses()[0] _lowerCamelCase : Dict = TensorFlowBenchmark(args=__snake_case ) try: _lowerCamelCase : Optional[int] = parser.parse_args_into_dataclasses()[0] except ValueError as e: _lowerCamelCase : Union[str, Any] = """Arg --no_{0} is no longer used, please use --no-{0} instead.""" _lowerCamelCase : List[str] = """ """.join(str(__snake_case ).split(""" """ )[:-1] ) _lowerCamelCase : Dict = """""" _lowerCamelCase : List[Any] = eval(str(__snake_case ).split(""" """ )[-1] ) _lowerCamelCase : Tuple = [] for arg in depreciated_args: # arg[2:] removes '--' if arg[2:] in TensorFlowBenchmark.deprecated_args: # arg[5:] removes '--no_' full_error_msg += arg_error_msg.format(arg[5:] ) else: wrong_args.append(__snake_case ) if len(__snake_case ) > 0: _lowerCamelCase : Tuple = full_error_msg + begin_error_msg + str(__snake_case ) raise ValueError(__snake_case ) benchmark.run() if __name__ == "__main__": main()
88
0
from ...configuration_utils import PretrainedConfig from ...utils import logging __UpperCAmelCase = logging.get_logger(__name__) __UpperCAmelCase = { '''google/switch-base-8''': '''https://huggingface.co/google/switch-base-8/blob/main/config.json''', } class lowerCAmelCase_ ( A_ ): UpperCAmelCase__ : int = "switch_transformers" UpperCAmelCase__ : Optional[int] = ["past_key_values"] UpperCAmelCase__ : Any = {"hidden_size": "d_model", "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers"} def __init__( self, SCREAMING_SNAKE_CASE_=3_2128, SCREAMING_SNAKE_CASE_=768, SCREAMING_SNAKE_CASE_=64, SCREAMING_SNAKE_CASE_=2048, SCREAMING_SNAKE_CASE_=64, SCREAMING_SNAKE_CASE_=12, SCREAMING_SNAKE_CASE_=3, SCREAMING_SNAKE_CASE_=12, SCREAMING_SNAKE_CASE_=3, SCREAMING_SNAKE_CASE_=12, SCREAMING_SNAKE_CASE_=8, SCREAMING_SNAKE_CASE_=False, SCREAMING_SNAKE_CASE_=0.01, SCREAMING_SNAKE_CASE_="float32", SCREAMING_SNAKE_CASE_=False, SCREAMING_SNAKE_CASE_=32, SCREAMING_SNAKE_CASE_=128, SCREAMING_SNAKE_CASE_=0.1, SCREAMING_SNAKE_CASE_=1e-6, SCREAMING_SNAKE_CASE_=0.0_01, SCREAMING_SNAKE_CASE_=0.0_01, SCREAMING_SNAKE_CASE_=1.0, SCREAMING_SNAKE_CASE_="relu", SCREAMING_SNAKE_CASE_=True, SCREAMING_SNAKE_CASE_=False, SCREAMING_SNAKE_CASE_=True, SCREAMING_SNAKE_CASE_=0, SCREAMING_SNAKE_CASE_=1, **SCREAMING_SNAKE_CASE_, ) -> Any: UpperCamelCase : Optional[int] = vocab_size UpperCamelCase : str = d_model UpperCamelCase : Tuple = d_kv UpperCamelCase : Any = d_ff UpperCamelCase : str = num_sparse_encoder_layers UpperCamelCase : Tuple = num_layers UpperCamelCase : List[Any] = ( num_decoder_layers if num_decoder_layers is not None else self.num_layers ) # default = symmetry UpperCamelCase : Optional[int] = num_sparse_decoder_layers # This tells us, each how many encoder layer we'll have to set a sparse layer. if self.num_sparse_encoder_layers > 0: UpperCamelCase : Union[str, Any] = self.num_layers // self.num_sparse_encoder_layers else: UpperCamelCase : Union[str, Any] = self.num_layers # HACK: this will create 0 sparse layers # This tells us, each how many encoder layer we'll have to set a sparse layer. if self.num_sparse_decoder_layers > 0: UpperCamelCase : str = self.num_decoder_layers // self.num_sparse_decoder_layers else: UpperCamelCase : Tuple = self.num_decoder_layers # HACK: this will create 0 sparse layers UpperCamelCase : Dict = num_heads UpperCamelCase : List[Any] = num_experts UpperCamelCase : Dict = expert_capacity UpperCamelCase : Tuple = router_bias UpperCamelCase : Any = router_jitter_noise if router_dtype not in ["float32", "float16", "bfloat16"]: raise ValueError(F"""`router_dtype` must be one of \'float32\', \'float16\' or \'bfloat16\', got {router_dtype}""" ) UpperCamelCase : List[Any] = router_dtype UpperCamelCase : List[Any] = router_ignore_padding_tokens UpperCamelCase : Optional[int] = relative_attention_num_buckets UpperCamelCase : List[str] = relative_attention_max_distance UpperCamelCase : Tuple = dropout_rate UpperCamelCase : List[Any] = layer_norm_epsilon UpperCamelCase : Dict = initializer_factor UpperCamelCase : List[Any] = feed_forward_proj UpperCamelCase : Optional[Any] = use_cache UpperCamelCase : str = add_router_probs UpperCamelCase : Optional[Any] = router_z_loss_coef UpperCamelCase : int = router_aux_loss_coef UpperCamelCase : Union[str, Any] = self.feed_forward_proj.split('-' ) UpperCamelCase : Any = act_info[-1] UpperCamelCase : Any = act_info[0] == """gated""" if len(SCREAMING_SNAKE_CASE_ ) > 1 and act_info[0] != "gated" or len(SCREAMING_SNAKE_CASE_ ) > 2: raise ValueError( F"""`feed_forward_proj`: {feed_forward_proj} is not a valid activation function of the dense layer.""" 'Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. ' '\'gated-gelu\' or \'relu\'' ) # for backwards compatibility if feed_forward_proj == "gated-gelu": UpperCamelCase : Dict = """gelu_new""" super().__init__( pad_token_id=SCREAMING_SNAKE_CASE_, eos_token_id=SCREAMING_SNAKE_CASE_, is_encoder_decoder=SCREAMING_SNAKE_CASE_, **SCREAMING_SNAKE_CASE_, )
40
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging UpperCAmelCase = logging.get_logger(__name__) UpperCAmelCase = { """kssteven/ibert-roberta-base""": """https://huggingface.co/kssteven/ibert-roberta-base/resolve/main/config.json""", """kssteven/ibert-roberta-large""": """https://huggingface.co/kssteven/ibert-roberta-large/resolve/main/config.json""", """kssteven/ibert-roberta-large-mnli""": ( """https://huggingface.co/kssteven/ibert-roberta-large-mnli/resolve/main/config.json""" ), } class lowercase__ ( A_ ): __UpperCAmelCase = '''ibert''' def __init__( self , SCREAMING_SNAKE_CASE=3_0522 , SCREAMING_SNAKE_CASE=768 , SCREAMING_SNAKE_CASE=12 , SCREAMING_SNAKE_CASE=12 , SCREAMING_SNAKE_CASE=3072 , SCREAMING_SNAKE_CASE="gelu" , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=512 , SCREAMING_SNAKE_CASE=2 , SCREAMING_SNAKE_CASE=0.02 , SCREAMING_SNAKE_CASE=1e-1_2 , SCREAMING_SNAKE_CASE=1 , SCREAMING_SNAKE_CASE=0 , SCREAMING_SNAKE_CASE=2 , SCREAMING_SNAKE_CASE="absolute" , SCREAMING_SNAKE_CASE=False , SCREAMING_SNAKE_CASE="none" , **SCREAMING_SNAKE_CASE , ) -> Any: super().__init__(pad_token_id=SCREAMING_SNAKE_CASE , bos_token_id=SCREAMING_SNAKE_CASE , eos_token_id=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE) _lowerCamelCase : Optional[int] = vocab_size _lowerCamelCase : Dict = hidden_size _lowerCamelCase : List[str] = num_hidden_layers _lowerCamelCase : int = num_attention_heads _lowerCamelCase : Tuple = hidden_act _lowerCamelCase : str = intermediate_size _lowerCamelCase : Union[str, Any] = hidden_dropout_prob _lowerCamelCase : Tuple = attention_probs_dropout_prob _lowerCamelCase : Any = max_position_embeddings _lowerCamelCase : Dict = type_vocab_size _lowerCamelCase : List[Any] = initializer_range _lowerCamelCase : Dict = layer_norm_eps _lowerCamelCase : List[Any] = position_embedding_type _lowerCamelCase : Any = quant_mode _lowerCamelCase : List[str] = force_dequant class lowercase__ ( A_ ): @property def UpperCamelCase_ ( self) -> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": _lowerCamelCase : Dict = {0: """batch""", 1: """choice""", 2: """sequence"""} else: _lowerCamelCase : Optional[int] = {0: """batch""", 1: """sequence"""} return OrderedDict( [ ("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ])
88
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) lowercase : Union[str, Any] = { 'configuration_whisper': ['WHISPER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'WhisperConfig', 'WhisperOnnxConfig'], 'feature_extraction_whisper': ['WhisperFeatureExtractor'], 'processing_whisper': ['WhisperProcessor'], 'tokenization_whisper': ['WhisperTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase : Dict = ['WhisperTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase : Dict = [ 'WHISPER_PRETRAINED_MODEL_ARCHIVE_LIST', 'WhisperForConditionalGeneration', 'WhisperModel', 'WhisperPreTrainedModel', 'WhisperForAudioClassification', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase : Optional[Any] = [ 'TF_WHISPER_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFWhisperForConditionalGeneration', 'TFWhisperModel', 'TFWhisperPreTrainedModel', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase : Tuple = [ 'FlaxWhisperForConditionalGeneration', 'FlaxWhisperModel', 'FlaxWhisperPreTrainedModel', 'FlaxWhisperForAudioClassification', ] if TYPE_CHECKING: from .configuration_whisper import WHISPER_PRETRAINED_CONFIG_ARCHIVE_MAP, WhisperConfig, WhisperOnnxConfig from .feature_extraction_whisper import WhisperFeatureExtractor from .processing_whisper import WhisperProcessor from .tokenization_whisper import WhisperTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_whisper_fast import WhisperTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_whisper import ( WHISPER_PRETRAINED_MODEL_ARCHIVE_LIST, WhisperForAudioClassification, WhisperForConditionalGeneration, WhisperModel, WhisperPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_whisper import ( TF_WHISPER_PRETRAINED_MODEL_ARCHIVE_LIST, TFWhisperForConditionalGeneration, TFWhisperModel, TFWhisperPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_whisper import ( FlaxWhisperForAudioClassification, FlaxWhisperForConditionalGeneration, FlaxWhisperModel, FlaxWhisperPreTrainedModel, ) else: import sys lowercase : Tuple = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
634
"""simple docstring""" from __future__ import annotations import queue class lowercase__ : def __init__( self , SCREAMING_SNAKE_CASE) -> int: _lowerCamelCase : int = data _lowerCamelCase : List[str] = None _lowerCamelCase : Any = None def _snake_case ( ): """simple docstring""" print("""\n********Press N to stop entering at any point of time********\n""" ) _lowerCamelCase : Optional[int] = input("""Enter the value of the root node: """ ).strip().lower() _lowerCamelCase : queue.Queue = queue.Queue() _lowerCamelCase : Optional[int] = TreeNode(int(__snake_case ) ) q.put(__snake_case ) while not q.empty(): _lowerCamelCase : Tuple = q.get() _lowerCamelCase : Any = F'Enter the left node of {node_found.data}: ' _lowerCamelCase : Union[str, Any] = input(__snake_case ).strip().lower() or """n""" if check == "n": return tree_node _lowerCamelCase : Dict = TreeNode(int(__snake_case ) ) _lowerCamelCase : List[str] = left_node q.put(__snake_case ) _lowerCamelCase : Optional[int] = F'Enter the right node of {node_found.data}: ' _lowerCamelCase : Optional[Any] = input(__snake_case ).strip().lower() or """n""" if check == "n": return tree_node _lowerCamelCase : List[Any] = TreeNode(int(__snake_case ) ) _lowerCamelCase : List[Any] = right_node q.put(__snake_case ) raise def _snake_case ( __snake_case : TreeNode ): """simple docstring""" if not isinstance(__snake_case , __snake_case ) or not node: return print(node.data , end=""",""" ) pre_order(node.left ) pre_order(node.right ) def _snake_case ( __snake_case : TreeNode ): """simple docstring""" if not isinstance(__snake_case , __snake_case ) or not node: return in_order(node.left ) print(node.data , end=""",""" ) in_order(node.right ) def _snake_case ( __snake_case : TreeNode ): """simple docstring""" if not isinstance(__snake_case , __snake_case ) or not node: return post_order(node.left ) post_order(node.right ) print(node.data , end=""",""" ) def _snake_case ( __snake_case : TreeNode ): """simple docstring""" if not isinstance(__snake_case , __snake_case ) or not node: return _lowerCamelCase : queue.Queue = queue.Queue() q.put(__snake_case ) while not q.empty(): _lowerCamelCase : Any = q.get() print(node_dequeued.data , end=""",""" ) if node_dequeued.left: q.put(node_dequeued.left ) if node_dequeued.right: q.put(node_dequeued.right ) def _snake_case ( __snake_case : TreeNode ): """simple docstring""" if not isinstance(__snake_case , __snake_case ) or not node: return _lowerCamelCase : queue.Queue = queue.Queue() q.put(__snake_case ) while not q.empty(): _lowerCamelCase : Optional[Any] = [] while not q.empty(): _lowerCamelCase : Dict = q.get() print(node_dequeued.data , end=""",""" ) if node_dequeued.left: list_.append(node_dequeued.left ) if node_dequeued.right: list_.append(node_dequeued.right ) print() for node in list_: q.put(__snake_case ) def _snake_case ( __snake_case : TreeNode ): """simple docstring""" if not isinstance(__snake_case , __snake_case ) or not node: return _lowerCamelCase : list[TreeNode] = [] _lowerCamelCase : Optional[int] = node while n or stack: while n: # start from root node, find its left child print(n.data , end=""",""" ) stack.append(__snake_case ) _lowerCamelCase : Tuple = n.left # end of while means current node doesn't have left child _lowerCamelCase : Optional[Any] = stack.pop() # start to traverse its right child _lowerCamelCase : Dict = n.right def _snake_case ( __snake_case : TreeNode ): """simple docstring""" if not isinstance(__snake_case , __snake_case ) or not node: return _lowerCamelCase : list[TreeNode] = [] _lowerCamelCase : int = node while n or stack: while n: stack.append(__snake_case ) _lowerCamelCase : Any = n.left _lowerCamelCase : Optional[Any] = stack.pop() print(n.data , end=""",""" ) _lowerCamelCase : List[Any] = n.right def _snake_case ( __snake_case : TreeNode ): """simple docstring""" if not isinstance(__snake_case , __snake_case ) or not node: return _lowerCamelCase , _lowerCamelCase : Union[str, Any] = [], [] _lowerCamelCase : Optional[Any] = node stacka.append(__snake_case ) while stacka: # to find the reversed order of post order, store it in stack2 _lowerCamelCase : Union[str, Any] = stacka.pop() if n.left: stacka.append(n.left ) if n.right: stacka.append(n.right ) stacka.append(__snake_case ) while stacka: # pop up from stack2 will be the post order print(stacka.pop().data , end=""",""" ) def _snake_case ( __snake_case : str = "" , __snake_case : Any=50 , __snake_case : List[str]="*" ): """simple docstring""" if not s: return "\n" + width * char _lowerCamelCase , _lowerCamelCase : Optional[int] = divmod(width - len(__snake_case ) - 2 , 2 ) return F'{left * char} {s} {(left + extra) * char}' if __name__ == "__main__": import doctest doctest.testmod() print(prompt("""Binary Tree Traversals""")) UpperCAmelCase = build_tree() print(prompt("""Pre Order Traversal""")) pre_order(node) print(prompt() + """\n""") print(prompt("""In Order Traversal""")) in_order(node) print(prompt() + """\n""") print(prompt("""Post Order Traversal""")) post_order(node) print(prompt() + """\n""") print(prompt("""Level Order Traversal""")) level_order(node) print(prompt() + """\n""") print(prompt("""Actual Level Order Traversal""")) level_order_actual(node) print("""*""" * 50 + """\n""") print(prompt("""Pre Order Traversal - Iteration Version""")) pre_order_iter(node) print(prompt() + """\n""") print(prompt("""In Order Traversal - Iteration Version""")) in_order_iter(node) print(prompt() + """\n""") print(prompt("""Post Order Traversal - Iteration Version""")) post_order_iter(node) print(prompt())
88
0
'''simple docstring''' import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging UpperCAmelCase_ : str = logging.get_logger(__name__) UpperCAmelCase_ : Tuple = {'''vocab_file''': '''sentencepiece.bpe.model'''} UpperCAmelCase_ : Optional[Any] = { '''vocab_file''': { '''moussaKam/mbarthez''': '''https://huggingface.co/moussaKam/mbarthez/resolve/main/sentencepiece.bpe.model''', '''moussaKam/barthez''': '''https://huggingface.co/moussaKam/barthez/resolve/main/sentencepiece.bpe.model''', '''moussaKam/barthez-orangesum-title''': ( '''https://huggingface.co/moussaKam/barthez-orangesum-title/resolve/main/sentencepiece.bpe.model''' ), }, } UpperCAmelCase_ : List[str] = { '''moussaKam/mbarthez''': 1_0_2_4, '''moussaKam/barthez''': 1_0_2_4, '''moussaKam/barthez-orangesum-title''': 1_0_2_4, } UpperCAmelCase_ : Optional[Any] = '''▁''' class lowerCAmelCase ( A_): __lowercase : int = VOCAB_FILES_NAMES __lowercase : Any = PRETRAINED_VOCAB_FILES_MAP __lowercase : List[str] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __lowercase : Optional[Any] = ['''input_ids''', '''attention_mask'''] def __init__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE="<s>" , __SCREAMING_SNAKE_CASE="</s>" , __SCREAMING_SNAKE_CASE="</s>" , __SCREAMING_SNAKE_CASE="<s>" , __SCREAMING_SNAKE_CASE="<unk>" , __SCREAMING_SNAKE_CASE="<pad>" , __SCREAMING_SNAKE_CASE="<mask>" , __SCREAMING_SNAKE_CASE = None , **__SCREAMING_SNAKE_CASE , ) -> None: '''simple docstring''' __snake_case = AddedToken(__SCREAMING_SNAKE_CASE , lstrip=__SCREAMING_SNAKE_CASE , rstrip=__SCREAMING_SNAKE_CASE ) if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) else mask_token __snake_case = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=__SCREAMING_SNAKE_CASE , eos_token=__SCREAMING_SNAKE_CASE , unk_token=__SCREAMING_SNAKE_CASE , sep_token=__SCREAMING_SNAKE_CASE , cls_token=__SCREAMING_SNAKE_CASE , pad_token=__SCREAMING_SNAKE_CASE , mask_token=__SCREAMING_SNAKE_CASE , sp_model_kwargs=self.sp_model_kwargs , **__SCREAMING_SNAKE_CASE , ) __snake_case = vocab_file __snake_case = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(__SCREAMING_SNAKE_CASE ) ) __snake_case = {"""<s>""": 0, """<pad>""": 1, """</s>""": 2, """<unk>""": 3} __snake_case = len(self.sp_model ) - 1 __snake_case = {v: k for k, v in self.fairseq_tokens_to_ids.items()} def lowerCAmelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None ) -> List[int]: '''simple docstring''' if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] __snake_case = [self.cls_token_id] __snake_case = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def lowerCAmelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = False ) -> List[int]: '''simple docstring''' if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__SCREAMING_SNAKE_CASE , token_ids_a=__SCREAMING_SNAKE_CASE , already_has_special_tokens=__SCREAMING_SNAKE_CASE ) if token_ids_a is None: return [1] + ([0] * len(__SCREAMING_SNAKE_CASE )) + [1] return [1] + ([0] * len(__SCREAMING_SNAKE_CASE )) + [1, 1] + ([0] * len(__SCREAMING_SNAKE_CASE )) + [1] def lowerCAmelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None ) -> List[int]: '''simple docstring''' __snake_case = [self.sep_token_id] __snake_case = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] @property def lowerCAmelCase ( self ) -> Union[str, Any]: '''simple docstring''' return len(self.sp_model ) def lowerCAmelCase ( self ) -> Dict: '''simple docstring''' __snake_case = {self.convert_ids_to_tokens(__SCREAMING_SNAKE_CASE ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def lowerCAmelCase ( self , __SCREAMING_SNAKE_CASE ) -> List[str]: '''simple docstring''' return self.sp_model.encode(__SCREAMING_SNAKE_CASE , out_type=__SCREAMING_SNAKE_CASE ) def lowerCAmelCase ( self , __SCREAMING_SNAKE_CASE ) -> str: '''simple docstring''' if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] __snake_case = self.sp_model.PieceToId(__SCREAMING_SNAKE_CASE ) return spm_id if spm_id else self.unk_token_id def lowerCAmelCase ( self , __SCREAMING_SNAKE_CASE ) -> List[str]: '''simple docstring''' if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(__SCREAMING_SNAKE_CASE ) def lowerCAmelCase ( self , __SCREAMING_SNAKE_CASE ) -> str: '''simple docstring''' __snake_case = [] __snake_case = """""" __snake_case = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(__SCREAMING_SNAKE_CASE ) + token __snake_case = True __snake_case = [] else: current_sub_tokens.append(__SCREAMING_SNAKE_CASE ) __snake_case = False out_string += self.sp_model.decode(__SCREAMING_SNAKE_CASE ) return out_string.strip() def __getstate__( self ) -> int: '''simple docstring''' __snake_case = self.__dict__.copy() __snake_case = None return state def __setstate__( self , __SCREAMING_SNAKE_CASE ) -> Dict: '''simple docstring''' __snake_case = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): __snake_case = {} __snake_case = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def lowerCAmelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None ) -> Tuple[str]: '''simple docstring''' if not os.path.isdir(__SCREAMING_SNAKE_CASE ): logger.error(F'''Vocabulary path ({save_directory}) should be a directory''' ) return __snake_case = os.path.join( __SCREAMING_SNAKE_CASE , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__SCREAMING_SNAKE_CASE ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , __SCREAMING_SNAKE_CASE ) elif not os.path.isfile(self.vocab_file ): with open(__SCREAMING_SNAKE_CASE , '''wb''' ) as fi: __snake_case = self.sp_model.serialized_model_proto() fi.write(__SCREAMING_SNAKE_CASE ) return (out_vocab_file,)
24
"""simple docstring""" from __future__ import annotations import unittest from transformers import XGLMConfig, XGLMTokenizer, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers.models.xglm.modeling_tf_xglm import ( TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST, TFXGLMForCausalLM, TFXGLMModel, ) @require_tf class lowercase__ : __UpperCAmelCase = XGLMConfig __UpperCAmelCase = {} __UpperCAmelCase = '''gelu''' def __init__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=14 , SCREAMING_SNAKE_CASE=7 , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=99 , SCREAMING_SNAKE_CASE=32 , SCREAMING_SNAKE_CASE=2 , SCREAMING_SNAKE_CASE=4 , SCREAMING_SNAKE_CASE=37 , SCREAMING_SNAKE_CASE="gelu" , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=512 , SCREAMING_SNAKE_CASE=0.02 , ) -> List[str]: _lowerCamelCase : Optional[int] = parent _lowerCamelCase : int = batch_size _lowerCamelCase : str = seq_length _lowerCamelCase : Any = is_training _lowerCamelCase : int = use_input_mask _lowerCamelCase : Union[str, Any] = use_labels _lowerCamelCase : str = vocab_size _lowerCamelCase : List[str] = d_model _lowerCamelCase : List[Any] = num_hidden_layers _lowerCamelCase : Dict = num_attention_heads _lowerCamelCase : int = ffn_dim _lowerCamelCase : str = activation_function _lowerCamelCase : Optional[int] = activation_dropout _lowerCamelCase : Tuple = attention_dropout _lowerCamelCase : Tuple = max_position_embeddings _lowerCamelCase : Dict = initializer_range _lowerCamelCase : Optional[Any] = None _lowerCamelCase : Union[str, Any] = 0 _lowerCamelCase : List[Any] = 2 _lowerCamelCase : str = 1 def UpperCamelCase_ ( self) -> int: return XGLMConfig.from_pretrained("""facebook/xglm-564M""") def UpperCamelCase_ ( self) -> int: _lowerCamelCase : Union[str, Any] = tf.clip_by_value( ids_tensor([self.batch_size, self.seq_length] , self.vocab_size) , clip_value_min=0 , clip_value_max=3) _lowerCamelCase : str = None if self.use_input_mask: _lowerCamelCase : Union[str, Any] = random_attention_mask([self.batch_size, self.seq_length]) _lowerCamelCase : Tuple = self.get_config() _lowerCamelCase : Optional[int] = floats_tensor([self.num_hidden_layers, self.num_attention_heads] , 2) return ( config, input_ids, input_mask, head_mask, ) def UpperCamelCase_ ( self) -> Optional[int]: return XGLMConfig( vocab_size=self.vocab_size , d_model=self.hidden_size , num_layers=self.num_hidden_layers , attention_heads=self.num_attention_heads , ffn_dim=self.ffn_dim , activation_function=self.activation_function , activation_dropout=self.activation_dropout , attention_dropout=self.attention_dropout , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , use_cache=SCREAMING_SNAKE_CASE , bos_token_id=self.bos_token_id , eos_token_id=self.eos_token_id , pad_token_id=self.pad_token_id , return_dict=SCREAMING_SNAKE_CASE , ) def UpperCamelCase_ ( self) -> Optional[int]: _lowerCamelCase : List[Any] = self.prepare_config_and_inputs() ( ( _lowerCamelCase ) , ( _lowerCamelCase ) , ( _lowerCamelCase ) , ( _lowerCamelCase ) , ) : str = config_and_inputs _lowerCamelCase : Optional[Any] = { """input_ids""": input_ids, """head_mask""": head_mask, } return config, inputs_dict @require_tf class lowercase__ ( A_ ,A_ ,unittest.TestCase ): __UpperCAmelCase = (TFXGLMModel, TFXGLMForCausalLM) if is_tf_available() else () __UpperCAmelCase = (TFXGLMForCausalLM,) if is_tf_available() else () __UpperCAmelCase = ( {'''feature-extraction''': TFXGLMModel, '''text-generation''': TFXGLMForCausalLM} if is_tf_available() else {} ) __UpperCAmelCase = False __UpperCAmelCase = False __UpperCAmelCase = False def UpperCamelCase_ ( self) -> Optional[Any]: _lowerCamelCase : Optional[Any] = TFXGLMModelTester(self) _lowerCamelCase : str = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE , n_embd=37) def UpperCamelCase_ ( self) -> Dict: self.config_tester.run_common_tests() @slow def UpperCamelCase_ ( self) -> List[Any]: for model_name in TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _lowerCamelCase : Tuple = TFXGLMModel.from_pretrained(SCREAMING_SNAKE_CASE) self.assertIsNotNone(SCREAMING_SNAKE_CASE) @unittest.skip(reason="""Currently, model embeddings are going to undergo a major refactor.""") def UpperCamelCase_ ( self) -> List[Any]: super().test_resize_token_embeddings() @require_tf class lowercase__ ( unittest.TestCase ): @slow def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE=True) -> List[Any]: _lowerCamelCase : List[str] = TFXGLMForCausalLM.from_pretrained("""facebook/xglm-564M""") _lowerCamelCase : Union[str, Any] = tf.convert_to_tensor([[2, 268, 9865]] , dtype=tf.intaa) # The dog # </s> The dog is a very friendly dog. He is very affectionate and loves to play with other # fmt: off _lowerCamelCase : Dict = [2, 268, 9865, 67, 11, 1988, 5_7252, 9865, 5, 984, 67, 1988, 21_3838, 1658, 53, 7_0446, 33, 6657, 278, 1581] # fmt: on _lowerCamelCase : str = model.generate(SCREAMING_SNAKE_CASE , do_sample=SCREAMING_SNAKE_CASE , num_beams=1) if verify_outputs: self.assertListEqual(output_ids[0].numpy().tolist() , SCREAMING_SNAKE_CASE) @slow def UpperCamelCase_ ( self) -> int: _lowerCamelCase : int = XGLMTokenizer.from_pretrained("""facebook/xglm-564M""") _lowerCamelCase : Tuple = TFXGLMForCausalLM.from_pretrained("""facebook/xglm-564M""") tf.random.set_seed(0) _lowerCamelCase : Union[str, Any] = tokenizer("""Today is a nice day and""" , return_tensors="""tf""") _lowerCamelCase : Any = tokenized.input_ids # forces the generation to happen on CPU, to avoid GPU-related quirks (and assure same output regardless of the available devices) with tf.device(""":/CPU:0"""): _lowerCamelCase : Any = model.generate(SCREAMING_SNAKE_CASE , do_sample=SCREAMING_SNAKE_CASE , seed=[7, 0]) _lowerCamelCase : List[str] = tokenizer.decode(output_ids[0] , skip_special_tokens=SCREAMING_SNAKE_CASE) _lowerCamelCase : Any = ( """Today is a nice day and warm evening here over Southern Alberta!! Today when they closed schools due""" ) self.assertEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) @slow def UpperCamelCase_ ( self) -> List[Any]: _lowerCamelCase : Optional[Any] = TFXGLMForCausalLM.from_pretrained("""facebook/xglm-564M""") _lowerCamelCase : Any = XGLMTokenizer.from_pretrained("""facebook/xglm-564M""") _lowerCamelCase : List[Any] = """left""" # use different length sentences to test batching _lowerCamelCase : List[Any] = [ """This is an extremelly long sentence that only exists to test the ability of the model to cope with """ """left-padding, such as in batched generation. The output for the sequence below should be the same """ """regardless of whether left padding is applied or not. When""", """Hello, my dog is a little""", ] _lowerCamelCase : Union[str, Any] = tokenizer(SCREAMING_SNAKE_CASE , return_tensors="""tf""" , padding=SCREAMING_SNAKE_CASE) _lowerCamelCase : int = inputs["""input_ids"""] _lowerCamelCase : List[Any] = model.generate(input_ids=SCREAMING_SNAKE_CASE , attention_mask=inputs["""attention_mask"""] , max_new_tokens=12) _lowerCamelCase : List[str] = tokenizer(sentences[0] , return_tensors="""tf""").input_ids _lowerCamelCase : Optional[Any] = model.generate(input_ids=SCREAMING_SNAKE_CASE , max_new_tokens=12) _lowerCamelCase : Tuple = tokenizer(sentences[1] , return_tensors="""tf""").input_ids _lowerCamelCase : int = model.generate(input_ids=SCREAMING_SNAKE_CASE , max_new_tokens=12) _lowerCamelCase : Optional[int] = tokenizer.batch_decode(SCREAMING_SNAKE_CASE , skip_special_tokens=SCREAMING_SNAKE_CASE) _lowerCamelCase : Optional[Any] = tokenizer.decode(output_non_padded[0] , skip_special_tokens=SCREAMING_SNAKE_CASE) _lowerCamelCase : Union[str, Any] = tokenizer.decode(output_padded[0] , skip_special_tokens=SCREAMING_SNAKE_CASE) _lowerCamelCase : Tuple = [ """This is an extremelly long sentence that only exists to test the ability of the model to cope with """ """left-padding, such as in batched generation. The output for the sequence below should be the same """ """regardless of whether left padding is applied or not. When left padding is applied, the sequence will be """ """a single""", """Hello, my dog is a little bit of a shy one, but he is very friendly""", ] self.assertListEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) self.assertListEqual(SCREAMING_SNAKE_CASE , [non_padded_sentence, padded_sentence])
88
0