code
stringlengths
87
55.2k
code_codestyle
int64
0
349
style_context
stringlengths
135
49.1k
style_context_codestyle
int64
0
349
label
int64
0
1
import unittest from transformers import JukeboxTokenizer from transformers.testing_utils import require_torch class UpperCamelCase__ ( unittest.TestCase ): '''simple docstring''' __snake_case : Dict = JukeboxTokenizer __snake_case : List[Any] = { "artist": "Zac Brown Band", "genres": "Country", "lyrics": "I met a traveller from an antique land,\n Who said \"Two vast and trunkless legs of stone\n Stand in the desert. . . . Near them, on the sand,\n Half sunk a shattered visage lies, whose frown,\n And wrinkled lip, and sneer of cold command,\n Tell that its sculptor well those passions read\n Which yet survive, stamped on these lifeless things,\n The hand that mocked them, and the heart that fed;\n And on the pedestal, these words appear:\n My name is Ozymandias, King of Kings;\n Look on my Works, ye Mighty, and despair!\n Nothing beside remains. Round the decay\n Of that colossal Wreck, boundless and bare\n The lone and level sands stretch far away\n ", } @require_torch def SCREAMING_SNAKE_CASE__ ( self : List[str] ) -> Optional[int]: '''simple docstring''' import torch SCREAMING_SNAKE_CASE = JukeboxTokenizer.from_pretrained("""openai/jukebox-1b-lyrics""" ) SCREAMING_SNAKE_CASE = tokenizer(**self.metas )["""input_ids"""] # fmt: off SCREAMING_SNAKE_CASE = [ torch.tensor([[ 0, 0, 0, 7169, 507, 9, 76, 39, 31, 46, 76, 27, 76, 46, 44, 27, 48, 31, 38, 38, 31, 44, 76, 32, 44, 41, 39, 76, 27, 40, 76, 27, 40, 46, 35, 43, 47, 31, 76, 38, 27, 40, 30, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 23, 34, 41, 76, 45, 27, 35, 30, 76, 71, 20, 49, 41, 76, 48, 27, 45, 46, 76, 27, 40, 30, 76, 46, 44, 47, 40, 37, 38, 31, 45, 45, 76, 38, 31, 33, 45, 76, 41, 32, 76, 45, 46, 41, 40, 31, 78, 76, 76, 76, 76, 76, 76, 76, 76, 19, 46, 27, 40, 30, 76, 35, 40, 76, 46, 34, 31, 76, 30, 31, 45, 31, 44, 46, 63, 76, 63, 76, 63, 76, 63, 76, 14, 31, 27, 44, 76, 46, 34, 31, 39, 64, 76, 41, 40, 76, 46, 34, 31, 76, 45, 27, 40, 30, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 8, 27, 38, 32, 76, 45, 47, 40, 37, 76, 27, 76, 45, 34, 27, 46, 46, 31, 44, 31, 30, 76, 48, 35, 45, 27, 33, 31, 76, 38, 35, 31, 45, 64, 76, 49, 34, 41, 45, 31, 76, 32, 44, 41, 49, 40, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 1, 40, 30, 76, 49, 44, 35, 40, 37, 38, 31, 30, 76, 38, 35, 42, 64, 76, 27, 40, 30, 76, 45, 40, 31, 31, 44, 76, 41, 32, 76, 29, 41, 38, 30, 76, 29, 41, 39, 39, 27, 40, 30, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 20, 31, 38, 38, 76, 46, 34, 27, 46, 76, 35, 46, 45, 76, 45, 29, 47, 38, 42, 46, 41, 44, 76, 49, 31, 38, 38, 76, 46, 34, 41, 45, 31, 76, 42, 27, 45, 45, 35, 41, 40, 45, 76, 44, 31, 27, 30, 78, 76, 76, 76, 76, 76, 76, 76, 76, 23, 34, 35, 29, 34, 76, 51, 31, 46, 76, 45, 47, 44, 48, 35, 48, 31, 64, 76, 45, 46, 27, 39, 42, 31, 30, 76, 41, 40, 76, 46, 34, 31, 45, 31, 76, 38, 35, 32, 31, 38, 31, 45, 45, 76, 46, 34, 35, 40, 33, 45, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 20, 34, 31, 76, 34, 27, 40, 30, 76, 46, 34, 27, 46, 76, 39, 41, 29, 37, 31, 30, 76, 46, 34, 31, 39, 64, 76, 27, 40, 30, 76, 46, 34, 31, 76, 34, 31, 27, 44, 46, 76, 46, 34, 27, 46, 76, 32, 31, 30, 66, 78, 76, 76, 76, 76, 76, 76, 76, 76, 1, 40, 30, 76, 41, 40, 76, 46, 34, 31, 76, 42, 31, 30, 31, 45, 46, 27, 38, 64, 76, 46, 34, 31, 45, 31, 76, 49, 41, 44, 30, 45, 76, 27, 42, 42, 31, 27, 44, 65, 78, 76, 76, 76, 76, 76, 76, 76, 76, 13, 51, 76, 40, 27, 39, 31, 76, 35, 45, 76, 15, 52, 51, 39, 27, 40, 30, 35, 27, 45, 64, 76, 11, 35, 40, 33, 76, 41, 32, 76, 11, 35, 40, 33, 45, 66, 78, 76, 76, 76, 76, 76, 76, 76, 76, 12, 41, 41, 37, 76, 41, 40, 76, 39, 51, 76, 23, 41, 44, 37, 45, 64, 76, 51, 31, 76, 13, 35, 33, 34, 46, 51, 64, 76, 27, 40, 30, 76, 30, 31, 45, 42, 27, 35, 44, 67, 78, 76, 76, 76, 76, 76, 76, 76, 76, 14, 41, 46, 34, 35, 40, 33, 76, 28, 31, 45, 35, 30, 31, 76, 44, 31, 39, 27, 35, 40, 45, 63, 76, 18, 41, 47, 40, 30, 76, 46, 34, 31, 76, 30, 31, 29, 27, 51, 78, 76, 76, 76, 76, 76, 76, 76, 76, 15, 32, 76, 46, 34, 27, 46, 76, 29, 41, 38, 41, 45, 45, 27, 38, 76, 23, 44, 31, 29, 37, 64, 76, 28, 41, 47, 40, 30, 38, 31, 45, 45, 76, 27, 40, 30, 76, 28, 27, 44, 31, 78, 76, 76, 76, 76, 76, 76, 76, 76, 20, 34, 31, 76, 38, 41, 40, 31, 76, 27, 40, 30, 76, 38, 31, 48, 31, 38, 76, 45, 27, 40, 30, 45, 76, 45, 46, 44, 31, 46, 29, 34, 76, 32, 27, 44, 76, 27, 49, 27, 51, 78, 76, 76, 76, 76, 76, 76, 76, 76]] ), torch.tensor([[0, 0, 0, 1069, 11]] ), torch.tensor([[0, 0, 0, 1069, 11]] ), ] # fmt: on self.assertTrue(torch.allclose(tokens[0] ,EXPECTED_OUTPUT[0] ) ) self.assertTrue(torch.allclose(tokens[1] ,EXPECTED_OUTPUT[1] ) ) self.assertTrue(torch.allclose(tokens[2] ,EXPECTED_OUTPUT[2] ) ) @require_torch def SCREAMING_SNAKE_CASE__ ( self : Any ) -> str: '''simple docstring''' import torch SCREAMING_SNAKE_CASE = JukeboxTokenizer.from_pretrained("""openai/jukebox-5b-lyrics""" ) SCREAMING_SNAKE_CASE = tokenizer(**self.metas )["""input_ids"""] # fmt: off SCREAMING_SNAKE_CASE = [ torch.tensor([[ 0, 0, 0, 1069, 11, -1, -1, -1, -1, 9, 77, 39, 31, 46, 77, 27, 77, 46, 44, 27, 48, 31, 38, 38, 31, 44, 77, 32, 44, 41, 39, 77, 27, 40, 77, 27, 40, 46, 35, 43, 47, 31, 77, 38, 27, 40, 30, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 23, 34, 41, 77, 45, 27, 35, 30, 77, 72, 20, 49, 41, 77, 48, 27, 45, 46, 77, 27, 40, 30, 77, 46, 44, 47, 40, 37, 38, 31, 45, 45, 77, 38, 31, 33, 45, 77, 41, 32, 77, 45, 46, 41, 40, 31, 79, 77, 77, 77, 77, 77, 77, 77, 77, 19, 46, 27, 40, 30, 77, 35, 40, 77, 46, 34, 31, 77, 30, 31, 45, 31, 44, 46, 63, 77, 63, 77, 63, 77, 63, 77, 14, 31, 27, 44, 77, 46, 34, 31, 39, 64, 77, 41, 40, 77, 46, 34, 31, 77, 45, 27, 40, 30, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 8, 27, 38, 32, 77, 45, 47, 40, 37, 77, 27, 77, 45, 34, 27, 46, 46, 31, 44, 31, 30, 77, 48, 35, 45, 27, 33, 31, 77, 38, 35, 31, 45, 64, 77, 49, 34, 41, 45, 31, 77, 32, 44, 41, 49, 40, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 1, 40, 30, 77, 49, 44, 35, 40, 37, 38, 31, 30, 77, 38, 35, 42, 64, 77, 27, 40, 30, 77, 45, 40, 31, 31, 44, 77, 41, 32, 77, 29, 41, 38, 30, 77, 29, 41, 39, 39, 27, 40, 30, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 20, 31, 38, 38, 77, 46, 34, 27, 46, 77, 35, 46, 45, 77, 45, 29, 47, 38, 42, 46, 41, 44, 77, 49, 31, 38, 38, 77, 46, 34, 41, 45, 31, 77, 42, 27, 45, 45, 35, 41, 40, 45, 77, 44, 31, 27, 30, 79, 77, 77, 77, 77, 77, 77, 77, 77, 23, 34, 35, 29, 34, 77, 51, 31, 46, 77, 45, 47, 44, 48, 35, 48, 31, 64, 77, 45, 46, 27, 39, 42, 31, 30, 77, 41, 40, 77, 46, 34, 31, 45, 31, 77, 38, 35, 32, 31, 38, 31, 45, 45, 77, 46, 34, 35, 40, 33, 45, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 20, 34, 31, 77, 34, 27, 40, 30, 77, 46, 34, 27, 46, 77, 39, 41, 29, 37, 31, 30, 77, 46, 34, 31, 39, 64, 77, 27, 40, 30, 77, 46, 34, 31, 77, 34, 31, 27, 44, 46, 77, 46, 34, 27, 46, 77, 32, 31, 30, 66, 79, 77, 77, 77, 77, 77, 77, 77, 77, 1, 40, 30, 77, 41, 40, 77, 46, 34, 31, 77, 42, 31, 30, 31, 45, 46, 27, 38, 64, 77, 46, 34, 31, 45, 31, 77, 49, 41, 44, 30, 45, 77, 27, 42, 42, 31, 27, 44, 65, 79, 77, 77, 77, 77, 77, 77, 77, 77, 13, 51, 77, 40, 27, 39, 31, 77, 35, 45, 77, 15, 52, 51, 39, 27, 40, 30, 35, 27, 45, 64, 77, 11, 35, 40, 33, 77, 41, 32, 77, 11, 35, 40, 33, 45, 66, 79, 77, 77, 77, 77, 77, 77, 77, 77, 12, 41, 41, 37, 77, 41, 40, 77, 39, 51, 77, 23, 41, 44, 37, 45, 64, 77, 51, 31, 77, 13, 35, 33, 34, 46, 51, 64, 77, 27, 40, 30, 77, 30, 31, 45, 42, 27, 35, 44, 67, 79, 77, 77, 77, 77, 77, 77, 77, 77, 14, 41, 46, 34, 35, 40, 33, 77, 28, 31, 45, 35, 30, 31, 77, 44, 31, 39, 27, 35, 40, 45, 63, 77, 18, 41, 47, 40, 30, 77, 46, 34, 31, 77, 30, 31, 29, 27, 51, 79, 77, 77, 77, 77, 77, 77, 77, 77, 15, 32, 77, 46, 34, 27, 46, 77, 29, 41, 38, 41, 45, 45, 27, 38, 77, 23, 44, 31, 29, 37, 64, 77, 28, 41, 47, 40, 30, 38, 31, 45, 45, 77, 27, 40, 30, 77, 28, 27, 44, 31, 79, 77, 77, 77, 77, 77, 77, 77, 77, 20, 34, 31, 77, 38, 41, 40, 31, 77, 27, 40, 30, 77, 38, 31, 48, 31, 38, 77, 45, 27, 40, 30, 45, 77, 45, 46, 44, 31, 46, 29, 34, 77, 32, 27, 44, 77, 27, 49, 27, 51, 79, 77, 77, 77, 77, 77, 77, 77, 77]] ), torch.tensor([[0, 0, 0, 1069, 11, -1, -1, -1, -1]] ), torch.tensor([[0, 0, 0, 1069, 11, -1, -1, -1, -1]] ), ] # fmt: on self.assertTrue(torch.allclose(tokens[0] ,EXPECTED_OUTPUT[0] ) ) self.assertTrue(torch.allclose(tokens[1] ,EXPECTED_OUTPUT[1] ) ) self.assertTrue(torch.allclose(tokens[2] ,EXPECTED_OUTPUT[2] ) )
296
from collections import OrderedDict from ...utils import logging from .auto_factory import _BaseAutoModelClass, _LazyAutoMapping, auto_class_update from .configuration_auto import CONFIG_MAPPING_NAMES SCREAMING_SNAKE_CASE_ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE_ = 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"""), ] ) SCREAMING_SNAKE_CASE_ = 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"""), ] ) SCREAMING_SNAKE_CASE_ = 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"""), ] ) SCREAMING_SNAKE_CASE_ = 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"""), ] ) SCREAMING_SNAKE_CASE_ = OrderedDict( [ # Model for Image-classsification ("""beit""", """FlaxBeitForImageClassification"""), ("""regnet""", """FlaxRegNetForImageClassification"""), ("""resnet""", """FlaxResNetForImageClassification"""), ("""vit""", """FlaxViTForImageClassification"""), ] ) SCREAMING_SNAKE_CASE_ = OrderedDict( [ ("""vision-encoder-decoder""", """FlaxVisionEncoderDecoderModel"""), ] ) SCREAMING_SNAKE_CASE_ = 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"""), ] ) SCREAMING_SNAKE_CASE_ = 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"""), ] ) SCREAMING_SNAKE_CASE_ = 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"""), ] ) SCREAMING_SNAKE_CASE_ = 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"""), ] ) SCREAMING_SNAKE_CASE_ = 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"""), ] ) SCREAMING_SNAKE_CASE_ = OrderedDict( [ ("""bert""", """FlaxBertForNextSentencePrediction"""), ] ) SCREAMING_SNAKE_CASE_ = OrderedDict( [ ("""speech-encoder-decoder""", """FlaxSpeechEncoderDecoderModel"""), ("""whisper""", """FlaxWhisperForConditionalGeneration"""), ] ) SCREAMING_SNAKE_CASE_ = OrderedDict( [ ("""whisper""", """FlaxWhisperForAudioClassification"""), ] ) SCREAMING_SNAKE_CASE_ = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_MAPPING_NAMES) SCREAMING_SNAKE_CASE_ = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_PRETRAINING_MAPPING_NAMES) SCREAMING_SNAKE_CASE_ = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MASKED_LM_MAPPING_NAMES) SCREAMING_SNAKE_CASE_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES ) SCREAMING_SNAKE_CASE_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES ) SCREAMING_SNAKE_CASE_ = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES) SCREAMING_SNAKE_CASE_ = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_CAUSAL_LM_MAPPING_NAMES) SCREAMING_SNAKE_CASE_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES ) SCREAMING_SNAKE_CASE_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES ) SCREAMING_SNAKE_CASE_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES ) SCREAMING_SNAKE_CASE_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES ) SCREAMING_SNAKE_CASE_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING_NAMES ) SCREAMING_SNAKE_CASE_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES ) SCREAMING_SNAKE_CASE_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES ) class UpperCamelCase__ ( _BaseAutoModelClass ): '''simple docstring''' __snake_case : List[str] = FLAX_MODEL_MAPPING SCREAMING_SNAKE_CASE_ = auto_class_update(FlaxAutoModel) class UpperCamelCase__ ( _BaseAutoModelClass ): '''simple docstring''' __snake_case : Dict = FLAX_MODEL_FOR_PRETRAINING_MAPPING SCREAMING_SNAKE_CASE_ = auto_class_update(FlaxAutoModelForPreTraining, head_doc="""pretraining""") class UpperCamelCase__ ( _BaseAutoModelClass ): '''simple docstring''' __snake_case : Optional[Any] = FLAX_MODEL_FOR_CAUSAL_LM_MAPPING SCREAMING_SNAKE_CASE_ = auto_class_update(FlaxAutoModelForCausalLM, head_doc="""causal language modeling""") class UpperCamelCase__ ( _BaseAutoModelClass ): '''simple docstring''' __snake_case : Any = FLAX_MODEL_FOR_MASKED_LM_MAPPING SCREAMING_SNAKE_CASE_ = auto_class_update(FlaxAutoModelForMaskedLM, head_doc="""masked language modeling""") class UpperCamelCase__ ( _BaseAutoModelClass ): '''simple docstring''' __snake_case : int = FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING SCREAMING_SNAKE_CASE_ = auto_class_update( FlaxAutoModelForSeqaSeqLM, head_doc="""sequence-to-sequence language modeling""", checkpoint_for_example="""t5-base""" ) class UpperCamelCase__ ( _BaseAutoModelClass ): '''simple docstring''' __snake_case : Optional[int] = FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING SCREAMING_SNAKE_CASE_ = auto_class_update( FlaxAutoModelForSequenceClassification, head_doc="""sequence classification""" ) class UpperCamelCase__ ( _BaseAutoModelClass ): '''simple docstring''' __snake_case : List[Any] = FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING SCREAMING_SNAKE_CASE_ = auto_class_update(FlaxAutoModelForQuestionAnswering, head_doc="""question answering""") class UpperCamelCase__ ( _BaseAutoModelClass ): '''simple docstring''' __snake_case : Tuple = FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING SCREAMING_SNAKE_CASE_ = auto_class_update( FlaxAutoModelForTokenClassification, head_doc="""token classification""" ) class UpperCamelCase__ ( _BaseAutoModelClass ): '''simple docstring''' __snake_case : Union[str, Any] = FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING SCREAMING_SNAKE_CASE_ = auto_class_update(FlaxAutoModelForMultipleChoice, head_doc="""multiple choice""") class UpperCamelCase__ ( _BaseAutoModelClass ): '''simple docstring''' __snake_case : List[str] = FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING SCREAMING_SNAKE_CASE_ = auto_class_update( FlaxAutoModelForNextSentencePrediction, head_doc="""next sentence prediction""" ) class UpperCamelCase__ ( _BaseAutoModelClass ): '''simple docstring''' __snake_case : Dict = FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING SCREAMING_SNAKE_CASE_ = auto_class_update( FlaxAutoModelForImageClassification, head_doc="""image classification""" ) class UpperCamelCase__ ( _BaseAutoModelClass ): '''simple docstring''' __snake_case : Dict = FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING SCREAMING_SNAKE_CASE_ = auto_class_update(FlaxAutoModelForVisionaSeq, head_doc="""vision-to-text modeling""") class UpperCamelCase__ ( _BaseAutoModelClass ): '''simple docstring''' __snake_case : Optional[Any] = FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING SCREAMING_SNAKE_CASE_ = auto_class_update( FlaxAutoModelForSpeechSeqaSeq, head_doc="""sequence-to-sequence speech-to-text modeling""" )
296
1
from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices SCREAMING_SNAKE_CASE_ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE_ = { """shi-labs/nat-mini-in1k-224""": """https://huggingface.co/shi-labs/nat-mini-in1k-224/resolve/main/config.json""", # See all Nat models at https://huggingface.co/models?filter=nat } class UpperCamelCase__ ( lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __snake_case : Optional[int] = "nat" __snake_case : Dict = { "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers", } def __init__( self : str ,lowerCamelCase__ : Dict=4 ,lowerCamelCase__ : List[str]=3 ,lowerCamelCase__ : Optional[Any]=64 ,lowerCamelCase__ : Tuple=[3, 4, 6, 5] ,lowerCamelCase__ : Union[str, Any]=[2, 4, 8, 16] ,lowerCamelCase__ : List[str]=7 ,lowerCamelCase__ : Optional[int]=3.0 ,lowerCamelCase__ : Union[str, Any]=True ,lowerCamelCase__ : Any=0.0 ,lowerCamelCase__ : Any=0.0 ,lowerCamelCase__ : str=0.1 ,lowerCamelCase__ : Optional[int]="gelu" ,lowerCamelCase__ : List[Any]=0.02 ,lowerCamelCase__ : int=1e-5 ,lowerCamelCase__ : str=0.0 ,lowerCamelCase__ : List[Any]=None ,lowerCamelCase__ : Union[str, Any]=None ,**lowerCamelCase__ : Optional[Any] ,) -> Any: '''simple docstring''' super().__init__(**lowerCamelCase__ ) SCREAMING_SNAKE_CASE = patch_size SCREAMING_SNAKE_CASE = num_channels SCREAMING_SNAKE_CASE = embed_dim SCREAMING_SNAKE_CASE = depths SCREAMING_SNAKE_CASE = len(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = num_heads SCREAMING_SNAKE_CASE = kernel_size 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 Nat work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model SCREAMING_SNAKE_CASE = int(embed_dim * 2 ** (len(lowerCamelCase__ ) - 1) ) SCREAMING_SNAKE_CASE = layer_scale_init_value SCREAMING_SNAKE_CASE = ["""stem"""] + [F"""stage{idx}""" for idx in range(1 ,len(lowerCamelCase__ ) + 1 )] SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE = get_aligned_output_features_output_indices( out_features=lowerCamelCase__ ,out_indices=lowerCamelCase__ ,stage_names=self.stage_names )
296
from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ..auto import CONFIG_MAPPING SCREAMING_SNAKE_CASE_ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE_ = { """microsoft/table-transformer-detection""": ( """https://huggingface.co/microsoft/table-transformer-detection/resolve/main/config.json""" ), } class UpperCamelCase__ ( lowerCAmelCase_ ): '''simple docstring''' __snake_case : Union[str, Any] = "table-transformer" __snake_case : Union[str, Any] = ["past_key_values"] __snake_case : List[Any] = { "hidden_size": "d_model", "num_attention_heads": "encoder_attention_heads", } def __init__( self : Optional[int] ,lowerCamelCase__ : Optional[Any]=True ,lowerCamelCase__ : Optional[Any]=None ,lowerCamelCase__ : List[Any]=3 ,lowerCamelCase__ : Optional[int]=100 ,lowerCamelCase__ : List[Any]=6 ,lowerCamelCase__ : Dict=2048 ,lowerCamelCase__ : List[Any]=8 ,lowerCamelCase__ : Dict=6 ,lowerCamelCase__ : Dict=2048 ,lowerCamelCase__ : Any=8 ,lowerCamelCase__ : Optional[int]=0.0 ,lowerCamelCase__ : int=0.0 ,lowerCamelCase__ : List[Any]=True ,lowerCamelCase__ : Optional[int]="relu" ,lowerCamelCase__ : Tuple=256 ,lowerCamelCase__ : Any=0.1 ,lowerCamelCase__ : Optional[Any]=0.0 ,lowerCamelCase__ : Tuple=0.0 ,lowerCamelCase__ : List[Any]=0.02 ,lowerCamelCase__ : int=1.0 ,lowerCamelCase__ : List[str]=False ,lowerCamelCase__ : Optional[Any]="sine" ,lowerCamelCase__ : List[str]="resnet50" ,lowerCamelCase__ : Optional[Any]=True ,lowerCamelCase__ : List[str]=False ,lowerCamelCase__ : int=1 ,lowerCamelCase__ : Dict=5 ,lowerCamelCase__ : Tuple=2 ,lowerCamelCase__ : Union[str, Any]=1 ,lowerCamelCase__ : str=1 ,lowerCamelCase__ : Any=5 ,lowerCamelCase__ : Tuple=2 ,lowerCamelCase__ : str=0.1 ,**lowerCamelCase__ : List[str] ,) -> Optional[int]: '''simple docstring''' if backbone_config is not None and use_timm_backbone: raise ValueError("""You can't specify both `backbone_config` and `use_timm_backbone`.""" ) if not use_timm_backbone: if backbone_config is None: logger.info("""`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.""" ) SCREAMING_SNAKE_CASE = CONFIG_MAPPING["""resnet"""](out_features=["""stage4"""] ) elif isinstance(lowerCamelCase__ ,lowerCamelCase__ ): SCREAMING_SNAKE_CASE = backbone_config.get("""model_type""" ) SCREAMING_SNAKE_CASE = CONFIG_MAPPING[backbone_model_type] SCREAMING_SNAKE_CASE = config_class.from_dict(lowerCamelCase__ ) # set timm attributes to None SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE = None, None, None SCREAMING_SNAKE_CASE = use_timm_backbone SCREAMING_SNAKE_CASE = backbone_config SCREAMING_SNAKE_CASE = num_channels SCREAMING_SNAKE_CASE = num_queries SCREAMING_SNAKE_CASE = d_model SCREAMING_SNAKE_CASE = encoder_ffn_dim SCREAMING_SNAKE_CASE = encoder_layers SCREAMING_SNAKE_CASE = encoder_attention_heads SCREAMING_SNAKE_CASE = decoder_ffn_dim SCREAMING_SNAKE_CASE = decoder_layers SCREAMING_SNAKE_CASE = decoder_attention_heads SCREAMING_SNAKE_CASE = dropout SCREAMING_SNAKE_CASE = attention_dropout SCREAMING_SNAKE_CASE = activation_dropout SCREAMING_SNAKE_CASE = activation_function SCREAMING_SNAKE_CASE = init_std SCREAMING_SNAKE_CASE = init_xavier_std SCREAMING_SNAKE_CASE = encoder_layerdrop SCREAMING_SNAKE_CASE = decoder_layerdrop SCREAMING_SNAKE_CASE = encoder_layers SCREAMING_SNAKE_CASE = auxiliary_loss SCREAMING_SNAKE_CASE = position_embedding_type SCREAMING_SNAKE_CASE = backbone SCREAMING_SNAKE_CASE = use_pretrained_backbone SCREAMING_SNAKE_CASE = dilation # Hungarian matcher SCREAMING_SNAKE_CASE = class_cost SCREAMING_SNAKE_CASE = bbox_cost SCREAMING_SNAKE_CASE = giou_cost # Loss coefficients SCREAMING_SNAKE_CASE = mask_loss_coefficient SCREAMING_SNAKE_CASE = dice_loss_coefficient SCREAMING_SNAKE_CASE = bbox_loss_coefficient SCREAMING_SNAKE_CASE = giou_loss_coefficient SCREAMING_SNAKE_CASE = eos_coefficient super().__init__(is_encoder_decoder=lowerCamelCase__ ,**lowerCamelCase__ ) @property def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ) -> int: '''simple docstring''' return self.encoder_attention_heads @property def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ) -> int: '''simple docstring''' return self.d_model class UpperCamelCase__ ( lowerCAmelCase_ ): '''simple docstring''' __snake_case : int = version.parse("1.11" ) @property def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' return OrderedDict( [ ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}), ("""pixel_mask""", {0: """batch"""}), ] ) @property def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ) -> float: '''simple docstring''' return 1e-5 @property def SCREAMING_SNAKE_CASE__ ( self : Any ) -> int: '''simple docstring''' return 12
296
1
def __lowercase ( _SCREAMING_SNAKE_CASE = 1_00_00_00 ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE = set(range(3 , _SCREAMING_SNAKE_CASE , 2 ) ) primes.add(2 ) for p in range(3 , _SCREAMING_SNAKE_CASE , 2 ): if p not in primes: continue primes.difference_update(set(range(p * p , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) ) SCREAMING_SNAKE_CASE = [float(_SCREAMING_SNAKE_CASE ) for n in range(limit + 1 )] for p in primes: for n in range(_SCREAMING_SNAKE_CASE , limit + 1 , _SCREAMING_SNAKE_CASE ): phi[n] *= 1 - 1 / p return int(sum(phi[2:] ) ) if __name__ == "__main__": print(F'''{solution() = }''')
296
from collections import defaultdict from math import gcd def __lowercase ( _SCREAMING_SNAKE_CASE = 1_50_00_00 ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE = defaultdict(_SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE = 2 while 2 * euclid_m * (euclid_m + 1) <= limit: for euclid_n in range((euclid_m % 2) + 1 , _SCREAMING_SNAKE_CASE , 2 ): if gcd(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) > 1: continue SCREAMING_SNAKE_CASE = 2 * euclid_m * (euclid_m + euclid_n) for perimeter in range(_SCREAMING_SNAKE_CASE , limit + 1 , _SCREAMING_SNAKE_CASE ): frequencies[perimeter] += 1 euclid_m += 1 return sum(1 for frequency in frequencies.values() if frequency == 1 ) if __name__ == "__main__": print(F'''{solution() = }''')
296
1
import random class UpperCamelCase__ : '''simple docstring''' @staticmethod def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ : str ) -> tuple[list[int], list[int]]: '''simple docstring''' SCREAMING_SNAKE_CASE = [ord(lowerCamelCase__ ) for i in text] SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = [] for i in plain: SCREAMING_SNAKE_CASE = random.randint(1 ,300 ) SCREAMING_SNAKE_CASE = (i + k) * k cipher.append(lowerCamelCase__ ) key.append(lowerCamelCase__ ) return cipher, key @staticmethod def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ : list[int] ,lowerCamelCase__ : list[int] ) -> str: '''simple docstring''' SCREAMING_SNAKE_CASE = [] for i in range(len(lowerCamelCase__ ) ): SCREAMING_SNAKE_CASE = int((cipher[i] - (key[i]) ** 2) / key[i] ) plain.append(chr(lowerCamelCase__ ) ) return "".join(lowerCamelCase__ ) if __name__ == "__main__": SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = Onepad().encrypt("""Hello""") print(c, k) print(Onepad().decrypt(c, k))
296
from argparse import ArgumentParser from .env import EnvironmentCommand def __lowercase ( ) -> Dict: '''simple docstring''' SCREAMING_SNAKE_CASE = ArgumentParser("""Diffusers CLI tool""" , usage="""diffusers-cli <command> [<args>]""" ) SCREAMING_SNAKE_CASE = parser.add_subparsers(help="""diffusers-cli command helpers""" ) # Register commands EnvironmentCommand.register_subcommand(_SCREAMING_SNAKE_CASE ) # Let's go SCREAMING_SNAKE_CASE = parser.parse_args() if not hasattr(_SCREAMING_SNAKE_CASE , """func""" ): parser.print_help() exit(1 ) # Run SCREAMING_SNAKE_CASE = args.func(_SCREAMING_SNAKE_CASE ) service.run() if __name__ == "__main__": main()
296
1
from sklearn.metrics import mean_squared_error import datasets SCREAMING_SNAKE_CASE_ = """\ @article{scikit-learn, title={Scikit-learn: Machine Learning in {P}ython}, author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V. and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P. and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.}, journal={Journal of Machine Learning Research}, volume={12}, pages={2825--2830}, year={2011} } """ SCREAMING_SNAKE_CASE_ = """\ Mean Squared Error(MSE) is the average of the square of difference between the predicted and actual values. """ SCREAMING_SNAKE_CASE_ = """ Args: predictions: array-like of shape (n_samples,) or (n_samples, n_outputs) Estimated target values. references: array-like of shape (n_samples,) or (n_samples, n_outputs) Ground truth (correct) target values. sample_weight: array-like of shape (n_samples,), default=None Sample weights. multioutput: {\"raw_values\", \"uniform_average\"} or array-like of shape (n_outputs,), default=\"uniform_average\" Defines aggregating of multiple output values. Array-like value defines weights used to average errors. \"raw_values\" : Returns a full set of errors in case of multioutput input. \"uniform_average\" : Errors of all outputs are averaged with uniform weight. squared : bool, default=True If True returns MSE value, if False returns RMSE (Root Mean Squared Error) value. Returns: mse : mean squared error. Examples: >>> mse_metric = datasets.load_metric(\"mse\") >>> predictions = [2.5, 0.0, 2, 8] >>> references = [3, -0.5, 2, 7] >>> results = mse_metric.compute(predictions=predictions, references=references) >>> print(results) {'mse': 0.375} >>> rmse_result = mse_metric.compute(predictions=predictions, references=references, squared=False) >>> print(rmse_result) {'mse': 0.6123724356957945} If you're using multi-dimensional lists, then set the config as follows : >>> mse_metric = datasets.load_metric(\"mse\", \"multilist\") >>> predictions = [[0.5, 1], [-1, 1], [7, -6]] >>> references = [[0, 2], [-1, 2], [8, -5]] >>> results = mse_metric.compute(predictions=predictions, references=references) >>> print(results) {'mse': 0.7083333333333334} >>> results = mse_metric.compute(predictions=predictions, references=references, multioutput='raw_values') >>> print(results) # doctest: +NORMALIZE_WHITESPACE {'mse': array([0.41666667, 1. ])} """ @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class UpperCamelCase__ ( datasets.Metric ): '''simple docstring''' def SCREAMING_SNAKE_CASE__ ( self : Any ) -> Dict: '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION ,citation=_CITATION ,inputs_description=_KWARGS_DESCRIPTION ,features=datasets.Features(self._get_feature_types() ) ,reference_urls=[ """https://scikit-learn.org/stable/modules/generated/sklearn.metrics.mean_squared_error.html""" ] ,) def SCREAMING_SNAKE_CASE__ ( self : Any ) -> int: '''simple docstring''' if self.config_name == "multilist": return { "predictions": datasets.Sequence(datasets.Value("""float""" ) ), "references": datasets.Sequence(datasets.Value("""float""" ) ), } else: return { "predictions": datasets.Value("""float""" ), "references": datasets.Value("""float""" ), } def SCREAMING_SNAKE_CASE__ ( self : Tuple ,lowerCamelCase__ : int ,lowerCamelCase__ : List[Any] ,lowerCamelCase__ : List[Any]=None ,lowerCamelCase__ : Tuple="uniform_average" ,lowerCamelCase__ : List[str]=True ) -> List[str]: '''simple docstring''' SCREAMING_SNAKE_CASE = mean_squared_error( lowerCamelCase__ ,lowerCamelCase__ ,sample_weight=lowerCamelCase__ ,multioutput=lowerCamelCase__ ,squared=lowerCamelCase__ ) return {"mse": mse}
296
import argparse import json import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import AutoImageProcessor, SwinConfig, SwinForImageClassification def __lowercase ( _SCREAMING_SNAKE_CASE ) -> Union[str, Any]: '''simple docstring''' SCREAMING_SNAKE_CASE = SwinConfig() SCREAMING_SNAKE_CASE = swin_name.split("""_""" ) SCREAMING_SNAKE_CASE = name_split[1] SCREAMING_SNAKE_CASE = int(name_split[4] ) SCREAMING_SNAKE_CASE = int(name_split[3][-1] ) if model_size == "tiny": SCREAMING_SNAKE_CASE = 96 SCREAMING_SNAKE_CASE = (2, 2, 6, 2) SCREAMING_SNAKE_CASE = (3, 6, 12, 24) elif model_size == "small": SCREAMING_SNAKE_CASE = 96 SCREAMING_SNAKE_CASE = (2, 2, 18, 2) SCREAMING_SNAKE_CASE = (3, 6, 12, 24) elif model_size == "base": SCREAMING_SNAKE_CASE = 1_28 SCREAMING_SNAKE_CASE = (2, 2, 18, 2) SCREAMING_SNAKE_CASE = (4, 8, 16, 32) else: SCREAMING_SNAKE_CASE = 1_92 SCREAMING_SNAKE_CASE = (2, 2, 18, 2) SCREAMING_SNAKE_CASE = (6, 12, 24, 48) if "in22k" in swin_name: SCREAMING_SNAKE_CASE = 2_18_41 else: SCREAMING_SNAKE_CASE = 10_00 SCREAMING_SNAKE_CASE = """huggingface/label-files""" SCREAMING_SNAKE_CASE = """imagenet-1k-id2label.json""" SCREAMING_SNAKE_CASE = json.load(open(hf_hub_download(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , repo_type="""dataset""" ) , """r""" ) ) SCREAMING_SNAKE_CASE = {int(_SCREAMING_SNAKE_CASE ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE = idalabel SCREAMING_SNAKE_CASE = {v: k for k, v in idalabel.items()} SCREAMING_SNAKE_CASE = img_size SCREAMING_SNAKE_CASE = num_classes SCREAMING_SNAKE_CASE = embed_dim SCREAMING_SNAKE_CASE = depths SCREAMING_SNAKE_CASE = num_heads SCREAMING_SNAKE_CASE = window_size return config def __lowercase ( _SCREAMING_SNAKE_CASE ) -> Dict: '''simple docstring''' if "patch_embed.proj" in name: SCREAMING_SNAKE_CASE = name.replace("""patch_embed.proj""" , """embeddings.patch_embeddings.projection""" ) if "patch_embed.norm" in name: SCREAMING_SNAKE_CASE = name.replace("""patch_embed.norm""" , """embeddings.norm""" ) if "layers" in name: SCREAMING_SNAKE_CASE = """encoder.""" + name if "attn.proj" in name: SCREAMING_SNAKE_CASE = name.replace("""attn.proj""" , """attention.output.dense""" ) if "attn" in name: SCREAMING_SNAKE_CASE = name.replace("""attn""" , """attention.self""" ) if "norm1" in name: SCREAMING_SNAKE_CASE = name.replace("""norm1""" , """layernorm_before""" ) if "norm2" in name: SCREAMING_SNAKE_CASE = name.replace("""norm2""" , """layernorm_after""" ) if "mlp.fc1" in name: SCREAMING_SNAKE_CASE = name.replace("""mlp.fc1""" , """intermediate.dense""" ) if "mlp.fc2" in name: SCREAMING_SNAKE_CASE = name.replace("""mlp.fc2""" , """output.dense""" ) if name == "norm.weight": SCREAMING_SNAKE_CASE = """layernorm.weight""" if name == "norm.bias": SCREAMING_SNAKE_CASE = """layernorm.bias""" if "head" in name: SCREAMING_SNAKE_CASE = name.replace("""head""" , """classifier""" ) else: SCREAMING_SNAKE_CASE = """swin.""" + name return name def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Any: '''simple docstring''' for key in orig_state_dict.copy().keys(): SCREAMING_SNAKE_CASE = orig_state_dict.pop(_SCREAMING_SNAKE_CASE ) if "mask" in key: continue elif "qkv" in key: SCREAMING_SNAKE_CASE = key.split(""".""" ) SCREAMING_SNAKE_CASE = int(key_split[1] ) SCREAMING_SNAKE_CASE = int(key_split[3] ) SCREAMING_SNAKE_CASE = model.swin.encoder.layers[layer_num].blocks[block_num].attention.self.all_head_size if "weight" in key: SCREAMING_SNAKE_CASE = val[:dim, :] SCREAMING_SNAKE_CASE = val[ dim : dim * 2, : ] SCREAMING_SNAKE_CASE = val[-dim:, :] else: SCREAMING_SNAKE_CASE = val[ :dim ] SCREAMING_SNAKE_CASE = val[ dim : dim * 2 ] SCREAMING_SNAKE_CASE = val[ -dim: ] else: SCREAMING_SNAKE_CASE = val return orig_state_dict def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> List[str]: '''simple docstring''' SCREAMING_SNAKE_CASE = timm.create_model(_SCREAMING_SNAKE_CASE , pretrained=_SCREAMING_SNAKE_CASE ) timm_model.eval() SCREAMING_SNAKE_CASE = get_swin_config(_SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE = SwinForImageClassification(_SCREAMING_SNAKE_CASE ) model.eval() SCREAMING_SNAKE_CASE = convert_state_dict(timm_model.state_dict() , _SCREAMING_SNAKE_CASE ) model.load_state_dict(_SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE = """http://images.cocodataset.org/val2017/000000039769.jpg""" SCREAMING_SNAKE_CASE = AutoImageProcessor.from_pretrained("""microsoft/{}""".format(swin_name.replace("""_""" , """-""" ) ) ) SCREAMING_SNAKE_CASE = Image.open(requests.get(_SCREAMING_SNAKE_CASE , stream=_SCREAMING_SNAKE_CASE ).raw ) SCREAMING_SNAKE_CASE = image_processor(images=_SCREAMING_SNAKE_CASE , return_tensors="""pt""" ) SCREAMING_SNAKE_CASE = timm_model(inputs["""pixel_values"""] ) SCREAMING_SNAKE_CASE = model(**_SCREAMING_SNAKE_CASE ).logits assert torch.allclose(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , atol=1E-3 ) print(F"""Saving model {swin_name} to {pytorch_dump_folder_path}""" ) model.save_pretrained(_SCREAMING_SNAKE_CASE ) print(F"""Saving image processor to {pytorch_dump_folder_path}""" ) image_processor.save_pretrained(_SCREAMING_SNAKE_CASE ) if __name__ == "__main__": SCREAMING_SNAKE_CASE_ = argparse.ArgumentParser() # Required parameters parser.add_argument( """--swin_name""", default="""swin_tiny_patch4_window7_224""", type=str, help="""Name of the Swin timm model you'd like to convert.""", ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model directory.""" ) SCREAMING_SNAKE_CASE_ = parser.parse_args() convert_swin_checkpoint(args.swin_name, args.pytorch_dump_folder_path)
296
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_speech_available, is_tf_available, is_torch_available, ) SCREAMING_SNAKE_CASE_ = { """configuration_speech_to_text""": ["""SPEECH_TO_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """Speech2TextConfig"""], """processing_speech_to_text""": ["""Speech2TextProcessor"""], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE_ = ["""Speech2TextTokenizer"""] try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE_ = ["""Speech2TextFeatureExtractor"""] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE_ = [ """TF_SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFSpeech2TextForConditionalGeneration""", """TFSpeech2TextModel""", """TFSpeech2TextPreTrainedModel""", ] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE_ = [ """SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST""", """Speech2TextForConditionalGeneration""", """Speech2TextModel""", """Speech2TextPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_speech_to_text import SPEECH_TO_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP, SpeechaTextConfig from .processing_speech_to_text import SpeechaTextProcessor try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_speech_to_text import SpeechaTextTokenizer try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_speech_to_text import SpeechaTextFeatureExtractor try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_speech_to_text import ( TF_SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST, TFSpeechaTextForConditionalGeneration, TFSpeechaTextModel, TFSpeechaTextPreTrainedModel, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_speech_to_text import ( SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST, SpeechaTextForConditionalGeneration, SpeechaTextModel, SpeechaTextPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE_ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
296
import os from distutils.util import strtobool def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Tuple: '''simple docstring''' for e in env_keys: SCREAMING_SNAKE_CASE = int(os.environ.get(_SCREAMING_SNAKE_CASE , -1 ) ) if val >= 0: return val return default def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=False ) -> Optional[int]: '''simple docstring''' SCREAMING_SNAKE_CASE = os.environ.get(_SCREAMING_SNAKE_CASE , str(_SCREAMING_SNAKE_CASE ) ) return strtobool(_SCREAMING_SNAKE_CASE ) == 1 # As its name indicates `strtobool` actually returns an int... def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE="no" ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE = os.environ.get(_SCREAMING_SNAKE_CASE , str(_SCREAMING_SNAKE_CASE ) ) return value
296
1
from ...configuration_utils import PretrainedConfig from ...utils import logging SCREAMING_SNAKE_CASE_ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE_ = { """edbeeching/decision-transformer-gym-hopper-medium""": ( """https://huggingface.co/edbeeching/decision-transformer-gym-hopper-medium/resolve/main/config.json""" ), # See all DecisionTransformer models at https://huggingface.co/models?filter=decision_transformer } class UpperCamelCase__ ( lowerCAmelCase_ ): '''simple docstring''' __snake_case : Optional[int] = "decision_transformer" __snake_case : Any = ["past_key_values"] __snake_case : Optional[int] = { "max_position_embeddings": "n_positions", "num_attention_heads": "n_head", "num_hidden_layers": "n_layer", } def __init__( self : Union[str, Any] ,lowerCamelCase__ : int=17 ,lowerCamelCase__ : Dict=4 ,lowerCamelCase__ : int=128 ,lowerCamelCase__ : Tuple=4096 ,lowerCamelCase__ : Tuple=True ,lowerCamelCase__ : List[Any]=1 ,lowerCamelCase__ : Optional[int]=1024 ,lowerCamelCase__ : Optional[Any]=3 ,lowerCamelCase__ : Union[str, Any]=1 ,lowerCamelCase__ : Optional[int]=None ,lowerCamelCase__ : Dict="relu" ,lowerCamelCase__ : Optional[int]=0.1 ,lowerCamelCase__ : Optional[Any]=0.1 ,lowerCamelCase__ : Any=0.1 ,lowerCamelCase__ : List[Any]=1e-5 ,lowerCamelCase__ : Optional[Any]=0.02 ,lowerCamelCase__ : Dict=True ,lowerCamelCase__ : str=True ,lowerCamelCase__ : Dict=50256 ,lowerCamelCase__ : str=50256 ,lowerCamelCase__ : List[str]=False ,lowerCamelCase__ : List[Any]=False ,**lowerCamelCase__ : Optional[Any] ,) -> Union[str, Any]: '''simple docstring''' SCREAMING_SNAKE_CASE = state_dim SCREAMING_SNAKE_CASE = act_dim SCREAMING_SNAKE_CASE = hidden_size SCREAMING_SNAKE_CASE = max_ep_len SCREAMING_SNAKE_CASE = action_tanh SCREAMING_SNAKE_CASE = vocab_size SCREAMING_SNAKE_CASE = n_positions SCREAMING_SNAKE_CASE = n_layer SCREAMING_SNAKE_CASE = n_head SCREAMING_SNAKE_CASE = n_inner SCREAMING_SNAKE_CASE = activation_function SCREAMING_SNAKE_CASE = resid_pdrop SCREAMING_SNAKE_CASE = embd_pdrop SCREAMING_SNAKE_CASE = attn_pdrop SCREAMING_SNAKE_CASE = layer_norm_epsilon SCREAMING_SNAKE_CASE = initializer_range SCREAMING_SNAKE_CASE = scale_attn_weights SCREAMING_SNAKE_CASE = use_cache SCREAMING_SNAKE_CASE = scale_attn_by_inverse_layer_idx SCREAMING_SNAKE_CASE = reorder_and_upcast_attn SCREAMING_SNAKE_CASE = bos_token_id SCREAMING_SNAKE_CASE = eos_token_id super().__init__(bos_token_id=lowerCamelCase__ ,eos_token_id=lowerCamelCase__ ,**lowerCamelCase__ )
296
import dataclasses import json import warnings from dataclasses import dataclass, field from time import time from typing import List from ..utils import logging SCREAMING_SNAKE_CASE_ = logging.get_logger(__name__) def __lowercase ( _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None ) -> List[str]: '''simple docstring''' return field(default_factory=lambda: default , metadata=_SCREAMING_SNAKE_CASE ) @dataclass class UpperCamelCase__ : '''simple docstring''' __snake_case : 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" ) } , ) __snake_case : List[int] = list_field( default=[8] , metadata={"help": "List of batch sizes for which memory and time performance will be evaluated"} ) __snake_case : List[int] = list_field( default=[8, 32, 128, 512] , metadata={"help": "List of sequence lengths for which memory and time performance will be evaluated"} , ) __snake_case : bool = field( default=lowerCAmelCase_ , metadata={"help": "Whether to benchmark inference of model. Inference can be disabled via --no-inference."} , ) __snake_case : bool = field( default=lowerCAmelCase_ , metadata={"help": "Whether to run on available cuda devices. Cuda can be disabled via --no-cuda."} , ) __snake_case : bool = field( default=lowerCAmelCase_ , metadata={"help": "Whether to run on available tpu devices. TPU can be disabled via --no-tpu."} ) __snake_case : bool = field(default=lowerCAmelCase_ , metadata={"help": "Use FP16 to accelerate inference."} ) __snake_case : bool = field(default=lowerCAmelCase_ , metadata={"help": "Benchmark training of model"} ) __snake_case : bool = field(default=lowerCAmelCase_ , metadata={"help": "Verbose memory tracing"} ) __snake_case : bool = field( default=lowerCAmelCase_ , metadata={"help": "Whether to perform speed measurements. Speed measurements can be disabled via --no-speed."} , ) __snake_case : bool = field( default=lowerCAmelCase_ , metadata={ "help": "Whether to perform memory measurements. Memory measurements can be disabled via --no-memory" } , ) __snake_case : bool = field(default=lowerCAmelCase_ , metadata={"help": "Trace memory line by line"} ) __snake_case : bool = field(default=lowerCAmelCase_ , metadata={"help": "Save result to a CSV file"} ) __snake_case : bool = field(default=lowerCAmelCase_ , metadata={"help": "Save all print statements in a log file"} ) __snake_case : bool = field(default=lowerCAmelCase_ , metadata={"help": "Whether to print environment information"} ) __snake_case : bool = field( default=lowerCAmelCase_ , 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." ) } , ) __snake_case : str = field( default=F"inference_time_{round(time() )}.csv" , metadata={"help": "CSV filename used if saving time results to csv."} , ) __snake_case : str = field( default=F"inference_memory_{round(time() )}.csv" , metadata={"help": "CSV filename used if saving memory results to csv."} , ) __snake_case : str = field( default=F"train_time_{round(time() )}.csv" , metadata={"help": "CSV filename used if saving time results to csv for training."} , ) __snake_case : str = field( default=F"train_memory_{round(time() )}.csv" , metadata={"help": "CSV filename used if saving memory results to csv for training."} , ) __snake_case : str = field( default=F"env_info_{round(time() )}.csv" , metadata={"help": "CSV filename used if saving environment information."} , ) __snake_case : str = field( default=F"log_{round(time() )}.csv" , metadata={"help": "Log filename used if print statements are saved in log."} , ) __snake_case : int = field(default=3 , metadata={"help": "Times an experiment will be run."} ) __snake_case : bool = field( default=lowerCAmelCase_ , metadata={ "help": ( "Instead of loading the model as defined in `config.architectures` if exists, just load the pretrain" " model weights." ) } , ) def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ) -> Dict: '''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 SCREAMING_SNAKE_CASE__ ( self : Optional[int] ) -> Any: '''simple docstring''' return json.dumps(dataclasses.asdict(self ) ,indent=2 ) @property def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ) -> List[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 SCREAMING_SNAKE_CASE__ ( self : Optional[int] ) -> int: '''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
296
1
import tempfile import numpy as np import torch from transformers import AutoTokenizer, TaEncoderModel from diffusers import DDPMScheduler, UNetaDConditionModel from diffusers.models.attention_processor import AttnAddedKVProcessor from diffusers.pipelines.deepfloyd_if import IFWatermarker from diffusers.utils.testing_utils import torch_device from ..test_pipelines_common import to_np class UpperCamelCase__ : '''simple docstring''' def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ) -> Tuple: '''simple docstring''' torch.manual_seed(0 ) SCREAMING_SNAKE_CASE = TaEncoderModel.from_pretrained("""hf-internal-testing/tiny-random-t5""" ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained("""hf-internal-testing/tiny-random-t5""" ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE = UNetaDConditionModel( sample_size=32 ,layers_per_block=1 ,block_out_channels=[32, 64] ,down_block_types=[ """ResnetDownsampleBlock2D""", """SimpleCrossAttnDownBlock2D""", ] ,mid_block_type="""UNetMidBlock2DSimpleCrossAttn""" ,up_block_types=["""SimpleCrossAttnUpBlock2D""", """ResnetUpsampleBlock2D"""] ,in_channels=3 ,out_channels=6 ,cross_attention_dim=32 ,encoder_hid_dim=32 ,attention_head_dim=8 ,addition_embed_type="""text""" ,addition_embed_type_num_heads=2 ,cross_attention_norm="""group_norm""" ,resnet_time_scale_shift="""scale_shift""" ,act_fn="""gelu""" ,) unet.set_attn_processor(AttnAddedKVProcessor() ) # For reproducibility tests torch.manual_seed(0 ) SCREAMING_SNAKE_CASE = DDPMScheduler( num_train_timesteps=1000 ,beta_schedule="""squaredcos_cap_v2""" ,beta_start=0.0001 ,beta_end=0.02 ,thresholding=lowerCamelCase__ ,dynamic_thresholding_ratio=0.95 ,sample_max_value=1.0 ,prediction_type="""epsilon""" ,variance_type="""learned_range""" ,) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE = IFWatermarker() return { "text_encoder": text_encoder, "tokenizer": tokenizer, "unet": unet, "scheduler": scheduler, "watermarker": watermarker, "safety_checker": None, "feature_extractor": None, } def SCREAMING_SNAKE_CASE__ ( self : List[Any] ) -> Any: '''simple docstring''' torch.manual_seed(0 ) SCREAMING_SNAKE_CASE = TaEncoderModel.from_pretrained("""hf-internal-testing/tiny-random-t5""" ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained("""hf-internal-testing/tiny-random-t5""" ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE = UNetaDConditionModel( sample_size=32 ,layers_per_block=[1, 2] ,block_out_channels=[32, 64] ,down_block_types=[ """ResnetDownsampleBlock2D""", """SimpleCrossAttnDownBlock2D""", ] ,mid_block_type="""UNetMidBlock2DSimpleCrossAttn""" ,up_block_types=["""SimpleCrossAttnUpBlock2D""", """ResnetUpsampleBlock2D"""] ,in_channels=6 ,out_channels=6 ,cross_attention_dim=32 ,encoder_hid_dim=32 ,attention_head_dim=8 ,addition_embed_type="""text""" ,addition_embed_type_num_heads=2 ,cross_attention_norm="""group_norm""" ,resnet_time_scale_shift="""scale_shift""" ,act_fn="""gelu""" ,class_embed_type="""timestep""" ,mid_block_scale_factor=1.414 ,time_embedding_act_fn="""gelu""" ,time_embedding_dim=32 ,) unet.set_attn_processor(AttnAddedKVProcessor() ) # For reproducibility tests torch.manual_seed(0 ) SCREAMING_SNAKE_CASE = DDPMScheduler( num_train_timesteps=1000 ,beta_schedule="""squaredcos_cap_v2""" ,beta_start=0.0001 ,beta_end=0.02 ,thresholding=lowerCamelCase__ ,dynamic_thresholding_ratio=0.95 ,sample_max_value=1.0 ,prediction_type="""epsilon""" ,variance_type="""learned_range""" ,) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE = DDPMScheduler( num_train_timesteps=1000 ,beta_schedule="""squaredcos_cap_v2""" ,beta_start=0.0001 ,beta_end=0.02 ,) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE = IFWatermarker() return { "text_encoder": text_encoder, "tokenizer": tokenizer, "unet": unet, "scheduler": scheduler, "image_noising_scheduler": image_noising_scheduler, "watermarker": watermarker, "safety_checker": None, "feature_extractor": None, } def SCREAMING_SNAKE_CASE__ ( self : List[str] ) -> Optional[int]: '''simple docstring''' SCREAMING_SNAKE_CASE = self.get_dummy_components() SCREAMING_SNAKE_CASE = self.pipeline_class(**lowerCamelCase__ ) pipe.to(lowerCamelCase__ ) pipe.set_progress_bar_config(disable=lowerCamelCase__ ) SCREAMING_SNAKE_CASE = self.get_dummy_inputs(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = inputs["""prompt"""] SCREAMING_SNAKE_CASE = inputs["""generator"""] SCREAMING_SNAKE_CASE = inputs["""num_inference_steps"""] SCREAMING_SNAKE_CASE = inputs["""output_type"""] if "image" in inputs: SCREAMING_SNAKE_CASE = inputs["""image"""] else: SCREAMING_SNAKE_CASE = None if "mask_image" in inputs: SCREAMING_SNAKE_CASE = inputs["""mask_image"""] else: SCREAMING_SNAKE_CASE = None if "original_image" in inputs: SCREAMING_SNAKE_CASE = inputs["""original_image"""] else: SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE = pipe.encode_prompt(lowerCamelCase__ ) # inputs with prompt converted to embeddings SCREAMING_SNAKE_CASE = { """prompt_embeds""": prompt_embeds, """negative_prompt_embeds""": negative_prompt_embeds, """generator""": generator, """num_inference_steps""": num_inference_steps, """output_type""": output_type, } if image is not None: SCREAMING_SNAKE_CASE = image if mask_image is not None: SCREAMING_SNAKE_CASE = mask_image if original_image is not None: SCREAMING_SNAKE_CASE = original_image # set all optional components to None for optional_component in pipe._optional_components: setattr(lowerCamelCase__ ,lowerCamelCase__ ,lowerCamelCase__ ) SCREAMING_SNAKE_CASE = pipe(**lowerCamelCase__ )[0] with tempfile.TemporaryDirectory() as tmpdir: pipe.save_pretrained(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = self.pipeline_class.from_pretrained(lowerCamelCase__ ) pipe_loaded.to(lowerCamelCase__ ) pipe_loaded.set_progress_bar_config(disable=lowerCamelCase__ ) pipe_loaded.unet.set_attn_processor(AttnAddedKVProcessor() ) # For reproducibility tests for optional_component in pipe._optional_components: self.assertTrue( getattr(lowerCamelCase__ ,lowerCamelCase__ ) is None ,F"""`{optional_component}` did not stay set to None after loading.""" ,) SCREAMING_SNAKE_CASE = self.get_dummy_inputs(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = inputs["""generator"""] SCREAMING_SNAKE_CASE = inputs["""num_inference_steps"""] SCREAMING_SNAKE_CASE = inputs["""output_type"""] # inputs with prompt converted to embeddings SCREAMING_SNAKE_CASE = { """prompt_embeds""": prompt_embeds, """negative_prompt_embeds""": negative_prompt_embeds, """generator""": generator, """num_inference_steps""": num_inference_steps, """output_type""": output_type, } if image is not None: SCREAMING_SNAKE_CASE = image if mask_image is not None: SCREAMING_SNAKE_CASE = mask_image if original_image is not None: SCREAMING_SNAKE_CASE = original_image SCREAMING_SNAKE_CASE = pipe_loaded(**lowerCamelCase__ )[0] SCREAMING_SNAKE_CASE = np.abs(to_np(lowerCamelCase__ ) - to_np(lowerCamelCase__ ) ).max() self.assertLess(lowerCamelCase__ ,1e-4 ) def SCREAMING_SNAKE_CASE__ ( self : Dict ) -> Optional[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE = self.get_dummy_components() SCREAMING_SNAKE_CASE = self.pipeline_class(**lowerCamelCase__ ) pipe.to(lowerCamelCase__ ) pipe.set_progress_bar_config(disable=lowerCamelCase__ ) SCREAMING_SNAKE_CASE = self.get_dummy_inputs(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = pipe(**lowerCamelCase__ )[0] with tempfile.TemporaryDirectory() as tmpdir: pipe.save_pretrained(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = self.pipeline_class.from_pretrained(lowerCamelCase__ ) pipe_loaded.to(lowerCamelCase__ ) pipe_loaded.set_progress_bar_config(disable=lowerCamelCase__ ) pipe_loaded.unet.set_attn_processor(AttnAddedKVProcessor() ) # For reproducibility tests SCREAMING_SNAKE_CASE = self.get_dummy_inputs(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = pipe_loaded(**lowerCamelCase__ )[0] SCREAMING_SNAKE_CASE = np.abs(to_np(lowerCamelCase__ ) - to_np(lowerCamelCase__ ) ).max() self.assertLess(lowerCamelCase__ ,1e-4 )
296
import math import unittest def __lowercase ( _SCREAMING_SNAKE_CASE ) -> bool: '''simple docstring''' assert isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) and ( number >= 0 ), "'number' must been an int and positive" if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(math.sqrt(_SCREAMING_SNAKE_CASE ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True class UpperCamelCase__ ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE__ ( self : Dict ) -> Tuple: '''simple docstring''' self.assertTrue(is_prime(2 ) ) self.assertTrue(is_prime(3 ) ) self.assertTrue(is_prime(5 ) ) self.assertTrue(is_prime(7 ) ) self.assertTrue(is_prime(11 ) ) self.assertTrue(is_prime(13 ) ) self.assertTrue(is_prime(17 ) ) self.assertTrue(is_prime(19 ) ) self.assertTrue(is_prime(23 ) ) self.assertTrue(is_prime(29 ) ) def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ) -> Tuple: '''simple docstring''' with self.assertRaises(lowerCamelCase__ ): is_prime(-19 ) self.assertFalse( is_prime(0 ) ,"""Zero doesn't have any positive factors, primes must have exactly two.""" ,) self.assertFalse( is_prime(1 ) ,"""One only has 1 positive factor, primes must have exactly two.""" ,) self.assertFalse(is_prime(2 * 2 ) ) self.assertFalse(is_prime(2 * 3 ) ) self.assertFalse(is_prime(3 * 3 ) ) self.assertFalse(is_prime(3 * 5 ) ) self.assertFalse(is_prime(3 * 5 * 7 ) ) if __name__ == "__main__": unittest.main()
296
1
import argparse import json import os import fairseq import torch from fairseq.data import Dictionary from transformers import ( UniSpeechConfig, UniSpeechForCTC, UniSpeechForPreTraining, WavaVecaFeatureExtractor, WavaVecaPhonemeCTCTokenizer, WavaVecaProcessor, logging, ) logging.set_verbosity_info() SCREAMING_SNAKE_CASE_ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE_ = { """post_extract_proj""": """feature_projection.projection""", """encoder.pos_conv.0""": """encoder.pos_conv_embed.conv""", """self_attn.k_proj""": """encoder.layers.*.attention.k_proj""", """self_attn.v_proj""": """encoder.layers.*.attention.v_proj""", """self_attn.q_proj""": """encoder.layers.*.attention.q_proj""", """self_attn.out_proj""": """encoder.layers.*.attention.out_proj""", """self_attn_layer_norm""": """encoder.layers.*.layer_norm""", """fc1""": """encoder.layers.*.feed_forward.intermediate_dense""", """fc2""": """encoder.layers.*.feed_forward.output_dense""", """final_layer_norm""": """encoder.layers.*.final_layer_norm""", """encoder.layer_norm""": """encoder.layer_norm""", """w2v_model.layer_norm""": """feature_projection.layer_norm""", """quantizer.weight_proj""": """quantizer.weight_proj""", """quantizer.vars""": """quantizer.codevectors""", """project_q""": """project_q""", """final_proj""": """project_hid""", """w2v_encoder.proj""": """ctc_proj""", """mask_emb""": """masked_spec_embed""", } SCREAMING_SNAKE_CASE_ = [ """ctc_proj""", """quantizer.weight_proj""", """quantizer.codevectors""", """project_q""", """project_hid""", ] def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> str: '''simple docstring''' for attribute in key.split(""".""" ): if is_finetuned: if attribute in ["quantizer", "project_q", "project_hid"]: # those layers are only relevant for pretraining and should be dropped return if attribute == "ctc_proj": # we should rename `ctc_proj` to `lm_head` for fine-tuned phoneme models SCREAMING_SNAKE_CASE = """lm_head""" SCREAMING_SNAKE_CASE = getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if weight_type is not None: SCREAMING_SNAKE_CASE = getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ).shape else: SCREAMING_SNAKE_CASE = hf_pointer.shape assert hf_shape == value.shape, ( F"""Shape of hf {key + '.' + weight_type if weight_type is not None else ''} is {hf_shape}, but should be""" F""" {value.shape} for {full_name}""" ) if weight_type == "weight": SCREAMING_SNAKE_CASE = value elif weight_type == "weight_g": SCREAMING_SNAKE_CASE = value elif weight_type == "weight_v": SCREAMING_SNAKE_CASE = value elif weight_type == "bias": SCREAMING_SNAKE_CASE = value else: SCREAMING_SNAKE_CASE = value logger.info(F"""{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}.""" ) def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Tuple: '''simple docstring''' SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = fairseq_model.state_dict() SCREAMING_SNAKE_CASE = hf_model.unispeech.feature_extractor for name, value in fairseq_dict.items(): SCREAMING_SNAKE_CASE = False if "conv_layers" in name: load_conv_layer( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , hf_model.config.feat_extract_norm == """group""" , ) SCREAMING_SNAKE_CASE = True else: for key, mapped_key in MAPPING.items(): SCREAMING_SNAKE_CASE = """unispeech.""" + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key if key in name or key.split("""w2v_model.""" )[-1] == name.split(""".""" )[0]: SCREAMING_SNAKE_CASE = True if "*" in mapped_key: SCREAMING_SNAKE_CASE = name.split(_SCREAMING_SNAKE_CASE )[0].split(""".""" )[-2] SCREAMING_SNAKE_CASE = mapped_key.replace("""*""" , _SCREAMING_SNAKE_CASE ) if "weight_g" in name: SCREAMING_SNAKE_CASE = """weight_g""" elif "weight_v" in name: SCREAMING_SNAKE_CASE = """weight_v""" elif "bias" in name: SCREAMING_SNAKE_CASE = """bias""" elif "weight" in name: # TODO: don't match quantizer.weight_proj SCREAMING_SNAKE_CASE = """weight""" else: SCREAMING_SNAKE_CASE = None set_recursively(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) continue if not is_used: unused_weights.append(_SCREAMING_SNAKE_CASE ) logger.warning(F"""Unused weights: {unused_weights}""" ) def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE = full_name.split("""conv_layers.""" )[-1] SCREAMING_SNAKE_CASE = name.split(""".""" ) SCREAMING_SNAKE_CASE = int(items[0] ) SCREAMING_SNAKE_CASE = int(items[1] ) if type_id == 0: if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, ( F"""{full_name} has size {value.shape}, but""" F""" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.""" ) SCREAMING_SNAKE_CASE = value logger.info(F"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, ( F"""{full_name} has size {value.shape}, but""" F""" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.""" ) SCREAMING_SNAKE_CASE = value logger.info(F"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, ( F"""{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was""" " found." ) SCREAMING_SNAKE_CASE = value logger.info(F"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, ( F"""{full_name} has size {value.shape}, but""" F""" {feature_extractor[layer_id].layer_norm.weight.data.shape} was found.""" ) SCREAMING_SNAKE_CASE = value logger.info(F"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) else: unused_weights.append(_SCREAMING_SNAKE_CASE ) @torch.no_grad() def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=True ) -> List[Any]: '''simple docstring''' if config_path is not None: SCREAMING_SNAKE_CASE = UniSpeechConfig.from_pretrained(_SCREAMING_SNAKE_CASE ) else: SCREAMING_SNAKE_CASE = UniSpeechConfig() if is_finetuned: if dict_path: SCREAMING_SNAKE_CASE = Dictionary.load_from_json(_SCREAMING_SNAKE_CASE ) # important change bos & pad token id since CTC symbol is <pad> and # not <s> as in fairseq SCREAMING_SNAKE_CASE = target_dict.pad_index SCREAMING_SNAKE_CASE = target_dict.bos_index SCREAMING_SNAKE_CASE = target_dict.eos_index SCREAMING_SNAKE_CASE = len(target_dict.symbols ) SCREAMING_SNAKE_CASE = os.path.join(_SCREAMING_SNAKE_CASE , """vocab.json""" ) if not os.path.isdir(_SCREAMING_SNAKE_CASE ): logger.error("""--pytorch_dump_folder_path ({}) should be a directory""".format(_SCREAMING_SNAKE_CASE ) ) return os.makedirs(_SCREAMING_SNAKE_CASE , exist_ok=_SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE = target_dict.indices # fairseq has the <pad> and <s> switched SCREAMING_SNAKE_CASE = 42 SCREAMING_SNAKE_CASE = 43 with open(_SCREAMING_SNAKE_CASE , """w""" , encoding="""utf-8""" ) as vocab_handle: json.dump(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE = WavaVecaPhonemeCTCTokenizer( _SCREAMING_SNAKE_CASE , unk_token=target_dict.unk_word , pad_token=target_dict.pad_word , bos_token=target_dict.bos_word , eos_token=target_dict.eos_word , word_delimiter_token="""|""" , do_lower_case=_SCREAMING_SNAKE_CASE , ) SCREAMING_SNAKE_CASE = True if config.feat_extract_norm == """layer""" else False SCREAMING_SNAKE_CASE = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=1_60_00 , padding_value=0 , do_normalize=_SCREAMING_SNAKE_CASE , return_attention_mask=_SCREAMING_SNAKE_CASE , ) SCREAMING_SNAKE_CASE = WavaVecaProcessor(feature_extractor=_SCREAMING_SNAKE_CASE , tokenizer=_SCREAMING_SNAKE_CASE ) processor.save_pretrained(_SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE = UniSpeechForCTC(_SCREAMING_SNAKE_CASE ) else: SCREAMING_SNAKE_CASE = UniSpeechForPreTraining(_SCREAMING_SNAKE_CASE ) if is_finetuned: SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={"""data""": """/""".join(dict_path.split("""/""" )[:-1] ), """w2v_path""": checkpoint_path} ) else: SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE = fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path] ) SCREAMING_SNAKE_CASE = model[0].eval() recursively_load_weights(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) hf_unispeech.save_pretrained(_SCREAMING_SNAKE_CASE ) if __name__ == "__main__": SCREAMING_SNAKE_CASE_ = argparse.ArgumentParser() parser.add_argument("""--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model.""") parser.add_argument("""--checkpoint_path""", default=None, type=str, help="""Path to fairseq checkpoint""") parser.add_argument("""--dict_path""", default=None, type=str, help="""Path to dict of fine-tuned model""") parser.add_argument("""--config_path""", default=None, type=str, help="""Path to hf config.json of model to convert""") parser.add_argument( """--not_finetuned""", action="""store_true""", help="""Whether the model to convert is a fine-tuned model or not""" ) SCREAMING_SNAKE_CASE_ = parser.parse_args() convert_unispeech_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned )
296
import random class UpperCamelCase__ : '''simple docstring''' @staticmethod def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ : str ) -> tuple[list[int], list[int]]: '''simple docstring''' SCREAMING_SNAKE_CASE = [ord(lowerCamelCase__ ) for i in text] SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = [] for i in plain: SCREAMING_SNAKE_CASE = random.randint(1 ,300 ) SCREAMING_SNAKE_CASE = (i + k) * k cipher.append(lowerCamelCase__ ) key.append(lowerCamelCase__ ) return cipher, key @staticmethod def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ : list[int] ,lowerCamelCase__ : list[int] ) -> str: '''simple docstring''' SCREAMING_SNAKE_CASE = [] for i in range(len(lowerCamelCase__ ) ): SCREAMING_SNAKE_CASE = int((cipher[i] - (key[i]) ** 2) / key[i] ) plain.append(chr(lowerCamelCase__ ) ) return "".join(lowerCamelCase__ ) if __name__ == "__main__": SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = Onepad().encrypt("""Hello""") print(c, k) print(Onepad().decrypt(c, k))
296
1
def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> int: '''simple docstring''' if index == number_of_items: return 0 SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = knapsack(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , index + 1 ) if weights[index] <= max_weight: SCREAMING_SNAKE_CASE = values[index] + knapsack( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , max_weight - weights[index] , index + 1 ) return max(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if __name__ == "__main__": import doctest doctest.testmod()
296
from typing import List from ...configuration_utils import PretrainedConfig from ...utils import logging SCREAMING_SNAKE_CASE_ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE_ = { """snap-research/efficientformer-l1-300""": ( """https://huggingface.co/snap-research/efficientformer-l1-300/resolve/main/config.json""" ), } class UpperCamelCase__ ( lowerCAmelCase_ ): '''simple docstring''' __snake_case : int = "efficientformer" def __init__( self : Optional[int] ,lowerCamelCase__ : List[int] = [3, 2, 6, 4] ,lowerCamelCase__ : List[int] = [48, 96, 224, 448] ,lowerCamelCase__ : List[bool] = [True, True, True, True] ,lowerCamelCase__ : int = 448 ,lowerCamelCase__ : int = 32 ,lowerCamelCase__ : int = 4 ,lowerCamelCase__ : int = 7 ,lowerCamelCase__ : int = 5 ,lowerCamelCase__ : int = 8 ,lowerCamelCase__ : int = 4 ,lowerCamelCase__ : float = 0.0 ,lowerCamelCase__ : int = 16 ,lowerCamelCase__ : int = 3 ,lowerCamelCase__ : int = 3 ,lowerCamelCase__ : int = 3 ,lowerCamelCase__ : int = 2 ,lowerCamelCase__ : int = 1 ,lowerCamelCase__ : float = 0.0 ,lowerCamelCase__ : int = 1 ,lowerCamelCase__ : bool = True ,lowerCamelCase__ : bool = True ,lowerCamelCase__ : float = 1e-5 ,lowerCamelCase__ : str = "gelu" ,lowerCamelCase__ : float = 0.02 ,lowerCamelCase__ : float = 1e-1_2 ,lowerCamelCase__ : int = 224 ,lowerCamelCase__ : float = 1e-0_5 ,**lowerCamelCase__ : str ,) -> None: '''simple docstring''' super().__init__(**lowerCamelCase__ ) SCREAMING_SNAKE_CASE = hidden_act SCREAMING_SNAKE_CASE = hidden_dropout_prob SCREAMING_SNAKE_CASE = hidden_sizes SCREAMING_SNAKE_CASE = num_hidden_layers SCREAMING_SNAKE_CASE = num_attention_heads SCREAMING_SNAKE_CASE = initializer_range SCREAMING_SNAKE_CASE = layer_norm_eps SCREAMING_SNAKE_CASE = patch_size SCREAMING_SNAKE_CASE = num_channels SCREAMING_SNAKE_CASE = depths SCREAMING_SNAKE_CASE = mlp_expansion_ratio SCREAMING_SNAKE_CASE = downsamples SCREAMING_SNAKE_CASE = dim SCREAMING_SNAKE_CASE = key_dim SCREAMING_SNAKE_CASE = attention_ratio SCREAMING_SNAKE_CASE = resolution SCREAMING_SNAKE_CASE = pool_size SCREAMING_SNAKE_CASE = downsample_patch_size SCREAMING_SNAKE_CASE = downsample_stride SCREAMING_SNAKE_CASE = downsample_pad SCREAMING_SNAKE_CASE = drop_path_rate SCREAMING_SNAKE_CASE = num_metaad_blocks SCREAMING_SNAKE_CASE = distillation SCREAMING_SNAKE_CASE = use_layer_scale SCREAMING_SNAKE_CASE = layer_scale_init_value SCREAMING_SNAKE_CASE = image_size SCREAMING_SNAKE_CASE = batch_norm_eps
296
1
import string def __lowercase ( _SCREAMING_SNAKE_CASE ) -> None: '''simple docstring''' for key in range(len(string.ascii_uppercase ) ): SCREAMING_SNAKE_CASE = """""" for symbol in message: if symbol in string.ascii_uppercase: SCREAMING_SNAKE_CASE = string.ascii_uppercase.find(_SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE = num - key if num < 0: SCREAMING_SNAKE_CASE = num + len(string.ascii_uppercase ) SCREAMING_SNAKE_CASE = translated + string.ascii_uppercase[num] else: SCREAMING_SNAKE_CASE = translated + symbol print(F"""Decryption using Key #{key}: {translated}""" ) def __lowercase ( ) -> None: '''simple docstring''' SCREAMING_SNAKE_CASE = input("""Encrypted message: """ ) SCREAMING_SNAKE_CASE = message.upper() decrypt(_SCREAMING_SNAKE_CASE ) if __name__ == "__main__": import doctest doctest.testmod() main()
296
import importlib import shutil import threading import warnings from typing import List import fsspec import fsspec.asyn from . import compression from .hffilesystem import HfFileSystem SCREAMING_SNAKE_CASE_ = importlib.util.find_spec("""s3fs""") is not None if _has_safs: from .safilesystem import SaFileSystem # noqa: F401 SCREAMING_SNAKE_CASE_ = [ compression.BzaFileSystem, compression.GzipFileSystem, compression.LzaFileSystem, compression.XzFileSystem, compression.ZstdFileSystem, ] # Register custom filesystems for fs_class in COMPRESSION_FILESYSTEMS + [HfFileSystem]: if fs_class.protocol in fsspec.registry and fsspec.registry[fs_class.protocol] is not fs_class: warnings.warn(F'''A filesystem protocol was already set for {fs_class.protocol} and will be overwritten.''') fsspec.register_implementation(fs_class.protocol, fs_class, clobber=True) def __lowercase ( _SCREAMING_SNAKE_CASE ) -> str: '''simple docstring''' if "://" in dataset_path: SCREAMING_SNAKE_CASE = dataset_path.split("""://""" )[1] return dataset_path def __lowercase ( _SCREAMING_SNAKE_CASE ) -> bool: '''simple docstring''' if fs is not None and fs.protocol != "file": return True else: return False def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Dict: '''simple docstring''' SCREAMING_SNAKE_CASE = not is_remote_filesystem(_SCREAMING_SNAKE_CASE ) if is_local: # LocalFileSystem.mv does copy + rm, it is more efficient to simply move a local directory shutil.move(fs._strip_protocol(_SCREAMING_SNAKE_CASE ) , fs._strip_protocol(_SCREAMING_SNAKE_CASE ) ) else: fs.mv(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , recursive=_SCREAMING_SNAKE_CASE ) def __lowercase ( ) -> None: '''simple docstring''' if hasattr(fsspec.asyn , """reset_lock""" ): # for future fsspec>2022.05.0 fsspec.asyn.reset_lock() else: SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = threading.Lock()
296
1
import math import unittest from transformers import BioGptConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification, BioGptModel, BioGptTokenizer, ) from transformers.models.biogpt.modeling_biogpt import BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST class UpperCamelCase__ : '''simple docstring''' def __init__( self : Optional[Any] ,lowerCamelCase__ : Union[str, Any] ,lowerCamelCase__ : List[Any]=13 ,lowerCamelCase__ : Dict=7 ,lowerCamelCase__ : Union[str, Any]=True ,lowerCamelCase__ : Dict=True ,lowerCamelCase__ : List[str]=False ,lowerCamelCase__ : List[str]=True ,lowerCamelCase__ : List[Any]=99 ,lowerCamelCase__ : List[str]=32 ,lowerCamelCase__ : Union[str, Any]=5 ,lowerCamelCase__ : Union[str, Any]=4 ,lowerCamelCase__ : List[str]=37 ,lowerCamelCase__ : str="gelu" ,lowerCamelCase__ : Optional[Any]=0.1 ,lowerCamelCase__ : Dict=0.1 ,lowerCamelCase__ : Dict=512 ,lowerCamelCase__ : List[Any]=16 ,lowerCamelCase__ : Dict=2 ,lowerCamelCase__ : List[Any]=0.02 ,lowerCamelCase__ : Optional[int]=3 ,lowerCamelCase__ : Dict=4 ,lowerCamelCase__ : str=None ,) -> List[str]: '''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 def SCREAMING_SNAKE_CASE__ ( self : List[Any] ) -> Optional[int]: '''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 = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def SCREAMING_SNAKE_CASE__ ( self : List[str] ) -> Tuple: '''simple docstring''' return BioGptConfig( 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 ,) def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ,lowerCamelCase__ : Optional[int] ,lowerCamelCase__ : str ,lowerCamelCase__ : str ,lowerCamelCase__ : Dict ,lowerCamelCase__ : List[Any] ,lowerCamelCase__ : List[Any] ,lowerCamelCase__ : Any ) -> Union[str, Any]: '''simple docstring''' SCREAMING_SNAKE_CASE = BioGptModel(config=lowerCamelCase__ ) model.to(lowerCamelCase__ ) model.eval() SCREAMING_SNAKE_CASE = model(lowerCamelCase__ ,attention_mask=lowerCamelCase__ ) SCREAMING_SNAKE_CASE = model(lowerCamelCase__ ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ,lowerCamelCase__ : Union[str, Any] ,lowerCamelCase__ : str ,lowerCamelCase__ : List[str] ,lowerCamelCase__ : Dict ,lowerCamelCase__ : str ,lowerCamelCase__ : List[str] ,lowerCamelCase__ : List[str] ,lowerCamelCase__ : Optional[int] ,lowerCamelCase__ : Optional[int] ,) -> Dict: '''simple docstring''' SCREAMING_SNAKE_CASE = BioGptForCausalLM(config=lowerCamelCase__ ) model.to(lowerCamelCase__ ) model.eval() SCREAMING_SNAKE_CASE = model(lowerCamelCase__ ,attention_mask=lowerCamelCase__ ,token_type_ids=lowerCamelCase__ ,labels=lowerCamelCase__ ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.vocab_size) ) def SCREAMING_SNAKE_CASE__ ( self : Any ,lowerCamelCase__ : str ,lowerCamelCase__ : Union[str, Any] ,lowerCamelCase__ : List[Any] ,lowerCamelCase__ : int ,lowerCamelCase__ : List[str] ,*lowerCamelCase__ : Optional[int] ) -> Optional[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE = BioGptModel(config=lowerCamelCase__ ) model.to(lowerCamelCase__ ) model.eval() # create attention mask SCREAMING_SNAKE_CASE = torch.ones(input_ids.shape ,dtype=torch.long ,device=lowerCamelCase__ ) SCREAMING_SNAKE_CASE = self.seq_length // 2 SCREAMING_SNAKE_CASE = 0 # first forward pass SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE = model(lowerCamelCase__ ,attention_mask=lowerCamelCase__ ).to_tuple() # create hypothetical next token and extent to next_input_ids SCREAMING_SNAKE_CASE = ids_tensor((self.batch_size, 1) ,config.vocab_size ) # change a random masked slice from input_ids SCREAMING_SNAKE_CASE = ids_tensor((1,) ,lowerCamelCase__ ).item() + 1 SCREAMING_SNAKE_CASE = ids_tensor((self.batch_size, 1) ,config.vocab_size ).squeeze(-1 ) SCREAMING_SNAKE_CASE = random_other_next_tokens # append to next input_ids and attn_mask SCREAMING_SNAKE_CASE = torch.cat([input_ids, next_tokens] ,dim=-1 ) SCREAMING_SNAKE_CASE = torch.cat( [attn_mask, torch.ones((attn_mask.shape[0], 1) ,dtype=torch.long ,device=lowerCamelCase__ )] ,dim=1 ,) # get two different outputs SCREAMING_SNAKE_CASE = model(lowerCamelCase__ ,attention_mask=lowerCamelCase__ )["""last_hidden_state"""] SCREAMING_SNAKE_CASE = model(lowerCamelCase__ ,past_key_values=lowerCamelCase__ ,attention_mask=lowerCamelCase__ )["""last_hidden_state"""] # select random slice SCREAMING_SNAKE_CASE = ids_tensor((1,) ,output_from_past.shape[-1] ).item() SCREAMING_SNAKE_CASE = output_from_no_past[:, -1, random_slice_idx].detach() SCREAMING_SNAKE_CASE = output_from_past[:, 0, random_slice_idx].detach() # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(lowerCamelCase__ ,lowerCamelCase__ ,atol=1e-3 ) ) def SCREAMING_SNAKE_CASE__ ( self : List[str] ,lowerCamelCase__ : List[Any] ,lowerCamelCase__ : int ,lowerCamelCase__ : Dict ,lowerCamelCase__ : List[Any] ,lowerCamelCase__ : Dict ,*lowerCamelCase__ : str ) -> Dict: '''simple docstring''' SCREAMING_SNAKE_CASE = BioGptModel(config=lowerCamelCase__ ).to(lowerCamelCase__ ).eval() SCREAMING_SNAKE_CASE = torch.ones(input_ids.shape ,dtype=torch.long ,device=lowerCamelCase__ ) # first forward pass SCREAMING_SNAKE_CASE = model(lowerCamelCase__ ,attention_mask=lowerCamelCase__ ,use_cache=lowerCamelCase__ ) SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE = outputs.to_tuple() # create hypothetical multiple next token and extent to next_input_ids SCREAMING_SNAKE_CASE = ids_tensor((self.batch_size, 3) ,config.vocab_size ) SCREAMING_SNAKE_CASE = ids_tensor((self.batch_size, 3) ,2 ) # append to next input_ids and SCREAMING_SNAKE_CASE = torch.cat([input_ids, next_tokens] ,dim=-1 ) SCREAMING_SNAKE_CASE = torch.cat([attention_mask, next_attn_mask] ,dim=-1 ) SCREAMING_SNAKE_CASE = model(lowerCamelCase__ ,attention_mask=lowerCamelCase__ )["""last_hidden_state"""] SCREAMING_SNAKE_CASE = model(lowerCamelCase__ ,attention_mask=lowerCamelCase__ ,past_key_values=lowerCamelCase__ )[ """last_hidden_state""" ] # select random slice SCREAMING_SNAKE_CASE = ids_tensor((1,) ,output_from_past.shape[-1] ).item() SCREAMING_SNAKE_CASE = output_from_no_past[:, -3:, random_slice_idx].detach() SCREAMING_SNAKE_CASE = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(lowerCamelCase__ ,lowerCamelCase__ ,atol=1e-3 ) ) def SCREAMING_SNAKE_CASE__ ( self : str ,lowerCamelCase__ : int ,lowerCamelCase__ : int ,lowerCamelCase__ : str ,lowerCamelCase__ : Union[str, Any] ,lowerCamelCase__ : List[Any] ,*lowerCamelCase__ : str ,lowerCamelCase__ : Tuple=False ) -> List[str]: '''simple docstring''' SCREAMING_SNAKE_CASE = BioGptForCausalLM(lowerCamelCase__ ) model.to(lowerCamelCase__ ) if gradient_checkpointing: model.gradient_checkpointing_enable() SCREAMING_SNAKE_CASE = model(lowerCamelCase__ ,labels=lowerCamelCase__ ) self.parent.assertEqual(result.loss.shape ,() ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.vocab_size) ) result.loss.backward() def SCREAMING_SNAKE_CASE__ ( self : Tuple ,lowerCamelCase__ : List[Any] ,*lowerCamelCase__ : List[str] ) -> str: '''simple docstring''' SCREAMING_SNAKE_CASE = BioGptModel(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = model.config.initializer_range / math.sqrt(2 * model.config.num_hidden_layers ) for key in model.state_dict().keys(): if "c_proj" in key and "weight" in key: self.parent.assertLessEqual(abs(torch.std(model.state_dict()[key] ) - model_std ) ,0.001 ) self.parent.assertLessEqual(abs(torch.mean(model.state_dict()[key] ) - 0.0 ) ,0.01 ) def SCREAMING_SNAKE_CASE__ ( self : int ,lowerCamelCase__ : str ,lowerCamelCase__ : List[str] ,lowerCamelCase__ : Optional[int] ,lowerCamelCase__ : Union[str, Any] ,lowerCamelCase__ : Tuple ,*lowerCamelCase__ : Optional[int] ) -> List[str]: '''simple docstring''' SCREAMING_SNAKE_CASE = self.num_labels SCREAMING_SNAKE_CASE = BioGptForTokenClassification(lowerCamelCase__ ) model.to(lowerCamelCase__ ) model.eval() SCREAMING_SNAKE_CASE = model(lowerCamelCase__ ,attention_mask=lowerCamelCase__ ,token_type_ids=lowerCamelCase__ ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.num_labels) ) def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ) -> List[str]: '''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, """attention_mask""": input_mask} return config, inputs_dict @require_torch class UpperCamelCase__ ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , unittest.TestCase ): '''simple docstring''' __snake_case : Dict = ( (BioGptModel, BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification) if is_torch_available() else () ) __snake_case : Union[str, Any] = (BioGptForCausalLM,) if is_torch_available() else () __snake_case : List[Any] = ( { "feature-extraction": BioGptModel, "text-classification": BioGptForSequenceClassification, "text-generation": BioGptForCausalLM, "token-classification": BioGptForTokenClassification, "zero-shot": BioGptForSequenceClassification, } if is_torch_available() else {} ) __snake_case : int = False def SCREAMING_SNAKE_CASE__ ( self : Any ) -> List[str]: '''simple docstring''' SCREAMING_SNAKE_CASE = BioGptModelTester(self ) SCREAMING_SNAKE_CASE = ConfigTester(self ,config_class=lowerCamelCase__ ,hidden_size=37 ) def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ) -> Dict: '''simple docstring''' self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE__ ( self : Tuple ) -> List[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( self : List[Any] ) -> Tuple: '''simple docstring''' SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: SCREAMING_SNAKE_CASE = type self.model_tester.create_and_check_model(*lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( self : Dict ) -> Tuple: '''simple docstring''' SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_attention_mask_past(*lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( self : List[Any] ) -> Dict: '''simple docstring''' SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_forward_and_backwards(*lowerCamelCase__ ,gradient_checkpointing=lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( self : str ) -> Optional[int]: '''simple docstring''' SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_past_large_inputs(*lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( self : str ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_weight_initialization(*lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( self : Tuple ) -> Dict: '''simple docstring''' SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_for_token_classification(*lowerCamelCase__ ) @slow def SCREAMING_SNAKE_CASE__ ( self : List[str] ) -> Optional[int]: '''simple docstring''' SCREAMING_SNAKE_CASE = BioGptForCausalLM.from_pretrained("""microsoft/biogpt""" ) model.to(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = BioGptTokenizer.from_pretrained("""microsoft/biogpt""" ) SCREAMING_SNAKE_CASE = """left""" # Define PAD Token = EOS Token = 50256 SCREAMING_SNAKE_CASE = tokenizer.eos_token SCREAMING_SNAKE_CASE = model.config.eos_token_id # use different length sentences to test batching SCREAMING_SNAKE_CASE = [ """Hello, my dog is a little""", """Today, I""", ] SCREAMING_SNAKE_CASE = tokenizer(lowerCamelCase__ ,return_tensors="""pt""" ,padding=lowerCamelCase__ ) SCREAMING_SNAKE_CASE = inputs["""input_ids"""].to(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = model.generate( input_ids=lowerCamelCase__ ,attention_mask=inputs["""attention_mask"""].to(lowerCamelCase__ ) ,) SCREAMING_SNAKE_CASE = tokenizer(sentences[0] ,return_tensors="""pt""" ).input_ids.to(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = model.generate(input_ids=lowerCamelCase__ ) SCREAMING_SNAKE_CASE = inputs_non_padded.shape[-1] - inputs["""attention_mask"""][-1].long().sum().cpu().item() SCREAMING_SNAKE_CASE = tokenizer(sentences[1] ,return_tensors="""pt""" ).input_ids.to(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = model.generate(input_ids=lowerCamelCase__ ,max_length=model.config.max_length - num_paddings ) SCREAMING_SNAKE_CASE = tokenizer.batch_decode(lowerCamelCase__ ,skip_special_tokens=lowerCamelCase__ ) SCREAMING_SNAKE_CASE = tokenizer.decode(output_non_padded[0] ,skip_special_tokens=lowerCamelCase__ ) SCREAMING_SNAKE_CASE = tokenizer.decode(output_padded[0] ,skip_special_tokens=lowerCamelCase__ ) SCREAMING_SNAKE_CASE = [ """Hello, my dog is a little bit bigger than a little bit.""", """Today, I have a good idea of how to use the information""", ] self.assertListEqual(lowerCamelCase__ ,lowerCamelCase__ ) self.assertListEqual(lowerCamelCase__ ,[non_padded_sentence, padded_sentence] ) @slow def SCREAMING_SNAKE_CASE__ ( self : str ) -> Optional[int]: '''simple docstring''' for model_name in BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE = BioGptModel.from_pretrained(lowerCamelCase__ ) self.assertIsNotNone(lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( self : List[str] ) -> Dict: '''simple docstring''' SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE = 3 SCREAMING_SNAKE_CASE = input_dict["""input_ids"""] SCREAMING_SNAKE_CASE = input_ids.ne(1 ).to(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = ids_tensor([self.model_tester.batch_size] ,self.model_tester.type_sequence_label_size ) SCREAMING_SNAKE_CASE = BioGptForSequenceClassification(lowerCamelCase__ ) model.to(lowerCamelCase__ ) model.eval() SCREAMING_SNAKE_CASE = model(lowerCamelCase__ ,attention_mask=lowerCamelCase__ ,labels=lowerCamelCase__ ) self.assertEqual(result.logits.shape ,(self.model_tester.batch_size, self.model_tester.num_labels) ) def SCREAMING_SNAKE_CASE__ ( self : Any ) -> List[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE = 3 SCREAMING_SNAKE_CASE = """multi_label_classification""" SCREAMING_SNAKE_CASE = input_dict["""input_ids"""] SCREAMING_SNAKE_CASE = input_ids.ne(1 ).to(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = ids_tensor( [self.model_tester.batch_size, config.num_labels] ,self.model_tester.type_sequence_label_size ).to(torch.float ) SCREAMING_SNAKE_CASE = BioGptForSequenceClassification(lowerCamelCase__ ) model.to(lowerCamelCase__ ) model.eval() SCREAMING_SNAKE_CASE = model(lowerCamelCase__ ,attention_mask=lowerCamelCase__ ,labels=lowerCamelCase__ ) self.assertEqual(result.logits.shape ,(self.model_tester.batch_size, self.model_tester.num_labels) ) @require_torch class UpperCamelCase__ ( unittest.TestCase ): '''simple docstring''' @slow def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ) -> str: '''simple docstring''' SCREAMING_SNAKE_CASE = BioGptForCausalLM.from_pretrained("""microsoft/biogpt""" ) SCREAMING_SNAKE_CASE = torch.tensor([[2, 4805, 9, 656, 21]] ) SCREAMING_SNAKE_CASE = model(lowerCamelCase__ )[0] SCREAMING_SNAKE_CASE = 42384 SCREAMING_SNAKE_CASE = torch.Size((1, 5, vocab_size) ) self.assertEqual(output.shape ,lowerCamelCase__ ) SCREAMING_SNAKE_CASE = torch.tensor( [[[-9.5236, -9.8918, 10.4557], [-11.0469, -9.6423, 8.1022], [-8.8664, -7.8826, 5.5325]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] ,lowerCamelCase__ ,atol=1e-4 ) ) @slow def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE = BioGptTokenizer.from_pretrained("""microsoft/biogpt""" ) SCREAMING_SNAKE_CASE = BioGptForCausalLM.from_pretrained("""microsoft/biogpt""" ) model.to(lowerCamelCase__ ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE = tokenizer("""COVID-19 is""" ,return_tensors="""pt""" ).to(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = model.generate( **lowerCamelCase__ ,min_length=100 ,max_length=1024 ,num_beams=5 ,early_stopping=lowerCamelCase__ ,) SCREAMING_SNAKE_CASE = tokenizer.decode(output_ids[0] ,skip_special_tokens=lowerCamelCase__ ) SCREAMING_SNAKE_CASE = ( """COVID-19 is a global pandemic caused by severe acute respiratory syndrome coronavirus 2 (SARS-CoV-2), the""" """ causative agent of coronavirus disease 2019 (COVID-19), which has spread to more than 200 countries and""" """ territories, including the United States (US), Canada, Australia, New Zealand, the United Kingdom (UK),""" """ and the United States of America (USA), as of March 11, 2020, with more than 800,000 confirmed cases and""" """ more than 800,000 deaths.""" ) self.assertEqual(lowerCamelCase__ ,lowerCamelCase__ )
296
import unittest import numpy as np import torch from diffusers import KarrasVePipeline, KarrasVeScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class UpperCamelCase__ ( unittest.TestCase ): '''simple docstring''' @property def SCREAMING_SNAKE_CASE__ ( self : str ) -> Optional[int]: '''simple docstring''' torch.manual_seed(0 ) SCREAMING_SNAKE_CASE = UNetaDModel( block_out_channels=(32, 64) ,layers_per_block=2 ,sample_size=32 ,in_channels=3 ,out_channels=3 ,down_block_types=("""DownBlock2D""", """AttnDownBlock2D""") ,up_block_types=("""AttnUpBlock2D""", """UpBlock2D""") ,) return model def SCREAMING_SNAKE_CASE__ ( self : Tuple ) -> Union[str, Any]: '''simple docstring''' SCREAMING_SNAKE_CASE = self.dummy_uncond_unet SCREAMING_SNAKE_CASE = KarrasVeScheduler() SCREAMING_SNAKE_CASE = KarrasVePipeline(unet=lowerCamelCase__ ,scheduler=lowerCamelCase__ ) pipe.to(lowerCamelCase__ ) pipe.set_progress_bar_config(disable=lowerCamelCase__ ) SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE = pipe(num_inference_steps=2 ,generator=lowerCamelCase__ ,output_type="""numpy""" ).images SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE = pipe(num_inference_steps=2 ,generator=lowerCamelCase__ ,output_type="""numpy""" ,return_dict=lowerCamelCase__ )[0] SCREAMING_SNAKE_CASE = image[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) SCREAMING_SNAKE_CASE = np.array([0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 @slow @require_torch class UpperCamelCase__ ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ) -> Optional[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE = """google/ncsnpp-celebahq-256""" SCREAMING_SNAKE_CASE = UNetaDModel.from_pretrained(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = KarrasVeScheduler() SCREAMING_SNAKE_CASE = KarrasVePipeline(unet=lowerCamelCase__ ,scheduler=lowerCamelCase__ ) pipe.to(lowerCamelCase__ ) pipe.set_progress_bar_config(disable=lowerCamelCase__ ) SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE = pipe(num_inference_steps=20 ,generator=lowerCamelCase__ ,output_type="""numpy""" ).images SCREAMING_SNAKE_CASE = image[0, -3:, -3:, -1] assert image.shape == (1, 256, 256, 3) SCREAMING_SNAKE_CASE = np.array([0.578, 0.5811, 0.5924, 0.5809, 0.587, 0.5886, 0.5861, 0.5802, 0.586] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
296
1
import unittest import numpy as np def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None , ) -> np.ndarray: '''simple docstring''' SCREAMING_SNAKE_CASE = np.shape(_SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE = np.shape(_SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE = np.shape(_SCREAMING_SNAKE_CASE ) if shape_a[0] != shape_b[0]: SCREAMING_SNAKE_CASE = ( """Expected the same number of rows for A and B. """ F"""Instead found A of size {shape_a} and B of size {shape_b}""" ) raise ValueError(_SCREAMING_SNAKE_CASE ) if shape_b[1] != shape_c[1]: SCREAMING_SNAKE_CASE = ( """Expected the same number of columns for B and C. """ F"""Instead found B of size {shape_b} and C of size {shape_c}""" ) raise ValueError(_SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE = pseudo_inv if a_inv is None: try: SCREAMING_SNAKE_CASE = np.linalg.inv(_SCREAMING_SNAKE_CASE ) except np.linalg.LinAlgError: raise ValueError( """Input matrix A is not invertible. Cannot compute Schur complement.""" ) return mat_c - mat_b.T @ a_inv @ mat_b class UpperCamelCase__ ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE__ ( self : int ) -> None: '''simple docstring''' SCREAMING_SNAKE_CASE = np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]] ) SCREAMING_SNAKE_CASE = np.array([[0, 3], [3, 0], [2, 3]] ) SCREAMING_SNAKE_CASE = np.array([[2, 1], [6, 3]] ) SCREAMING_SNAKE_CASE = schur_complement(lowerCamelCase__ ,lowerCamelCase__ ,lowerCamelCase__ ) SCREAMING_SNAKE_CASE = np.block([[a, b], [b.T, c]] ) SCREAMING_SNAKE_CASE = np.linalg.det(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = np.linalg.det(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = np.linalg.det(lowerCamelCase__ ) self.assertAlmostEqual(lowerCamelCase__ ,det_a * det_s ) def SCREAMING_SNAKE_CASE__ ( self : str ) -> None: '''simple docstring''' SCREAMING_SNAKE_CASE = np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]] ) SCREAMING_SNAKE_CASE = np.array([[0, 3], [3, 0], [2, 3]] ) SCREAMING_SNAKE_CASE = np.array([[2, 1], [6, 3]] ) with self.assertRaises(lowerCamelCase__ ): schur_complement(lowerCamelCase__ ,lowerCamelCase__ ,lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( self : List[str] ) -> None: '''simple docstring''' SCREAMING_SNAKE_CASE = np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]] ) SCREAMING_SNAKE_CASE = np.array([[0, 3], [3, 0], [2, 3]] ) SCREAMING_SNAKE_CASE = np.array([[2, 1, 3], [6, 3, 5]] ) with self.assertRaises(lowerCamelCase__ ): schur_complement(lowerCamelCase__ ,lowerCamelCase__ ,lowerCamelCase__ ) if __name__ == "__main__": import doctest doctest.testmod() unittest.main()
296
from typing import Callable, Optional from .. import Features from ..packaged_modules.generator.generator import Generator from .abc import AbstractDatasetInputStream class UpperCamelCase__ ( lowerCAmelCase_ ): '''simple docstring''' def __init__( self : Union[str, Any] ,lowerCamelCase__ : Callable ,lowerCamelCase__ : Optional[Features] = None ,lowerCamelCase__ : str = None ,lowerCamelCase__ : bool = False ,lowerCamelCase__ : bool = False ,lowerCamelCase__ : Optional[dict] = None ,lowerCamelCase__ : Optional[int] = None ,**lowerCamelCase__ : Optional[Any] ,) -> List[str]: '''simple docstring''' super().__init__( features=lowerCamelCase__ ,cache_dir=lowerCamelCase__ ,keep_in_memory=lowerCamelCase__ ,streaming=lowerCamelCase__ ,num_proc=lowerCamelCase__ ,**lowerCamelCase__ ,) SCREAMING_SNAKE_CASE = Generator( cache_dir=lowerCamelCase__ ,features=lowerCamelCase__ ,generator=lowerCamelCase__ ,gen_kwargs=lowerCamelCase__ ,**lowerCamelCase__ ,) def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ) -> Optional[Any]: '''simple docstring''' if self.streaming: SCREAMING_SNAKE_CASE = self.builder.as_streaming_dataset(split="""train""" ) # Build regular (map-style) dataset else: SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = None self.builder.download_and_prepare( download_config=lowerCamelCase__ ,download_mode=lowerCamelCase__ ,verification_mode=lowerCamelCase__ ,base_path=lowerCamelCase__ ,num_proc=self.num_proc ,) SCREAMING_SNAKE_CASE = self.builder.as_dataset( split="""train""" ,verification_mode=lowerCamelCase__ ,in_memory=self.keep_in_memory ) return dataset
296
1
import warnings from ...utils import logging from .image_processing_flava import FlavaImageProcessor SCREAMING_SNAKE_CASE_ = logging.get_logger(__name__) class UpperCamelCase__ ( lowerCAmelCase_ ): '''simple docstring''' def __init__( self : Dict ,*lowerCamelCase__ : Dict ,**lowerCamelCase__ : Tuple ) -> None: '''simple docstring''' warnings.warn( """The class FlavaFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please""" """ use FlavaImageProcessor instead.""" ,lowerCamelCase__ ,) super().__init__(*lowerCamelCase__ ,**lowerCamelCase__ )
296
import logging from dataclasses import dataclass, field from typing import Optional from seqaseq_trainer import arg_to_scheduler from transformers import TrainingArguments SCREAMING_SNAKE_CASE_ = logging.getLogger(__name__) @dataclass class UpperCamelCase__ ( lowerCAmelCase_ ): '''simple docstring''' __snake_case : Optional[float] = field( default=0.0 , metadata={"help": "The label smoothing epsilon to apply (if not zero)."} ) __snake_case : bool = field(default=lowerCAmelCase_ , metadata={"help": "Whether to SortishSamler or not."} ) __snake_case : bool = field( default=lowerCAmelCase_ , metadata={"help": "Whether to use generate to calculate generative metrics (ROUGE, BLEU)."} ) __snake_case : bool = field(default=lowerCAmelCase_ , metadata={"help": "whether to use adafactor"} ) __snake_case : Optional[float] = field( default=lowerCAmelCase_ , metadata={"help": "Encoder layer dropout probability. Goes into model.config."} ) __snake_case : Optional[float] = field( default=lowerCAmelCase_ , metadata={"help": "Decoder layer dropout probability. Goes into model.config."} ) __snake_case : Optional[float] = field(default=lowerCAmelCase_ , metadata={"help": "Dropout probability. Goes into model.config."} ) __snake_case : Optional[float] = field( default=lowerCAmelCase_ , metadata={"help": "Attention dropout probability. Goes into model.config."} ) __snake_case : Optional[str] = field( default="linear" , metadata={"help": F"Which lr scheduler to use. Selected in {sorted(arg_to_scheduler.keys() )}"} , )
296
1
import unittest from transformers import ( MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_CAUSAL_LM_MAPPING, TextGenerationPipeline, logging, pipeline, ) from transformers.testing_utils import ( CaptureLogger, is_pipeline_test, require_accelerate, require_tf, require_torch, require_torch_gpu, require_torch_or_tf, ) from .test_pipelines_common import ANY @is_pipeline_test @require_torch_or_tf class UpperCamelCase__ ( unittest.TestCase ): '''simple docstring''' __snake_case : Union[str, Any] = MODEL_FOR_CAUSAL_LM_MAPPING __snake_case : List[Any] = TF_MODEL_FOR_CAUSAL_LM_MAPPING @require_torch def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ) -> Optional[int]: '''simple docstring''' SCREAMING_SNAKE_CASE = pipeline(task="""text-generation""" ,model="""sshleifer/tiny-ctrl""" ,framework="""pt""" ) # Using `do_sample=False` to force deterministic output SCREAMING_SNAKE_CASE = text_generator("""This is a test""" ,do_sample=lowerCamelCase__ ) self.assertEqual( lowerCamelCase__ ,[ { """generated_text""": ( """This is a test ☃ ☃ segmental segmental segmental 议议eski eski flutter flutter Lacy oscope.""" """ oscope. FiliFili@@""" ) } ] ,) SCREAMING_SNAKE_CASE = text_generator(["""This is a test""", """This is a second test"""] ) self.assertEqual( lowerCamelCase__ ,[ [ { """generated_text""": ( """This is a test ☃ ☃ segmental segmental segmental 议议eski eski flutter flutter Lacy oscope.""" """ oscope. FiliFili@@""" ) } ], [ { """generated_text""": ( """This is a second test ☃ segmental segmental segmental 议议eski eski flutter flutter Lacy""" """ oscope. oscope. FiliFili@@""" ) } ], ] ,) SCREAMING_SNAKE_CASE = text_generator("""This is a test""" ,do_sample=lowerCamelCase__ ,num_return_sequences=2 ,return_tensors=lowerCamelCase__ ) self.assertEqual( lowerCamelCase__ ,[ {"""generated_token_ids""": ANY(lowerCamelCase__ )}, {"""generated_token_ids""": ANY(lowerCamelCase__ )}, ] ,) SCREAMING_SNAKE_CASE = text_generator.model.config.eos_token_id SCREAMING_SNAKE_CASE = """<pad>""" SCREAMING_SNAKE_CASE = text_generator( ["""This is a test""", """This is a second test"""] ,do_sample=lowerCamelCase__ ,num_return_sequences=2 ,batch_size=2 ,return_tensors=lowerCamelCase__ ,) self.assertEqual( lowerCamelCase__ ,[ [ {"""generated_token_ids""": ANY(lowerCamelCase__ )}, {"""generated_token_ids""": ANY(lowerCamelCase__ )}, ], [ {"""generated_token_ids""": ANY(lowerCamelCase__ )}, {"""generated_token_ids""": ANY(lowerCamelCase__ )}, ], ] ,) @require_tf def SCREAMING_SNAKE_CASE__ ( self : List[str] ) -> Tuple: '''simple docstring''' SCREAMING_SNAKE_CASE = pipeline(task="""text-generation""" ,model="""sshleifer/tiny-ctrl""" ,framework="""tf""" ) # Using `do_sample=False` to force deterministic output SCREAMING_SNAKE_CASE = text_generator("""This is a test""" ,do_sample=lowerCamelCase__ ) self.assertEqual( lowerCamelCase__ ,[ { """generated_text""": ( """This is a test FeyFeyFey(Croatis.), s.), Cannes Cannes Cannes 閲閲Cannes Cannes Cannes 攵""" """ please,""" ) } ] ,) SCREAMING_SNAKE_CASE = text_generator(["""This is a test""", """This is a second test"""] ,do_sample=lowerCamelCase__ ) self.assertEqual( lowerCamelCase__ ,[ [ { """generated_text""": ( """This is a test FeyFeyFey(Croatis.), s.), Cannes Cannes Cannes 閲閲Cannes Cannes Cannes 攵""" """ please,""" ) } ], [ { """generated_text""": ( """This is a second test Chieftain Chieftain prefecture prefecture prefecture Cannes Cannes""" """ Cannes 閲閲Cannes Cannes Cannes 攵 please,""" ) } ], ] ,) def SCREAMING_SNAKE_CASE__ ( self : Any ,lowerCamelCase__ : List[str] ,lowerCamelCase__ : List[str] ,lowerCamelCase__ : List[str] ) -> List[str]: '''simple docstring''' SCREAMING_SNAKE_CASE = TextGenerationPipeline(model=lowerCamelCase__ ,tokenizer=lowerCamelCase__ ) return text_generator, ["This is a test", "Another test"] def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ) -> Tuple: '''simple docstring''' SCREAMING_SNAKE_CASE = """Hello I believe in""" SCREAMING_SNAKE_CASE = pipeline("""text-generation""" ,model="""hf-internal-testing/tiny-random-gpt2""" ) SCREAMING_SNAKE_CASE = text_generator(lowerCamelCase__ ) self.assertEqual( lowerCamelCase__ ,[{"""generated_text""": """Hello I believe in fe fe fe fe fe fe fe fe fe fe fe fe"""}] ,) SCREAMING_SNAKE_CASE = text_generator(lowerCamelCase__ ,stop_sequence=""" fe""" ) self.assertEqual(lowerCamelCase__ ,[{"""generated_text""": """Hello I believe in fe"""}] ) def SCREAMING_SNAKE_CASE__ ( self : List[Any] ,lowerCamelCase__ : int ,lowerCamelCase__ : Dict ) -> str: '''simple docstring''' SCREAMING_SNAKE_CASE = text_generator.model SCREAMING_SNAKE_CASE = text_generator.tokenizer SCREAMING_SNAKE_CASE = text_generator("""This is a test""" ) self.assertEqual(lowerCamelCase__ ,[{"""generated_text""": ANY(lowerCamelCase__ )}] ) self.assertTrue(outputs[0]["""generated_text"""].startswith("""This is a test""" ) ) SCREAMING_SNAKE_CASE = text_generator("""This is a test""" ,return_full_text=lowerCamelCase__ ) self.assertEqual(lowerCamelCase__ ,[{"""generated_text""": ANY(lowerCamelCase__ )}] ) self.assertNotIn("""This is a test""" ,outputs[0]["""generated_text"""] ) SCREAMING_SNAKE_CASE = pipeline(task="""text-generation""" ,model=lowerCamelCase__ ,tokenizer=lowerCamelCase__ ,return_full_text=lowerCamelCase__ ) SCREAMING_SNAKE_CASE = text_generator("""This is a test""" ) self.assertEqual(lowerCamelCase__ ,[{"""generated_text""": ANY(lowerCamelCase__ )}] ) self.assertNotIn("""This is a test""" ,outputs[0]["""generated_text"""] ) SCREAMING_SNAKE_CASE = text_generator("""This is a test""" ,return_full_text=lowerCamelCase__ ) self.assertEqual(lowerCamelCase__ ,[{"""generated_text""": ANY(lowerCamelCase__ )}] ) self.assertTrue(outputs[0]["""generated_text"""].startswith("""This is a test""" ) ) SCREAMING_SNAKE_CASE = text_generator(["""This is great !""", """Something else"""] ,num_return_sequences=2 ,do_sample=lowerCamelCase__ ) self.assertEqual( lowerCamelCase__ ,[ [{"""generated_text""": ANY(lowerCamelCase__ )}, {"""generated_text""": ANY(lowerCamelCase__ )}], [{"""generated_text""": ANY(lowerCamelCase__ )}, {"""generated_text""": ANY(lowerCamelCase__ )}], ] ,) if text_generator.tokenizer.pad_token is not None: SCREAMING_SNAKE_CASE = text_generator( ["""This is great !""", """Something else"""] ,num_return_sequences=2 ,batch_size=2 ,do_sample=lowerCamelCase__ ) self.assertEqual( lowerCamelCase__ ,[ [{"""generated_text""": ANY(lowerCamelCase__ )}, {"""generated_text""": ANY(lowerCamelCase__ )}], [{"""generated_text""": ANY(lowerCamelCase__ )}, {"""generated_text""": ANY(lowerCamelCase__ )}], ] ,) with self.assertRaises(lowerCamelCase__ ): SCREAMING_SNAKE_CASE = text_generator("""test""" ,return_full_text=lowerCamelCase__ ,return_text=lowerCamelCase__ ) with self.assertRaises(lowerCamelCase__ ): SCREAMING_SNAKE_CASE = text_generator("""test""" ,return_full_text=lowerCamelCase__ ,return_tensors=lowerCamelCase__ ) with self.assertRaises(lowerCamelCase__ ): SCREAMING_SNAKE_CASE = text_generator("""test""" ,return_text=lowerCamelCase__ ,return_tensors=lowerCamelCase__ ) # Empty prompt is slighly special # it requires BOS token to exist. # Special case for Pegasus which will always append EOS so will # work even without BOS. if ( text_generator.tokenizer.bos_token_id is not None or "Pegasus" in tokenizer.__class__.__name__ or "Git" in model.__class__.__name__ ): SCREAMING_SNAKE_CASE = text_generator("""""" ) self.assertEqual(lowerCamelCase__ ,[{"""generated_text""": ANY(lowerCamelCase__ )}] ) else: with self.assertRaises((ValueError, AssertionError) ): SCREAMING_SNAKE_CASE = text_generator("""""" ) if text_generator.framework == "tf": # TF generation does not support max_new_tokens, and it's impossible # to control long generation with only max_length without # fancy calculation, dismissing tests for now. return # We don't care about infinite range models. # They already work. # Skip this test for XGLM, since it uses sinusoidal positional embeddings which are resized on-the-fly. SCREAMING_SNAKE_CASE = ["""RwkvForCausalLM""", """XGLMForCausalLM""", """GPTNeoXForCausalLM"""] if ( tokenizer.model_max_length < 10000 and text_generator.model.__class__.__name__ not in EXTRA_MODELS_CAN_HANDLE_LONG_INPUTS ): # Handling of large generations with self.assertRaises((RuntimeError, IndexError, ValueError, AssertionError) ): text_generator("""This is a test""" * 500 ,max_new_tokens=20 ) SCREAMING_SNAKE_CASE = text_generator("""This is a test""" * 500 ,handle_long_generation="""hole""" ,max_new_tokens=20 ) # Hole strategy cannot work with self.assertRaises(lowerCamelCase__ ): text_generator( """This is a test""" * 500 ,handle_long_generation="""hole""" ,max_new_tokens=tokenizer.model_max_length + 10 ,) @require_torch @require_accelerate @require_torch_gpu def SCREAMING_SNAKE_CASE__ ( self : Tuple ) -> Union[str, Any]: '''simple docstring''' import torch # Classic `model_kwargs` SCREAMING_SNAKE_CASE = pipeline( model="""hf-internal-testing/tiny-random-bloom""" ,model_kwargs={"""device_map""": """auto""", """torch_dtype""": torch.bfloataa} ,) self.assertEqual(pipe.model.device ,torch.device(0 ) ) self.assertEqual(pipe.model.lm_head.weight.dtype ,torch.bfloataa ) SCREAMING_SNAKE_CASE = pipe("""This is a test""" ) self.assertEqual( lowerCamelCase__ ,[ { """generated_text""": ( """This is a test test test test test test test test test test test test test test test test""" """ test""" ) } ] ,) # Upgraded those two to real pipeline arguments (they just get sent for the model as they're unlikely to mean anything else.) SCREAMING_SNAKE_CASE = pipeline(model="""hf-internal-testing/tiny-random-bloom""" ,device_map="""auto""" ,torch_dtype=torch.bfloataa ) self.assertEqual(pipe.model.device ,torch.device(0 ) ) self.assertEqual(pipe.model.lm_head.weight.dtype ,torch.bfloataa ) SCREAMING_SNAKE_CASE = pipe("""This is a test""" ) self.assertEqual( lowerCamelCase__ ,[ { """generated_text""": ( """This is a test test test test test test test test test test test test test test test test""" """ test""" ) } ] ,) # torch_dtype will be automatically set to float32 if not provided - check: https://github.com/huggingface/transformers/pull/20602 SCREAMING_SNAKE_CASE = pipeline(model="""hf-internal-testing/tiny-random-bloom""" ,device_map="""auto""" ) self.assertEqual(pipe.model.device ,torch.device(0 ) ) self.assertEqual(pipe.model.lm_head.weight.dtype ,torch.floataa ) SCREAMING_SNAKE_CASE = pipe("""This is a test""" ) self.assertEqual( lowerCamelCase__ ,[ { """generated_text""": ( """This is a test test test test test test test test test test test test test test test test""" """ test""" ) } ] ,) @require_torch @require_torch_gpu def SCREAMING_SNAKE_CASE__ ( self : int ) -> List[str]: '''simple docstring''' import torch SCREAMING_SNAKE_CASE = pipeline(model="""hf-internal-testing/tiny-random-bloom""" ,device=0 ,torch_dtype=torch.floataa ) pipe("""This is a test""" ) @require_torch @require_accelerate @require_torch_gpu def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ) -> List[str]: '''simple docstring''' import torch SCREAMING_SNAKE_CASE = pipeline(model="""hf-internal-testing/tiny-random-bloom""" ,device_map="""auto""" ,torch_dtype=torch.floataa ) pipe("""This is a test""" ,do_sample=lowerCamelCase__ ,top_p=0.5 ) def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ) -> Optional[int]: '''simple docstring''' SCREAMING_SNAKE_CASE = """Hello world""" SCREAMING_SNAKE_CASE = pipeline("""text-generation""" ,model="""hf-internal-testing/tiny-random-gpt2""" ) if text_generator.model.framework == "tf": SCREAMING_SNAKE_CASE = logging.get_logger("""transformers.generation.tf_utils""" ) else: SCREAMING_SNAKE_CASE = logging.get_logger("""transformers.generation.utils""" ) SCREAMING_SNAKE_CASE = """Both `max_new_tokens`""" # The beggining of the message to be checked in this test # Both are set by the user -> log warning with CaptureLogger(lowerCamelCase__ ) as cl: SCREAMING_SNAKE_CASE = text_generator(lowerCamelCase__ ,max_length=10 ,max_new_tokens=1 ) self.assertIn(lowerCamelCase__ ,cl.out ) # The user only sets one -> no warning with CaptureLogger(lowerCamelCase__ ) as cl: SCREAMING_SNAKE_CASE = text_generator(lowerCamelCase__ ,max_new_tokens=1 ) self.assertNotIn(lowerCamelCase__ ,cl.out ) with CaptureLogger(lowerCamelCase__ ) as cl: SCREAMING_SNAKE_CASE = text_generator(lowerCamelCase__ ,max_length=10 ) self.assertNotIn(lowerCamelCase__ ,cl.out )
296
import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, DPMSolverMultistepScheduler, TextToVideoSDPipeline, UNetaDConditionModel, ) from diffusers.utils import is_xformers_available, load_numpy, skip_mps, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() @skip_mps class UpperCamelCase__ ( lowerCAmelCase_ , unittest.TestCase ): '''simple docstring''' __snake_case : List[str] = TextToVideoSDPipeline __snake_case : int = TEXT_TO_IMAGE_PARAMS __snake_case : Tuple = TEXT_TO_IMAGE_BATCH_PARAMS # No `output_type`. __snake_case : Dict = frozenset( [ "num_inference_steps", "generator", "latents", "return_dict", "callback", "callback_steps", ] ) def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ) -> Optional[int]: '''simple docstring''' torch.manual_seed(0 ) SCREAMING_SNAKE_CASE = UNetaDConditionModel( block_out_channels=(32, 64, 64, 64) ,layers_per_block=2 ,sample_size=32 ,in_channels=4 ,out_channels=4 ,down_block_types=("""CrossAttnDownBlock3D""", """CrossAttnDownBlock3D""", """CrossAttnDownBlock3D""", """DownBlock3D""") ,up_block_types=("""UpBlock3D""", """CrossAttnUpBlock3D""", """CrossAttnUpBlock3D""", """CrossAttnUpBlock3D""") ,cross_attention_dim=32 ,attention_head_dim=4 ,) SCREAMING_SNAKE_CASE = DDIMScheduler( beta_start=0.00085 ,beta_end=0.012 ,beta_schedule="""scaled_linear""" ,clip_sample=lowerCamelCase__ ,set_alpha_to_one=lowerCamelCase__ ,) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE = AutoencoderKL( block_out_channels=[32, 64] ,in_channels=3 ,out_channels=3 ,down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] ,up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] ,latent_channels=4 ,sample_size=128 ,) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE = CLIPTextConfig( bos_token_id=0 ,eos_token_id=2 ,hidden_size=32 ,intermediate_size=37 ,layer_norm_eps=1e-0_5 ,num_attention_heads=4 ,num_hidden_layers=5 ,pad_token_id=1 ,vocab_size=1000 ,hidden_act="""gelu""" ,projection_dim=512 ,) SCREAMING_SNAKE_CASE = CLIPTextModel(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) SCREAMING_SNAKE_CASE = { """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, } return components def SCREAMING_SNAKE_CASE__ ( self : int ,lowerCamelCase__ : Optional[Any] ,lowerCamelCase__ : int=0 ) -> List[Any]: '''simple docstring''' if str(lowerCamelCase__ ).startswith("""mps""" ): SCREAMING_SNAKE_CASE = torch.manual_seed(lowerCamelCase__ ) else: SCREAMING_SNAKE_CASE = torch.Generator(device=lowerCamelCase__ ).manual_seed(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = { """prompt""": """A painting of a squirrel eating a burger""", """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 6.0, """output_type""": """pt""", } return inputs def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ) -> List[str]: '''simple docstring''' SCREAMING_SNAKE_CASE = """cpu""" # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE = self.get_dummy_components() SCREAMING_SNAKE_CASE = TextToVideoSDPipeline(**lowerCamelCase__ ) SCREAMING_SNAKE_CASE = sd_pipe.to(lowerCamelCase__ ) sd_pipe.set_progress_bar_config(disable=lowerCamelCase__ ) SCREAMING_SNAKE_CASE = self.get_dummy_inputs(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = """np""" SCREAMING_SNAKE_CASE = sd_pipe(**lowerCamelCase__ ).frames SCREAMING_SNAKE_CASE = frames[0][-3:, -3:, -1] assert frames[0].shape == (64, 64, 3) SCREAMING_SNAKE_CASE = np.array([158.0, 160.0, 153.0, 125.0, 100.0, 121.0, 111.0, 93.0, 113.0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def SCREAMING_SNAKE_CASE__ ( self : Dict ) -> int: '''simple docstring''' self._test_attention_slicing_forward_pass(test_mean_pixel_difference=lowerCamelCase__ ,expected_max_diff=3e-3 ) @unittest.skipIf( torch_device != """cuda""" or not is_xformers_available() ,reason="""XFormers attention is only available with CUDA and `xformers` installed""" ,) def SCREAMING_SNAKE_CASE__ ( self : Tuple ) -> Any: '''simple docstring''' self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=lowerCamelCase__ ,expected_max_diff=1e-2 ) @unittest.skip(reason="""Batching needs to be properly figured out first for this pipeline.""" ) def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ) -> List[Any]: '''simple docstring''' pass @unittest.skip(reason="""Batching needs to be properly figured out first for this pipeline.""" ) def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ) -> Any: '''simple docstring''' pass @unittest.skip(reason="""`num_images_per_prompt` argument is not supported for this pipeline.""" ) def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ) -> Tuple: '''simple docstring''' pass def SCREAMING_SNAKE_CASE__ ( self : List[str] ) -> Optional[Any]: '''simple docstring''' return super().test_progress_bar() @slow @skip_mps class UpperCamelCase__ ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE__ ( self : Any ) -> Optional[int]: '''simple docstring''' SCREAMING_SNAKE_CASE = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/text_to_video/video.npy""" ) SCREAMING_SNAKE_CASE = TextToVideoSDPipeline.from_pretrained("""damo-vilab/text-to-video-ms-1.7b""" ) SCREAMING_SNAKE_CASE = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config ) SCREAMING_SNAKE_CASE = pipe.to("""cuda""" ) SCREAMING_SNAKE_CASE = """Spiderman is surfing""" SCREAMING_SNAKE_CASE = torch.Generator(device="""cpu""" ).manual_seed(0 ) SCREAMING_SNAKE_CASE = pipe(lowerCamelCase__ ,generator=lowerCamelCase__ ,num_inference_steps=25 ,output_type="""pt""" ).frames SCREAMING_SNAKE_CASE = video_frames.cpu().numpy() assert np.abs(expected_video - video ).mean() < 5e-2 def SCREAMING_SNAKE_CASE__ ( self : Any ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/text_to_video/video_2step.npy""" ) SCREAMING_SNAKE_CASE = TextToVideoSDPipeline.from_pretrained("""damo-vilab/text-to-video-ms-1.7b""" ) SCREAMING_SNAKE_CASE = pipe.to("""cuda""" ) SCREAMING_SNAKE_CASE = """Spiderman is surfing""" SCREAMING_SNAKE_CASE = torch.Generator(device="""cpu""" ).manual_seed(0 ) SCREAMING_SNAKE_CASE = pipe(lowerCamelCase__ ,generator=lowerCamelCase__ ,num_inference_steps=2 ,output_type="""pt""" ).frames SCREAMING_SNAKE_CASE = video_frames.cpu().numpy() assert np.abs(expected_video - video ).mean() < 5e-2
296
1
import unittest import torch from torch import nn from accelerate.test_utils import require_cuda from accelerate.utils.memory import find_executable_batch_size, release_memory def __lowercase ( ) -> Union[str, Any]: '''simple docstring''' raise RuntimeError("""CUDA out of memory.""" ) class UpperCamelCase__ ( nn.Module ): '''simple docstring''' def __init__( self : List[Any] ) -> Optional[Any]: '''simple docstring''' super().__init__() SCREAMING_SNAKE_CASE = nn.Linear(3 ,4 ) SCREAMING_SNAKE_CASE = nn.BatchNormad(4 ) SCREAMING_SNAKE_CASE = nn.Linear(4 ,5 ) def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ,lowerCamelCase__ : Dict ) -> List[str]: '''simple docstring''' return self.lineara(self.batchnorm(self.lineara(lowerCamelCase__ ) ) ) class UpperCamelCase__ ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE__ ( self : int ) -> str: '''simple docstring''' SCREAMING_SNAKE_CASE = [] @find_executable_batch_size(starting_batch_size=128 ) def mock_training_loop_function(lowerCamelCase__ : Any ): nonlocal batch_sizes batch_sizes.append(lowerCamelCase__ ) if batch_size != 8: raise_fake_out_of_memory() mock_training_loop_function() self.assertListEqual(lowerCamelCase__ ,[128, 64, 32, 16, 8] ) def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ) -> List[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE = [] @find_executable_batch_size(starting_batch_size=128 ) def mock_training_loop_function(lowerCamelCase__ : List[Any] ,lowerCamelCase__ : Optional[Any] ): nonlocal batch_sizes batch_sizes.append(lowerCamelCase__ ) if batch_size != 8: raise_fake_out_of_memory() return batch_size, arga SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE = mock_training_loop_function("""hello""" ) self.assertListEqual(lowerCamelCase__ ,[128, 64, 32, 16, 8] ) self.assertListEqual([bs, arga] ,[8, """hello"""] ) def SCREAMING_SNAKE_CASE__ ( self : str ) -> List[Any]: '''simple docstring''' @find_executable_batch_size(starting_batch_size=0 ) def mock_training_loop_function(lowerCamelCase__ : Tuple ): pass with self.assertRaises(lowerCamelCase__ ) as cm: mock_training_loop_function() self.assertIn("""No executable batch size found, reached zero.""" ,cm.exception.args[0] ) def SCREAMING_SNAKE_CASE__ ( self : int ) -> str: '''simple docstring''' @find_executable_batch_size(starting_batch_size=16 ) def mock_training_loop_function(lowerCamelCase__ : Dict ): if batch_size > 0: raise_fake_out_of_memory() pass with self.assertRaises(lowerCamelCase__ ) as cm: mock_training_loop_function() self.assertIn("""No executable batch size found, reached zero.""" ,cm.exception.args[0] ) def SCREAMING_SNAKE_CASE__ ( self : Dict ) -> str: '''simple docstring''' @find_executable_batch_size(starting_batch_size=128 ) def mock_training_loop_function(lowerCamelCase__ : Dict ,lowerCamelCase__ : Any ,lowerCamelCase__ : Union[str, Any] ): if batch_size != 8: raise raise_fake_out_of_memory() with self.assertRaises(lowerCamelCase__ ) as cm: mock_training_loop_function(128 ,"""hello""" ,"""world""" ) self.assertIn("""Batch size was passed into `f`""" ,cm.exception.args[0] ) self.assertIn("""`f(arg1='hello', arg2='world')""" ,cm.exception.args[0] ) def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ) -> Union[str, Any]: '''simple docstring''' @find_executable_batch_size(starting_batch_size=16 ) def mock_training_loop_function(lowerCamelCase__ : Tuple ): raise ValueError("""Oops, we had an error!""" ) with self.assertRaises(lowerCamelCase__ ) as cm: mock_training_loop_function() self.assertIn("""Oops, we had an error!""" ,cm.exception.args[0] ) @require_cuda def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ) -> Optional[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE = torch.cuda.memory_allocated() SCREAMING_SNAKE_CASE = ModelForTest() model.cuda() self.assertGreater(torch.cuda.memory_allocated() ,lowerCamelCase__ ) SCREAMING_SNAKE_CASE = release_memory(lowerCamelCase__ ) self.assertEqual(torch.cuda.memory_allocated() ,lowerCamelCase__ )
296
def __lowercase ( _SCREAMING_SNAKE_CASE = 10 ) -> str: '''simple docstring''' if not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) or n < 0: raise ValueError("""Invalid input""" ) SCREAMING_SNAKE_CASE = 10**n SCREAMING_SNAKE_CASE = 2_84_33 * (pow(2 , 7_83_04_57 , _SCREAMING_SNAKE_CASE )) + 1 return str(number % modulus ) if __name__ == "__main__": from doctest import testmod testmod() print(F'''{solution(1_0) = }''')
296
1
def __lowercase ( _SCREAMING_SNAKE_CASE ) -> Union[str, Any]: '''simple docstring''' return [ { 0: [1, 2], 1: [0, 2], 2: [0, 1, 3, 5], 3: [2, 4], 4: [3], 5: [2, 6, 8], 6: [5, 7], 7: [6, 8], 8: [5, 7], }, { 0: [6], 1: [9], 2: [4, 5], 3: [4], 4: [2, 3], 5: [2], 6: [0, 7], 7: [6], 8: [], 9: [1], }, { 0: [4], 1: [6], 2: [], 3: [5, 6, 7], 4: [0, 6], 5: [3, 8, 9], 6: [1, 3, 4, 7], 7: [3, 6, 8, 9], 8: [5, 7], 9: [5, 7], }, { 0: [1, 3], 1: [0, 2, 4], 2: [1, 3, 4], 3: [0, 2, 4], 4: [1, 2, 3], }, ][index] def __lowercase ( _SCREAMING_SNAKE_CASE ) -> list[tuple[int, int]]: '''simple docstring''' SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = len(_SCREAMING_SNAKE_CASE ) # No of vertices in graph SCREAMING_SNAKE_CASE = [0] * n SCREAMING_SNAKE_CASE = [False] * n def dfs(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = id_ id_ += 1 for to in graph[at]: if to == parent: pass elif not visited[to]: dfs(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , id_ ) SCREAMING_SNAKE_CASE = min(low[at] , low[to] ) if id_ <= low[to]: bridges.append((at, to) if at < to else (to, at) ) else: # This edge is a back edge and cannot be a bridge SCREAMING_SNAKE_CASE = min(low[at] , low[to] ) SCREAMING_SNAKE_CASE = [] for i in range(_SCREAMING_SNAKE_CASE ): if not visited[i]: dfs(_SCREAMING_SNAKE_CASE , -1 , _SCREAMING_SNAKE_CASE , id_ ) return bridges if __name__ == "__main__": import doctest doctest.testmod()
296
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) SCREAMING_SNAKE_CASE_ = { """configuration_llama""": ["""LLAMA_PRETRAINED_CONFIG_ARCHIVE_MAP""", """LlamaConfig"""], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE_ = ["""LlamaTokenizer"""] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE_ = ["""LlamaTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE_ = [ """LlamaForCausalLM""", """LlamaModel""", """LlamaPreTrainedModel""", """LlamaForSequenceClassification""", ] if TYPE_CHECKING: from .configuration_llama import LLAMA_PRETRAINED_CONFIG_ARCHIVE_MAP, LlamaConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_llama import LlamaTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_llama_fast import LlamaTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_llama import LlamaForCausalLM, LlamaForSequenceClassification, LlamaModel, LlamaPreTrainedModel else: import sys SCREAMING_SNAKE_CASE_ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
296
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available SCREAMING_SNAKE_CASE_ = { """configuration_data2vec_audio""": ["""DATA2VEC_AUDIO_PRETRAINED_CONFIG_ARCHIVE_MAP""", """Data2VecAudioConfig"""], """configuration_data2vec_text""": [ """DATA2VEC_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """Data2VecTextConfig""", """Data2VecTextOnnxConfig""", ], """configuration_data2vec_vision""": [ """DATA2VEC_VISION_PRETRAINED_CONFIG_ARCHIVE_MAP""", """Data2VecVisionConfig""", """Data2VecVisionOnnxConfig""", ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE_ = [ """DATA2VEC_AUDIO_PRETRAINED_MODEL_ARCHIVE_LIST""", """Data2VecAudioForAudioFrameClassification""", """Data2VecAudioForCTC""", """Data2VecAudioForSequenceClassification""", """Data2VecAudioForXVector""", """Data2VecAudioModel""", """Data2VecAudioPreTrainedModel""", ] SCREAMING_SNAKE_CASE_ = [ """DATA2VEC_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST""", """Data2VecTextForCausalLM""", """Data2VecTextForMaskedLM""", """Data2VecTextForMultipleChoice""", """Data2VecTextForQuestionAnswering""", """Data2VecTextForSequenceClassification""", """Data2VecTextForTokenClassification""", """Data2VecTextModel""", """Data2VecTextPreTrainedModel""", ] SCREAMING_SNAKE_CASE_ = [ """DATA2VEC_VISION_PRETRAINED_MODEL_ARCHIVE_LIST""", """Data2VecVisionForImageClassification""", """Data2VecVisionForMaskedImageModeling""", """Data2VecVisionForSemanticSegmentation""", """Data2VecVisionModel""", """Data2VecVisionPreTrainedModel""", ] if is_tf_available(): SCREAMING_SNAKE_CASE_ = [ """TFData2VecVisionForImageClassification""", """TFData2VecVisionForSemanticSegmentation""", """TFData2VecVisionModel""", """TFData2VecVisionPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_dataavec_audio import DATA2VEC_AUDIO_PRETRAINED_CONFIG_ARCHIVE_MAP, DataaVecAudioConfig from .configuration_dataavec_text import ( DATA2VEC_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP, DataaVecTextConfig, DataaVecTextOnnxConfig, ) from .configuration_dataavec_vision import ( DATA2VEC_VISION_PRETRAINED_CONFIG_ARCHIVE_MAP, DataaVecVisionConfig, DataaVecVisionOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_dataavec_audio import ( DATA2VEC_AUDIO_PRETRAINED_MODEL_ARCHIVE_LIST, DataaVecAudioForAudioFrameClassification, DataaVecAudioForCTC, DataaVecAudioForSequenceClassification, DataaVecAudioForXVector, DataaVecAudioModel, DataaVecAudioPreTrainedModel, ) from .modeling_dataavec_text import ( DATA2VEC_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST, DataaVecTextForCausalLM, DataaVecTextForMaskedLM, DataaVecTextForMultipleChoice, DataaVecTextForQuestionAnswering, DataaVecTextForSequenceClassification, DataaVecTextForTokenClassification, DataaVecTextModel, DataaVecTextPreTrainedModel, ) from .modeling_dataavec_vision import ( DATA2VEC_VISION_PRETRAINED_MODEL_ARCHIVE_LIST, DataaVecVisionForImageClassification, DataaVecVisionForMaskedImageModeling, DataaVecVisionForSemanticSegmentation, DataaVecVisionModel, DataaVecVisionPreTrainedModel, ) if is_tf_available(): from .modeling_tf_dataavec_vision import ( TFDataaVecVisionForImageClassification, TFDataaVecVisionForSemanticSegmentation, TFDataaVecVisionModel, TFDataaVecVisionPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE_ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
296
from pathlib import Path import fire def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> List[str]: '''simple docstring''' SCREAMING_SNAKE_CASE = Path(_SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE = Path(_SCREAMING_SNAKE_CASE ) dest_dir.mkdir(exist_ok=_SCREAMING_SNAKE_CASE ) for path in src_dir.iterdir(): SCREAMING_SNAKE_CASE = [x.rstrip() for x in list(path.open().readlines() )][:n] SCREAMING_SNAKE_CASE = dest_dir.joinpath(path.name ) print(_SCREAMING_SNAKE_CASE ) dest_path.open("""w""" ).write("""\n""".join(_SCREAMING_SNAKE_CASE ) ) if __name__ == "__main__": fire.Fire(minify)
296
1
from cva import destroyAllWindows, imread, imshow, waitKey def __lowercase ( _SCREAMING_SNAKE_CASE ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE = img.shape[0], img.shape[1] # converting each pixel's color to its negative for i in range(_SCREAMING_SNAKE_CASE ): for j in range(_SCREAMING_SNAKE_CASE ): SCREAMING_SNAKE_CASE = [2_55, 2_55, 2_55] - img[i][j] return img if __name__ == "__main__": # read original image SCREAMING_SNAKE_CASE_ = imread("""image_data/lena.jpg""", 1) # convert to its negative SCREAMING_SNAKE_CASE_ = convert_to_negative(img) # show result image imshow("""negative of original image""", img) waitKey(0) destroyAllWindows()
296
import importlib import json import os import sys import tempfile import unittest from pathlib import Path import transformers import transformers.models.auto from transformers.models.auto.configuration_auto import CONFIG_MAPPING, AutoConfig from transformers.models.bert.configuration_bert import BertConfig from transformers.models.roberta.configuration_roberta import RobertaConfig from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, get_tests_dir sys.path.append(str(Path(__file__).parent.parent.parent.parent / """utils""")) from test_module.custom_configuration import CustomConfig # noqa E402 SCREAMING_SNAKE_CASE_ = get_tests_dir("""fixtures/dummy-config.json""") class UpperCamelCase__ ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ) -> Optional[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE = 0 def SCREAMING_SNAKE_CASE__ ( self : Any ) -> str: '''simple docstring''' self.assertIsNotNone(transformers.models.auto.__spec__ ) self.assertIsNotNone(importlib.util.find_spec("""transformers.models.auto""" ) ) def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ) -> List[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained("""bert-base-uncased""" ) self.assertIsInstance(lowerCamelCase__ ,lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( self : int ) -> Optional[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained(lowerCamelCase__ ) self.assertIsInstance(lowerCamelCase__ ,lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ) -> List[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained(lowerCamelCase__ ) self.assertIsInstance(lowerCamelCase__ ,lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( self : Tuple ) -> Optional[int]: '''simple docstring''' SCREAMING_SNAKE_CASE = AutoConfig.for_model("""roberta""" ) self.assertIsInstance(lowerCamelCase__ ,lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( self : int ) -> int: '''simple docstring''' with tempfile.TemporaryDirectory() as tmp_dir: # This model name contains bert and roberta, but roberta ends up being picked. SCREAMING_SNAKE_CASE = os.path.join(lowerCamelCase__ ,"""fake-roberta""" ) os.makedirs(lowerCamelCase__ ,exist_ok=lowerCamelCase__ ) with open(os.path.join(lowerCamelCase__ ,"""config.json""" ) ,"""w""" ) as f: f.write(json.dumps({} ) ) SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained(lowerCamelCase__ ) self.assertEqual(type(lowerCamelCase__ ) ,lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( self : Dict ) -> str: '''simple docstring''' try: AutoConfig.register("""custom""" ,lowerCamelCase__ ) # Wrong model type will raise an error with self.assertRaises(lowerCamelCase__ ): AutoConfig.register("""model""" ,lowerCamelCase__ ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(lowerCamelCase__ ): AutoConfig.register("""bert""" ,lowerCamelCase__ ) # Now that the config is registered, it can be used as any other config with the auto-API SCREAMING_SNAKE_CASE = CustomConfig() with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained(lowerCamelCase__ ) self.assertIsInstance(lowerCamelCase__ ,lowerCamelCase__ ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] def SCREAMING_SNAKE_CASE__ ( self : str ) -> Dict: '''simple docstring''' with self.assertRaisesRegex( lowerCamelCase__ ,"""bert-base is not a local folder and is not a valid model identifier""" ): SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained("""bert-base""" ) def SCREAMING_SNAKE_CASE__ ( self : Dict ) -> str: '''simple docstring''' with self.assertRaisesRegex( lowerCamelCase__ ,R"""aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)""" ): SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained(lowerCamelCase__ ,revision="""aaaaaa""" ) def SCREAMING_SNAKE_CASE__ ( self : Tuple ) -> List[Any]: '''simple docstring''' with self.assertRaisesRegex( lowerCamelCase__ ,"""hf-internal-testing/no-config-test-repo does not appear to have a file named config.json.""" ,): SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained("""hf-internal-testing/no-config-test-repo""" ) def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ) -> Union[str, Any]: '''simple docstring''' with self.assertRaises(lowerCamelCase__ ): SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained("""hf-internal-testing/test_dynamic_model""" ) # If remote code is disabled, we can't load this config. with self.assertRaises(lowerCamelCase__ ): SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained("""hf-internal-testing/test_dynamic_model""" ,trust_remote_code=lowerCamelCase__ ) SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained("""hf-internal-testing/test_dynamic_model""" ,trust_remote_code=lowerCamelCase__ ) self.assertEqual(config.__class__.__name__ ,"""NewModelConfig""" ) # Test config can be reloaded. with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained(lowerCamelCase__ ,trust_remote_code=lowerCamelCase__ ) self.assertEqual(reloaded_config.__class__.__name__ ,"""NewModelConfig""" ) def SCREAMING_SNAKE_CASE__ ( self : Dict ) -> Union[str, Any]: '''simple docstring''' class UpperCamelCase__ ( lowerCAmelCase_ ): '''simple docstring''' __snake_case : Union[str, Any] = "new-model" try: AutoConfig.register("""new-model""" ,lowerCamelCase__ ) # If remote code is not set, the default is to use local SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained("""hf-internal-testing/test_dynamic_model""" ) self.assertEqual(config.__class__.__name__ ,"""NewModelConfigLocal""" ) # If remote code is disabled, we load the local one. SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained("""hf-internal-testing/test_dynamic_model""" ,trust_remote_code=lowerCamelCase__ ) self.assertEqual(config.__class__.__name__ ,"""NewModelConfigLocal""" ) # If remote is enabled, we load from the Hub SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained("""hf-internal-testing/test_dynamic_model""" ,trust_remote_code=lowerCamelCase__ ) self.assertEqual(config.__class__.__name__ ,"""NewModelConfig""" ) finally: if "new-model" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["new-model"]
296
1
from __future__ import annotations import copy import tempfile import unittest from transformers import CONFIG_MAPPING, AutoConfig, BertConfig, GPTaConfig, TaConfig, TapasConfig, is_tf_available from transformers.testing_utils import ( DUMMY_UNKNOWN_IDENTIFIER, SMALL_MODEL_IDENTIFIER, RequestCounter, require_tensorflow_probability, require_tf, slow, ) from ..bert.test_modeling_bert import BertModelTester if is_tf_available(): from transformers import ( TFAutoModel, TFAutoModelForCausalLM, TFAutoModelForMaskedLM, TFAutoModelForPreTraining, TFAutoModelForQuestionAnswering, TFAutoModelForSeqaSeqLM, TFAutoModelForSequenceClassification, TFAutoModelForTableQuestionAnswering, TFAutoModelForTokenClassification, TFAutoModelWithLMHead, TFBertForMaskedLM, TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification, TFBertModel, TFFunnelBaseModel, TFFunnelModel, TFGPTaLMHeadModel, TFRobertaForMaskedLM, TFTaForConditionalGeneration, TFTapasForQuestionAnswering, ) from transformers.models.auto.modeling_tf_auto import ( TF_MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_MASKED_LM_MAPPING, TF_MODEL_FOR_PRETRAINING_MAPPING, TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, TF_MODEL_MAPPING, ) from transformers.models.bert.modeling_tf_bert import TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST from transformers.models.gpta.modeling_tf_gpta import TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST from transformers.models.ta.modeling_tf_ta import TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST from transformers.models.tapas.modeling_tf_tapas import TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST class UpperCamelCase__ ( lowerCAmelCase_ ): '''simple docstring''' __snake_case : Tuple = "new-model" if is_tf_available(): class UpperCamelCase__ ( lowerCAmelCase_ ): '''simple docstring''' __snake_case : List[Any] = NewModelConfig @require_tf class UpperCamelCase__ ( unittest.TestCase ): '''simple docstring''' @slow def SCREAMING_SNAKE_CASE__ ( self : Dict ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE = """bert-base-cased""" SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained(lowerCamelCase__ ) self.assertIsNotNone(lowerCamelCase__ ) self.assertIsInstance(lowerCamelCase__ ,lowerCamelCase__ ) SCREAMING_SNAKE_CASE = TFAutoModel.from_pretrained(lowerCamelCase__ ) self.assertIsNotNone(lowerCamelCase__ ) self.assertIsInstance(lowerCamelCase__ ,lowerCamelCase__ ) @slow def SCREAMING_SNAKE_CASE__ ( self : Tuple ) -> Dict: '''simple docstring''' SCREAMING_SNAKE_CASE = """bert-base-cased""" SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained(lowerCamelCase__ ) self.assertIsNotNone(lowerCamelCase__ ) self.assertIsInstance(lowerCamelCase__ ,lowerCamelCase__ ) SCREAMING_SNAKE_CASE = TFAutoModelForPreTraining.from_pretrained(lowerCamelCase__ ) self.assertIsNotNone(lowerCamelCase__ ) self.assertIsInstance(lowerCamelCase__ ,lowerCamelCase__ ) @slow def SCREAMING_SNAKE_CASE__ ( self : int ) -> List[str]: '''simple docstring''' for model_name in TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained(lowerCamelCase__ ) self.assertIsNotNone(lowerCamelCase__ ) self.assertIsInstance(lowerCamelCase__ ,lowerCamelCase__ ) SCREAMING_SNAKE_CASE = TFAutoModelForCausalLM.from_pretrained(lowerCamelCase__ ) SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE = TFAutoModelForCausalLM.from_pretrained(lowerCamelCase__ ,output_loading_info=lowerCamelCase__ ) self.assertIsNotNone(lowerCamelCase__ ) self.assertIsInstance(lowerCamelCase__ ,lowerCamelCase__ ) @slow def SCREAMING_SNAKE_CASE__ ( self : Any ) -> Any: '''simple docstring''' for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained(lowerCamelCase__ ) self.assertIsNotNone(lowerCamelCase__ ) self.assertIsInstance(lowerCamelCase__ ,lowerCamelCase__ ) SCREAMING_SNAKE_CASE = TFAutoModelWithLMHead.from_pretrained(lowerCamelCase__ ) self.assertIsNotNone(lowerCamelCase__ ) self.assertIsInstance(lowerCamelCase__ ,lowerCamelCase__ ) @slow def SCREAMING_SNAKE_CASE__ ( self : Tuple ) -> List[Any]: '''simple docstring''' for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained(lowerCamelCase__ ) self.assertIsNotNone(lowerCamelCase__ ) self.assertIsInstance(lowerCamelCase__ ,lowerCamelCase__ ) SCREAMING_SNAKE_CASE = TFAutoModelForMaskedLM.from_pretrained(lowerCamelCase__ ) SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE = TFAutoModelForMaskedLM.from_pretrained(lowerCamelCase__ ,output_loading_info=lowerCamelCase__ ) self.assertIsNotNone(lowerCamelCase__ ) self.assertIsInstance(lowerCamelCase__ ,lowerCamelCase__ ) @slow def SCREAMING_SNAKE_CASE__ ( self : Dict ) -> Tuple: '''simple docstring''' for model_name in TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained(lowerCamelCase__ ) self.assertIsNotNone(lowerCamelCase__ ) self.assertIsInstance(lowerCamelCase__ ,lowerCamelCase__ ) SCREAMING_SNAKE_CASE = TFAutoModelForSeqaSeqLM.from_pretrained(lowerCamelCase__ ) SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE = TFAutoModelForSeqaSeqLM.from_pretrained(lowerCamelCase__ ,output_loading_info=lowerCamelCase__ ) self.assertIsNotNone(lowerCamelCase__ ) self.assertIsInstance(lowerCamelCase__ ,lowerCamelCase__ ) @slow def SCREAMING_SNAKE_CASE__ ( self : str ) -> List[str]: '''simple docstring''' for model_name in ["bert-base-uncased"]: SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained(lowerCamelCase__ ) self.assertIsNotNone(lowerCamelCase__ ) self.assertIsInstance(lowerCamelCase__ ,lowerCamelCase__ ) SCREAMING_SNAKE_CASE = TFAutoModelForSequenceClassification.from_pretrained(lowerCamelCase__ ) self.assertIsNotNone(lowerCamelCase__ ) self.assertIsInstance(lowerCamelCase__ ,lowerCamelCase__ ) @slow def SCREAMING_SNAKE_CASE__ ( self : int ) -> Union[str, Any]: '''simple docstring''' for model_name in ["bert-base-uncased"]: SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained(lowerCamelCase__ ) self.assertIsNotNone(lowerCamelCase__ ) self.assertIsInstance(lowerCamelCase__ ,lowerCamelCase__ ) SCREAMING_SNAKE_CASE = TFAutoModelForQuestionAnswering.from_pretrained(lowerCamelCase__ ) self.assertIsNotNone(lowerCamelCase__ ) self.assertIsInstance(lowerCamelCase__ ,lowerCamelCase__ ) @slow @require_tensorflow_probability def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ) -> str: '''simple docstring''' for model_name in TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST[5:6]: SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained(lowerCamelCase__ ) self.assertIsNotNone(lowerCamelCase__ ) self.assertIsInstance(lowerCamelCase__ ,lowerCamelCase__ ) SCREAMING_SNAKE_CASE = TFAutoModelForTableQuestionAnswering.from_pretrained(lowerCamelCase__ ) SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE = TFAutoModelForTableQuestionAnswering.from_pretrained( lowerCamelCase__ ,output_loading_info=lowerCamelCase__ ) self.assertIsNotNone(lowerCamelCase__ ) self.assertIsInstance(lowerCamelCase__ ,lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ) -> str: '''simple docstring''' SCREAMING_SNAKE_CASE = TFAutoModelWithLMHead.from_pretrained(lowerCamelCase__ ) self.assertIsInstance(lowerCamelCase__ ,lowerCamelCase__ ) self.assertEqual(model.num_parameters() ,14410 ) self.assertEqual(model.num_parameters(only_trainable=lowerCamelCase__ ) ,14410 ) def SCREAMING_SNAKE_CASE__ ( self : List[str] ) -> List[str]: '''simple docstring''' SCREAMING_SNAKE_CASE = TFAutoModelWithLMHead.from_pretrained(lowerCamelCase__ ) self.assertIsInstance(lowerCamelCase__ ,lowerCamelCase__ ) self.assertEqual(model.num_parameters() ,14410 ) self.assertEqual(model.num_parameters(only_trainable=lowerCamelCase__ ) ,14410 ) def SCREAMING_SNAKE_CASE__ ( self : List[str] ) -> Union[str, Any]: '''simple docstring''' SCREAMING_SNAKE_CASE = TFAutoModel.from_pretrained("""sgugger/funnel-random-tiny""" ) self.assertIsInstance(lowerCamelCase__ ,lowerCamelCase__ ) SCREAMING_SNAKE_CASE = copy.deepcopy(model.config ) SCREAMING_SNAKE_CASE = ["""FunnelBaseModel"""] SCREAMING_SNAKE_CASE = TFAutoModel.from_config(lowerCamelCase__ ) self.assertIsInstance(lowerCamelCase__ ,lowerCamelCase__ ) with tempfile.TemporaryDirectory() as tmp_dir: model.save_pretrained(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = TFAutoModel.from_pretrained(lowerCamelCase__ ) self.assertIsInstance(lowerCamelCase__ ,lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ) -> str: '''simple docstring''' try: AutoConfig.register("""new-model""" ,lowerCamelCase__ ) SCREAMING_SNAKE_CASE = [ TFAutoModel, TFAutoModelForCausalLM, TFAutoModelForMaskedLM, TFAutoModelForPreTraining, TFAutoModelForQuestionAnswering, TFAutoModelForSequenceClassification, TFAutoModelForTokenClassification, ] for auto_class in auto_classes: with self.subTest(auto_class.__name__ ): # Wrong config class will raise an error with self.assertRaises(lowerCamelCase__ ): auto_class.register(lowerCamelCase__ ,lowerCamelCase__ ) auto_class.register(lowerCamelCase__ ,lowerCamelCase__ ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(lowerCamelCase__ ): auto_class.register(lowerCamelCase__ ,lowerCamelCase__ ) # Now that the config is registered, it can be used as any other config with the auto-API SCREAMING_SNAKE_CASE = BertModelTester(self ).get_config() SCREAMING_SNAKE_CASE = NewModelConfig(**tiny_config.to_dict() ) SCREAMING_SNAKE_CASE = auto_class.from_config(lowerCamelCase__ ) self.assertIsInstance(lowerCamelCase__ ,lowerCamelCase__ ) with tempfile.TemporaryDirectory() as tmp_dir: model.save_pretrained(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = auto_class.from_pretrained(lowerCamelCase__ ) self.assertIsInstance(lowerCamelCase__ ,lowerCamelCase__ ) finally: if "new-model" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["new-model"] for mapping in ( TF_MODEL_MAPPING, TF_MODEL_FOR_PRETRAINING_MAPPING, TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, TF_MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_MASKED_LM_MAPPING, ): if NewModelConfig in mapping._extra_content: del mapping._extra_content[NewModelConfig] def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ) -> Optional[int]: '''simple docstring''' with self.assertRaisesRegex( lowerCamelCase__ ,"""bert-base is not a local folder and is not a valid model identifier""" ): SCREAMING_SNAKE_CASE = TFAutoModel.from_pretrained("""bert-base""" ) def SCREAMING_SNAKE_CASE__ ( self : Dict ) -> List[str]: '''simple docstring''' with self.assertRaisesRegex( lowerCamelCase__ ,R"""aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)""" ): SCREAMING_SNAKE_CASE = TFAutoModel.from_pretrained(lowerCamelCase__ ,revision="""aaaaaa""" ) def SCREAMING_SNAKE_CASE__ ( self : Dict ) -> Union[str, Any]: '''simple docstring''' with self.assertRaisesRegex( lowerCamelCase__ ,"""hf-internal-testing/config-no-model does not appear to have a file named pytorch_model.bin""" ,): SCREAMING_SNAKE_CASE = TFAutoModel.from_pretrained("""hf-internal-testing/config-no-model""" ) def SCREAMING_SNAKE_CASE__ ( self : int ) -> Optional[Any]: '''simple docstring''' with self.assertRaisesRegex(lowerCamelCase__ ,"""Use `from_pt=True` to load this model""" ): SCREAMING_SNAKE_CASE = TFAutoModel.from_pretrained("""hf-internal-testing/tiny-bert-pt-only""" ) def SCREAMING_SNAKE_CASE__ ( self : Any ) -> str: '''simple docstring''' SCREAMING_SNAKE_CASE = TFAutoModel.from_pretrained("""hf-internal-testing/tiny-random-bert""" ) with RequestCounter() as counter: SCREAMING_SNAKE_CASE = TFAutoModel.from_pretrained("""hf-internal-testing/tiny-random-bert""" ) self.assertEqual(counter.get_request_count ,0 ) self.assertEqual(counter.head_request_count ,1 ) self.assertEqual(counter.other_request_count ,0 ) # With a sharded checkpoint SCREAMING_SNAKE_CASE = TFAutoModel.from_pretrained("""ArthurZ/tiny-random-bert-sharded""" ) with RequestCounter() as counter: SCREAMING_SNAKE_CASE = TFAutoModel.from_pretrained("""ArthurZ/tiny-random-bert-sharded""" ) self.assertEqual(counter.get_request_count ,0 ) self.assertEqual(counter.head_request_count ,1 ) self.assertEqual(counter.other_request_count ,0 )
296
import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging SCREAMING_SNAKE_CASE_ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE_ = { """microsoft/git-base""": """https://huggingface.co/microsoft/git-base/resolve/main/config.json""", } class UpperCamelCase__ ( lowerCAmelCase_ ): '''simple docstring''' __snake_case : Dict = "git_vision_model" def __init__( self : List[Any] ,lowerCamelCase__ : Dict=768 ,lowerCamelCase__ : Union[str, Any]=3072 ,lowerCamelCase__ : Optional[int]=12 ,lowerCamelCase__ : Tuple=12 ,lowerCamelCase__ : Tuple=3 ,lowerCamelCase__ : Optional[Any]=224 ,lowerCamelCase__ : Union[str, Any]=16 ,lowerCamelCase__ : List[Any]="quick_gelu" ,lowerCamelCase__ : Optional[Any]=1e-5 ,lowerCamelCase__ : str=0.0 ,lowerCamelCase__ : Optional[int]=0.02 ,**lowerCamelCase__ : Union[str, Any] ,) -> Optional[int]: '''simple docstring''' super().__init__(**lowerCamelCase__ ) SCREAMING_SNAKE_CASE = hidden_size SCREAMING_SNAKE_CASE = intermediate_size SCREAMING_SNAKE_CASE = num_hidden_layers SCREAMING_SNAKE_CASE = num_attention_heads SCREAMING_SNAKE_CASE = num_channels SCREAMING_SNAKE_CASE = patch_size SCREAMING_SNAKE_CASE = image_size SCREAMING_SNAKE_CASE = initializer_range SCREAMING_SNAKE_CASE = attention_dropout SCREAMING_SNAKE_CASE = layer_norm_eps SCREAMING_SNAKE_CASE = hidden_act @classmethod def SCREAMING_SNAKE_CASE__ ( cls : Tuple ,lowerCamelCase__ : Union[str, os.PathLike] ,**lowerCamelCase__ : int ) -> "PretrainedConfig": '''simple docstring''' cls._set_token_in_kwargs(lowerCamelCase__ ) SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE = cls.get_config_dict(lowerCamelCase__ ,**lowerCamelCase__ ) # get the vision config dict if we are loading from GITConfig if config_dict.get("""model_type""" ) == "git": SCREAMING_SNAKE_CASE = config_dict["""vision_config"""] if "model_type" in config_dict and hasattr(cls ,"""model_type""" ) and config_dict["model_type"] != cls.model_type: logger.warning( F"""You are using a model of type {config_dict['model_type']} to instantiate a model of type """ F"""{cls.model_type}. This is not supported for all configurations of models and can yield errors.""" ) return cls.from_dict(lowerCamelCase__ ,**lowerCamelCase__ ) class UpperCamelCase__ ( lowerCAmelCase_ ): '''simple docstring''' __snake_case : Dict = "git" def __init__( self : Optional[int] ,lowerCamelCase__ : int=None ,lowerCamelCase__ : str=30522 ,lowerCamelCase__ : Tuple=768 ,lowerCamelCase__ : Union[str, Any]=6 ,lowerCamelCase__ : str=12 ,lowerCamelCase__ : List[str]=3072 ,lowerCamelCase__ : Dict="gelu" ,lowerCamelCase__ : Tuple=0.1 ,lowerCamelCase__ : Any=0.1 ,lowerCamelCase__ : List[str]=1024 ,lowerCamelCase__ : List[str]=0.02 ,lowerCamelCase__ : str=1e-1_2 ,lowerCamelCase__ : Optional[int]=0 ,lowerCamelCase__ : Optional[int]="absolute" ,lowerCamelCase__ : Optional[Any]=True ,lowerCamelCase__ : str=False ,lowerCamelCase__ : int=101 ,lowerCamelCase__ : int=102 ,lowerCamelCase__ : Dict=None ,**lowerCamelCase__ : List[Any] ,) -> Optional[Any]: '''simple docstring''' super().__init__(bos_token_id=lowerCamelCase__ ,eos_token_id=lowerCamelCase__ ,pad_token_id=lowerCamelCase__ ,**lowerCamelCase__ ) if vision_config is None: SCREAMING_SNAKE_CASE = {} logger.info("""vision_config is None. initializing the GitVisionConfig with default values.""" ) SCREAMING_SNAKE_CASE = GitVisionConfig(**lowerCamelCase__ ) SCREAMING_SNAKE_CASE = vocab_size SCREAMING_SNAKE_CASE = hidden_size SCREAMING_SNAKE_CASE = num_hidden_layers SCREAMING_SNAKE_CASE = num_attention_heads SCREAMING_SNAKE_CASE = hidden_act SCREAMING_SNAKE_CASE = intermediate_size SCREAMING_SNAKE_CASE = hidden_dropout_prob SCREAMING_SNAKE_CASE = attention_probs_dropout_prob SCREAMING_SNAKE_CASE = max_position_embeddings SCREAMING_SNAKE_CASE = initializer_range SCREAMING_SNAKE_CASE = layer_norm_eps SCREAMING_SNAKE_CASE = position_embedding_type SCREAMING_SNAKE_CASE = use_cache SCREAMING_SNAKE_CASE = tie_word_embeddings SCREAMING_SNAKE_CASE = num_image_with_embedding SCREAMING_SNAKE_CASE = bos_token_id SCREAMING_SNAKE_CASE = eos_token_id def SCREAMING_SNAKE_CASE__ ( self : Dict ) -> Optional[int]: '''simple docstring''' SCREAMING_SNAKE_CASE = copy.deepcopy(self.__dict__ ) SCREAMING_SNAKE_CASE = self.vision_config.to_dict() SCREAMING_SNAKE_CASE = self.__class__.model_type return output
296
1
import argparse import OmegaConf import torch from diffusers import DDIMScheduler, LDMPipeline, UNetLDMModel, VQModel def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE = OmegaConf.load(_SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE = torch.load(_SCREAMING_SNAKE_CASE , map_location="""cpu""" )["""model"""] SCREAMING_SNAKE_CASE = list(state_dict.keys() ) # extract state_dict for VQVAE SCREAMING_SNAKE_CASE = {} SCREAMING_SNAKE_CASE = """first_stage_model.""" for key in keys: if key.startswith(_SCREAMING_SNAKE_CASE ): SCREAMING_SNAKE_CASE = state_dict[key] # extract state_dict for UNetLDM SCREAMING_SNAKE_CASE = {} SCREAMING_SNAKE_CASE = """model.diffusion_model.""" for key in keys: if key.startswith(_SCREAMING_SNAKE_CASE ): SCREAMING_SNAKE_CASE = state_dict[key] SCREAMING_SNAKE_CASE = config.model.params.first_stage_config.params SCREAMING_SNAKE_CASE = config.model.params.unet_config.params SCREAMING_SNAKE_CASE = VQModel(**_SCREAMING_SNAKE_CASE ).eval() vqvae.load_state_dict(_SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE = UNetLDMModel(**_SCREAMING_SNAKE_CASE ).eval() unet.load_state_dict(_SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE = DDIMScheduler( timesteps=config.model.params.timesteps , beta_schedule="""scaled_linear""" , beta_start=config.model.params.linear_start , beta_end=config.model.params.linear_end , clip_sample=_SCREAMING_SNAKE_CASE , ) SCREAMING_SNAKE_CASE = LDMPipeline(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) pipeline.save_pretrained(_SCREAMING_SNAKE_CASE ) if __name__ == "__main__": SCREAMING_SNAKE_CASE_ = argparse.ArgumentParser() parser.add_argument("""--checkpoint_path""", type=str, required=True) parser.add_argument("""--config_path""", type=str, required=True) parser.add_argument("""--output_path""", type=str, required=True) SCREAMING_SNAKE_CASE_ = parser.parse_args() convert_ldm_original(args.checkpoint_path, args.config_path, args.output_path)
296
import itertools import os import random import tempfile import unittest import numpy as np from transformers import TvltFeatureExtractor, is_datasets_available from transformers.testing_utils import check_json_file_has_correct_format, require_torch, require_torchaudio from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin if is_torch_available(): import torch if is_datasets_available(): from datasets import load_dataset SCREAMING_SNAKE_CASE_ = random.Random() def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=1.0 , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None ) -> Tuple: '''simple docstring''' if rng is None: SCREAMING_SNAKE_CASE = global_rng SCREAMING_SNAKE_CASE = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values class UpperCamelCase__ ( unittest.TestCase ): '''simple docstring''' def __init__( self : List[Any] ,lowerCamelCase__ : str ,lowerCamelCase__ : Optional[int]=7 ,lowerCamelCase__ : Optional[Any]=400 ,lowerCamelCase__ : List[str]=2000 ,lowerCamelCase__ : List[str]=2048 ,lowerCamelCase__ : Any=128 ,lowerCamelCase__ : List[str]=1 ,lowerCamelCase__ : str=512 ,lowerCamelCase__ : Optional[Any]=30 ,lowerCamelCase__ : Tuple=44100 ,) -> Tuple: '''simple docstring''' SCREAMING_SNAKE_CASE = parent SCREAMING_SNAKE_CASE = batch_size SCREAMING_SNAKE_CASE = min_seq_length SCREAMING_SNAKE_CASE = max_seq_length SCREAMING_SNAKE_CASE = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) SCREAMING_SNAKE_CASE = spectrogram_length SCREAMING_SNAKE_CASE = feature_size SCREAMING_SNAKE_CASE = num_audio_channels SCREAMING_SNAKE_CASE = hop_length SCREAMING_SNAKE_CASE = chunk_length SCREAMING_SNAKE_CASE = sampling_rate def SCREAMING_SNAKE_CASE__ ( self : List[Any] ) -> Optional[int]: '''simple docstring''' return { "spectrogram_length": self.spectrogram_length, "feature_size": self.feature_size, "num_audio_channels": self.num_audio_channels, "hop_length": self.hop_length, "chunk_length": self.chunk_length, "sampling_rate": self.sampling_rate, } def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ,lowerCamelCase__ : Tuple=False ,lowerCamelCase__ : Union[str, Any]=False ) -> str: '''simple docstring''' def _flatten(lowerCamelCase__ : List[Any] ): return list(itertools.chain(*lowerCamelCase__ ) ) if equal_length: SCREAMING_SNAKE_CASE = [floats_list((self.max_seq_length, self.feature_size) ) for _ in range(self.batch_size )] else: # make sure that inputs increase in size SCREAMING_SNAKE_CASE = [ floats_list((x, self.feature_size) ) for x in range(self.min_seq_length ,self.max_seq_length ,self.seq_length_diff ) ] if numpify: SCREAMING_SNAKE_CASE = [np.asarray(lowerCamelCase__ ) for x in speech_inputs] return speech_inputs @require_torch @require_torchaudio class UpperCamelCase__ ( lowerCAmelCase_ , unittest.TestCase ): '''simple docstring''' __snake_case : List[Any] = TvltFeatureExtractor def SCREAMING_SNAKE_CASE__ ( self : str ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE = TvltFeatureExtractionTester(self ) def SCREAMING_SNAKE_CASE__ ( self : List[Any] ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_dict ) self.assertTrue(hasattr(lowerCamelCase__ ,"""spectrogram_length""" ) ) self.assertTrue(hasattr(lowerCamelCase__ ,"""feature_size""" ) ) self.assertTrue(hasattr(lowerCamelCase__ ,"""num_audio_channels""" ) ) self.assertTrue(hasattr(lowerCamelCase__ ,"""hop_length""" ) ) self.assertTrue(hasattr(lowerCamelCase__ ,"""chunk_length""" ) ) self.assertTrue(hasattr(lowerCamelCase__ ,"""sampling_rate""" ) ) def SCREAMING_SNAKE_CASE__ ( self : str ) -> Union[str, Any]: '''simple docstring''' SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: SCREAMING_SNAKE_CASE = feat_extract_first.save_pretrained(lowerCamelCase__ )[0] check_json_file_has_correct_format(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = self.feature_extraction_class.from_pretrained(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = feat_extract_first.to_dict() SCREAMING_SNAKE_CASE = feat_extract_second.to_dict() SCREAMING_SNAKE_CASE = dict_first.pop("""mel_filters""" ) SCREAMING_SNAKE_CASE = dict_second.pop("""mel_filters""" ) self.assertTrue(np.allclose(lowerCamelCase__ ,lowerCamelCase__ ) ) self.assertEqual(lowerCamelCase__ ,lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( self : Any ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: SCREAMING_SNAKE_CASE = os.path.join(lowerCamelCase__ ,"""feat_extract.json""" ) feat_extract_first.to_json_file(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = self.feature_extraction_class.from_json_file(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = feat_extract_first.to_dict() SCREAMING_SNAKE_CASE = feat_extract_second.to_dict() SCREAMING_SNAKE_CASE = dict_first.pop("""mel_filters""" ) SCREAMING_SNAKE_CASE = dict_second.pop("""mel_filters""" ) self.assertTrue(np.allclose(lowerCamelCase__ ,lowerCamelCase__ ) ) self.assertEqual(lowerCamelCase__ ,lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( self : str ) -> Optional[int]: '''simple docstring''' SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_dict ) # create three inputs of length 800, 1000, and 1200 SCREAMING_SNAKE_CASE = [floats_list((1, x) )[0] for x in range(800 ,1400 ,200 )] SCREAMING_SNAKE_CASE = [np.asarray(lowerCamelCase__ ) for speech_input in speech_inputs] # Test not batched input SCREAMING_SNAKE_CASE = feature_extractor(np_speech_inputs[0] ,return_tensors="""np""" ,sampling_rate=44100 ).audio_values self.assertTrue(encoded_audios.ndim == 4 ) self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size ) self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length ) self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels ) # Test batched SCREAMING_SNAKE_CASE = feature_extractor(lowerCamelCase__ ,return_tensors="""np""" ,sampling_rate=44100 ).audio_values self.assertTrue(encoded_audios.ndim == 4 ) self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size ) self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length ) self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels ) # Test audio masking SCREAMING_SNAKE_CASE = feature_extractor( lowerCamelCase__ ,return_tensors="""np""" ,sampling_rate=44100 ,mask_audio=lowerCamelCase__ ).audio_values self.assertTrue(encoded_audios.ndim == 4 ) self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size ) self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length ) self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels ) # Test 2-D numpy arrays are batched. SCREAMING_SNAKE_CASE = [floats_list((1, x) )[0] for x in (800, 800, 800)] SCREAMING_SNAKE_CASE = np.asarray(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = feature_extractor(lowerCamelCase__ ,return_tensors="""np""" ,sampling_rate=44100 ).audio_values self.assertTrue(encoded_audios.ndim == 4 ) self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size ) self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length ) self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels ) def SCREAMING_SNAKE_CASE__ ( self : Any ,lowerCamelCase__ : str ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE = load_dataset("""hf-internal-testing/librispeech_asr_dummy""" ,"""clean""" ,split="""validation""" ) # automatic decoding with librispeech SCREAMING_SNAKE_CASE = ds.sort("""id""" ).select(range(lowerCamelCase__ ) )[:num_samples]["""audio"""] return [x["array"] for x in speech_samples] def SCREAMING_SNAKE_CASE__ ( self : Tuple ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE = self._load_datasamples(1 ) SCREAMING_SNAKE_CASE = TvltFeatureExtractor() SCREAMING_SNAKE_CASE = feature_extractor(lowerCamelCase__ ,return_tensors="""pt""" ).audio_values self.assertEquals(audio_values.shape ,(1, 1, 192, 128) ) SCREAMING_SNAKE_CASE = torch.tensor([[-0.3032, -0.2708], [-0.4434, -0.4007]] ) self.assertTrue(torch.allclose(audio_values[0, 0, :2, :2] ,lowerCamelCase__ ,atol=1e-4 ) )
296
1
from dataclasses import dataclass from typing import Dict, Optional, Tuple, Union import torch import torch.nn as nn from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, apply_forward_hook from .attention_processor import AttentionProcessor, AttnProcessor from .modeling_utils import ModelMixin from .vae import Decoder, DecoderOutput, DiagonalGaussianDistribution, Encoder @dataclass class UpperCamelCase__ ( lowerCAmelCase_ ): '''simple docstring''' __snake_case : "DiagonalGaussianDistribution" class UpperCamelCase__ ( lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __snake_case : str = True @register_to_config def __init__( self : str ,lowerCamelCase__ : int = 3 ,lowerCamelCase__ : int = 3 ,lowerCamelCase__ : Tuple[str] = ("DownEncoderBlock2D",) ,lowerCamelCase__ : Tuple[str] = ("UpDecoderBlock2D",) ,lowerCamelCase__ : Tuple[int] = (64,) ,lowerCamelCase__ : int = 1 ,lowerCamelCase__ : str = "silu" ,lowerCamelCase__ : int = 4 ,lowerCamelCase__ : int = 32 ,lowerCamelCase__ : int = 32 ,lowerCamelCase__ : float = 0.18215 ,) -> Tuple: '''simple docstring''' super().__init__() # pass init params to Encoder SCREAMING_SNAKE_CASE = Encoder( in_channels=lowerCamelCase__ ,out_channels=lowerCamelCase__ ,down_block_types=lowerCamelCase__ ,block_out_channels=lowerCamelCase__ ,layers_per_block=lowerCamelCase__ ,act_fn=lowerCamelCase__ ,norm_num_groups=lowerCamelCase__ ,double_z=lowerCamelCase__ ,) # pass init params to Decoder SCREAMING_SNAKE_CASE = Decoder( in_channels=lowerCamelCase__ ,out_channels=lowerCamelCase__ ,up_block_types=lowerCamelCase__ ,block_out_channels=lowerCamelCase__ ,layers_per_block=lowerCamelCase__ ,norm_num_groups=lowerCamelCase__ ,act_fn=lowerCamelCase__ ,) SCREAMING_SNAKE_CASE = nn.Convad(2 * latent_channels ,2 * latent_channels ,1 ) SCREAMING_SNAKE_CASE = nn.Convad(lowerCamelCase__ ,lowerCamelCase__ ,1 ) SCREAMING_SNAKE_CASE = False SCREAMING_SNAKE_CASE = False # only relevant if vae tiling is enabled SCREAMING_SNAKE_CASE = self.config.sample_size SCREAMING_SNAKE_CASE = ( self.config.sample_size[0] if isinstance(self.config.sample_size ,(list, tuple) ) else self.config.sample_size ) SCREAMING_SNAKE_CASE = int(sample_size / (2 ** (len(self.config.block_out_channels ) - 1)) ) SCREAMING_SNAKE_CASE = 0.25 def SCREAMING_SNAKE_CASE__ ( self : str ,lowerCamelCase__ : List[str] ,lowerCamelCase__ : Optional[Any]=False ) -> Union[str, Any]: '''simple docstring''' if isinstance(lowerCamelCase__ ,(Encoder, Decoder) ): SCREAMING_SNAKE_CASE = value def SCREAMING_SNAKE_CASE__ ( self : List[Any] ,lowerCamelCase__ : bool = True ) -> Optional[int]: '''simple docstring''' SCREAMING_SNAKE_CASE = use_tiling def SCREAMING_SNAKE_CASE__ ( self : Tuple ) -> List[Any]: '''simple docstring''' self.enable_tiling(lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ) -> Optional[int]: '''simple docstring''' SCREAMING_SNAKE_CASE = True def SCREAMING_SNAKE_CASE__ ( self : str ) -> str: '''simple docstring''' SCREAMING_SNAKE_CASE = False @property # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.attn_processors def SCREAMING_SNAKE_CASE__ ( self : Dict ) -> Dict[str, AttentionProcessor]: '''simple docstring''' SCREAMING_SNAKE_CASE = {} def fn_recursive_add_processors(lowerCamelCase__ : str ,lowerCamelCase__ : torch.nn.Module ,lowerCamelCase__ : Dict[str, AttentionProcessor] ): if hasattr(lowerCamelCase__ ,"""set_processor""" ): SCREAMING_SNAKE_CASE = module.processor for sub_name, child in module.named_children(): fn_recursive_add_processors(F"""{name}.{sub_name}""" ,lowerCamelCase__ ,lowerCamelCase__ ) return processors for name, module in self.named_children(): fn_recursive_add_processors(lowerCamelCase__ ,lowerCamelCase__ ,lowerCamelCase__ ) return processors def SCREAMING_SNAKE_CASE__ ( self : Dict ,lowerCamelCase__ : Union[AttentionProcessor, Dict[str, AttentionProcessor]] ) -> str: '''simple docstring''' SCREAMING_SNAKE_CASE = len(self.attn_processors.keys() ) if isinstance(lowerCamelCase__ ,lowerCamelCase__ ) and len(lowerCamelCase__ ) != count: raise ValueError( F"""A dict of processors was passed, but the number of processors {len(lowerCamelCase__ )} does not match the""" F""" number of attention layers: {count}. Please make sure to pass {count} processor classes.""" ) def fn_recursive_attn_processor(lowerCamelCase__ : str ,lowerCamelCase__ : torch.nn.Module ,lowerCamelCase__ : Optional[int] ): if hasattr(lowerCamelCase__ ,"""set_processor""" ): if not isinstance(lowerCamelCase__ ,lowerCamelCase__ ): module.set_processor(lowerCamelCase__ ) else: module.set_processor(processor.pop(F"""{name}.processor""" ) ) for sub_name, child in module.named_children(): fn_recursive_attn_processor(F"""{name}.{sub_name}""" ,lowerCamelCase__ ,lowerCamelCase__ ) for name, module in self.named_children(): fn_recursive_attn_processor(lowerCamelCase__ ,lowerCamelCase__ ,lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ) -> Dict: '''simple docstring''' self.set_attn_processor(AttnProcessor() ) @apply_forward_hook def SCREAMING_SNAKE_CASE__ ( self : List[Any] ,lowerCamelCase__ : torch.FloatTensor ,lowerCamelCase__ : bool = True ) -> AutoencoderKLOutput: '''simple docstring''' if self.use_tiling and (x.shape[-1] > self.tile_sample_min_size or x.shape[-2] > self.tile_sample_min_size): return self.tiled_encode(lowerCamelCase__ ,return_dict=lowerCamelCase__ ) if self.use_slicing and x.shape[0] > 1: SCREAMING_SNAKE_CASE = [self.encoder(lowerCamelCase__ ) for x_slice in x.split(1 )] SCREAMING_SNAKE_CASE = torch.cat(lowerCamelCase__ ) else: SCREAMING_SNAKE_CASE = self.encoder(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = self.quant_conv(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = DiagonalGaussianDistribution(lowerCamelCase__ ) if not return_dict: return (posterior,) return AutoencoderKLOutput(latent_dist=lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ,lowerCamelCase__ : torch.FloatTensor ,lowerCamelCase__ : bool = True ) -> Union[DecoderOutput, torch.FloatTensor]: '''simple docstring''' if self.use_tiling and (z.shape[-1] > self.tile_latent_min_size or z.shape[-2] > self.tile_latent_min_size): return self.tiled_decode(lowerCamelCase__ ,return_dict=lowerCamelCase__ ) SCREAMING_SNAKE_CASE = self.post_quant_conv(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = self.decoder(lowerCamelCase__ ) if not return_dict: return (dec,) return DecoderOutput(sample=lowerCamelCase__ ) @apply_forward_hook def SCREAMING_SNAKE_CASE__ ( self : str ,lowerCamelCase__ : torch.FloatTensor ,lowerCamelCase__ : bool = True ) -> Union[DecoderOutput, torch.FloatTensor]: '''simple docstring''' if self.use_slicing and z.shape[0] > 1: SCREAMING_SNAKE_CASE = [self._decode(lowerCamelCase__ ).sample for z_slice in z.split(1 )] SCREAMING_SNAKE_CASE = torch.cat(lowerCamelCase__ ) else: SCREAMING_SNAKE_CASE = self._decode(lowerCamelCase__ ).sample if not return_dict: return (decoded,) return DecoderOutput(sample=lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( self : Dict ,lowerCamelCase__ : List[str] ,lowerCamelCase__ : Optional[int] ,lowerCamelCase__ : Tuple ) -> Optional[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE = min(a.shape[2] ,b.shape[2] ,lowerCamelCase__ ) for y in range(lowerCamelCase__ ): SCREAMING_SNAKE_CASE = a[:, :, -blend_extent + y, :] * (1 - y / blend_extent) + b[:, :, y, :] * (y / blend_extent) return b def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ,lowerCamelCase__ : Any ,lowerCamelCase__ : List[Any] ,lowerCamelCase__ : Any ) -> str: '''simple docstring''' SCREAMING_SNAKE_CASE = min(a.shape[3] ,b.shape[3] ,lowerCamelCase__ ) for x in range(lowerCamelCase__ ): SCREAMING_SNAKE_CASE = a[:, :, :, -blend_extent + x] * (1 - x / blend_extent) + b[:, :, :, x] * (x / blend_extent) return b def SCREAMING_SNAKE_CASE__ ( self : Tuple ,lowerCamelCase__ : torch.FloatTensor ,lowerCamelCase__ : bool = True ) -> AutoencoderKLOutput: '''simple docstring''' SCREAMING_SNAKE_CASE = int(self.tile_sample_min_size * (1 - self.tile_overlap_factor) ) SCREAMING_SNAKE_CASE = int(self.tile_latent_min_size * self.tile_overlap_factor ) SCREAMING_SNAKE_CASE = self.tile_latent_min_size - blend_extent # Split the image into 512x512 tiles and encode them separately. SCREAMING_SNAKE_CASE = [] for i in range(0 ,x.shape[2] ,lowerCamelCase__ ): SCREAMING_SNAKE_CASE = [] for j in range(0 ,x.shape[3] ,lowerCamelCase__ ): SCREAMING_SNAKE_CASE = x[:, :, i : i + self.tile_sample_min_size, j : j + self.tile_sample_min_size] SCREAMING_SNAKE_CASE = self.encoder(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = self.quant_conv(lowerCamelCase__ ) row.append(lowerCamelCase__ ) rows.append(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = [] for i, row in enumerate(lowerCamelCase__ ): SCREAMING_SNAKE_CASE = [] for j, tile in enumerate(lowerCamelCase__ ): # blend the above tile and the left tile # to the current tile and add the current tile to the result row if i > 0: SCREAMING_SNAKE_CASE = self.blend_v(rows[i - 1][j] ,lowerCamelCase__ ,lowerCamelCase__ ) if j > 0: SCREAMING_SNAKE_CASE = self.blend_h(row[j - 1] ,lowerCamelCase__ ,lowerCamelCase__ ) result_row.append(tile[:, :, :row_limit, :row_limit] ) result_rows.append(torch.cat(lowerCamelCase__ ,dim=3 ) ) SCREAMING_SNAKE_CASE = torch.cat(lowerCamelCase__ ,dim=2 ) SCREAMING_SNAKE_CASE = DiagonalGaussianDistribution(lowerCamelCase__ ) if not return_dict: return (posterior,) return AutoencoderKLOutput(latent_dist=lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ,lowerCamelCase__ : torch.FloatTensor ,lowerCamelCase__ : bool = True ) -> Union[DecoderOutput, torch.FloatTensor]: '''simple docstring''' SCREAMING_SNAKE_CASE = int(self.tile_latent_min_size * (1 - self.tile_overlap_factor) ) SCREAMING_SNAKE_CASE = int(self.tile_sample_min_size * self.tile_overlap_factor ) SCREAMING_SNAKE_CASE = self.tile_sample_min_size - blend_extent # Split z into overlapping 64x64 tiles and decode them separately. # The tiles have an overlap to avoid seams between tiles. SCREAMING_SNAKE_CASE = [] for i in range(0 ,z.shape[2] ,lowerCamelCase__ ): SCREAMING_SNAKE_CASE = [] for j in range(0 ,z.shape[3] ,lowerCamelCase__ ): SCREAMING_SNAKE_CASE = z[:, :, i : i + self.tile_latent_min_size, j : j + self.tile_latent_min_size] SCREAMING_SNAKE_CASE = self.post_quant_conv(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = self.decoder(lowerCamelCase__ ) row.append(lowerCamelCase__ ) rows.append(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = [] for i, row in enumerate(lowerCamelCase__ ): SCREAMING_SNAKE_CASE = [] for j, tile in enumerate(lowerCamelCase__ ): # blend the above tile and the left tile # to the current tile and add the current tile to the result row if i > 0: SCREAMING_SNAKE_CASE = self.blend_v(rows[i - 1][j] ,lowerCamelCase__ ,lowerCamelCase__ ) if j > 0: SCREAMING_SNAKE_CASE = self.blend_h(row[j - 1] ,lowerCamelCase__ ,lowerCamelCase__ ) result_row.append(tile[:, :, :row_limit, :row_limit] ) result_rows.append(torch.cat(lowerCamelCase__ ,dim=3 ) ) SCREAMING_SNAKE_CASE = torch.cat(lowerCamelCase__ ,dim=2 ) if not return_dict: return (dec,) return DecoderOutput(sample=lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ,lowerCamelCase__ : torch.FloatTensor ,lowerCamelCase__ : bool = False ,lowerCamelCase__ : bool = True ,lowerCamelCase__ : Optional[torch.Generator] = None ,) -> Union[DecoderOutput, torch.FloatTensor]: '''simple docstring''' SCREAMING_SNAKE_CASE = sample SCREAMING_SNAKE_CASE = self.encode(lowerCamelCase__ ).latent_dist if sample_posterior: SCREAMING_SNAKE_CASE = posterior.sample(generator=lowerCamelCase__ ) else: SCREAMING_SNAKE_CASE = posterior.mode() SCREAMING_SNAKE_CASE = self.decode(lowerCamelCase__ ).sample if not return_dict: return (dec,) return DecoderOutput(sample=lowerCamelCase__ )
296
import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( MobileViTConfig, MobileViTForImageClassification, MobileViTForSemanticSegmentation, MobileViTImageProcessor, ) from transformers.utils import logging logging.set_verbosity_info() SCREAMING_SNAKE_CASE_ = logging.get_logger(__name__) def __lowercase ( _SCREAMING_SNAKE_CASE ) -> Optional[int]: '''simple docstring''' SCREAMING_SNAKE_CASE = MobileViTConfig() # size of the architecture if "mobilevit_s" in mobilevit_name: SCREAMING_SNAKE_CASE = [1_44, 1_92, 2_40] SCREAMING_SNAKE_CASE = [16, 32, 64, 96, 1_28, 1_60, 6_40] elif "mobilevit_xs" in mobilevit_name: SCREAMING_SNAKE_CASE = [96, 1_20, 1_44] SCREAMING_SNAKE_CASE = [16, 32, 48, 64, 80, 96, 3_84] elif "mobilevit_xxs" in mobilevit_name: SCREAMING_SNAKE_CASE = [64, 80, 96] SCREAMING_SNAKE_CASE = [16, 16, 24, 48, 64, 80, 3_20] SCREAMING_SNAKE_CASE = 0.05 SCREAMING_SNAKE_CASE = 2.0 if mobilevit_name.startswith("""deeplabv3_""" ): SCREAMING_SNAKE_CASE = 5_12 SCREAMING_SNAKE_CASE = 16 SCREAMING_SNAKE_CASE = 21 SCREAMING_SNAKE_CASE = """pascal-voc-id2label.json""" else: SCREAMING_SNAKE_CASE = 10_00 SCREAMING_SNAKE_CASE = """imagenet-1k-id2label.json""" SCREAMING_SNAKE_CASE = """huggingface/label-files""" SCREAMING_SNAKE_CASE = json.load(open(hf_hub_download(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , repo_type="""dataset""" ) , """r""" ) ) SCREAMING_SNAKE_CASE = {int(_SCREAMING_SNAKE_CASE ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE = idalabel SCREAMING_SNAKE_CASE = {v: k for k, v in idalabel.items()} return config def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=False ) -> str: '''simple docstring''' for i in range(1 , 6 ): if F"""layer_{i}.""" in name: SCREAMING_SNAKE_CASE = name.replace(F"""layer_{i}.""" , F"""encoder.layer.{i - 1}.""" ) if "conv_1." in name: SCREAMING_SNAKE_CASE = name.replace("""conv_1.""" , """conv_stem.""" ) if ".block." in name: SCREAMING_SNAKE_CASE = name.replace(""".block.""" , """.""" ) if "exp_1x1" in name: SCREAMING_SNAKE_CASE = name.replace("""exp_1x1""" , """expand_1x1""" ) if "red_1x1" in name: SCREAMING_SNAKE_CASE = name.replace("""red_1x1""" , """reduce_1x1""" ) if ".local_rep.conv_3x3." in name: SCREAMING_SNAKE_CASE = name.replace(""".local_rep.conv_3x3.""" , """.conv_kxk.""" ) if ".local_rep.conv_1x1." in name: SCREAMING_SNAKE_CASE = name.replace(""".local_rep.conv_1x1.""" , """.conv_1x1.""" ) if ".norm." in name: SCREAMING_SNAKE_CASE = name.replace(""".norm.""" , """.normalization.""" ) if ".conv." in name: SCREAMING_SNAKE_CASE = name.replace(""".conv.""" , """.convolution.""" ) if ".conv_proj." in name: SCREAMING_SNAKE_CASE = name.replace(""".conv_proj.""" , """.conv_projection.""" ) for i in range(0 , 2 ): for j in range(0 , 4 ): if F""".{i}.{j}.""" in name: SCREAMING_SNAKE_CASE = name.replace(F""".{i}.{j}.""" , F""".{i}.layer.{j}.""" ) for i in range(2 , 6 ): for j in range(0 , 4 ): if F""".{i}.{j}.""" in name: SCREAMING_SNAKE_CASE = name.replace(F""".{i}.{j}.""" , F""".{i}.""" ) if "expand_1x1" in name: SCREAMING_SNAKE_CASE = name.replace("""expand_1x1""" , """downsampling_layer.expand_1x1""" ) if "conv_3x3" in name: SCREAMING_SNAKE_CASE = name.replace("""conv_3x3""" , """downsampling_layer.conv_3x3""" ) if "reduce_1x1" in name: SCREAMING_SNAKE_CASE = name.replace("""reduce_1x1""" , """downsampling_layer.reduce_1x1""" ) for i in range(2 , 5 ): if F""".global_rep.{i}.weight""" in name: SCREAMING_SNAKE_CASE = name.replace(F""".global_rep.{i}.weight""" , """.layernorm.weight""" ) if F""".global_rep.{i}.bias""" in name: SCREAMING_SNAKE_CASE = name.replace(F""".global_rep.{i}.bias""" , """.layernorm.bias""" ) if ".global_rep." in name: SCREAMING_SNAKE_CASE = name.replace(""".global_rep.""" , """.transformer.""" ) if ".pre_norm_mha.0." in name: SCREAMING_SNAKE_CASE = name.replace(""".pre_norm_mha.0.""" , """.layernorm_before.""" ) if ".pre_norm_mha.1.out_proj." in name: SCREAMING_SNAKE_CASE = name.replace(""".pre_norm_mha.1.out_proj.""" , """.attention.output.dense.""" ) if ".pre_norm_ffn.0." in name: SCREAMING_SNAKE_CASE = name.replace(""".pre_norm_ffn.0.""" , """.layernorm_after.""" ) if ".pre_norm_ffn.1." in name: SCREAMING_SNAKE_CASE = name.replace(""".pre_norm_ffn.1.""" , """.intermediate.dense.""" ) if ".pre_norm_ffn.4." in name: SCREAMING_SNAKE_CASE = name.replace(""".pre_norm_ffn.4.""" , """.output.dense.""" ) if ".transformer." in name: SCREAMING_SNAKE_CASE = name.replace(""".transformer.""" , """.transformer.layer.""" ) if ".aspp_layer." in name: SCREAMING_SNAKE_CASE = name.replace(""".aspp_layer.""" , """.""" ) if ".aspp_pool." in name: SCREAMING_SNAKE_CASE = name.replace(""".aspp_pool.""" , """.""" ) if "seg_head." in name: SCREAMING_SNAKE_CASE = name.replace("""seg_head.""" , """segmentation_head.""" ) if "segmentation_head.classifier.classifier." in name: SCREAMING_SNAKE_CASE = name.replace("""segmentation_head.classifier.classifier.""" , """segmentation_head.classifier.""" ) if "classifier.fc." in name: SCREAMING_SNAKE_CASE = name.replace("""classifier.fc.""" , """classifier.""" ) elif (not base_model) and ("segmentation_head." not in name): SCREAMING_SNAKE_CASE = """mobilevit.""" + name return name def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=False ) -> Dict: '''simple docstring''' if base_model: SCREAMING_SNAKE_CASE = """""" else: SCREAMING_SNAKE_CASE = """mobilevit.""" for key in orig_state_dict.copy().keys(): SCREAMING_SNAKE_CASE = orig_state_dict.pop(_SCREAMING_SNAKE_CASE ) if key[:8] == "encoder.": SCREAMING_SNAKE_CASE = key[8:] if "qkv" in key: SCREAMING_SNAKE_CASE = key.split(""".""" ) SCREAMING_SNAKE_CASE = int(key_split[0][6:] ) - 1 SCREAMING_SNAKE_CASE = int(key_split[3] ) SCREAMING_SNAKE_CASE = model.get_submodule(F"""{model_prefix}encoder.layer.{layer_num}""" ) SCREAMING_SNAKE_CASE = layer.transformer.layer[transformer_num].attention.attention.all_head_size SCREAMING_SNAKE_CASE = ( F"""{model_prefix}encoder.layer.{layer_num}.transformer.layer.{transformer_num}.attention.attention.""" ) if "weight" in key: SCREAMING_SNAKE_CASE = val[:dim, :] SCREAMING_SNAKE_CASE = val[dim : dim * 2, :] SCREAMING_SNAKE_CASE = val[-dim:, :] else: SCREAMING_SNAKE_CASE = val[:dim] SCREAMING_SNAKE_CASE = val[dim : dim * 2] SCREAMING_SNAKE_CASE = val[-dim:] else: SCREAMING_SNAKE_CASE = val return orig_state_dict def __lowercase ( ) -> str: '''simple docstring''' SCREAMING_SNAKE_CASE = """http://images.cocodataset.org/val2017/000000039769.jpg""" SCREAMING_SNAKE_CASE = Image.open(requests.get(_SCREAMING_SNAKE_CASE , stream=_SCREAMING_SNAKE_CASE ).raw ) return im @torch.no_grad() def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=False ) -> str: '''simple docstring''' SCREAMING_SNAKE_CASE = get_mobilevit_config(_SCREAMING_SNAKE_CASE ) # load original state_dict SCREAMING_SNAKE_CASE = torch.load(_SCREAMING_SNAKE_CASE , map_location="""cpu""" ) # load 🤗 model if mobilevit_name.startswith("""deeplabv3_""" ): SCREAMING_SNAKE_CASE = MobileViTForSemanticSegmentation(_SCREAMING_SNAKE_CASE ).eval() else: SCREAMING_SNAKE_CASE = MobileViTForImageClassification(_SCREAMING_SNAKE_CASE ).eval() SCREAMING_SNAKE_CASE = convert_state_dict(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) model.load_state_dict(_SCREAMING_SNAKE_CASE ) # Check outputs on an image, prepared by MobileViTImageProcessor SCREAMING_SNAKE_CASE = MobileViTImageProcessor(crop_size=config.image_size , size=config.image_size + 32 ) SCREAMING_SNAKE_CASE = image_processor(images=prepare_img() , return_tensors="""pt""" ) SCREAMING_SNAKE_CASE = model(**_SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE = outputs.logits if mobilevit_name.startswith("""deeplabv3_""" ): assert logits.shape == (1, 21, 32, 32) if mobilevit_name == "deeplabv3_mobilevit_s": SCREAMING_SNAKE_CASE = torch.tensor( [ [[6.2_065, 6.1_292, 6.2_070], [6.1_079, 6.1_254, 6.1_747], [6.0_042, 6.1_071, 6.1_034]], [[-6.9_253, -6.8_653, -7.0_398], [-7.3_218, -7.3_983, -7.3_670], [-7.1_961, -7.2_482, -7.1_569]], [[-4.4_723, -4.4_348, -4.3_769], [-5.3_629, -5.4_632, -5.4_598], [-5.1_587, -5.3_402, -5.5_059]], ] ) elif mobilevit_name == "deeplabv3_mobilevit_xs": SCREAMING_SNAKE_CASE = torch.tensor( [ [[5.4_449, 5.5_733, 5.6_314], [5.1_815, 5.3_930, 5.5_963], [5.1_656, 5.4_333, 5.4_853]], [[-9.4_423, -9.7_766, -9.6_714], [-9.1_581, -9.5_720, -9.5_519], [-9.1_006, -9.6_458, -9.5_703]], [[-7.7_721, -7.3_716, -7.1_583], [-8.4_599, -8.0_624, -7.7_944], [-8.4_172, -7.8_366, -7.5_025]], ] ) elif mobilevit_name == "deeplabv3_mobilevit_xxs": SCREAMING_SNAKE_CASE = torch.tensor( [ [[6.9_811, 6.9_743, 7.3_123], [7.1_777, 7.1_931, 7.3_938], [7.5_633, 7.8_050, 7.8_901]], [[-10.5_536, -10.2_332, -10.2_924], [-10.2_336, -9.8_624, -9.5_964], [-10.8_840, -10.8_158, -10.6_659]], [[-3.4_938, -3.0_631, -2.8_620], [-3.4_205, -2.8_135, -2.6_875], [-3.4_179, -2.7_945, -2.8_750]], ] ) else: raise ValueError(F"""Unknown mobilevit_name: {mobilevit_name}""" ) assert torch.allclose(logits[0, :3, :3, :3] , _SCREAMING_SNAKE_CASE , atol=1E-4 ) else: assert logits.shape == (1, 10_00) if mobilevit_name == "mobilevit_s": SCREAMING_SNAKE_CASE = torch.tensor([-0.9_866, 0.2_392, -1.1_241] ) elif mobilevit_name == "mobilevit_xs": SCREAMING_SNAKE_CASE = torch.tensor([-2.4_761, -0.9_399, -1.9_587] ) elif mobilevit_name == "mobilevit_xxs": SCREAMING_SNAKE_CASE = torch.tensor([-1.9_364, -1.2_327, -0.4_653] ) else: raise ValueError(F"""Unknown mobilevit_name: {mobilevit_name}""" ) assert torch.allclose(logits[0, :3] , _SCREAMING_SNAKE_CASE , atol=1E-4 ) Path(_SCREAMING_SNAKE_CASE ).mkdir(exist_ok=_SCREAMING_SNAKE_CASE ) print(F"""Saving model {mobilevit_name} to {pytorch_dump_folder_path}""" ) model.save_pretrained(_SCREAMING_SNAKE_CASE ) print(F"""Saving image processor to {pytorch_dump_folder_path}""" ) image_processor.save_pretrained(_SCREAMING_SNAKE_CASE ) if push_to_hub: SCREAMING_SNAKE_CASE = { """mobilevit_s""": """mobilevit-small""", """mobilevit_xs""": """mobilevit-x-small""", """mobilevit_xxs""": """mobilevit-xx-small""", """deeplabv3_mobilevit_s""": """deeplabv3-mobilevit-small""", """deeplabv3_mobilevit_xs""": """deeplabv3-mobilevit-x-small""", """deeplabv3_mobilevit_xxs""": """deeplabv3-mobilevit-xx-small""", } print("""Pushing to the hub...""" ) SCREAMING_SNAKE_CASE = model_mapping[mobilevit_name] image_processor.push_to_hub(_SCREAMING_SNAKE_CASE , organization="""apple""" ) model.push_to_hub(_SCREAMING_SNAKE_CASE , organization="""apple""" ) if __name__ == "__main__": SCREAMING_SNAKE_CASE_ = argparse.ArgumentParser() # Required parameters parser.add_argument( """--mobilevit_name""", default="""mobilevit_s""", type=str, help=( """Name of the MobileViT model you'd like to convert. Should be one of 'mobilevit_s', 'mobilevit_xs',""" """ 'mobilevit_xxs', 'deeplabv3_mobilevit_s', 'deeplabv3_mobilevit_xs', 'deeplabv3_mobilevit_xxs'.""" ), ) parser.add_argument( """--checkpoint_path""", required=True, type=str, help="""Path to the original state dict (.pt file).""" ) parser.add_argument( """--pytorch_dump_folder_path""", required=True, type=str, help="""Path to the output PyTorch model directory.""" ) parser.add_argument( """--push_to_hub""", action="""store_true""", help="""Whether or not to push the converted model to the 🤗 hub.""" ) SCREAMING_SNAKE_CASE_ = parser.parse_args() convert_movilevit_checkpoint( args.mobilevit_name, args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub )
296
1
import torch from transformers import CamembertForMaskedLM, CamembertTokenizer def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=5 ) -> Tuple: '''simple docstring''' assert masked_input.count("""<mask>""" ) == 1 SCREAMING_SNAKE_CASE = torch.tensor(tokenizer.encode(_SCREAMING_SNAKE_CASE , add_special_tokens=_SCREAMING_SNAKE_CASE ) ).unsqueeze(0 ) # Batch size 1 SCREAMING_SNAKE_CASE = model(_SCREAMING_SNAKE_CASE )[0] # The last hidden-state is the first element of the output tuple SCREAMING_SNAKE_CASE = (input_ids.squeeze() == tokenizer.mask_token_id).nonzero().item() SCREAMING_SNAKE_CASE = logits[0, masked_index, :] SCREAMING_SNAKE_CASE = logits.softmax(dim=0 ) SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE = prob.topk(k=_SCREAMING_SNAKE_CASE , dim=0 ) SCREAMING_SNAKE_CASE = """ """.join( [tokenizer.convert_ids_to_tokens(indices[i].item() ) for i in range(len(_SCREAMING_SNAKE_CASE ) )] ) SCREAMING_SNAKE_CASE = tokenizer.mask_token SCREAMING_SNAKE_CASE = [] for index, predicted_token_bpe in enumerate(topk_predicted_token_bpe.split(""" """ ) ): SCREAMING_SNAKE_CASE = predicted_token_bpe.replace("""\u2581""" , """ """ ) if " {0}".format(_SCREAMING_SNAKE_CASE ) in masked_input: topk_filled_outputs.append( ( masked_input.replace(""" {0}""".format(_SCREAMING_SNAKE_CASE ) , _SCREAMING_SNAKE_CASE ), values[index].item(), predicted_token, ) ) else: topk_filled_outputs.append( ( masked_input.replace(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ), values[index].item(), predicted_token, ) ) return topk_filled_outputs SCREAMING_SNAKE_CASE_ = CamembertTokenizer.from_pretrained("""camembert-base""") SCREAMING_SNAKE_CASE_ = CamembertForMaskedLM.from_pretrained("""camembert-base""") model.eval() SCREAMING_SNAKE_CASE_ = """Le camembert est <mask> :)""" print(fill_mask(masked_input, model, tokenizer, topk=3))
296
from collections import OrderedDict from ...utils import logging from .auto_factory import _BaseAutoModelClass, _LazyAutoMapping, auto_class_update from .configuration_auto import CONFIG_MAPPING_NAMES SCREAMING_SNAKE_CASE_ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE_ = 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"""), ] ) SCREAMING_SNAKE_CASE_ = 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"""), ] ) SCREAMING_SNAKE_CASE_ = 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"""), ] ) SCREAMING_SNAKE_CASE_ = 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"""), ] ) SCREAMING_SNAKE_CASE_ = OrderedDict( [ # Model for Image-classsification ("""beit""", """FlaxBeitForImageClassification"""), ("""regnet""", """FlaxRegNetForImageClassification"""), ("""resnet""", """FlaxResNetForImageClassification"""), ("""vit""", """FlaxViTForImageClassification"""), ] ) SCREAMING_SNAKE_CASE_ = OrderedDict( [ ("""vision-encoder-decoder""", """FlaxVisionEncoderDecoderModel"""), ] ) SCREAMING_SNAKE_CASE_ = 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"""), ] ) SCREAMING_SNAKE_CASE_ = 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"""), ] ) SCREAMING_SNAKE_CASE_ = 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"""), ] ) SCREAMING_SNAKE_CASE_ = 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"""), ] ) SCREAMING_SNAKE_CASE_ = 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"""), ] ) SCREAMING_SNAKE_CASE_ = OrderedDict( [ ("""bert""", """FlaxBertForNextSentencePrediction"""), ] ) SCREAMING_SNAKE_CASE_ = OrderedDict( [ ("""speech-encoder-decoder""", """FlaxSpeechEncoderDecoderModel"""), ("""whisper""", """FlaxWhisperForConditionalGeneration"""), ] ) SCREAMING_SNAKE_CASE_ = OrderedDict( [ ("""whisper""", """FlaxWhisperForAudioClassification"""), ] ) SCREAMING_SNAKE_CASE_ = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_MAPPING_NAMES) SCREAMING_SNAKE_CASE_ = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_PRETRAINING_MAPPING_NAMES) SCREAMING_SNAKE_CASE_ = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MASKED_LM_MAPPING_NAMES) SCREAMING_SNAKE_CASE_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES ) SCREAMING_SNAKE_CASE_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES ) SCREAMING_SNAKE_CASE_ = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES) SCREAMING_SNAKE_CASE_ = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_CAUSAL_LM_MAPPING_NAMES) SCREAMING_SNAKE_CASE_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES ) SCREAMING_SNAKE_CASE_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES ) SCREAMING_SNAKE_CASE_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES ) SCREAMING_SNAKE_CASE_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES ) SCREAMING_SNAKE_CASE_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING_NAMES ) SCREAMING_SNAKE_CASE_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES ) SCREAMING_SNAKE_CASE_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES ) class UpperCamelCase__ ( _BaseAutoModelClass ): '''simple docstring''' __snake_case : List[str] = FLAX_MODEL_MAPPING SCREAMING_SNAKE_CASE_ = auto_class_update(FlaxAutoModel) class UpperCamelCase__ ( _BaseAutoModelClass ): '''simple docstring''' __snake_case : Dict = FLAX_MODEL_FOR_PRETRAINING_MAPPING SCREAMING_SNAKE_CASE_ = auto_class_update(FlaxAutoModelForPreTraining, head_doc="""pretraining""") class UpperCamelCase__ ( _BaseAutoModelClass ): '''simple docstring''' __snake_case : Optional[Any] = FLAX_MODEL_FOR_CAUSAL_LM_MAPPING SCREAMING_SNAKE_CASE_ = auto_class_update(FlaxAutoModelForCausalLM, head_doc="""causal language modeling""") class UpperCamelCase__ ( _BaseAutoModelClass ): '''simple docstring''' __snake_case : Any = FLAX_MODEL_FOR_MASKED_LM_MAPPING SCREAMING_SNAKE_CASE_ = auto_class_update(FlaxAutoModelForMaskedLM, head_doc="""masked language modeling""") class UpperCamelCase__ ( _BaseAutoModelClass ): '''simple docstring''' __snake_case : int = FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING SCREAMING_SNAKE_CASE_ = auto_class_update( FlaxAutoModelForSeqaSeqLM, head_doc="""sequence-to-sequence language modeling""", checkpoint_for_example="""t5-base""" ) class UpperCamelCase__ ( _BaseAutoModelClass ): '''simple docstring''' __snake_case : Optional[int] = FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING SCREAMING_SNAKE_CASE_ = auto_class_update( FlaxAutoModelForSequenceClassification, head_doc="""sequence classification""" ) class UpperCamelCase__ ( _BaseAutoModelClass ): '''simple docstring''' __snake_case : List[Any] = FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING SCREAMING_SNAKE_CASE_ = auto_class_update(FlaxAutoModelForQuestionAnswering, head_doc="""question answering""") class UpperCamelCase__ ( _BaseAutoModelClass ): '''simple docstring''' __snake_case : Tuple = FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING SCREAMING_SNAKE_CASE_ = auto_class_update( FlaxAutoModelForTokenClassification, head_doc="""token classification""" ) class UpperCamelCase__ ( _BaseAutoModelClass ): '''simple docstring''' __snake_case : Union[str, Any] = FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING SCREAMING_SNAKE_CASE_ = auto_class_update(FlaxAutoModelForMultipleChoice, head_doc="""multiple choice""") class UpperCamelCase__ ( _BaseAutoModelClass ): '''simple docstring''' __snake_case : List[str] = FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING SCREAMING_SNAKE_CASE_ = auto_class_update( FlaxAutoModelForNextSentencePrediction, head_doc="""next sentence prediction""" ) class UpperCamelCase__ ( _BaseAutoModelClass ): '''simple docstring''' __snake_case : Dict = FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING SCREAMING_SNAKE_CASE_ = auto_class_update( FlaxAutoModelForImageClassification, head_doc="""image classification""" ) class UpperCamelCase__ ( _BaseAutoModelClass ): '''simple docstring''' __snake_case : Dict = FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING SCREAMING_SNAKE_CASE_ = auto_class_update(FlaxAutoModelForVisionaSeq, head_doc="""vision-to-text modeling""") class UpperCamelCase__ ( _BaseAutoModelClass ): '''simple docstring''' __snake_case : Optional[Any] = FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING SCREAMING_SNAKE_CASE_ = auto_class_update( FlaxAutoModelForSpeechSeqaSeq, head_doc="""sequence-to-sequence speech-to-text modeling""" )
296
1
import argparse import os from transformers.utils import direct_transformers_import # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_task_guides.py SCREAMING_SNAKE_CASE_ = """src/transformers""" SCREAMING_SNAKE_CASE_ = """docs/source/en/tasks""" def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Optional[Any]: '''simple docstring''' with open(_SCREAMING_SNAKE_CASE , """r""" , encoding="""utf-8""" , newline="""\n""" ) as f: SCREAMING_SNAKE_CASE = f.readlines() # Find the start prompt. SCREAMING_SNAKE_CASE = 0 while not lines[start_index].startswith(_SCREAMING_SNAKE_CASE ): start_index += 1 start_index += 1 SCREAMING_SNAKE_CASE = start_index while not lines[end_index].startswith(_SCREAMING_SNAKE_CASE ): end_index += 1 end_index -= 1 while len(lines[start_index] ) <= 1: start_index += 1 while len(lines[end_index] ) <= 1: end_index -= 1 end_index += 1 return "".join(lines[start_index:end_index] ), start_index, end_index, lines # This is to make sure the transformers module imported is the one in the repo. SCREAMING_SNAKE_CASE_ = direct_transformers_import(TRANSFORMERS_PATH) SCREAMING_SNAKE_CASE_ = { """asr.md""": transformers_module.models.auto.modeling_auto.MODEL_FOR_CTC_MAPPING_NAMES, """audio_classification.md""": transformers_module.models.auto.modeling_auto.MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES, """language_modeling.md""": transformers_module.models.auto.modeling_auto.MODEL_FOR_CAUSAL_LM_MAPPING_NAMES, """image_classification.md""": transformers_module.models.auto.modeling_auto.MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES, """masked_language_modeling.md""": transformers_module.models.auto.modeling_auto.MODEL_FOR_MASKED_LM_MAPPING_NAMES, """multiple_choice.md""": transformers_module.models.auto.modeling_auto.MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES, """object_detection.md""": transformers_module.models.auto.modeling_auto.MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES, """question_answering.md""": transformers_module.models.auto.modeling_auto.MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES, """semantic_segmentation.md""": transformers_module.models.auto.modeling_auto.MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES, """sequence_classification.md""": transformers_module.models.auto.modeling_auto.MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES, """summarization.md""": transformers_module.models.auto.modeling_auto.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES, """token_classification.md""": transformers_module.models.auto.modeling_auto.MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES, """translation.md""": transformers_module.models.auto.modeling_auto.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES, """video_classification.md""": transformers_module.models.auto.modeling_auto.MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING_NAMES, """document_question_answering.md""": transformers_module.models.auto.modeling_auto.MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES, """monocular_depth_estimation.md""": transformers_module.models.auto.modeling_auto.MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES, } # This list contains model types used in some task guides that are not in `CONFIG_MAPPING_NAMES` (therefore not in any # `MODEL_MAPPING_NAMES` or any `MODEL_FOR_XXX_MAPPING_NAMES`). SCREAMING_SNAKE_CASE_ = { """summarization.md""": ("""nllb""",), """translation.md""": ("""nllb""",), } def __lowercase ( _SCREAMING_SNAKE_CASE ) -> List[str]: '''simple docstring''' SCREAMING_SNAKE_CASE = TASK_GUIDE_TO_MODELS[task_guide] SCREAMING_SNAKE_CASE = SPECIAL_TASK_GUIDE_TO_MODEL_TYPES.get(_SCREAMING_SNAKE_CASE , set() ) SCREAMING_SNAKE_CASE = { code: name for code, name in transformers_module.MODEL_NAMES_MAPPING.items() if (code in model_maping_names or code in special_model_types) } return ", ".join([F"""[{name}](../model_doc/{code})""" for code, name in model_names.items()] ) + "\n" def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=False ) -> Dict: '''simple docstring''' SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE = _find_text_in_file( filename=os.path.join(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) , start_prompt="""<!--This tip is automatically generated by `make fix-copies`, do not fill manually!-->""" , end_prompt="""<!--End of the generated tip-->""" , ) SCREAMING_SNAKE_CASE = get_model_list_for_task(_SCREAMING_SNAKE_CASE ) if current_list != new_list: if overwrite: with open(os.path.join(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) , """w""" , encoding="""utf-8""" , newline="""\n""" ) as f: f.writelines(lines[:start_index] + [new_list] + lines[end_index:] ) else: raise ValueError( F"""The list of models that can be used in the {task_guide} guide needs an update. Run `make fix-copies`""" """ to fix this.""" ) if __name__ == "__main__": SCREAMING_SNAKE_CASE_ = argparse.ArgumentParser() parser.add_argument("""--fix_and_overwrite""", action="""store_true""", help="""Whether to fix inconsistencies.""") SCREAMING_SNAKE_CASE_ = parser.parse_args() for task_guide in TASK_GUIDE_TO_MODELS.keys(): check_model_list_for_task(task_guide, args.fix_and_overwrite)
296
from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ..auto import CONFIG_MAPPING SCREAMING_SNAKE_CASE_ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE_ = { """microsoft/table-transformer-detection""": ( """https://huggingface.co/microsoft/table-transformer-detection/resolve/main/config.json""" ), } class UpperCamelCase__ ( lowerCAmelCase_ ): '''simple docstring''' __snake_case : Union[str, Any] = "table-transformer" __snake_case : Union[str, Any] = ["past_key_values"] __snake_case : List[Any] = { "hidden_size": "d_model", "num_attention_heads": "encoder_attention_heads", } def __init__( self : Optional[int] ,lowerCamelCase__ : Optional[Any]=True ,lowerCamelCase__ : Optional[Any]=None ,lowerCamelCase__ : List[Any]=3 ,lowerCamelCase__ : Optional[int]=100 ,lowerCamelCase__ : List[Any]=6 ,lowerCamelCase__ : Dict=2048 ,lowerCamelCase__ : List[Any]=8 ,lowerCamelCase__ : Dict=6 ,lowerCamelCase__ : Dict=2048 ,lowerCamelCase__ : Any=8 ,lowerCamelCase__ : Optional[int]=0.0 ,lowerCamelCase__ : int=0.0 ,lowerCamelCase__ : List[Any]=True ,lowerCamelCase__ : Optional[int]="relu" ,lowerCamelCase__ : Tuple=256 ,lowerCamelCase__ : Any=0.1 ,lowerCamelCase__ : Optional[Any]=0.0 ,lowerCamelCase__ : Tuple=0.0 ,lowerCamelCase__ : List[Any]=0.02 ,lowerCamelCase__ : int=1.0 ,lowerCamelCase__ : List[str]=False ,lowerCamelCase__ : Optional[Any]="sine" ,lowerCamelCase__ : List[str]="resnet50" ,lowerCamelCase__ : Optional[Any]=True ,lowerCamelCase__ : List[str]=False ,lowerCamelCase__ : int=1 ,lowerCamelCase__ : Dict=5 ,lowerCamelCase__ : Tuple=2 ,lowerCamelCase__ : Union[str, Any]=1 ,lowerCamelCase__ : str=1 ,lowerCamelCase__ : Any=5 ,lowerCamelCase__ : Tuple=2 ,lowerCamelCase__ : str=0.1 ,**lowerCamelCase__ : List[str] ,) -> Optional[int]: '''simple docstring''' if backbone_config is not None and use_timm_backbone: raise ValueError("""You can't specify both `backbone_config` and `use_timm_backbone`.""" ) if not use_timm_backbone: if backbone_config is None: logger.info("""`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.""" ) SCREAMING_SNAKE_CASE = CONFIG_MAPPING["""resnet"""](out_features=["""stage4"""] ) elif isinstance(lowerCamelCase__ ,lowerCamelCase__ ): SCREAMING_SNAKE_CASE = backbone_config.get("""model_type""" ) SCREAMING_SNAKE_CASE = CONFIG_MAPPING[backbone_model_type] SCREAMING_SNAKE_CASE = config_class.from_dict(lowerCamelCase__ ) # set timm attributes to None SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE = None, None, None SCREAMING_SNAKE_CASE = use_timm_backbone SCREAMING_SNAKE_CASE = backbone_config SCREAMING_SNAKE_CASE = num_channels SCREAMING_SNAKE_CASE = num_queries SCREAMING_SNAKE_CASE = d_model SCREAMING_SNAKE_CASE = encoder_ffn_dim SCREAMING_SNAKE_CASE = encoder_layers SCREAMING_SNAKE_CASE = encoder_attention_heads SCREAMING_SNAKE_CASE = decoder_ffn_dim SCREAMING_SNAKE_CASE = decoder_layers SCREAMING_SNAKE_CASE = decoder_attention_heads SCREAMING_SNAKE_CASE = dropout SCREAMING_SNAKE_CASE = attention_dropout SCREAMING_SNAKE_CASE = activation_dropout SCREAMING_SNAKE_CASE = activation_function SCREAMING_SNAKE_CASE = init_std SCREAMING_SNAKE_CASE = init_xavier_std SCREAMING_SNAKE_CASE = encoder_layerdrop SCREAMING_SNAKE_CASE = decoder_layerdrop SCREAMING_SNAKE_CASE = encoder_layers SCREAMING_SNAKE_CASE = auxiliary_loss SCREAMING_SNAKE_CASE = position_embedding_type SCREAMING_SNAKE_CASE = backbone SCREAMING_SNAKE_CASE = use_pretrained_backbone SCREAMING_SNAKE_CASE = dilation # Hungarian matcher SCREAMING_SNAKE_CASE = class_cost SCREAMING_SNAKE_CASE = bbox_cost SCREAMING_SNAKE_CASE = giou_cost # Loss coefficients SCREAMING_SNAKE_CASE = mask_loss_coefficient SCREAMING_SNAKE_CASE = dice_loss_coefficient SCREAMING_SNAKE_CASE = bbox_loss_coefficient SCREAMING_SNAKE_CASE = giou_loss_coefficient SCREAMING_SNAKE_CASE = eos_coefficient super().__init__(is_encoder_decoder=lowerCamelCase__ ,**lowerCamelCase__ ) @property def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ) -> int: '''simple docstring''' return self.encoder_attention_heads @property def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ) -> int: '''simple docstring''' return self.d_model class UpperCamelCase__ ( lowerCAmelCase_ ): '''simple docstring''' __snake_case : int = version.parse("1.11" ) @property def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' return OrderedDict( [ ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}), ("""pixel_mask""", {0: """batch"""}), ] ) @property def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ) -> float: '''simple docstring''' return 1e-5 @property def SCREAMING_SNAKE_CASE__ ( self : Any ) -> int: '''simple docstring''' return 12
296
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available SCREAMING_SNAKE_CASE_ = { """configuration_mvp""": ["""MVP_PRETRAINED_CONFIG_ARCHIVE_MAP""", """MvpConfig""", """MvpOnnxConfig"""], """tokenization_mvp""": ["""MvpTokenizer"""], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE_ = ["""MvpTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE_ = [ """MVP_PRETRAINED_MODEL_ARCHIVE_LIST""", """MvpForCausalLM""", """MvpForConditionalGeneration""", """MvpForQuestionAnswering""", """MvpForSequenceClassification""", """MvpModel""", """MvpPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_mvp import MVP_PRETRAINED_CONFIG_ARCHIVE_MAP, MvpConfig, MvpOnnxConfig from .tokenization_mvp import MvpTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mvp_fast import MvpTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mvp import ( MVP_PRETRAINED_MODEL_ARCHIVE_LIST, MvpForCausalLM, MvpForConditionalGeneration, MvpForQuestionAnswering, MvpForSequenceClassification, MvpModel, MvpPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE_ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
296
from collections import defaultdict from math import gcd def __lowercase ( _SCREAMING_SNAKE_CASE = 1_50_00_00 ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE = defaultdict(_SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE = 2 while 2 * euclid_m * (euclid_m + 1) <= limit: for euclid_n in range((euclid_m % 2) + 1 , _SCREAMING_SNAKE_CASE , 2 ): if gcd(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) > 1: continue SCREAMING_SNAKE_CASE = 2 * euclid_m * (euclid_m + euclid_n) for perimeter in range(_SCREAMING_SNAKE_CASE , limit + 1 , _SCREAMING_SNAKE_CASE ): frequencies[perimeter] += 1 euclid_m += 1 return sum(1 for frequency in frequencies.values() if frequency == 1 ) if __name__ == "__main__": print(F'''{solution() = }''')
296
1
from __future__ import annotations def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None ) -> list[list[str]]: '''simple docstring''' SCREAMING_SNAKE_CASE = word_bank or [] # create a table SCREAMING_SNAKE_CASE = len(_SCREAMING_SNAKE_CASE ) + 1 SCREAMING_SNAKE_CASE = [] for _ in range(_SCREAMING_SNAKE_CASE ): table.append([] ) # seed value SCREAMING_SNAKE_CASE = [[]] # because empty string has empty combination # iterate through the indices for i in range(_SCREAMING_SNAKE_CASE ): # condition if table[i] != []: for word in word_bank: # slice condition if target[i : i + len(_SCREAMING_SNAKE_CASE )] == word: SCREAMING_SNAKE_CASE = [ [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(_SCREAMING_SNAKE_CASE )] += new_combinations # combinations are in reverse order so reverse for better output for combination in table[len(_SCREAMING_SNAKE_CASE )]: combination.reverse() return table[len(_SCREAMING_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"""], ) )
296
from argparse import ArgumentParser from .env import EnvironmentCommand def __lowercase ( ) -> Dict: '''simple docstring''' SCREAMING_SNAKE_CASE = ArgumentParser("""Diffusers CLI tool""" , usage="""diffusers-cli <command> [<args>]""" ) SCREAMING_SNAKE_CASE = parser.add_subparsers(help="""diffusers-cli command helpers""" ) # Register commands EnvironmentCommand.register_subcommand(_SCREAMING_SNAKE_CASE ) # Let's go SCREAMING_SNAKE_CASE = parser.parse_args() if not hasattr(_SCREAMING_SNAKE_CASE , """func""" ): parser.print_help() exit(1 ) # Run SCREAMING_SNAKE_CASE = args.func(_SCREAMING_SNAKE_CASE ) service.run() if __name__ == "__main__": main()
296
1
class UpperCamelCase__ : '''simple docstring''' def __init__( self : int ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE = {} def SCREAMING_SNAKE_CASE__ ( self : str ) -> None: '''simple docstring''' print(self.vertex ) for i in self.vertex: print(lowerCamelCase__ ,""" -> """ ,""" -> """.join([str(lowerCamelCase__ ) for j in self.vertex[i]] ) ) def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ,lowerCamelCase__ : int ,lowerCamelCase__ : int ) -> None: '''simple docstring''' if from_vertex in self.vertex: self.vertex[from_vertex].append(lowerCamelCase__ ) else: # else make a new vertex SCREAMING_SNAKE_CASE = [to_vertex] def SCREAMING_SNAKE_CASE__ ( self : Dict ) -> None: '''simple docstring''' SCREAMING_SNAKE_CASE = [False] * len(self.vertex ) # call the recursive helper function for i in range(len(self.vertex ) ): if not visited[i]: self.dfs_recursive(lowerCamelCase__ ,lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ,lowerCamelCase__ : int ,lowerCamelCase__ : list ) -> None: '''simple docstring''' SCREAMING_SNAKE_CASE = True print(lowerCamelCase__ ,end=""" """ ) # Recur for all the vertices that are adjacent to this node for i in self.vertex: if not visited[i]: self.dfs_recursive(lowerCamelCase__ ,lowerCamelCase__ ) if __name__ == "__main__": SCREAMING_SNAKE_CASE_ = Graph() g.add_edge(0, 1) g.add_edge(0, 2) g.add_edge(1, 2) g.add_edge(2, 0) g.add_edge(2, 3) g.add_edge(3, 3) g.print_graph() print("""DFS:""") g.dfs() # OUTPUT: # 0 -> 1 -> 2 # 1 -> 2 # 2 -> 0 -> 3 # 3 -> 3 # DFS: # 0 1 2 3
296
import argparse import json import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import AutoImageProcessor, SwinConfig, SwinForImageClassification def __lowercase ( _SCREAMING_SNAKE_CASE ) -> Union[str, Any]: '''simple docstring''' SCREAMING_SNAKE_CASE = SwinConfig() SCREAMING_SNAKE_CASE = swin_name.split("""_""" ) SCREAMING_SNAKE_CASE = name_split[1] SCREAMING_SNAKE_CASE = int(name_split[4] ) SCREAMING_SNAKE_CASE = int(name_split[3][-1] ) if model_size == "tiny": SCREAMING_SNAKE_CASE = 96 SCREAMING_SNAKE_CASE = (2, 2, 6, 2) SCREAMING_SNAKE_CASE = (3, 6, 12, 24) elif model_size == "small": SCREAMING_SNAKE_CASE = 96 SCREAMING_SNAKE_CASE = (2, 2, 18, 2) SCREAMING_SNAKE_CASE = (3, 6, 12, 24) elif model_size == "base": SCREAMING_SNAKE_CASE = 1_28 SCREAMING_SNAKE_CASE = (2, 2, 18, 2) SCREAMING_SNAKE_CASE = (4, 8, 16, 32) else: SCREAMING_SNAKE_CASE = 1_92 SCREAMING_SNAKE_CASE = (2, 2, 18, 2) SCREAMING_SNAKE_CASE = (6, 12, 24, 48) if "in22k" in swin_name: SCREAMING_SNAKE_CASE = 2_18_41 else: SCREAMING_SNAKE_CASE = 10_00 SCREAMING_SNAKE_CASE = """huggingface/label-files""" SCREAMING_SNAKE_CASE = """imagenet-1k-id2label.json""" SCREAMING_SNAKE_CASE = json.load(open(hf_hub_download(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , repo_type="""dataset""" ) , """r""" ) ) SCREAMING_SNAKE_CASE = {int(_SCREAMING_SNAKE_CASE ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE = idalabel SCREAMING_SNAKE_CASE = {v: k for k, v in idalabel.items()} SCREAMING_SNAKE_CASE = img_size SCREAMING_SNAKE_CASE = num_classes SCREAMING_SNAKE_CASE = embed_dim SCREAMING_SNAKE_CASE = depths SCREAMING_SNAKE_CASE = num_heads SCREAMING_SNAKE_CASE = window_size return config def __lowercase ( _SCREAMING_SNAKE_CASE ) -> Dict: '''simple docstring''' if "patch_embed.proj" in name: SCREAMING_SNAKE_CASE = name.replace("""patch_embed.proj""" , """embeddings.patch_embeddings.projection""" ) if "patch_embed.norm" in name: SCREAMING_SNAKE_CASE = name.replace("""patch_embed.norm""" , """embeddings.norm""" ) if "layers" in name: SCREAMING_SNAKE_CASE = """encoder.""" + name if "attn.proj" in name: SCREAMING_SNAKE_CASE = name.replace("""attn.proj""" , """attention.output.dense""" ) if "attn" in name: SCREAMING_SNAKE_CASE = name.replace("""attn""" , """attention.self""" ) if "norm1" in name: SCREAMING_SNAKE_CASE = name.replace("""norm1""" , """layernorm_before""" ) if "norm2" in name: SCREAMING_SNAKE_CASE = name.replace("""norm2""" , """layernorm_after""" ) if "mlp.fc1" in name: SCREAMING_SNAKE_CASE = name.replace("""mlp.fc1""" , """intermediate.dense""" ) if "mlp.fc2" in name: SCREAMING_SNAKE_CASE = name.replace("""mlp.fc2""" , """output.dense""" ) if name == "norm.weight": SCREAMING_SNAKE_CASE = """layernorm.weight""" if name == "norm.bias": SCREAMING_SNAKE_CASE = """layernorm.bias""" if "head" in name: SCREAMING_SNAKE_CASE = name.replace("""head""" , """classifier""" ) else: SCREAMING_SNAKE_CASE = """swin.""" + name return name def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Any: '''simple docstring''' for key in orig_state_dict.copy().keys(): SCREAMING_SNAKE_CASE = orig_state_dict.pop(_SCREAMING_SNAKE_CASE ) if "mask" in key: continue elif "qkv" in key: SCREAMING_SNAKE_CASE = key.split(""".""" ) SCREAMING_SNAKE_CASE = int(key_split[1] ) SCREAMING_SNAKE_CASE = int(key_split[3] ) SCREAMING_SNAKE_CASE = model.swin.encoder.layers[layer_num].blocks[block_num].attention.self.all_head_size if "weight" in key: SCREAMING_SNAKE_CASE = val[:dim, :] SCREAMING_SNAKE_CASE = val[ dim : dim * 2, : ] SCREAMING_SNAKE_CASE = val[-dim:, :] else: SCREAMING_SNAKE_CASE = val[ :dim ] SCREAMING_SNAKE_CASE = val[ dim : dim * 2 ] SCREAMING_SNAKE_CASE = val[ -dim: ] else: SCREAMING_SNAKE_CASE = val return orig_state_dict def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> List[str]: '''simple docstring''' SCREAMING_SNAKE_CASE = timm.create_model(_SCREAMING_SNAKE_CASE , pretrained=_SCREAMING_SNAKE_CASE ) timm_model.eval() SCREAMING_SNAKE_CASE = get_swin_config(_SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE = SwinForImageClassification(_SCREAMING_SNAKE_CASE ) model.eval() SCREAMING_SNAKE_CASE = convert_state_dict(timm_model.state_dict() , _SCREAMING_SNAKE_CASE ) model.load_state_dict(_SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE = """http://images.cocodataset.org/val2017/000000039769.jpg""" SCREAMING_SNAKE_CASE = AutoImageProcessor.from_pretrained("""microsoft/{}""".format(swin_name.replace("""_""" , """-""" ) ) ) SCREAMING_SNAKE_CASE = Image.open(requests.get(_SCREAMING_SNAKE_CASE , stream=_SCREAMING_SNAKE_CASE ).raw ) SCREAMING_SNAKE_CASE = image_processor(images=_SCREAMING_SNAKE_CASE , return_tensors="""pt""" ) SCREAMING_SNAKE_CASE = timm_model(inputs["""pixel_values"""] ) SCREAMING_SNAKE_CASE = model(**_SCREAMING_SNAKE_CASE ).logits assert torch.allclose(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , atol=1E-3 ) print(F"""Saving model {swin_name} to {pytorch_dump_folder_path}""" ) model.save_pretrained(_SCREAMING_SNAKE_CASE ) print(F"""Saving image processor to {pytorch_dump_folder_path}""" ) image_processor.save_pretrained(_SCREAMING_SNAKE_CASE ) if __name__ == "__main__": SCREAMING_SNAKE_CASE_ = argparse.ArgumentParser() # Required parameters parser.add_argument( """--swin_name""", default="""swin_tiny_patch4_window7_224""", type=str, help="""Name of the Swin timm model you'd like to convert.""", ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model directory.""" ) SCREAMING_SNAKE_CASE_ = parser.parse_args() convert_swin_checkpoint(args.swin_name, args.pytorch_dump_folder_path)
296
1
import unittest from transformers import CamembertTokenizer, CamembertTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.utils import is_torch_available from ...test_tokenization_common import TokenizerTesterMixin SCREAMING_SNAKE_CASE_ = get_tests_dir("""fixtures/test_sentencepiece.model""") SCREAMING_SNAKE_CASE_ = get_tests_dir("""fixtures/test_sentencepiece_bpe.model""") SCREAMING_SNAKE_CASE_ = """pt""" if is_torch_available() else """tf""" @require_sentencepiece @require_tokenizers class UpperCamelCase__ ( lowerCAmelCase_ , unittest.TestCase ): '''simple docstring''' __snake_case : Tuple = CamembertTokenizer __snake_case : Tuple = CamembertTokenizerFast __snake_case : int = True __snake_case : Union[str, Any] = True def SCREAMING_SNAKE_CASE__ ( self : Dict ) -> Optional[Any]: '''simple docstring''' super().setUp() # We have a SentencePiece fixture for testing SCREAMING_SNAKE_CASE = CamembertTokenizer(lowerCamelCase__ ) tokenizer.save_pretrained(self.tmpdirname ) def SCREAMING_SNAKE_CASE__ ( self : List[str] ) -> str: '''simple docstring''' SCREAMING_SNAKE_CASE = """<pad>""" SCREAMING_SNAKE_CASE = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(lowerCamelCase__ ) ,lowerCamelCase__ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(lowerCamelCase__ ) ,lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( self : List[str] ) -> Dict: '''simple docstring''' SCREAMING_SNAKE_CASE = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] ,"""<s>NOTUSED""" ) self.assertEqual(vocab_keys[1] ,"""<pad>""" ) self.assertEqual(vocab_keys[-1] ,"""<mask>""" ) self.assertEqual(len(lowerCamelCase__ ) ,1004 ) def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ) -> List[Any]: '''simple docstring''' self.assertEqual(self.get_tokenizer().vocab_size ,1005 ) def SCREAMING_SNAKE_CASE__ ( self : Dict ) -> Dict: '''simple docstring''' SCREAMING_SNAKE_CASE = CamembertTokenizer(lowerCamelCase__ ) tokenizer.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE = CamembertTokenizerFast.from_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE = """I was born in 92000, and this is falsé.""" SCREAMING_SNAKE_CASE = tokenizer.encode(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = rust_tokenizer.encode(lowerCamelCase__ ) self.assertListEqual(lowerCamelCase__ ,lowerCamelCase__ ) SCREAMING_SNAKE_CASE = tokenizer.encode(lowerCamelCase__ ,add_special_tokens=lowerCamelCase__ ) SCREAMING_SNAKE_CASE = rust_tokenizer.encode(lowerCamelCase__ ,add_special_tokens=lowerCamelCase__ ) self.assertListEqual(lowerCamelCase__ ,lowerCamelCase__ ) # <unk> tokens are not the same for `rust` than for `slow`. # Because spm gives back raw token instead of `unk` in EncodeAsPieces # tokens = tokenizer.tokenize(sequence) SCREAMING_SNAKE_CASE = tokenizer.convert_ids_to_tokens(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = rust_tokenizer.tokenize(lowerCamelCase__ ) self.assertListEqual(lowerCamelCase__ ,lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ) -> Optional[int]: '''simple docstring''' if not self.test_rust_tokenizer: return SCREAMING_SNAKE_CASE = self.get_tokenizer() SCREAMING_SNAKE_CASE = self.get_rust_tokenizer() SCREAMING_SNAKE_CASE = """I was born in 92000, and this is falsé.""" SCREAMING_SNAKE_CASE = tokenizer.tokenize(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = rust_tokenizer.tokenize(lowerCamelCase__ ) self.assertListEqual(lowerCamelCase__ ,lowerCamelCase__ ) SCREAMING_SNAKE_CASE = tokenizer.encode(lowerCamelCase__ ,add_special_tokens=lowerCamelCase__ ) SCREAMING_SNAKE_CASE = rust_tokenizer.encode(lowerCamelCase__ ,add_special_tokens=lowerCamelCase__ ) self.assertListEqual(lowerCamelCase__ ,lowerCamelCase__ ) SCREAMING_SNAKE_CASE = self.get_rust_tokenizer() SCREAMING_SNAKE_CASE = tokenizer.encode(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = rust_tokenizer.encode(lowerCamelCase__ ) self.assertListEqual(lowerCamelCase__ ,lowerCamelCase__ ) @slow def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ) -> Union[str, Any]: '''simple docstring''' SCREAMING_SNAKE_CASE = {"""input_ids""": [[5, 54, 7196, 297, 30, 23, 776, 18, 11, 3215, 3705, 8252, 22, 3164, 1181, 2116, 29, 16, 813, 25, 791, 3314, 20, 3446, 38, 27575, 120, 6, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [5, 468, 17, 11, 9088, 20, 1517, 8, 22804, 18818, 10, 38, 629, 607, 607, 142, 19, 7196, 867, 56, 10326, 24, 2267, 20, 416, 5072, 15612, 233, 734, 7, 2399, 27, 16, 3015, 1649, 7, 24, 20, 4338, 2399, 27, 13, 3400, 14, 13, 6189, 8, 930, 9, 6]], """attention_mask""": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]} # noqa: E501 # fmt: on # camembert is a french model. So we also use french texts. SCREAMING_SNAKE_CASE = [ """Le transformeur est un modèle d'apprentissage profond introduit en 2017, """ """utilisé principalement dans le domaine du traitement automatique des langues (TAL).""", """À l'instar des réseaux de neurones récurrents (RNN), les transformeurs sont conçus """ """pour gérer des données séquentielles, telles que le langage naturel, pour des tâches """ """telles que la traduction et la synthèse de texte.""", ] self.tokenizer_integration_test_util( expected_encoding=lowerCamelCase__ ,model_name="""camembert-base""" ,revision="""3a0641d9a1aeb7e848a74299e7e4c4bca216b4cf""" ,sequences=lowerCamelCase__ ,)
296
import os from distutils.util import strtobool def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Tuple: '''simple docstring''' for e in env_keys: SCREAMING_SNAKE_CASE = int(os.environ.get(_SCREAMING_SNAKE_CASE , -1 ) ) if val >= 0: return val return default def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=False ) -> Optional[int]: '''simple docstring''' SCREAMING_SNAKE_CASE = os.environ.get(_SCREAMING_SNAKE_CASE , str(_SCREAMING_SNAKE_CASE ) ) return strtobool(_SCREAMING_SNAKE_CASE ) == 1 # As its name indicates `strtobool` actually returns an int... def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE="no" ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE = os.environ.get(_SCREAMING_SNAKE_CASE , str(_SCREAMING_SNAKE_CASE ) ) return value
296
1
from __future__ import annotations def __lowercase ( _SCREAMING_SNAKE_CASE ) -> bool: '''simple docstring''' SCREAMING_SNAKE_CASE = len(_SCREAMING_SNAKE_CASE ) # We need to create solution object to save path. SCREAMING_SNAKE_CASE = [[0 for _ in range(_SCREAMING_SNAKE_CASE )] for _ in range(_SCREAMING_SNAKE_CASE )] SCREAMING_SNAKE_CASE = run_maze(_SCREAMING_SNAKE_CASE , 0 , 0 , _SCREAMING_SNAKE_CASE ) if solved: print("""\n""".join(str(_SCREAMING_SNAKE_CASE ) for row in solutions ) ) else: print("""No solution exists!""" ) return solved def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> bool: '''simple docstring''' SCREAMING_SNAKE_CASE = len(_SCREAMING_SNAKE_CASE ) # Final check point. if i == j == (size - 1): SCREAMING_SNAKE_CASE = 1 return True SCREAMING_SNAKE_CASE = (not i < 0) and (not j < 0) # Check lower bounds SCREAMING_SNAKE_CASE = (i < size) and (j < size) # Check upper bounds if lower_flag and upper_flag: # check for already visited and block points. SCREAMING_SNAKE_CASE = (not solutions[i][j]) and (not maze[i][j]) if block_flag: # check visited SCREAMING_SNAKE_CASE = 1 # check for directions if ( run_maze(_SCREAMING_SNAKE_CASE , i + 1 , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) or run_maze(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , j + 1 , _SCREAMING_SNAKE_CASE ) or run_maze(_SCREAMING_SNAKE_CASE , i - 1 , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) or run_maze(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , j - 1 , _SCREAMING_SNAKE_CASE ) ): return True SCREAMING_SNAKE_CASE = 0 return False return False if __name__ == "__main__": import doctest doctest.testmod()
296
import dataclasses import json import warnings from dataclasses import dataclass, field from time import time from typing import List from ..utils import logging SCREAMING_SNAKE_CASE_ = logging.get_logger(__name__) def __lowercase ( _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None ) -> List[str]: '''simple docstring''' return field(default_factory=lambda: default , metadata=_SCREAMING_SNAKE_CASE ) @dataclass class UpperCamelCase__ : '''simple docstring''' __snake_case : 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" ) } , ) __snake_case : List[int] = list_field( default=[8] , metadata={"help": "List of batch sizes for which memory and time performance will be evaluated"} ) __snake_case : List[int] = list_field( default=[8, 32, 128, 512] , metadata={"help": "List of sequence lengths for which memory and time performance will be evaluated"} , ) __snake_case : bool = field( default=lowerCAmelCase_ , metadata={"help": "Whether to benchmark inference of model. Inference can be disabled via --no-inference."} , ) __snake_case : bool = field( default=lowerCAmelCase_ , metadata={"help": "Whether to run on available cuda devices. Cuda can be disabled via --no-cuda."} , ) __snake_case : bool = field( default=lowerCAmelCase_ , metadata={"help": "Whether to run on available tpu devices. TPU can be disabled via --no-tpu."} ) __snake_case : bool = field(default=lowerCAmelCase_ , metadata={"help": "Use FP16 to accelerate inference."} ) __snake_case : bool = field(default=lowerCAmelCase_ , metadata={"help": "Benchmark training of model"} ) __snake_case : bool = field(default=lowerCAmelCase_ , metadata={"help": "Verbose memory tracing"} ) __snake_case : bool = field( default=lowerCAmelCase_ , metadata={"help": "Whether to perform speed measurements. Speed measurements can be disabled via --no-speed."} , ) __snake_case : bool = field( default=lowerCAmelCase_ , metadata={ "help": "Whether to perform memory measurements. Memory measurements can be disabled via --no-memory" } , ) __snake_case : bool = field(default=lowerCAmelCase_ , metadata={"help": "Trace memory line by line"} ) __snake_case : bool = field(default=lowerCAmelCase_ , metadata={"help": "Save result to a CSV file"} ) __snake_case : bool = field(default=lowerCAmelCase_ , metadata={"help": "Save all print statements in a log file"} ) __snake_case : bool = field(default=lowerCAmelCase_ , metadata={"help": "Whether to print environment information"} ) __snake_case : bool = field( default=lowerCAmelCase_ , 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." ) } , ) __snake_case : str = field( default=F"inference_time_{round(time() )}.csv" , metadata={"help": "CSV filename used if saving time results to csv."} , ) __snake_case : str = field( default=F"inference_memory_{round(time() )}.csv" , metadata={"help": "CSV filename used if saving memory results to csv."} , ) __snake_case : str = field( default=F"train_time_{round(time() )}.csv" , metadata={"help": "CSV filename used if saving time results to csv for training."} , ) __snake_case : str = field( default=F"train_memory_{round(time() )}.csv" , metadata={"help": "CSV filename used if saving memory results to csv for training."} , ) __snake_case : str = field( default=F"env_info_{round(time() )}.csv" , metadata={"help": "CSV filename used if saving environment information."} , ) __snake_case : str = field( default=F"log_{round(time() )}.csv" , metadata={"help": "Log filename used if print statements are saved in log."} , ) __snake_case : int = field(default=3 , metadata={"help": "Times an experiment will be run."} ) __snake_case : bool = field( default=lowerCAmelCase_ , metadata={ "help": ( "Instead of loading the model as defined in `config.architectures` if exists, just load the pretrain" " model weights." ) } , ) def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ) -> Dict: '''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 SCREAMING_SNAKE_CASE__ ( self : Optional[int] ) -> Any: '''simple docstring''' return json.dumps(dataclasses.asdict(self ) ,indent=2 ) @property def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ) -> List[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 SCREAMING_SNAKE_CASE__ ( self : Optional[int] ) -> int: '''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
296
1
import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging SCREAMING_SNAKE_CASE_ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE_ = { """microsoft/wavlm-base""": """https://huggingface.co/microsoft/wavlm-base/resolve/main/config.json""", # See all WavLM models at https://huggingface.co/models?filter=wavlm } class UpperCamelCase__ ( lowerCAmelCase_ ): '''simple docstring''' __snake_case : str = "wavlm" def __init__( self : Optional[int] ,lowerCamelCase__ : Union[str, Any]=32 ,lowerCamelCase__ : List[Any]=768 ,lowerCamelCase__ : str=12 ,lowerCamelCase__ : List[str]=12 ,lowerCamelCase__ : str=3072 ,lowerCamelCase__ : Dict="gelu" ,lowerCamelCase__ : Union[str, Any]=0.1 ,lowerCamelCase__ : str=0.1 ,lowerCamelCase__ : List[str]=0.1 ,lowerCamelCase__ : List[Any]=0.0 ,lowerCamelCase__ : int=0.1 ,lowerCamelCase__ : Dict=0.1 ,lowerCamelCase__ : str=0.02 ,lowerCamelCase__ : int=1e-5 ,lowerCamelCase__ : Tuple="group" ,lowerCamelCase__ : List[Any]="gelu" ,lowerCamelCase__ : List[str]=(512, 512, 512, 512, 512, 512, 512) ,lowerCamelCase__ : Dict=(5, 2, 2, 2, 2, 2, 2) ,lowerCamelCase__ : Dict=(10, 3, 3, 3, 3, 2, 2) ,lowerCamelCase__ : int=False ,lowerCamelCase__ : int=128 ,lowerCamelCase__ : Tuple=16 ,lowerCamelCase__ : Any=320 ,lowerCamelCase__ : str=800 ,lowerCamelCase__ : Tuple=False ,lowerCamelCase__ : Any=True ,lowerCamelCase__ : Optional[int]=0.05 ,lowerCamelCase__ : List[Any]=10 ,lowerCamelCase__ : List[str]=2 ,lowerCamelCase__ : str=0.0 ,lowerCamelCase__ : List[Any]=10 ,lowerCamelCase__ : int=320 ,lowerCamelCase__ : int=2 ,lowerCamelCase__ : Optional[int]=0.1 ,lowerCamelCase__ : Dict=100 ,lowerCamelCase__ : List[Any]=256 ,lowerCamelCase__ : List[Any]=256 ,lowerCamelCase__ : Dict=0.1 ,lowerCamelCase__ : Optional[Any]="mean" ,lowerCamelCase__ : Dict=False ,lowerCamelCase__ : Union[str, Any]=False ,lowerCamelCase__ : Optional[Any]=256 ,lowerCamelCase__ : Any=(512, 512, 512, 512, 1500) ,lowerCamelCase__ : Tuple=(5, 3, 3, 1, 1) ,lowerCamelCase__ : Optional[Any]=(1, 2, 3, 1, 1) ,lowerCamelCase__ : Optional[int]=512 ,lowerCamelCase__ : Optional[int]=80 ,lowerCamelCase__ : Optional[Any]=0 ,lowerCamelCase__ : Optional[Any]=1 ,lowerCamelCase__ : Any=2 ,lowerCamelCase__ : Union[str, Any]=False ,lowerCamelCase__ : Optional[Any]=3 ,lowerCamelCase__ : List[Any]=2 ,lowerCamelCase__ : Tuple=3 ,lowerCamelCase__ : Union[str, Any]=None ,**lowerCamelCase__ : List[Any] ,) -> Tuple: '''simple docstring''' super().__init__(**lowerCamelCase__ ,pad_token_id=lowerCamelCase__ ,bos_token_id=lowerCamelCase__ ,eos_token_id=lowerCamelCase__ ) SCREAMING_SNAKE_CASE = hidden_size SCREAMING_SNAKE_CASE = feat_extract_norm SCREAMING_SNAKE_CASE = feat_extract_activation SCREAMING_SNAKE_CASE = list(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = list(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = list(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = conv_bias SCREAMING_SNAKE_CASE = num_buckets SCREAMING_SNAKE_CASE = max_bucket_distance SCREAMING_SNAKE_CASE = num_conv_pos_embeddings SCREAMING_SNAKE_CASE = num_conv_pos_embedding_groups SCREAMING_SNAKE_CASE = len(self.conv_dim ) SCREAMING_SNAKE_CASE = num_hidden_layers SCREAMING_SNAKE_CASE = intermediate_size SCREAMING_SNAKE_CASE = hidden_act SCREAMING_SNAKE_CASE = num_attention_heads SCREAMING_SNAKE_CASE = hidden_dropout SCREAMING_SNAKE_CASE = attention_dropout SCREAMING_SNAKE_CASE = activation_dropout SCREAMING_SNAKE_CASE = feat_proj_dropout SCREAMING_SNAKE_CASE = final_dropout SCREAMING_SNAKE_CASE = layerdrop SCREAMING_SNAKE_CASE = layer_norm_eps SCREAMING_SNAKE_CASE = initializer_range SCREAMING_SNAKE_CASE = num_ctc_classes SCREAMING_SNAKE_CASE = vocab_size SCREAMING_SNAKE_CASE = do_stable_layer_norm SCREAMING_SNAKE_CASE = use_weighted_layer_sum SCREAMING_SNAKE_CASE = classifier_proj_size if ( (len(self.conv_stride ) != self.num_feat_extract_layers) or (len(self.conv_kernel ) != self.num_feat_extract_layers) or (len(self.conv_dim ) != self.num_feat_extract_layers) ): raise ValueError( """Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` ==""" """ `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) =""" F""" {len(self.conv_dim )}`, `len(config.conv_stride) = {len(self.conv_stride )}`,""" F""" `len(config.conv_kernel) = {len(self.conv_kernel )}`.""" ) # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 SCREAMING_SNAKE_CASE = apply_spec_augment SCREAMING_SNAKE_CASE = mask_time_prob SCREAMING_SNAKE_CASE = mask_time_length SCREAMING_SNAKE_CASE = mask_time_min_masks SCREAMING_SNAKE_CASE = mask_feature_prob SCREAMING_SNAKE_CASE = mask_feature_length # parameters for pretraining with codevector quantized representations SCREAMING_SNAKE_CASE = num_codevectors_per_group SCREAMING_SNAKE_CASE = num_codevector_groups SCREAMING_SNAKE_CASE = contrastive_logits_temperature SCREAMING_SNAKE_CASE = num_negatives SCREAMING_SNAKE_CASE = codevector_dim SCREAMING_SNAKE_CASE = proj_codevector_dim SCREAMING_SNAKE_CASE = diversity_loss_weight # ctc loss SCREAMING_SNAKE_CASE = ctc_loss_reduction SCREAMING_SNAKE_CASE = ctc_zero_infinity # adapter SCREAMING_SNAKE_CASE = add_adapter SCREAMING_SNAKE_CASE = adapter_kernel_size SCREAMING_SNAKE_CASE = adapter_stride SCREAMING_SNAKE_CASE = num_adapter_layers SCREAMING_SNAKE_CASE = output_hidden_size or hidden_size # SequenceClassification-specific parameter. Feel free to ignore for other classes. SCREAMING_SNAKE_CASE = classifier_proj_size # XVector-specific parameters. Feel free to ignore for other classes. SCREAMING_SNAKE_CASE = list(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = list(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = list(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = xvector_output_dim @property def SCREAMING_SNAKE_CASE__ ( self : Tuple ) -> Optional[int]: '''simple docstring''' return functools.reduce(operator.mul ,self.conv_stride ,1 )
296
import math import unittest def __lowercase ( _SCREAMING_SNAKE_CASE ) -> bool: '''simple docstring''' assert isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) and ( number >= 0 ), "'number' must been an int and positive" if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(math.sqrt(_SCREAMING_SNAKE_CASE ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True class UpperCamelCase__ ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE__ ( self : Dict ) -> Tuple: '''simple docstring''' self.assertTrue(is_prime(2 ) ) self.assertTrue(is_prime(3 ) ) self.assertTrue(is_prime(5 ) ) self.assertTrue(is_prime(7 ) ) self.assertTrue(is_prime(11 ) ) self.assertTrue(is_prime(13 ) ) self.assertTrue(is_prime(17 ) ) self.assertTrue(is_prime(19 ) ) self.assertTrue(is_prime(23 ) ) self.assertTrue(is_prime(29 ) ) def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ) -> Tuple: '''simple docstring''' with self.assertRaises(lowerCamelCase__ ): is_prime(-19 ) self.assertFalse( is_prime(0 ) ,"""Zero doesn't have any positive factors, primes must have exactly two.""" ,) self.assertFalse( is_prime(1 ) ,"""One only has 1 positive factor, primes must have exactly two.""" ,) self.assertFalse(is_prime(2 * 2 ) ) self.assertFalse(is_prime(2 * 3 ) ) self.assertFalse(is_prime(3 * 3 ) ) self.assertFalse(is_prime(3 * 5 ) ) self.assertFalse(is_prime(3 * 5 * 7 ) ) if __name__ == "__main__": unittest.main()
296
1
import unittest from transformers import MPNetConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MPNetForMaskedLM, MPNetForMultipleChoice, MPNetForQuestionAnswering, MPNetForSequenceClassification, MPNetForTokenClassification, MPNetModel, ) class UpperCamelCase__ : '''simple docstring''' def __init__( self : Tuple ,lowerCamelCase__ : Optional[int] ,lowerCamelCase__ : Any=13 ,lowerCamelCase__ : Tuple=7 ,lowerCamelCase__ : Optional[int]=True ,lowerCamelCase__ : Optional[Any]=True ,lowerCamelCase__ : List[Any]=False ,lowerCamelCase__ : Tuple=True ,lowerCamelCase__ : List[Any]=99 ,lowerCamelCase__ : Dict=64 ,lowerCamelCase__ : List[Any]=5 ,lowerCamelCase__ : Tuple=4 ,lowerCamelCase__ : Optional[Any]=64 ,lowerCamelCase__ : Union[str, Any]="gelu" ,lowerCamelCase__ : Optional[int]=0.1 ,lowerCamelCase__ : List[str]=0.1 ,lowerCamelCase__ : Tuple=512 ,lowerCamelCase__ : Tuple=16 ,lowerCamelCase__ : List[str]=2 ,lowerCamelCase__ : Tuple=0.02 ,lowerCamelCase__ : Any=3 ,lowerCamelCase__ : str=4 ,lowerCamelCase__ : List[Any]=None ,) -> Union[str, Any]: '''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 def SCREAMING_SNAKE_CASE__ ( self : List[str] ) -> str: '''simple docstring''' return MPNetConfig.from_pretrained("""microsoft/mpnet-base""" ) def SCREAMING_SNAKE_CASE__ ( self : Dict ) -> Any: '''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 SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = None if self.use_labels: SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] ,self.type_sequence_label_size ) SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] ,self.num_labels ) SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] ,self.num_choices ) SCREAMING_SNAKE_CASE = self.get_config() return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ) -> int: '''simple docstring''' return MPNetConfig( 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 ,initializer_range=self.initializer_range ,) def SCREAMING_SNAKE_CASE__ ( self : Any ,lowerCamelCase__ : Tuple ,lowerCamelCase__ : Union[str, Any] ,lowerCamelCase__ : Tuple ,lowerCamelCase__ : List[str] ,lowerCamelCase__ : Optional[Any] ,lowerCamelCase__ : Dict ) -> List[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE = MPNetModel(config=lowerCamelCase__ ) model.to(lowerCamelCase__ ) model.eval() SCREAMING_SNAKE_CASE = model(lowerCamelCase__ ,lowerCamelCase__ ) SCREAMING_SNAKE_CASE = model(lowerCamelCase__ ) 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 SCREAMING_SNAKE_CASE__ ( self : Any ,lowerCamelCase__ : Optional[int] ,lowerCamelCase__ : Tuple ,lowerCamelCase__ : Tuple ,lowerCamelCase__ : Union[str, Any] ,lowerCamelCase__ : Dict ,lowerCamelCase__ : Tuple ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE = MPNetForQuestionAnswering(config=lowerCamelCase__ ) model.to(lowerCamelCase__ ) model.eval() SCREAMING_SNAKE_CASE = model( lowerCamelCase__ ,attention_mask=lowerCamelCase__ ,start_positions=lowerCamelCase__ ,end_positions=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) ) def SCREAMING_SNAKE_CASE__ ( self : Any ,lowerCamelCase__ : List[Any] ,lowerCamelCase__ : Optional[Any] ,lowerCamelCase__ : List[str] ,lowerCamelCase__ : Optional[Any] ,lowerCamelCase__ : Union[str, Any] ,lowerCamelCase__ : Tuple ) -> List[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE = self.num_labels SCREAMING_SNAKE_CASE = MPNetForSequenceClassification(lowerCamelCase__ ) model.to(lowerCamelCase__ ) model.eval() SCREAMING_SNAKE_CASE = model(lowerCamelCase__ ,attention_mask=lowerCamelCase__ ,labels=lowerCamelCase__ ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_labels) ) def SCREAMING_SNAKE_CASE__ ( self : Tuple ,lowerCamelCase__ : int ,lowerCamelCase__ : List[Any] ,lowerCamelCase__ : Dict ,lowerCamelCase__ : str ,lowerCamelCase__ : List[str] ,lowerCamelCase__ : Tuple ) -> str: '''simple docstring''' SCREAMING_SNAKE_CASE = self.num_choices SCREAMING_SNAKE_CASE = MPNetForMultipleChoice(config=lowerCamelCase__ ) model.to(lowerCamelCase__ ) model.eval() SCREAMING_SNAKE_CASE = input_ids.unsqueeze(1 ).expand(-1 ,self.num_choices ,-1 ).contiguous() SCREAMING_SNAKE_CASE = input_mask.unsqueeze(1 ).expand(-1 ,self.num_choices ,-1 ).contiguous() SCREAMING_SNAKE_CASE = model( lowerCamelCase__ ,attention_mask=lowerCamelCase__ ,labels=lowerCamelCase__ ,) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_choices) ) def SCREAMING_SNAKE_CASE__ ( self : str ,lowerCamelCase__ : Any ,lowerCamelCase__ : Optional[int] ,lowerCamelCase__ : Optional[int] ,lowerCamelCase__ : Dict ,lowerCamelCase__ : Tuple ,lowerCamelCase__ : str ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE = self.num_labels SCREAMING_SNAKE_CASE = MPNetForTokenClassification(config=lowerCamelCase__ ) model.to(lowerCamelCase__ ) model.eval() SCREAMING_SNAKE_CASE = model(lowerCamelCase__ ,attention_mask=lowerCamelCase__ ,labels=lowerCamelCase__ ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.num_labels) ) def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ) -> Optional[Any]: '''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)) = config_and_inputs SCREAMING_SNAKE_CASE = {"""input_ids""": input_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class UpperCamelCase__ ( lowerCAmelCase_ , lowerCAmelCase_ , unittest.TestCase ): '''simple docstring''' __snake_case : List[Any] = ( ( MPNetForMaskedLM, MPNetForMultipleChoice, MPNetForQuestionAnswering, MPNetForSequenceClassification, MPNetForTokenClassification, MPNetModel, ) if is_torch_available() else () ) __snake_case : str = ( { "feature-extraction": MPNetModel, "fill-mask": MPNetForMaskedLM, "question-answering": MPNetForQuestionAnswering, "text-classification": MPNetForSequenceClassification, "token-classification": MPNetForTokenClassification, "zero-shot": MPNetForSequenceClassification, } if is_torch_available() else {} ) __snake_case : Tuple = False __snake_case : Tuple = True def SCREAMING_SNAKE_CASE__ ( self : int ) -> Tuple: '''simple docstring''' SCREAMING_SNAKE_CASE = MPNetModelTester(self ) SCREAMING_SNAKE_CASE = ConfigTester(self ,config_class=lowerCamelCase__ ,hidden_size=37 ) def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ) -> Optional[int]: '''simple docstring''' self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE__ ( self : Dict ) -> Optional[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mpnet_model(*lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ) -> Dict: '''simple docstring''' SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mpnet_for_sequence_classification(*lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( self : int ) -> Optional[int]: '''simple docstring''' SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mpnet_for_multiple_choice(*lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ) -> Union[str, Any]: '''simple docstring''' SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mpnet_for_token_classification(*lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( self : List[Any] ) -> Tuple: '''simple docstring''' SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mpnet_for_question_answering(*lowerCamelCase__ ) @require_torch class UpperCamelCase__ ( unittest.TestCase ): '''simple docstring''' @slow def SCREAMING_SNAKE_CASE__ ( self : Tuple ) -> Tuple: '''simple docstring''' SCREAMING_SNAKE_CASE = MPNetModel.from_pretrained("""microsoft/mpnet-base""" ) SCREAMING_SNAKE_CASE = torch.tensor([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 1588, 2]] ) SCREAMING_SNAKE_CASE = model(lowerCamelCase__ )[0] SCREAMING_SNAKE_CASE = torch.Size((1, 11, 768) ) self.assertEqual(output.shape ,lowerCamelCase__ ) SCREAMING_SNAKE_CASE = torch.tensor( [[[-0.0550, 0.1943, -0.0740], [-0.0562, 0.2211, -0.0579], [-0.0437, 0.3337, -0.0641]]] ) # compare the actual values for a slice. self.assertTrue(torch.allclose(output[:, :3, :3] ,lowerCamelCase__ ,atol=1e-4 ) )
296
import random class UpperCamelCase__ : '''simple docstring''' @staticmethod def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ : str ) -> tuple[list[int], list[int]]: '''simple docstring''' SCREAMING_SNAKE_CASE = [ord(lowerCamelCase__ ) for i in text] SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = [] for i in plain: SCREAMING_SNAKE_CASE = random.randint(1 ,300 ) SCREAMING_SNAKE_CASE = (i + k) * k cipher.append(lowerCamelCase__ ) key.append(lowerCamelCase__ ) return cipher, key @staticmethod def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ : list[int] ,lowerCamelCase__ : list[int] ) -> str: '''simple docstring''' SCREAMING_SNAKE_CASE = [] for i in range(len(lowerCamelCase__ ) ): SCREAMING_SNAKE_CASE = int((cipher[i] - (key[i]) ** 2) / key[i] ) plain.append(chr(lowerCamelCase__ ) ) return "".join(lowerCamelCase__ ) if __name__ == "__main__": SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = Onepad().encrypt("""Hello""") print(c, k) print(Onepad().decrypt(c, k))
296
1
def __lowercase ( _SCREAMING_SNAKE_CASE ) -> int: '''simple docstring''' if not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): raise ValueError("""Input must be an integer""" ) if input_num <= 0: raise ValueError("""Input must be positive""" ) return sum( divisor for divisor in range(1 , input_num // 2 + 1 ) if input_num % divisor == 0 ) if __name__ == "__main__": import doctest doctest.testmod()
296
from typing import List from ...configuration_utils import PretrainedConfig from ...utils import logging SCREAMING_SNAKE_CASE_ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE_ = { """snap-research/efficientformer-l1-300""": ( """https://huggingface.co/snap-research/efficientformer-l1-300/resolve/main/config.json""" ), } class UpperCamelCase__ ( lowerCAmelCase_ ): '''simple docstring''' __snake_case : int = "efficientformer" def __init__( self : Optional[int] ,lowerCamelCase__ : List[int] = [3, 2, 6, 4] ,lowerCamelCase__ : List[int] = [48, 96, 224, 448] ,lowerCamelCase__ : List[bool] = [True, True, True, True] ,lowerCamelCase__ : int = 448 ,lowerCamelCase__ : int = 32 ,lowerCamelCase__ : int = 4 ,lowerCamelCase__ : int = 7 ,lowerCamelCase__ : int = 5 ,lowerCamelCase__ : int = 8 ,lowerCamelCase__ : int = 4 ,lowerCamelCase__ : float = 0.0 ,lowerCamelCase__ : int = 16 ,lowerCamelCase__ : int = 3 ,lowerCamelCase__ : int = 3 ,lowerCamelCase__ : int = 3 ,lowerCamelCase__ : int = 2 ,lowerCamelCase__ : int = 1 ,lowerCamelCase__ : float = 0.0 ,lowerCamelCase__ : int = 1 ,lowerCamelCase__ : bool = True ,lowerCamelCase__ : bool = True ,lowerCamelCase__ : float = 1e-5 ,lowerCamelCase__ : str = "gelu" ,lowerCamelCase__ : float = 0.02 ,lowerCamelCase__ : float = 1e-1_2 ,lowerCamelCase__ : int = 224 ,lowerCamelCase__ : float = 1e-0_5 ,**lowerCamelCase__ : str ,) -> None: '''simple docstring''' super().__init__(**lowerCamelCase__ ) SCREAMING_SNAKE_CASE = hidden_act SCREAMING_SNAKE_CASE = hidden_dropout_prob SCREAMING_SNAKE_CASE = hidden_sizes SCREAMING_SNAKE_CASE = num_hidden_layers SCREAMING_SNAKE_CASE = num_attention_heads SCREAMING_SNAKE_CASE = initializer_range SCREAMING_SNAKE_CASE = layer_norm_eps SCREAMING_SNAKE_CASE = patch_size SCREAMING_SNAKE_CASE = num_channels SCREAMING_SNAKE_CASE = depths SCREAMING_SNAKE_CASE = mlp_expansion_ratio SCREAMING_SNAKE_CASE = downsamples SCREAMING_SNAKE_CASE = dim SCREAMING_SNAKE_CASE = key_dim SCREAMING_SNAKE_CASE = attention_ratio SCREAMING_SNAKE_CASE = resolution SCREAMING_SNAKE_CASE = pool_size SCREAMING_SNAKE_CASE = downsample_patch_size SCREAMING_SNAKE_CASE = downsample_stride SCREAMING_SNAKE_CASE = downsample_pad SCREAMING_SNAKE_CASE = drop_path_rate SCREAMING_SNAKE_CASE = num_metaad_blocks SCREAMING_SNAKE_CASE = distillation SCREAMING_SNAKE_CASE = use_layer_scale SCREAMING_SNAKE_CASE = layer_scale_init_value SCREAMING_SNAKE_CASE = image_size SCREAMING_SNAKE_CASE = batch_norm_eps
296
1
import json import os from typing import Dict, List, Optional, Tuple import regex as re from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging SCREAMING_SNAKE_CASE_ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE_ = { """vocab_file""": """vocab.json""", """merges_file""": """merges.txt""", """tokenizer_config_file""": """tokenizer_config.json""", } SCREAMING_SNAKE_CASE_ = { """vocab_file""": { """facebook/blenderbot_small-90M""": """https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/vocab.json""" }, """merges_file""": { """facebook/blenderbot_small-90M""": """https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/merges.txt""" }, """tokenizer_config_file""": { """facebook/blenderbot_small-90M""": ( """https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/tokenizer_config.json""" ) }, } SCREAMING_SNAKE_CASE_ = {"""facebook/blenderbot_small-90M""": 5_1_2} def __lowercase ( _SCREAMING_SNAKE_CASE ) -> str: '''simple docstring''' SCREAMING_SNAKE_CASE = set() SCREAMING_SNAKE_CASE = word[0] for char in word[1:]: pairs.add((prev_char, char) ) SCREAMING_SNAKE_CASE = char SCREAMING_SNAKE_CASE = set(_SCREAMING_SNAKE_CASE ) return pairs class UpperCamelCase__ ( lowerCAmelCase_ ): '''simple docstring''' __snake_case : Tuple = VOCAB_FILES_NAMES __snake_case : str = PRETRAINED_VOCAB_FILES_MAP __snake_case : Optional[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __snake_case : str = ["input_ids", "attention_mask"] def __init__( self : Any ,lowerCamelCase__ : Tuple ,lowerCamelCase__ : Optional[Any] ,lowerCamelCase__ : Dict="__start__" ,lowerCamelCase__ : int="__end__" ,lowerCamelCase__ : List[str]="__unk__" ,lowerCamelCase__ : int="__null__" ,**lowerCamelCase__ : List[str] ,) -> Optional[int]: '''simple docstring''' super().__init__(unk_token=lowerCamelCase__ ,bos_token=lowerCamelCase__ ,eos_token=lowerCamelCase__ ,pad_token=lowerCamelCase__ ,**lowerCamelCase__ ) with open(lowerCamelCase__ ,encoding="""utf-8""" ) as vocab_handle: SCREAMING_SNAKE_CASE = json.load(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = {v: k for k, v in self.encoder.items()} with open(lowerCamelCase__ ,encoding="""utf-8""" ) as merges_handle: SCREAMING_SNAKE_CASE = merges_handle.read().split("""\n""" )[1:-1] SCREAMING_SNAKE_CASE = [tuple(merge.split() ) for merge in merges] SCREAMING_SNAKE_CASE = dict(zip(lowerCamelCase__ ,range(len(lowerCamelCase__ ) ) ) ) SCREAMING_SNAKE_CASE = {} @property def SCREAMING_SNAKE_CASE__ ( self : str ) -> int: '''simple docstring''' return len(self.encoder ) def SCREAMING_SNAKE_CASE__ ( self : Any ) -> Dict: '''simple docstring''' return dict(self.encoder ,**self.added_tokens_encoder ) def SCREAMING_SNAKE_CASE__ ( self : int ,lowerCamelCase__ : str ) -> str: '''simple docstring''' if token in self.cache: return self.cache[token] SCREAMING_SNAKE_CASE = re.sub("""([.,!?()])""" ,R""" \1""" ,lowerCamelCase__ ) SCREAMING_SNAKE_CASE = re.sub("""(')""" ,R""" \1 """ ,lowerCamelCase__ ) SCREAMING_SNAKE_CASE = re.sub(R"""\s{2,}""" ,""" """ ,lowerCamelCase__ ) if "\n" in token: SCREAMING_SNAKE_CASE = token.replace("""\n""" ,""" __newln__""" ) SCREAMING_SNAKE_CASE = token.split(""" """ ) SCREAMING_SNAKE_CASE = [] for token in tokens: if not len(lowerCamelCase__ ): continue SCREAMING_SNAKE_CASE = token.lower() SCREAMING_SNAKE_CASE = tuple(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = tuple(list(word[:-1] ) + [word[-1] + """</w>"""] ) SCREAMING_SNAKE_CASE = get_pairs(lowerCamelCase__ ) if not pairs: words.append(lowerCamelCase__ ) continue while True: SCREAMING_SNAKE_CASE = min(lowerCamelCase__ ,key=lambda lowerCamelCase__ : self.bpe_ranks.get(lowerCamelCase__ ,float("""inf""" ) ) ) if bigram not in self.bpe_ranks: break SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE = bigram SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = 0 while i < len(lowerCamelCase__ ): try: SCREAMING_SNAKE_CASE = word.index(lowerCamelCase__ ,lowerCamelCase__ ) new_word.extend(word[i:j] ) SCREAMING_SNAKE_CASE = j except ValueError: new_word.extend(word[i:] ) break if word[i] == first and i < len(lowerCamelCase__ ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 SCREAMING_SNAKE_CASE = tuple(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = new_word if len(lowerCamelCase__ ) == 1: break else: SCREAMING_SNAKE_CASE = get_pairs(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = """@@ """.join(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = word[:-4] SCREAMING_SNAKE_CASE = word words.append(lowerCamelCase__ ) return " ".join(lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( self : int ,lowerCamelCase__ : str ) -> List[str]: '''simple docstring''' SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = re.findall(R"""\S+\n?""" ,lowerCamelCase__ ) for token in words: split_tokens.extend(list(self.bpe(lowerCamelCase__ ).split(""" """ ) ) ) return split_tokens def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ,lowerCamelCase__ : str ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE = token.lower() return self.encoder.get(lowerCamelCase__ ,self.encoder.get(self.unk_token ) ) def SCREAMING_SNAKE_CASE__ ( self : Tuple ,lowerCamelCase__ : int ) -> str: '''simple docstring''' return self.decoder.get(lowerCamelCase__ ,self.unk_token ) def SCREAMING_SNAKE_CASE__ ( self : int ,lowerCamelCase__ : List[str] ) -> str: '''simple docstring''' SCREAMING_SNAKE_CASE = """ """.join(lowerCamelCase__ ).replace("""@@ """ ,"""""" ).strip() return out_string def SCREAMING_SNAKE_CASE__ ( self : Dict ,lowerCamelCase__ : str ,lowerCamelCase__ : Optional[str] = None ) -> Tuple[str]: '''simple docstring''' if not os.path.isdir(lowerCamelCase__ ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return SCREAMING_SNAKE_CASE = os.path.join( lowerCamelCase__ ,(filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) SCREAMING_SNAKE_CASE = os.path.join( lowerCamelCase__ ,(filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""merges_file"""] ) with open(lowerCamelCase__ ,"""w""" ,encoding="""utf-8""" ) as f: f.write(json.dumps(self.encoder ,indent=2 ,sort_keys=lowerCamelCase__ ,ensure_ascii=lowerCamelCase__ ) + """\n""" ) SCREAMING_SNAKE_CASE = 0 with open(lowerCamelCase__ ,"""w""" ,encoding="""utf-8""" ) as writer: writer.write("""#version: 0.2\n""" ) for bpe_tokens, token_index in sorted(self.bpe_ranks.items() ,key=lambda lowerCamelCase__ : kv[1] ): if index != token_index: logger.warning( F"""Saving vocabulary to {merge_file}: BPE merge indices are not consecutive.""" """ Please check that the tokenizer is not corrupted!""" ) SCREAMING_SNAKE_CASE = token_index writer.write(""" """.join(lowerCamelCase__ ) + """\n""" ) index += 1 return vocab_file, merge_file
296
import importlib import shutil import threading import warnings from typing import List import fsspec import fsspec.asyn from . import compression from .hffilesystem import HfFileSystem SCREAMING_SNAKE_CASE_ = importlib.util.find_spec("""s3fs""") is not None if _has_safs: from .safilesystem import SaFileSystem # noqa: F401 SCREAMING_SNAKE_CASE_ = [ compression.BzaFileSystem, compression.GzipFileSystem, compression.LzaFileSystem, compression.XzFileSystem, compression.ZstdFileSystem, ] # Register custom filesystems for fs_class in COMPRESSION_FILESYSTEMS + [HfFileSystem]: if fs_class.protocol in fsspec.registry and fsspec.registry[fs_class.protocol] is not fs_class: warnings.warn(F'''A filesystem protocol was already set for {fs_class.protocol} and will be overwritten.''') fsspec.register_implementation(fs_class.protocol, fs_class, clobber=True) def __lowercase ( _SCREAMING_SNAKE_CASE ) -> str: '''simple docstring''' if "://" in dataset_path: SCREAMING_SNAKE_CASE = dataset_path.split("""://""" )[1] return dataset_path def __lowercase ( _SCREAMING_SNAKE_CASE ) -> bool: '''simple docstring''' if fs is not None and fs.protocol != "file": return True else: return False def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Dict: '''simple docstring''' SCREAMING_SNAKE_CASE = not is_remote_filesystem(_SCREAMING_SNAKE_CASE ) if is_local: # LocalFileSystem.mv does copy + rm, it is more efficient to simply move a local directory shutil.move(fs._strip_protocol(_SCREAMING_SNAKE_CASE ) , fs._strip_protocol(_SCREAMING_SNAKE_CASE ) ) else: fs.mv(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , recursive=_SCREAMING_SNAKE_CASE ) def __lowercase ( ) -> None: '''simple docstring''' if hasattr(fsspec.asyn , """reset_lock""" ): # for future fsspec>2022.05.0 fsspec.asyn.reset_lock() else: SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = threading.Lock()
296
1
from __future__ import annotations import time from collections.abc import Sequence from random import randint from matplotlib import pyplot as plt def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> tuple[int | None, int | None, float]: '''simple docstring''' if not arr: return None, None, 0 if low == high: return low, high, arr[low] SCREAMING_SNAKE_CASE = (low + high) // 2 SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE = max_subarray(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE = max_subarray(_SCREAMING_SNAKE_CASE , mid + 1 , _SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE = max_cross_sum(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if left_sum >= right_sum and left_sum >= cross_sum: return left_low, left_high, left_sum elif right_sum >= left_sum and right_sum >= cross_sum: return right_low, right_high, right_sum return cross_left, cross_right, cross_sum def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> tuple[int, int, float]: '''simple docstring''' SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE = float("""-inf""" ), -1 SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE = float("""-inf""" ), -1 SCREAMING_SNAKE_CASE = 0 for i in range(_SCREAMING_SNAKE_CASE , low - 1 , -1 ): summ += arr[i] if summ > left_sum: SCREAMING_SNAKE_CASE = summ SCREAMING_SNAKE_CASE = i SCREAMING_SNAKE_CASE = 0 for i in range(mid + 1 , high + 1 ): summ += arr[i] if summ > right_sum: SCREAMING_SNAKE_CASE = summ SCREAMING_SNAKE_CASE = i return max_left, max_right, (left_sum + right_sum) def __lowercase ( _SCREAMING_SNAKE_CASE ) -> float: '''simple docstring''' SCREAMING_SNAKE_CASE = [randint(1 , _SCREAMING_SNAKE_CASE ) for _ in range(_SCREAMING_SNAKE_CASE )] SCREAMING_SNAKE_CASE = time.time() max_subarray(_SCREAMING_SNAKE_CASE , 0 , input_size - 1 ) SCREAMING_SNAKE_CASE = time.time() return end - start def __lowercase ( ) -> None: '''simple docstring''' SCREAMING_SNAKE_CASE = [10, 1_00, 10_00, 1_00_00, 5_00_00, 10_00_00, 20_00_00, 30_00_00, 40_00_00, 50_00_00] SCREAMING_SNAKE_CASE = [time_max_subarray(_SCREAMING_SNAKE_CASE ) for input_size in input_sizes] print("""No of Inputs\t\tTime Taken""" ) for input_size, runtime in zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): print(_SCREAMING_SNAKE_CASE , """\t\t""" , _SCREAMING_SNAKE_CASE ) plt.plot(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) plt.xlabel("""Number of Inputs""" ) plt.ylabel("""Time taken in seconds""" ) plt.show() if __name__ == "__main__": from doctest import testmod testmod()
296
import unittest import numpy as np import torch from diffusers import KarrasVePipeline, KarrasVeScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class UpperCamelCase__ ( unittest.TestCase ): '''simple docstring''' @property def SCREAMING_SNAKE_CASE__ ( self : str ) -> Optional[int]: '''simple docstring''' torch.manual_seed(0 ) SCREAMING_SNAKE_CASE = UNetaDModel( block_out_channels=(32, 64) ,layers_per_block=2 ,sample_size=32 ,in_channels=3 ,out_channels=3 ,down_block_types=("""DownBlock2D""", """AttnDownBlock2D""") ,up_block_types=("""AttnUpBlock2D""", """UpBlock2D""") ,) return model def SCREAMING_SNAKE_CASE__ ( self : Tuple ) -> Union[str, Any]: '''simple docstring''' SCREAMING_SNAKE_CASE = self.dummy_uncond_unet SCREAMING_SNAKE_CASE = KarrasVeScheduler() SCREAMING_SNAKE_CASE = KarrasVePipeline(unet=lowerCamelCase__ ,scheduler=lowerCamelCase__ ) pipe.to(lowerCamelCase__ ) pipe.set_progress_bar_config(disable=lowerCamelCase__ ) SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE = pipe(num_inference_steps=2 ,generator=lowerCamelCase__ ,output_type="""numpy""" ).images SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE = pipe(num_inference_steps=2 ,generator=lowerCamelCase__ ,output_type="""numpy""" ,return_dict=lowerCamelCase__ )[0] SCREAMING_SNAKE_CASE = image[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) SCREAMING_SNAKE_CASE = np.array([0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 @slow @require_torch class UpperCamelCase__ ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ) -> Optional[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE = """google/ncsnpp-celebahq-256""" SCREAMING_SNAKE_CASE = UNetaDModel.from_pretrained(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = KarrasVeScheduler() SCREAMING_SNAKE_CASE = KarrasVePipeline(unet=lowerCamelCase__ ,scheduler=lowerCamelCase__ ) pipe.to(lowerCamelCase__ ) pipe.set_progress_bar_config(disable=lowerCamelCase__ ) SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE = pipe(num_inference_steps=20 ,generator=lowerCamelCase__ ,output_type="""numpy""" ).images SCREAMING_SNAKE_CASE = image[0, -3:, -3:, -1] assert image.shape == (1, 256, 256, 3) SCREAMING_SNAKE_CASE = np.array([0.578, 0.5811, 0.5924, 0.5809, 0.587, 0.5886, 0.5861, 0.5802, 0.586] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
296
1
from typing import List from .keymap import KEYMAP, get_character def __lowercase ( _SCREAMING_SNAKE_CASE ) -> Optional[int]: '''simple docstring''' def decorator(_SCREAMING_SNAKE_CASE ): SCREAMING_SNAKE_CASE = getattr(_SCREAMING_SNAKE_CASE , """handle_key""" , [] ) handle += [key] setattr(_SCREAMING_SNAKE_CASE , """handle_key""" , _SCREAMING_SNAKE_CASE ) return func return decorator def __lowercase ( *_SCREAMING_SNAKE_CASE ) -> List[Any]: '''simple docstring''' def decorator(_SCREAMING_SNAKE_CASE ): SCREAMING_SNAKE_CASE = getattr(_SCREAMING_SNAKE_CASE , """handle_key""" , [] ) handle += keys setattr(_SCREAMING_SNAKE_CASE , """handle_key""" , _SCREAMING_SNAKE_CASE ) return func return decorator class UpperCamelCase__ ( lowerCAmelCase_ ): '''simple docstring''' def __new__( cls : Tuple ,lowerCamelCase__ : Union[str, Any] ,lowerCamelCase__ : List[str] ,lowerCamelCase__ : Any ) -> Dict: '''simple docstring''' SCREAMING_SNAKE_CASE = super().__new__(cls ,lowerCamelCase__ ,lowerCamelCase__ ,lowerCamelCase__ ) if not hasattr(lowerCamelCase__ ,"""key_handler""" ): setattr(lowerCamelCase__ ,"""key_handler""" ,{} ) setattr(lowerCamelCase__ ,"""handle_input""" ,KeyHandler.handle_input ) for value in attrs.values(): SCREAMING_SNAKE_CASE = getattr(lowerCamelCase__ ,"""handle_key""" ,[] ) for key in handled_keys: SCREAMING_SNAKE_CASE = value return new_cls @staticmethod def SCREAMING_SNAKE_CASE__ ( cls : Union[str, Any] ) -> Tuple: '''simple docstring''' SCREAMING_SNAKE_CASE = get_character() if char != KEYMAP["undefined"]: SCREAMING_SNAKE_CASE = ord(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = cls.key_handler.get(lowerCamelCase__ ) if handler: SCREAMING_SNAKE_CASE = char return handler(cls ) else: return None def __lowercase ( cls ) -> Optional[Any]: '''simple docstring''' return KeyHandler(cls.__name__ , cls.__bases__ , cls.__dict__.copy() )
296
from typing import Callable, Optional from .. import Features from ..packaged_modules.generator.generator import Generator from .abc import AbstractDatasetInputStream class UpperCamelCase__ ( lowerCAmelCase_ ): '''simple docstring''' def __init__( self : Union[str, Any] ,lowerCamelCase__ : Callable ,lowerCamelCase__ : Optional[Features] = None ,lowerCamelCase__ : str = None ,lowerCamelCase__ : bool = False ,lowerCamelCase__ : bool = False ,lowerCamelCase__ : Optional[dict] = None ,lowerCamelCase__ : Optional[int] = None ,**lowerCamelCase__ : Optional[Any] ,) -> List[str]: '''simple docstring''' super().__init__( features=lowerCamelCase__ ,cache_dir=lowerCamelCase__ ,keep_in_memory=lowerCamelCase__ ,streaming=lowerCamelCase__ ,num_proc=lowerCamelCase__ ,**lowerCamelCase__ ,) SCREAMING_SNAKE_CASE = Generator( cache_dir=lowerCamelCase__ ,features=lowerCamelCase__ ,generator=lowerCamelCase__ ,gen_kwargs=lowerCamelCase__ ,**lowerCamelCase__ ,) def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ) -> Optional[Any]: '''simple docstring''' if self.streaming: SCREAMING_SNAKE_CASE = self.builder.as_streaming_dataset(split="""train""" ) # Build regular (map-style) dataset else: SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = None self.builder.download_and_prepare( download_config=lowerCamelCase__ ,download_mode=lowerCamelCase__ ,verification_mode=lowerCamelCase__ ,base_path=lowerCamelCase__ ,num_proc=self.num_proc ,) SCREAMING_SNAKE_CASE = self.builder.as_dataset( split="""train""" ,verification_mode=lowerCamelCase__ ,in_memory=self.keep_in_memory ) return dataset
296
1
import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging SCREAMING_SNAKE_CASE_ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE_ = { """microsoft/git-base""": """https://huggingface.co/microsoft/git-base/resolve/main/config.json""", } class UpperCamelCase__ ( lowerCAmelCase_ ): '''simple docstring''' __snake_case : Dict = "git_vision_model" def __init__( self : List[Any] ,lowerCamelCase__ : Dict=768 ,lowerCamelCase__ : Union[str, Any]=3072 ,lowerCamelCase__ : Optional[int]=12 ,lowerCamelCase__ : Tuple=12 ,lowerCamelCase__ : Tuple=3 ,lowerCamelCase__ : Optional[Any]=224 ,lowerCamelCase__ : Union[str, Any]=16 ,lowerCamelCase__ : List[Any]="quick_gelu" ,lowerCamelCase__ : Optional[Any]=1e-5 ,lowerCamelCase__ : str=0.0 ,lowerCamelCase__ : Optional[int]=0.02 ,**lowerCamelCase__ : Union[str, Any] ,) -> Optional[int]: '''simple docstring''' super().__init__(**lowerCamelCase__ ) SCREAMING_SNAKE_CASE = hidden_size SCREAMING_SNAKE_CASE = intermediate_size SCREAMING_SNAKE_CASE = num_hidden_layers SCREAMING_SNAKE_CASE = num_attention_heads SCREAMING_SNAKE_CASE = num_channels SCREAMING_SNAKE_CASE = patch_size SCREAMING_SNAKE_CASE = image_size SCREAMING_SNAKE_CASE = initializer_range SCREAMING_SNAKE_CASE = attention_dropout SCREAMING_SNAKE_CASE = layer_norm_eps SCREAMING_SNAKE_CASE = hidden_act @classmethod def SCREAMING_SNAKE_CASE__ ( cls : Tuple ,lowerCamelCase__ : Union[str, os.PathLike] ,**lowerCamelCase__ : int ) -> "PretrainedConfig": '''simple docstring''' cls._set_token_in_kwargs(lowerCamelCase__ ) SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE = cls.get_config_dict(lowerCamelCase__ ,**lowerCamelCase__ ) # get the vision config dict if we are loading from GITConfig if config_dict.get("""model_type""" ) == "git": SCREAMING_SNAKE_CASE = config_dict["""vision_config"""] if "model_type" in config_dict and hasattr(cls ,"""model_type""" ) and config_dict["model_type"] != cls.model_type: logger.warning( F"""You are using a model of type {config_dict['model_type']} to instantiate a model of type """ F"""{cls.model_type}. This is not supported for all configurations of models and can yield errors.""" ) return cls.from_dict(lowerCamelCase__ ,**lowerCamelCase__ ) class UpperCamelCase__ ( lowerCAmelCase_ ): '''simple docstring''' __snake_case : Dict = "git" def __init__( self : Optional[int] ,lowerCamelCase__ : int=None ,lowerCamelCase__ : str=30522 ,lowerCamelCase__ : Tuple=768 ,lowerCamelCase__ : Union[str, Any]=6 ,lowerCamelCase__ : str=12 ,lowerCamelCase__ : List[str]=3072 ,lowerCamelCase__ : Dict="gelu" ,lowerCamelCase__ : Tuple=0.1 ,lowerCamelCase__ : Any=0.1 ,lowerCamelCase__ : List[str]=1024 ,lowerCamelCase__ : List[str]=0.02 ,lowerCamelCase__ : str=1e-1_2 ,lowerCamelCase__ : Optional[int]=0 ,lowerCamelCase__ : Optional[int]="absolute" ,lowerCamelCase__ : Optional[Any]=True ,lowerCamelCase__ : str=False ,lowerCamelCase__ : int=101 ,lowerCamelCase__ : int=102 ,lowerCamelCase__ : Dict=None ,**lowerCamelCase__ : List[Any] ,) -> Optional[Any]: '''simple docstring''' super().__init__(bos_token_id=lowerCamelCase__ ,eos_token_id=lowerCamelCase__ ,pad_token_id=lowerCamelCase__ ,**lowerCamelCase__ ) if vision_config is None: SCREAMING_SNAKE_CASE = {} logger.info("""vision_config is None. initializing the GitVisionConfig with default values.""" ) SCREAMING_SNAKE_CASE = GitVisionConfig(**lowerCamelCase__ ) SCREAMING_SNAKE_CASE = vocab_size SCREAMING_SNAKE_CASE = hidden_size SCREAMING_SNAKE_CASE = num_hidden_layers SCREAMING_SNAKE_CASE = num_attention_heads SCREAMING_SNAKE_CASE = hidden_act SCREAMING_SNAKE_CASE = intermediate_size SCREAMING_SNAKE_CASE = hidden_dropout_prob SCREAMING_SNAKE_CASE = attention_probs_dropout_prob SCREAMING_SNAKE_CASE = max_position_embeddings SCREAMING_SNAKE_CASE = initializer_range SCREAMING_SNAKE_CASE = layer_norm_eps SCREAMING_SNAKE_CASE = position_embedding_type SCREAMING_SNAKE_CASE = use_cache SCREAMING_SNAKE_CASE = tie_word_embeddings SCREAMING_SNAKE_CASE = num_image_with_embedding SCREAMING_SNAKE_CASE = bos_token_id SCREAMING_SNAKE_CASE = eos_token_id def SCREAMING_SNAKE_CASE__ ( self : Dict ) -> Optional[int]: '''simple docstring''' SCREAMING_SNAKE_CASE = copy.deepcopy(self.__dict__ ) SCREAMING_SNAKE_CASE = self.vision_config.to_dict() SCREAMING_SNAKE_CASE = self.__class__.model_type return output
296
import logging from dataclasses import dataclass, field from typing import Optional from seqaseq_trainer import arg_to_scheduler from transformers import TrainingArguments SCREAMING_SNAKE_CASE_ = logging.getLogger(__name__) @dataclass class UpperCamelCase__ ( lowerCAmelCase_ ): '''simple docstring''' __snake_case : Optional[float] = field( default=0.0 , metadata={"help": "The label smoothing epsilon to apply (if not zero)."} ) __snake_case : bool = field(default=lowerCAmelCase_ , metadata={"help": "Whether to SortishSamler or not."} ) __snake_case : bool = field( default=lowerCAmelCase_ , metadata={"help": "Whether to use generate to calculate generative metrics (ROUGE, BLEU)."} ) __snake_case : bool = field(default=lowerCAmelCase_ , metadata={"help": "whether to use adafactor"} ) __snake_case : Optional[float] = field( default=lowerCAmelCase_ , metadata={"help": "Encoder layer dropout probability. Goes into model.config."} ) __snake_case : Optional[float] = field( default=lowerCAmelCase_ , metadata={"help": "Decoder layer dropout probability. Goes into model.config."} ) __snake_case : Optional[float] = field(default=lowerCAmelCase_ , metadata={"help": "Dropout probability. Goes into model.config."} ) __snake_case : Optional[float] = field( default=lowerCAmelCase_ , metadata={"help": "Attention dropout probability. Goes into model.config."} ) __snake_case : Optional[str] = field( default="linear" , metadata={"help": F"Which lr scheduler to use. Selected in {sorted(arg_to_scheduler.keys() )}"} , )
296
1
from datasets.utils.patching import _PatchedModuleObj, patch_submodule from . import _test_patching def __lowercase ( ) -> Optional[int]: '''simple docstring''' import os as original_os from os import path as original_path from os import rename as original_rename from os.path import dirname as original_dirname from os.path import join as original_join assert _test_patching.os is original_os assert _test_patching.path is original_path assert _test_patching.join is original_join assert _test_patching.renamed_os is original_os assert _test_patching.renamed_path is original_path assert _test_patching.renamed_join is original_join SCREAMING_SNAKE_CASE = """__test_patch_submodule_mock__""" with patch_submodule(_test_patching , """os.path.join""" , _SCREAMING_SNAKE_CASE ): # Every way to access os.path.join must be patched, and the rest must stay untouched # check os.path.join assert isinstance(_test_patching.os , _PatchedModuleObj ) assert isinstance(_test_patching.os.path , _PatchedModuleObj ) assert _test_patching.os.path.join is mock # check path.join assert isinstance(_test_patching.path , _PatchedModuleObj ) assert _test_patching.path.join is mock # check join assert _test_patching.join is mock # check that the other attributes are untouched assert _test_patching.os.rename is original_rename assert _test_patching.path.dirname is original_dirname assert _test_patching.os.path.dirname is original_dirname # Even renamed modules or objects must be patched # check renamed_os.path.join assert isinstance(_test_patching.renamed_os , _PatchedModuleObj ) assert isinstance(_test_patching.renamed_os.path , _PatchedModuleObj ) assert _test_patching.renamed_os.path.join is mock # check renamed_path.join assert isinstance(_test_patching.renamed_path , _PatchedModuleObj ) assert _test_patching.renamed_path.join is mock # check renamed_join assert _test_patching.renamed_join is mock # check that the other attributes are untouched assert _test_patching.renamed_os.rename is original_rename assert _test_patching.renamed_path.dirname is original_dirname assert _test_patching.renamed_os.path.dirname is original_dirname # check that everthing is back to normal when the patch is over assert _test_patching.os is original_os assert _test_patching.path is original_path assert _test_patching.join is original_join assert _test_patching.renamed_os is original_os assert _test_patching.renamed_path is original_path assert _test_patching.renamed_join is original_join def __lowercase ( ) -> str: '''simple docstring''' assert _test_patching.open is open SCREAMING_SNAKE_CASE = """__test_patch_submodule_builtin_mock__""" # _test_patching has "open" in its globals assert _test_patching.open is open with patch_submodule(_test_patching , """open""" , _SCREAMING_SNAKE_CASE ): assert _test_patching.open is mock # check that everthing is back to normal when the patch is over assert _test_patching.open is open def __lowercase ( ) -> Union[str, Any]: '''simple docstring''' SCREAMING_SNAKE_CASE = """__test_patch_submodule_missing_mock__""" with patch_submodule(_test_patching , """pandas.read_csv""" , _SCREAMING_SNAKE_CASE ): pass def __lowercase ( ) -> Optional[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE = """__test_patch_submodule_missing_builtin_mock__""" # _test_patching doesn't have "len" in its globals assert getattr(_test_patching , """len""" , _SCREAMING_SNAKE_CASE ) is None with patch_submodule(_test_patching , """len""" , _SCREAMING_SNAKE_CASE ): assert _test_patching.len is mock assert _test_patching.len is len def __lowercase ( ) -> List[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE = """__test_patch_submodule_start_and_stop_mock__""" SCREAMING_SNAKE_CASE = patch_submodule(_test_patching , """open""" , _SCREAMING_SNAKE_CASE ) assert _test_patching.open is open patch.start() assert _test_patching.open is mock patch.stop() assert _test_patching.open is open def __lowercase ( ) -> Any: '''simple docstring''' from os import rename as original_rename from os.path import dirname as original_dirname from os.path import join as original_join SCREAMING_SNAKE_CASE = """__test_patch_submodule_successive_join__""" SCREAMING_SNAKE_CASE = """__test_patch_submodule_successive_dirname__""" SCREAMING_SNAKE_CASE = """__test_patch_submodule_successive_rename__""" assert _test_patching.os.path.join is original_join assert _test_patching.os.path.dirname is original_dirname assert _test_patching.os.rename is original_rename with patch_submodule(_test_patching , """os.path.join""" , _SCREAMING_SNAKE_CASE ): with patch_submodule(_test_patching , """os.rename""" , _SCREAMING_SNAKE_CASE ): with patch_submodule(_test_patching , """os.path.dirname""" , _SCREAMING_SNAKE_CASE ): assert _test_patching.os.path.join is mock_join assert _test_patching.os.path.dirname is mock_dirname assert _test_patching.os.rename is mock_rename # try another order with patch_submodule(_test_patching , """os.rename""" , _SCREAMING_SNAKE_CASE ): with patch_submodule(_test_patching , """os.path.join""" , _SCREAMING_SNAKE_CASE ): with patch_submodule(_test_patching , """os.path.dirname""" , _SCREAMING_SNAKE_CASE ): assert _test_patching.os.path.join is mock_join assert _test_patching.os.path.dirname is mock_dirname assert _test_patching.os.rename is mock_rename assert _test_patching.os.path.join is original_join assert _test_patching.os.path.dirname is original_dirname assert _test_patching.os.rename is original_rename def __lowercase ( ) -> str: '''simple docstring''' SCREAMING_SNAKE_CASE = """__test_patch_submodule_doesnt_exist_mock__""" with patch_submodule(_test_patching , """__module_that_doesn_exist__.__attribute_that_doesn_exist__""" , _SCREAMING_SNAKE_CASE ): pass with patch_submodule(_test_patching , """os.__attribute_that_doesn_exist__""" , _SCREAMING_SNAKE_CASE ): pass
296
import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, DPMSolverMultistepScheduler, TextToVideoSDPipeline, UNetaDConditionModel, ) from diffusers.utils import is_xformers_available, load_numpy, skip_mps, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() @skip_mps class UpperCamelCase__ ( lowerCAmelCase_ , unittest.TestCase ): '''simple docstring''' __snake_case : List[str] = TextToVideoSDPipeline __snake_case : int = TEXT_TO_IMAGE_PARAMS __snake_case : Tuple = TEXT_TO_IMAGE_BATCH_PARAMS # No `output_type`. __snake_case : Dict = frozenset( [ "num_inference_steps", "generator", "latents", "return_dict", "callback", "callback_steps", ] ) def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ) -> Optional[int]: '''simple docstring''' torch.manual_seed(0 ) SCREAMING_SNAKE_CASE = UNetaDConditionModel( block_out_channels=(32, 64, 64, 64) ,layers_per_block=2 ,sample_size=32 ,in_channels=4 ,out_channels=4 ,down_block_types=("""CrossAttnDownBlock3D""", """CrossAttnDownBlock3D""", """CrossAttnDownBlock3D""", """DownBlock3D""") ,up_block_types=("""UpBlock3D""", """CrossAttnUpBlock3D""", """CrossAttnUpBlock3D""", """CrossAttnUpBlock3D""") ,cross_attention_dim=32 ,attention_head_dim=4 ,) SCREAMING_SNAKE_CASE = DDIMScheduler( beta_start=0.00085 ,beta_end=0.012 ,beta_schedule="""scaled_linear""" ,clip_sample=lowerCamelCase__ ,set_alpha_to_one=lowerCamelCase__ ,) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE = AutoencoderKL( block_out_channels=[32, 64] ,in_channels=3 ,out_channels=3 ,down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] ,up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] ,latent_channels=4 ,sample_size=128 ,) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE = CLIPTextConfig( bos_token_id=0 ,eos_token_id=2 ,hidden_size=32 ,intermediate_size=37 ,layer_norm_eps=1e-0_5 ,num_attention_heads=4 ,num_hidden_layers=5 ,pad_token_id=1 ,vocab_size=1000 ,hidden_act="""gelu""" ,projection_dim=512 ,) SCREAMING_SNAKE_CASE = CLIPTextModel(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) SCREAMING_SNAKE_CASE = { """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, } return components def SCREAMING_SNAKE_CASE__ ( self : int ,lowerCamelCase__ : Optional[Any] ,lowerCamelCase__ : int=0 ) -> List[Any]: '''simple docstring''' if str(lowerCamelCase__ ).startswith("""mps""" ): SCREAMING_SNAKE_CASE = torch.manual_seed(lowerCamelCase__ ) else: SCREAMING_SNAKE_CASE = torch.Generator(device=lowerCamelCase__ ).manual_seed(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = { """prompt""": """A painting of a squirrel eating a burger""", """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 6.0, """output_type""": """pt""", } return inputs def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ) -> List[str]: '''simple docstring''' SCREAMING_SNAKE_CASE = """cpu""" # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE = self.get_dummy_components() SCREAMING_SNAKE_CASE = TextToVideoSDPipeline(**lowerCamelCase__ ) SCREAMING_SNAKE_CASE = sd_pipe.to(lowerCamelCase__ ) sd_pipe.set_progress_bar_config(disable=lowerCamelCase__ ) SCREAMING_SNAKE_CASE = self.get_dummy_inputs(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = """np""" SCREAMING_SNAKE_CASE = sd_pipe(**lowerCamelCase__ ).frames SCREAMING_SNAKE_CASE = frames[0][-3:, -3:, -1] assert frames[0].shape == (64, 64, 3) SCREAMING_SNAKE_CASE = np.array([158.0, 160.0, 153.0, 125.0, 100.0, 121.0, 111.0, 93.0, 113.0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def SCREAMING_SNAKE_CASE__ ( self : Dict ) -> int: '''simple docstring''' self._test_attention_slicing_forward_pass(test_mean_pixel_difference=lowerCamelCase__ ,expected_max_diff=3e-3 ) @unittest.skipIf( torch_device != """cuda""" or not is_xformers_available() ,reason="""XFormers attention is only available with CUDA and `xformers` installed""" ,) def SCREAMING_SNAKE_CASE__ ( self : Tuple ) -> Any: '''simple docstring''' self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=lowerCamelCase__ ,expected_max_diff=1e-2 ) @unittest.skip(reason="""Batching needs to be properly figured out first for this pipeline.""" ) def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ) -> List[Any]: '''simple docstring''' pass @unittest.skip(reason="""Batching needs to be properly figured out first for this pipeline.""" ) def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ) -> Any: '''simple docstring''' pass @unittest.skip(reason="""`num_images_per_prompt` argument is not supported for this pipeline.""" ) def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ) -> Tuple: '''simple docstring''' pass def SCREAMING_SNAKE_CASE__ ( self : List[str] ) -> Optional[Any]: '''simple docstring''' return super().test_progress_bar() @slow @skip_mps class UpperCamelCase__ ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE__ ( self : Any ) -> Optional[int]: '''simple docstring''' SCREAMING_SNAKE_CASE = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/text_to_video/video.npy""" ) SCREAMING_SNAKE_CASE = TextToVideoSDPipeline.from_pretrained("""damo-vilab/text-to-video-ms-1.7b""" ) SCREAMING_SNAKE_CASE = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config ) SCREAMING_SNAKE_CASE = pipe.to("""cuda""" ) SCREAMING_SNAKE_CASE = """Spiderman is surfing""" SCREAMING_SNAKE_CASE = torch.Generator(device="""cpu""" ).manual_seed(0 ) SCREAMING_SNAKE_CASE = pipe(lowerCamelCase__ ,generator=lowerCamelCase__ ,num_inference_steps=25 ,output_type="""pt""" ).frames SCREAMING_SNAKE_CASE = video_frames.cpu().numpy() assert np.abs(expected_video - video ).mean() < 5e-2 def SCREAMING_SNAKE_CASE__ ( self : Any ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/text_to_video/video_2step.npy""" ) SCREAMING_SNAKE_CASE = TextToVideoSDPipeline.from_pretrained("""damo-vilab/text-to-video-ms-1.7b""" ) SCREAMING_SNAKE_CASE = pipe.to("""cuda""" ) SCREAMING_SNAKE_CASE = """Spiderman is surfing""" SCREAMING_SNAKE_CASE = torch.Generator(device="""cpu""" ).manual_seed(0 ) SCREAMING_SNAKE_CASE = pipe(lowerCamelCase__ ,generator=lowerCamelCase__ ,num_inference_steps=2 ,output_type="""pt""" ).frames SCREAMING_SNAKE_CASE = video_frames.cpu().numpy() assert np.abs(expected_video - video ).mean() < 5e-2
296
1
from ..utils import DummyObject, requires_backends class UpperCamelCase__ ( metaclass=lowerCAmelCase_ ): '''simple docstring''' __snake_case : str = ["onnx"] def __init__( self : List[str] ,*lowerCamelCase__ : str ,**lowerCamelCase__ : List[Any] ) -> List[str]: '''simple docstring''' requires_backends(self ,["""onnx"""] ) @classmethod def SCREAMING_SNAKE_CASE__ ( cls : Dict ,*lowerCamelCase__ : List[str] ,**lowerCamelCase__ : str ) -> Optional[int]: '''simple docstring''' requires_backends(cls ,["""onnx"""] ) @classmethod def SCREAMING_SNAKE_CASE__ ( cls : str ,*lowerCamelCase__ : int ,**lowerCamelCase__ : Any ) -> Optional[int]: '''simple docstring''' requires_backends(cls ,["""onnx"""] )
296
def __lowercase ( _SCREAMING_SNAKE_CASE = 10 ) -> str: '''simple docstring''' if not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) or n < 0: raise ValueError("""Invalid input""" ) SCREAMING_SNAKE_CASE = 10**n SCREAMING_SNAKE_CASE = 2_84_33 * (pow(2 , 7_83_04_57 , _SCREAMING_SNAKE_CASE )) + 1 return str(number % modulus ) if __name__ == "__main__": from doctest import testmod testmod() print(F'''{solution(1_0) = }''')
296
1
import os import shutil from pathlib import Path from typing import Optional, Union import numpy as np from huggingface_hub import hf_hub_download from ..utils import ONNX_EXTERNAL_WEIGHTS_NAME, ONNX_WEIGHTS_NAME, is_onnx_available, logging if is_onnx_available(): import onnxruntime as ort SCREAMING_SNAKE_CASE_ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE_ = { """tensor(bool)""": np.bool_, """tensor(int8)""": np.inta, """tensor(uint8)""": np.uinta, """tensor(int16)""": np.intaa, """tensor(uint16)""": np.uintaa, """tensor(int32)""": np.intaa, """tensor(uint32)""": np.uintaa, """tensor(int64)""": np.intaa, """tensor(uint64)""": np.uintaa, """tensor(float16)""": np.floataa, """tensor(float)""": np.floataa, """tensor(double)""": np.floataa, } class UpperCamelCase__ : '''simple docstring''' def __init__( self : List[str] ,lowerCamelCase__ : Any=None ,**lowerCamelCase__ : Tuple ) -> int: '''simple docstring''' logger.info("""`diffusers.OnnxRuntimeModel` is experimental and might change in the future.""" ) SCREAMING_SNAKE_CASE = model SCREAMING_SNAKE_CASE = kwargs.get("""model_save_dir""" ,lowerCamelCase__ ) SCREAMING_SNAKE_CASE = kwargs.get("""latest_model_name""" ,lowerCamelCase__ ) def __call__( self : Union[str, Any] ,**lowerCamelCase__ : List[Any] ) -> str: '''simple docstring''' SCREAMING_SNAKE_CASE = {k: np.array(lowerCamelCase__ ) for k, v in kwargs.items()} return self.model.run(lowerCamelCase__ ,lowerCamelCase__ ) @staticmethod def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ : Union[str, Path] ,lowerCamelCase__ : List[Any]=None ,lowerCamelCase__ : Union[str, Any]=None ) -> int: '''simple docstring''' if provider is None: logger.info("""No onnxruntime provider specified, using CPUExecutionProvider""" ) SCREAMING_SNAKE_CASE = """CPUExecutionProvider""" return ort.InferenceSession(lowerCamelCase__ ,providers=[provider] ,sess_options=lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( self : List[Any] ,lowerCamelCase__ : Union[str, Path] ,lowerCamelCase__ : Optional[str] = None ,**lowerCamelCase__ : Dict ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE = file_name if file_name is not None else ONNX_WEIGHTS_NAME SCREAMING_SNAKE_CASE = self.model_save_dir.joinpath(self.latest_model_name ) SCREAMING_SNAKE_CASE = Path(lowerCamelCase__ ).joinpath(lowerCamelCase__ ) try: shutil.copyfile(lowerCamelCase__ ,lowerCamelCase__ ) except shutil.SameFileError: pass # copy external weights (for models >2GB) SCREAMING_SNAKE_CASE = self.model_save_dir.joinpath(lowerCamelCase__ ) if src_path.exists(): SCREAMING_SNAKE_CASE = Path(lowerCamelCase__ ).joinpath(lowerCamelCase__ ) try: shutil.copyfile(lowerCamelCase__ ,lowerCamelCase__ ) except shutil.SameFileError: pass def SCREAMING_SNAKE_CASE__ ( self : List[str] ,lowerCamelCase__ : Union[str, os.PathLike] ,**lowerCamelCase__ : Dict ,) -> Optional[int]: '''simple docstring''' if os.path.isfile(lowerCamelCase__ ): logger.error(F"""Provided path ({save_directory}) should be a directory, not a file""" ) return os.makedirs(lowerCamelCase__ ,exist_ok=lowerCamelCase__ ) # saving model weights/files self._save_pretrained(lowerCamelCase__ ,**lowerCamelCase__ ) @classmethod def SCREAMING_SNAKE_CASE__ ( cls : List[Any] ,lowerCamelCase__ : Union[str, Path] ,lowerCamelCase__ : Optional[Union[bool, str, None]] = None ,lowerCamelCase__ : Optional[Union[str, None]] = None ,lowerCamelCase__ : bool = False ,lowerCamelCase__ : Optional[str] = None ,lowerCamelCase__ : Optional[str] = None ,lowerCamelCase__ : Optional[str] = None ,lowerCamelCase__ : Optional["ort.SessionOptions"] = None ,**lowerCamelCase__ : Dict ,) -> Union[str, Any]: '''simple docstring''' SCREAMING_SNAKE_CASE = file_name if file_name is not None else ONNX_WEIGHTS_NAME # load model from local directory if os.path.isdir(lowerCamelCase__ ): SCREAMING_SNAKE_CASE = OnnxRuntimeModel.load_model( os.path.join(lowerCamelCase__ ,lowerCamelCase__ ) ,provider=lowerCamelCase__ ,sess_options=lowerCamelCase__ ) SCREAMING_SNAKE_CASE = Path(lowerCamelCase__ ) # load model from hub else: # download model SCREAMING_SNAKE_CASE = hf_hub_download( repo_id=lowerCamelCase__ ,filename=lowerCamelCase__ ,use_auth_token=lowerCamelCase__ ,revision=lowerCamelCase__ ,cache_dir=lowerCamelCase__ ,force_download=lowerCamelCase__ ,) SCREAMING_SNAKE_CASE = Path(lowerCamelCase__ ).parent SCREAMING_SNAKE_CASE = Path(lowerCamelCase__ ).name SCREAMING_SNAKE_CASE = OnnxRuntimeModel.load_model(lowerCamelCase__ ,provider=lowerCamelCase__ ,sess_options=lowerCamelCase__ ) return cls(model=lowerCamelCase__ ,**lowerCamelCase__ ) @classmethod def SCREAMING_SNAKE_CASE__ ( cls : Optional[int] ,lowerCamelCase__ : Union[str, Path] ,lowerCamelCase__ : bool = True ,lowerCamelCase__ : Optional[str] = None ,lowerCamelCase__ : Optional[str] = None ,**lowerCamelCase__ : str ,) -> Dict: '''simple docstring''' SCREAMING_SNAKE_CASE = None if len(str(lowerCamelCase__ ).split("""@""" ) ) == 2: SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE = model_id.split("""@""" ) return cls._from_pretrained( model_id=lowerCamelCase__ ,revision=lowerCamelCase__ ,cache_dir=lowerCamelCase__ ,force_download=lowerCamelCase__ ,use_auth_token=lowerCamelCase__ ,**lowerCamelCase__ ,)
296
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) SCREAMING_SNAKE_CASE_ = { """configuration_llama""": ["""LLAMA_PRETRAINED_CONFIG_ARCHIVE_MAP""", """LlamaConfig"""], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE_ = ["""LlamaTokenizer"""] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE_ = ["""LlamaTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE_ = [ """LlamaForCausalLM""", """LlamaModel""", """LlamaPreTrainedModel""", """LlamaForSequenceClassification""", ] if TYPE_CHECKING: from .configuration_llama import LLAMA_PRETRAINED_CONFIG_ARCHIVE_MAP, LlamaConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_llama import LlamaTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_llama_fast import LlamaTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_llama import LlamaForCausalLM, LlamaForSequenceClassification, LlamaModel, LlamaPreTrainedModel else: import sys SCREAMING_SNAKE_CASE_ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
296
1
import os from collections import namedtuple import pytest from datasets import ClassLabel, Features, Sequence, Value from datasets.commands.test import TestCommand from datasets.info import DatasetInfo, DatasetInfosDict SCREAMING_SNAKE_CASE_ = namedtuple( """_TestCommandArgs""", [ """dataset""", """name""", """cache_dir""", """data_dir""", """all_configs""", """save_infos""", """ignore_verifications""", """force_redownload""", """clear_cache""", ], defaults=[None, None, None, False, False, False, False, False], ) def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> List[Any]: '''simple docstring''' return (abs(source - target ) / target) < 0.01 @pytest.mark.integration def __lowercase ( _SCREAMING_SNAKE_CASE ) -> str: '''simple docstring''' SCREAMING_SNAKE_CASE = _TestCommandArgs(dataset=_SCREAMING_SNAKE_CASE , all_configs=_SCREAMING_SNAKE_CASE , save_infos=_SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE = TestCommand(*_SCREAMING_SNAKE_CASE ) test_command.run() SCREAMING_SNAKE_CASE = os.path.join(_SCREAMING_SNAKE_CASE , """README.md""" ) assert os.path.exists(_SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE = DatasetInfosDict.from_directory(_SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE = DatasetInfosDict( { """default""": DatasetInfo( features=Features( { """tokens""": Sequence(Value("""string""" ) ), """ner_tags""": Sequence( ClassLabel(names=["""O""", """B-PER""", """I-PER""", """B-ORG""", """I-ORG""", """B-LOC""", """I-LOC"""] ) ), """langs""": Sequence(Value("""string""" ) ), """spans""": Sequence(Value("""string""" ) ), } ) , splits=[ { """name""": """train""", """num_bytes""": 2_35_15_63, """num_examples""": 1_00_00, }, { """name""": """validation""", """num_bytes""": 23_84_18, """num_examples""": 10_00, }, ] , download_size=3_94_06_80 , dataset_size=2_58_99_81 , ) } ) assert dataset_infos.keys() == expected_dataset_infos.keys() for key in DatasetInfo._INCLUDED_INFO_IN_YAML: SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE = getattr(dataset_infos["""default"""] , _SCREAMING_SNAKE_CASE ), getattr(expected_dataset_infos["""default"""] , _SCREAMING_SNAKE_CASE ) if key == "num_bytes": assert is_apercent_close(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif key == "splits": assert list(_SCREAMING_SNAKE_CASE ) == list(_SCREAMING_SNAKE_CASE ) for split in result: assert result[split].name == expected[split].name assert result[split].num_examples == expected[split].num_examples assert is_apercent_close(result[split].num_bytes , expected[split].num_bytes ) else: result == expected
296
from pathlib import Path import fire def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> List[str]: '''simple docstring''' SCREAMING_SNAKE_CASE = Path(_SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE = Path(_SCREAMING_SNAKE_CASE ) dest_dir.mkdir(exist_ok=_SCREAMING_SNAKE_CASE ) for path in src_dir.iterdir(): SCREAMING_SNAKE_CASE = [x.rstrip() for x in list(path.open().readlines() )][:n] SCREAMING_SNAKE_CASE = dest_dir.joinpath(path.name ) print(_SCREAMING_SNAKE_CASE ) dest_path.open("""w""" ).write("""\n""".join(_SCREAMING_SNAKE_CASE ) ) if __name__ == "__main__": fire.Fire(minify)
296
1
import logging from dataclasses import dataclass, field from pathlib import Path from typing import Optional, Union from .generation.configuration_utils import GenerationConfig from .training_args import TrainingArguments from .utils import add_start_docstrings SCREAMING_SNAKE_CASE_ = logging.getLogger(__name__) @dataclass @add_start_docstrings(TrainingArguments.__doc__ ) class UpperCamelCase__ ( lowerCAmelCase_ ): '''simple docstring''' __snake_case : bool = field(default=lowerCAmelCase_ , metadata={"help": "Whether to use SortishSampler or not."} ) __snake_case : bool = field( default=lowerCAmelCase_ , metadata={"help": "Whether to use generate to calculate generative metrics (ROUGE, BLEU)."} ) __snake_case : Optional[int] = field( default=lowerCAmelCase_ , metadata={ "help": ( "The `max_length` to use on each evaluation loop when `predict_with_generate=True`. Will default " "to the `max_length` value of the model configuration." ) } , ) __snake_case : Optional[int] = field( default=lowerCAmelCase_ , metadata={ "help": ( "The `num_beams` to use on each evaluation loop when `predict_with_generate=True`. Will default " "to the `num_beams` value of the model configuration." ) } , ) __snake_case : Optional[Union[str, Path, GenerationConfig]] = field( default=lowerCAmelCase_ , metadata={ "help": "Model id, file path or url pointing to a GenerationConfig json file, to use during prediction." } , ) def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ) -> Tuple: '''simple docstring''' SCREAMING_SNAKE_CASE = super().to_dict() for k, v in d.items(): if isinstance(lowerCamelCase__ ,lowerCamelCase__ ): SCREAMING_SNAKE_CASE = v.to_dict() return d
296
import importlib import json import os import sys import tempfile import unittest from pathlib import Path import transformers import transformers.models.auto from transformers.models.auto.configuration_auto import CONFIG_MAPPING, AutoConfig from transformers.models.bert.configuration_bert import BertConfig from transformers.models.roberta.configuration_roberta import RobertaConfig from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, get_tests_dir sys.path.append(str(Path(__file__).parent.parent.parent.parent / """utils""")) from test_module.custom_configuration import CustomConfig # noqa E402 SCREAMING_SNAKE_CASE_ = get_tests_dir("""fixtures/dummy-config.json""") class UpperCamelCase__ ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ) -> Optional[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE = 0 def SCREAMING_SNAKE_CASE__ ( self : Any ) -> str: '''simple docstring''' self.assertIsNotNone(transformers.models.auto.__spec__ ) self.assertIsNotNone(importlib.util.find_spec("""transformers.models.auto""" ) ) def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ) -> List[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained("""bert-base-uncased""" ) self.assertIsInstance(lowerCamelCase__ ,lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( self : int ) -> Optional[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained(lowerCamelCase__ ) self.assertIsInstance(lowerCamelCase__ ,lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ) -> List[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained(lowerCamelCase__ ) self.assertIsInstance(lowerCamelCase__ ,lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( self : Tuple ) -> Optional[int]: '''simple docstring''' SCREAMING_SNAKE_CASE = AutoConfig.for_model("""roberta""" ) self.assertIsInstance(lowerCamelCase__ ,lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( self : int ) -> int: '''simple docstring''' with tempfile.TemporaryDirectory() as tmp_dir: # This model name contains bert and roberta, but roberta ends up being picked. SCREAMING_SNAKE_CASE = os.path.join(lowerCamelCase__ ,"""fake-roberta""" ) os.makedirs(lowerCamelCase__ ,exist_ok=lowerCamelCase__ ) with open(os.path.join(lowerCamelCase__ ,"""config.json""" ) ,"""w""" ) as f: f.write(json.dumps({} ) ) SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained(lowerCamelCase__ ) self.assertEqual(type(lowerCamelCase__ ) ,lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( self : Dict ) -> str: '''simple docstring''' try: AutoConfig.register("""custom""" ,lowerCamelCase__ ) # Wrong model type will raise an error with self.assertRaises(lowerCamelCase__ ): AutoConfig.register("""model""" ,lowerCamelCase__ ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(lowerCamelCase__ ): AutoConfig.register("""bert""" ,lowerCamelCase__ ) # Now that the config is registered, it can be used as any other config with the auto-API SCREAMING_SNAKE_CASE = CustomConfig() with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained(lowerCamelCase__ ) self.assertIsInstance(lowerCamelCase__ ,lowerCamelCase__ ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] def SCREAMING_SNAKE_CASE__ ( self : str ) -> Dict: '''simple docstring''' with self.assertRaisesRegex( lowerCamelCase__ ,"""bert-base is not a local folder and is not a valid model identifier""" ): SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained("""bert-base""" ) def SCREAMING_SNAKE_CASE__ ( self : Dict ) -> str: '''simple docstring''' with self.assertRaisesRegex( lowerCamelCase__ ,R"""aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)""" ): SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained(lowerCamelCase__ ,revision="""aaaaaa""" ) def SCREAMING_SNAKE_CASE__ ( self : Tuple ) -> List[Any]: '''simple docstring''' with self.assertRaisesRegex( lowerCamelCase__ ,"""hf-internal-testing/no-config-test-repo does not appear to have a file named config.json.""" ,): SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained("""hf-internal-testing/no-config-test-repo""" ) def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ) -> Union[str, Any]: '''simple docstring''' with self.assertRaises(lowerCamelCase__ ): SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained("""hf-internal-testing/test_dynamic_model""" ) # If remote code is disabled, we can't load this config. with self.assertRaises(lowerCamelCase__ ): SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained("""hf-internal-testing/test_dynamic_model""" ,trust_remote_code=lowerCamelCase__ ) SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained("""hf-internal-testing/test_dynamic_model""" ,trust_remote_code=lowerCamelCase__ ) self.assertEqual(config.__class__.__name__ ,"""NewModelConfig""" ) # Test config can be reloaded. with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained(lowerCamelCase__ ,trust_remote_code=lowerCamelCase__ ) self.assertEqual(reloaded_config.__class__.__name__ ,"""NewModelConfig""" ) def SCREAMING_SNAKE_CASE__ ( self : Dict ) -> Union[str, Any]: '''simple docstring''' class UpperCamelCase__ ( lowerCAmelCase_ ): '''simple docstring''' __snake_case : Union[str, Any] = "new-model" try: AutoConfig.register("""new-model""" ,lowerCamelCase__ ) # If remote code is not set, the default is to use local SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained("""hf-internal-testing/test_dynamic_model""" ) self.assertEqual(config.__class__.__name__ ,"""NewModelConfigLocal""" ) # If remote code is disabled, we load the local one. SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained("""hf-internal-testing/test_dynamic_model""" ,trust_remote_code=lowerCamelCase__ ) self.assertEqual(config.__class__.__name__ ,"""NewModelConfigLocal""" ) # If remote is enabled, we load from the Hub SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained("""hf-internal-testing/test_dynamic_model""" ,trust_remote_code=lowerCamelCase__ ) self.assertEqual(config.__class__.__name__ ,"""NewModelConfig""" ) finally: if "new-model" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["new-model"]
296
1
from __future__ import annotations import math import numpy as np from numpy.linalg import norm def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> float: '''simple docstring''' return math.sqrt(sum(pow(a - b , 2 ) for a, b in zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) ) def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> list[list[list[float] | float]]: '''simple docstring''' if dataset.ndim != value_array.ndim: SCREAMING_SNAKE_CASE = ( """Wrong input data's dimensions... """ F"""dataset : {dataset.ndim}, value_array : {value_array.ndim}""" ) raise ValueError(_SCREAMING_SNAKE_CASE ) try: if dataset.shape[1] != value_array.shape[1]: SCREAMING_SNAKE_CASE = ( """Wrong input data's shape... """ F"""dataset : {dataset.shape[1]}, value_array : {value_array.shape[1]}""" ) raise ValueError(_SCREAMING_SNAKE_CASE ) except IndexError: if dataset.ndim != value_array.ndim: raise TypeError("""Wrong shape""" ) if dataset.dtype != value_array.dtype: SCREAMING_SNAKE_CASE = ( """Input data have different datatype... """ F"""dataset : {dataset.dtype}, value_array : {value_array.dtype}""" ) raise TypeError(_SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE = [] for value in value_array: SCREAMING_SNAKE_CASE = euclidean(_SCREAMING_SNAKE_CASE , dataset[0] ) SCREAMING_SNAKE_CASE = dataset[0].tolist() for dataset_value in dataset[1:]: SCREAMING_SNAKE_CASE = euclidean(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if dist > temp_dist: SCREAMING_SNAKE_CASE = temp_dist SCREAMING_SNAKE_CASE = dataset_value.tolist() answer.append([vector, dist] ) return answer def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> float: '''simple docstring''' return np.dot(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) / (norm(_SCREAMING_SNAKE_CASE ) * norm(_SCREAMING_SNAKE_CASE )) if __name__ == "__main__": import doctest doctest.testmod()
296
import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging SCREAMING_SNAKE_CASE_ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE_ = { """microsoft/git-base""": """https://huggingface.co/microsoft/git-base/resolve/main/config.json""", } class UpperCamelCase__ ( lowerCAmelCase_ ): '''simple docstring''' __snake_case : Dict = "git_vision_model" def __init__( self : List[Any] ,lowerCamelCase__ : Dict=768 ,lowerCamelCase__ : Union[str, Any]=3072 ,lowerCamelCase__ : Optional[int]=12 ,lowerCamelCase__ : Tuple=12 ,lowerCamelCase__ : Tuple=3 ,lowerCamelCase__ : Optional[Any]=224 ,lowerCamelCase__ : Union[str, Any]=16 ,lowerCamelCase__ : List[Any]="quick_gelu" ,lowerCamelCase__ : Optional[Any]=1e-5 ,lowerCamelCase__ : str=0.0 ,lowerCamelCase__ : Optional[int]=0.02 ,**lowerCamelCase__ : Union[str, Any] ,) -> Optional[int]: '''simple docstring''' super().__init__(**lowerCamelCase__ ) SCREAMING_SNAKE_CASE = hidden_size SCREAMING_SNAKE_CASE = intermediate_size SCREAMING_SNAKE_CASE = num_hidden_layers SCREAMING_SNAKE_CASE = num_attention_heads SCREAMING_SNAKE_CASE = num_channels SCREAMING_SNAKE_CASE = patch_size SCREAMING_SNAKE_CASE = image_size SCREAMING_SNAKE_CASE = initializer_range SCREAMING_SNAKE_CASE = attention_dropout SCREAMING_SNAKE_CASE = layer_norm_eps SCREAMING_SNAKE_CASE = hidden_act @classmethod def SCREAMING_SNAKE_CASE__ ( cls : Tuple ,lowerCamelCase__ : Union[str, os.PathLike] ,**lowerCamelCase__ : int ) -> "PretrainedConfig": '''simple docstring''' cls._set_token_in_kwargs(lowerCamelCase__ ) SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE = cls.get_config_dict(lowerCamelCase__ ,**lowerCamelCase__ ) # get the vision config dict if we are loading from GITConfig if config_dict.get("""model_type""" ) == "git": SCREAMING_SNAKE_CASE = config_dict["""vision_config"""] if "model_type" in config_dict and hasattr(cls ,"""model_type""" ) and config_dict["model_type"] != cls.model_type: logger.warning( F"""You are using a model of type {config_dict['model_type']} to instantiate a model of type """ F"""{cls.model_type}. This is not supported for all configurations of models and can yield errors.""" ) return cls.from_dict(lowerCamelCase__ ,**lowerCamelCase__ ) class UpperCamelCase__ ( lowerCAmelCase_ ): '''simple docstring''' __snake_case : Dict = "git" def __init__( self : Optional[int] ,lowerCamelCase__ : int=None ,lowerCamelCase__ : str=30522 ,lowerCamelCase__ : Tuple=768 ,lowerCamelCase__ : Union[str, Any]=6 ,lowerCamelCase__ : str=12 ,lowerCamelCase__ : List[str]=3072 ,lowerCamelCase__ : Dict="gelu" ,lowerCamelCase__ : Tuple=0.1 ,lowerCamelCase__ : Any=0.1 ,lowerCamelCase__ : List[str]=1024 ,lowerCamelCase__ : List[str]=0.02 ,lowerCamelCase__ : str=1e-1_2 ,lowerCamelCase__ : Optional[int]=0 ,lowerCamelCase__ : Optional[int]="absolute" ,lowerCamelCase__ : Optional[Any]=True ,lowerCamelCase__ : str=False ,lowerCamelCase__ : int=101 ,lowerCamelCase__ : int=102 ,lowerCamelCase__ : Dict=None ,**lowerCamelCase__ : List[Any] ,) -> Optional[Any]: '''simple docstring''' super().__init__(bos_token_id=lowerCamelCase__ ,eos_token_id=lowerCamelCase__ ,pad_token_id=lowerCamelCase__ ,**lowerCamelCase__ ) if vision_config is None: SCREAMING_SNAKE_CASE = {} logger.info("""vision_config is None. initializing the GitVisionConfig with default values.""" ) SCREAMING_SNAKE_CASE = GitVisionConfig(**lowerCamelCase__ ) SCREAMING_SNAKE_CASE = vocab_size SCREAMING_SNAKE_CASE = hidden_size SCREAMING_SNAKE_CASE = num_hidden_layers SCREAMING_SNAKE_CASE = num_attention_heads SCREAMING_SNAKE_CASE = hidden_act SCREAMING_SNAKE_CASE = intermediate_size SCREAMING_SNAKE_CASE = hidden_dropout_prob SCREAMING_SNAKE_CASE = attention_probs_dropout_prob SCREAMING_SNAKE_CASE = max_position_embeddings SCREAMING_SNAKE_CASE = initializer_range SCREAMING_SNAKE_CASE = layer_norm_eps SCREAMING_SNAKE_CASE = position_embedding_type SCREAMING_SNAKE_CASE = use_cache SCREAMING_SNAKE_CASE = tie_word_embeddings SCREAMING_SNAKE_CASE = num_image_with_embedding SCREAMING_SNAKE_CASE = bos_token_id SCREAMING_SNAKE_CASE = eos_token_id def SCREAMING_SNAKE_CASE__ ( self : Dict ) -> Optional[int]: '''simple docstring''' SCREAMING_SNAKE_CASE = copy.deepcopy(self.__dict__ ) SCREAMING_SNAKE_CASE = self.vision_config.to_dict() SCREAMING_SNAKE_CASE = self.__class__.model_type return output
296
1
import qiskit def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> qiskit.result.counts.Counts: '''simple docstring''' SCREAMING_SNAKE_CASE = qiskit.Aer.get_backend("""aer_simulator""" ) # Create a Quantum Circuit acting on the q register SCREAMING_SNAKE_CASE = qiskit.QuantumCircuit(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # Map the quantum measurement to the classical bits circuit.measure([0] , [0] ) # Execute the circuit on the simulator SCREAMING_SNAKE_CASE = qiskit.execute(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , shots=10_00 ) # Return the histogram data of the results of the experiment. return job.result().get_counts(_SCREAMING_SNAKE_CASE ) if __name__ == "__main__": print(F'''Total count for various states are: {single_qubit_measure(1, 1)}''')
296
import itertools import os import random import tempfile import unittest import numpy as np from transformers import TvltFeatureExtractor, is_datasets_available from transformers.testing_utils import check_json_file_has_correct_format, require_torch, require_torchaudio from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin if is_torch_available(): import torch if is_datasets_available(): from datasets import load_dataset SCREAMING_SNAKE_CASE_ = random.Random() def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=1.0 , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None ) -> Tuple: '''simple docstring''' if rng is None: SCREAMING_SNAKE_CASE = global_rng SCREAMING_SNAKE_CASE = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values class UpperCamelCase__ ( unittest.TestCase ): '''simple docstring''' def __init__( self : List[Any] ,lowerCamelCase__ : str ,lowerCamelCase__ : Optional[int]=7 ,lowerCamelCase__ : Optional[Any]=400 ,lowerCamelCase__ : List[str]=2000 ,lowerCamelCase__ : List[str]=2048 ,lowerCamelCase__ : Any=128 ,lowerCamelCase__ : List[str]=1 ,lowerCamelCase__ : str=512 ,lowerCamelCase__ : Optional[Any]=30 ,lowerCamelCase__ : Tuple=44100 ,) -> Tuple: '''simple docstring''' SCREAMING_SNAKE_CASE = parent SCREAMING_SNAKE_CASE = batch_size SCREAMING_SNAKE_CASE = min_seq_length SCREAMING_SNAKE_CASE = max_seq_length SCREAMING_SNAKE_CASE = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) SCREAMING_SNAKE_CASE = spectrogram_length SCREAMING_SNAKE_CASE = feature_size SCREAMING_SNAKE_CASE = num_audio_channels SCREAMING_SNAKE_CASE = hop_length SCREAMING_SNAKE_CASE = chunk_length SCREAMING_SNAKE_CASE = sampling_rate def SCREAMING_SNAKE_CASE__ ( self : List[Any] ) -> Optional[int]: '''simple docstring''' return { "spectrogram_length": self.spectrogram_length, "feature_size": self.feature_size, "num_audio_channels": self.num_audio_channels, "hop_length": self.hop_length, "chunk_length": self.chunk_length, "sampling_rate": self.sampling_rate, } def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ,lowerCamelCase__ : Tuple=False ,lowerCamelCase__ : Union[str, Any]=False ) -> str: '''simple docstring''' def _flatten(lowerCamelCase__ : List[Any] ): return list(itertools.chain(*lowerCamelCase__ ) ) if equal_length: SCREAMING_SNAKE_CASE = [floats_list((self.max_seq_length, self.feature_size) ) for _ in range(self.batch_size )] else: # make sure that inputs increase in size SCREAMING_SNAKE_CASE = [ floats_list((x, self.feature_size) ) for x in range(self.min_seq_length ,self.max_seq_length ,self.seq_length_diff ) ] if numpify: SCREAMING_SNAKE_CASE = [np.asarray(lowerCamelCase__ ) for x in speech_inputs] return speech_inputs @require_torch @require_torchaudio class UpperCamelCase__ ( lowerCAmelCase_ , unittest.TestCase ): '''simple docstring''' __snake_case : List[Any] = TvltFeatureExtractor def SCREAMING_SNAKE_CASE__ ( self : str ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE = TvltFeatureExtractionTester(self ) def SCREAMING_SNAKE_CASE__ ( self : List[Any] ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_dict ) self.assertTrue(hasattr(lowerCamelCase__ ,"""spectrogram_length""" ) ) self.assertTrue(hasattr(lowerCamelCase__ ,"""feature_size""" ) ) self.assertTrue(hasattr(lowerCamelCase__ ,"""num_audio_channels""" ) ) self.assertTrue(hasattr(lowerCamelCase__ ,"""hop_length""" ) ) self.assertTrue(hasattr(lowerCamelCase__ ,"""chunk_length""" ) ) self.assertTrue(hasattr(lowerCamelCase__ ,"""sampling_rate""" ) ) def SCREAMING_SNAKE_CASE__ ( self : str ) -> Union[str, Any]: '''simple docstring''' SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: SCREAMING_SNAKE_CASE = feat_extract_first.save_pretrained(lowerCamelCase__ )[0] check_json_file_has_correct_format(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = self.feature_extraction_class.from_pretrained(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = feat_extract_first.to_dict() SCREAMING_SNAKE_CASE = feat_extract_second.to_dict() SCREAMING_SNAKE_CASE = dict_first.pop("""mel_filters""" ) SCREAMING_SNAKE_CASE = dict_second.pop("""mel_filters""" ) self.assertTrue(np.allclose(lowerCamelCase__ ,lowerCamelCase__ ) ) self.assertEqual(lowerCamelCase__ ,lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( self : Any ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: SCREAMING_SNAKE_CASE = os.path.join(lowerCamelCase__ ,"""feat_extract.json""" ) feat_extract_first.to_json_file(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = self.feature_extraction_class.from_json_file(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = feat_extract_first.to_dict() SCREAMING_SNAKE_CASE = feat_extract_second.to_dict() SCREAMING_SNAKE_CASE = dict_first.pop("""mel_filters""" ) SCREAMING_SNAKE_CASE = dict_second.pop("""mel_filters""" ) self.assertTrue(np.allclose(lowerCamelCase__ ,lowerCamelCase__ ) ) self.assertEqual(lowerCamelCase__ ,lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( self : str ) -> Optional[int]: '''simple docstring''' SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_dict ) # create three inputs of length 800, 1000, and 1200 SCREAMING_SNAKE_CASE = [floats_list((1, x) )[0] for x in range(800 ,1400 ,200 )] SCREAMING_SNAKE_CASE = [np.asarray(lowerCamelCase__ ) for speech_input in speech_inputs] # Test not batched input SCREAMING_SNAKE_CASE = feature_extractor(np_speech_inputs[0] ,return_tensors="""np""" ,sampling_rate=44100 ).audio_values self.assertTrue(encoded_audios.ndim == 4 ) self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size ) self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length ) self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels ) # Test batched SCREAMING_SNAKE_CASE = feature_extractor(lowerCamelCase__ ,return_tensors="""np""" ,sampling_rate=44100 ).audio_values self.assertTrue(encoded_audios.ndim == 4 ) self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size ) self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length ) self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels ) # Test audio masking SCREAMING_SNAKE_CASE = feature_extractor( lowerCamelCase__ ,return_tensors="""np""" ,sampling_rate=44100 ,mask_audio=lowerCamelCase__ ).audio_values self.assertTrue(encoded_audios.ndim == 4 ) self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size ) self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length ) self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels ) # Test 2-D numpy arrays are batched. SCREAMING_SNAKE_CASE = [floats_list((1, x) )[0] for x in (800, 800, 800)] SCREAMING_SNAKE_CASE = np.asarray(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = feature_extractor(lowerCamelCase__ ,return_tensors="""np""" ,sampling_rate=44100 ).audio_values self.assertTrue(encoded_audios.ndim == 4 ) self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size ) self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length ) self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels ) def SCREAMING_SNAKE_CASE__ ( self : Any ,lowerCamelCase__ : str ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE = load_dataset("""hf-internal-testing/librispeech_asr_dummy""" ,"""clean""" ,split="""validation""" ) # automatic decoding with librispeech SCREAMING_SNAKE_CASE = ds.sort("""id""" ).select(range(lowerCamelCase__ ) )[:num_samples]["""audio"""] return [x["array"] for x in speech_samples] def SCREAMING_SNAKE_CASE__ ( self : Tuple ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE = self._load_datasamples(1 ) SCREAMING_SNAKE_CASE = TvltFeatureExtractor() SCREAMING_SNAKE_CASE = feature_extractor(lowerCamelCase__ ,return_tensors="""pt""" ).audio_values self.assertEquals(audio_values.shape ,(1, 1, 192, 128) ) SCREAMING_SNAKE_CASE = torch.tensor([[-0.3032, -0.2708], [-0.4434, -0.4007]] ) self.assertTrue(torch.allclose(audio_values[0, 0, :2, :2] ,lowerCamelCase__ ,atol=1e-4 ) )
296
1
import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import AddedToken from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_rembert import RemBertTokenizer else: SCREAMING_SNAKE_CASE_ = None SCREAMING_SNAKE_CASE_ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE_ = {"""vocab_file""": """sentencepiece.model""", """tokenizer_file""": """tokenizer.json"""} SCREAMING_SNAKE_CASE_ = { """vocab_file""": { """google/rembert""": """https://huggingface.co/google/rembert/resolve/main/sentencepiece.model""", }, """tokenizer_file""": { """google/rembert""": """https://huggingface.co/google/rembert/resolve/main/tokenizer.json""", }, } SCREAMING_SNAKE_CASE_ = { """google/rembert""": 2_5_6, } SCREAMING_SNAKE_CASE_ = """▁""" class UpperCamelCase__ ( lowerCAmelCase_ ): '''simple docstring''' __snake_case : Any = VOCAB_FILES_NAMES __snake_case : Any = PRETRAINED_VOCAB_FILES_MAP __snake_case : Any = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __snake_case : Dict = RemBertTokenizer def __init__( self : Union[str, Any] ,lowerCamelCase__ : Optional[int]=None ,lowerCamelCase__ : Union[str, Any]=None ,lowerCamelCase__ : Optional[Any]=True ,lowerCamelCase__ : int=True ,lowerCamelCase__ : Dict=False ,lowerCamelCase__ : Optional[int]="[CLS]" ,lowerCamelCase__ : Dict="[SEP]" ,lowerCamelCase__ : List[Any]="<unk>" ,lowerCamelCase__ : str="[SEP]" ,lowerCamelCase__ : List[Any]="<pad>" ,lowerCamelCase__ : Optional[Any]="[CLS]" ,lowerCamelCase__ : Optional[int]="[MASK]" ,**lowerCamelCase__ : Optional[int] ,) -> List[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE = AddedToken(lowerCamelCase__ ,lstrip=lowerCamelCase__ ,rstrip=lowerCamelCase__ ) if isinstance(lowerCamelCase__ ,lowerCamelCase__ ) else mask_token super().__init__( lowerCamelCase__ ,tokenizer_file=lowerCamelCase__ ,do_lower_case=lowerCamelCase__ ,remove_space=lowerCamelCase__ ,keep_accents=lowerCamelCase__ ,bos_token=lowerCamelCase__ ,eos_token=lowerCamelCase__ ,unk_token=lowerCamelCase__ ,sep_token=lowerCamelCase__ ,pad_token=lowerCamelCase__ ,cls_token=lowerCamelCase__ ,mask_token=lowerCamelCase__ ,**lowerCamelCase__ ,) SCREAMING_SNAKE_CASE = do_lower_case SCREAMING_SNAKE_CASE = remove_space SCREAMING_SNAKE_CASE = keep_accents SCREAMING_SNAKE_CASE = vocab_file SCREAMING_SNAKE_CASE = False if not self.vocab_file else True def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ,lowerCamelCase__ : List[int] ,lowerCamelCase__ : Optional[List[int]] = None ) -> List[int]: '''simple docstring''' SCREAMING_SNAKE_CASE = [self.sep_token_id] SCREAMING_SNAKE_CASE = [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 SCREAMING_SNAKE_CASE__ ( self : int ,lowerCamelCase__ : List[int] ,lowerCamelCase__ : Optional[List[int]] = None ,lowerCamelCase__ : bool = False ) -> List[int]: '''simple docstring''' if already_has_special_tokens: if token_ids_a is not None: raise ValueError( """You should not supply a second sequence if the provided sequence of """ """ids is already formatted with special tokens for the model.""" ) return [1 if x in [self.sep_token_id, self.cls_token_id] else 0 for x in token_ids_a] if token_ids_a is not None: return [1] + ([0] * len(lowerCamelCase__ )) + [1] + ([0] * len(lowerCamelCase__ )) + [1] return [1] + ([0] * len(lowerCamelCase__ )) + [1] def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ,lowerCamelCase__ : List[int] ,lowerCamelCase__ : Optional[List[int]] = None ) -> List[int]: '''simple docstring''' SCREAMING_SNAKE_CASE = [self.sep_token_id] SCREAMING_SNAKE_CASE = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def SCREAMING_SNAKE_CASE__ ( self : List[str] ,lowerCamelCase__ : str ,lowerCamelCase__ : Optional[str] = None ) -> Tuple[str]: '''simple docstring''' if not os.path.isdir(lowerCamelCase__ ): logger.error("""Vocabulary path ({}) should be a directory""".format(lowerCamelCase__ ) ) return SCREAMING_SNAKE_CASE = os.path.join( lowerCamelCase__ ,(filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(lowerCamelCase__ ): copyfile(self.vocab_file ,lowerCamelCase__ ) return (out_vocab_file,)
296
import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( MobileViTConfig, MobileViTForImageClassification, MobileViTForSemanticSegmentation, MobileViTImageProcessor, ) from transformers.utils import logging logging.set_verbosity_info() SCREAMING_SNAKE_CASE_ = logging.get_logger(__name__) def __lowercase ( _SCREAMING_SNAKE_CASE ) -> Optional[int]: '''simple docstring''' SCREAMING_SNAKE_CASE = MobileViTConfig() # size of the architecture if "mobilevit_s" in mobilevit_name: SCREAMING_SNAKE_CASE = [1_44, 1_92, 2_40] SCREAMING_SNAKE_CASE = [16, 32, 64, 96, 1_28, 1_60, 6_40] elif "mobilevit_xs" in mobilevit_name: SCREAMING_SNAKE_CASE = [96, 1_20, 1_44] SCREAMING_SNAKE_CASE = [16, 32, 48, 64, 80, 96, 3_84] elif "mobilevit_xxs" in mobilevit_name: SCREAMING_SNAKE_CASE = [64, 80, 96] SCREAMING_SNAKE_CASE = [16, 16, 24, 48, 64, 80, 3_20] SCREAMING_SNAKE_CASE = 0.05 SCREAMING_SNAKE_CASE = 2.0 if mobilevit_name.startswith("""deeplabv3_""" ): SCREAMING_SNAKE_CASE = 5_12 SCREAMING_SNAKE_CASE = 16 SCREAMING_SNAKE_CASE = 21 SCREAMING_SNAKE_CASE = """pascal-voc-id2label.json""" else: SCREAMING_SNAKE_CASE = 10_00 SCREAMING_SNAKE_CASE = """imagenet-1k-id2label.json""" SCREAMING_SNAKE_CASE = """huggingface/label-files""" SCREAMING_SNAKE_CASE = json.load(open(hf_hub_download(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , repo_type="""dataset""" ) , """r""" ) ) SCREAMING_SNAKE_CASE = {int(_SCREAMING_SNAKE_CASE ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE = idalabel SCREAMING_SNAKE_CASE = {v: k for k, v in idalabel.items()} return config def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=False ) -> str: '''simple docstring''' for i in range(1 , 6 ): if F"""layer_{i}.""" in name: SCREAMING_SNAKE_CASE = name.replace(F"""layer_{i}.""" , F"""encoder.layer.{i - 1}.""" ) if "conv_1." in name: SCREAMING_SNAKE_CASE = name.replace("""conv_1.""" , """conv_stem.""" ) if ".block." in name: SCREAMING_SNAKE_CASE = name.replace(""".block.""" , """.""" ) if "exp_1x1" in name: SCREAMING_SNAKE_CASE = name.replace("""exp_1x1""" , """expand_1x1""" ) if "red_1x1" in name: SCREAMING_SNAKE_CASE = name.replace("""red_1x1""" , """reduce_1x1""" ) if ".local_rep.conv_3x3." in name: SCREAMING_SNAKE_CASE = name.replace(""".local_rep.conv_3x3.""" , """.conv_kxk.""" ) if ".local_rep.conv_1x1." in name: SCREAMING_SNAKE_CASE = name.replace(""".local_rep.conv_1x1.""" , """.conv_1x1.""" ) if ".norm." in name: SCREAMING_SNAKE_CASE = name.replace(""".norm.""" , """.normalization.""" ) if ".conv." in name: SCREAMING_SNAKE_CASE = name.replace(""".conv.""" , """.convolution.""" ) if ".conv_proj." in name: SCREAMING_SNAKE_CASE = name.replace(""".conv_proj.""" , """.conv_projection.""" ) for i in range(0 , 2 ): for j in range(0 , 4 ): if F""".{i}.{j}.""" in name: SCREAMING_SNAKE_CASE = name.replace(F""".{i}.{j}.""" , F""".{i}.layer.{j}.""" ) for i in range(2 , 6 ): for j in range(0 , 4 ): if F""".{i}.{j}.""" in name: SCREAMING_SNAKE_CASE = name.replace(F""".{i}.{j}.""" , F""".{i}.""" ) if "expand_1x1" in name: SCREAMING_SNAKE_CASE = name.replace("""expand_1x1""" , """downsampling_layer.expand_1x1""" ) if "conv_3x3" in name: SCREAMING_SNAKE_CASE = name.replace("""conv_3x3""" , """downsampling_layer.conv_3x3""" ) if "reduce_1x1" in name: SCREAMING_SNAKE_CASE = name.replace("""reduce_1x1""" , """downsampling_layer.reduce_1x1""" ) for i in range(2 , 5 ): if F""".global_rep.{i}.weight""" in name: SCREAMING_SNAKE_CASE = name.replace(F""".global_rep.{i}.weight""" , """.layernorm.weight""" ) if F""".global_rep.{i}.bias""" in name: SCREAMING_SNAKE_CASE = name.replace(F""".global_rep.{i}.bias""" , """.layernorm.bias""" ) if ".global_rep." in name: SCREAMING_SNAKE_CASE = name.replace(""".global_rep.""" , """.transformer.""" ) if ".pre_norm_mha.0." in name: SCREAMING_SNAKE_CASE = name.replace(""".pre_norm_mha.0.""" , """.layernorm_before.""" ) if ".pre_norm_mha.1.out_proj." in name: SCREAMING_SNAKE_CASE = name.replace(""".pre_norm_mha.1.out_proj.""" , """.attention.output.dense.""" ) if ".pre_norm_ffn.0." in name: SCREAMING_SNAKE_CASE = name.replace(""".pre_norm_ffn.0.""" , """.layernorm_after.""" ) if ".pre_norm_ffn.1." in name: SCREAMING_SNAKE_CASE = name.replace(""".pre_norm_ffn.1.""" , """.intermediate.dense.""" ) if ".pre_norm_ffn.4." in name: SCREAMING_SNAKE_CASE = name.replace(""".pre_norm_ffn.4.""" , """.output.dense.""" ) if ".transformer." in name: SCREAMING_SNAKE_CASE = name.replace(""".transformer.""" , """.transformer.layer.""" ) if ".aspp_layer." in name: SCREAMING_SNAKE_CASE = name.replace(""".aspp_layer.""" , """.""" ) if ".aspp_pool." in name: SCREAMING_SNAKE_CASE = name.replace(""".aspp_pool.""" , """.""" ) if "seg_head." in name: SCREAMING_SNAKE_CASE = name.replace("""seg_head.""" , """segmentation_head.""" ) if "segmentation_head.classifier.classifier." in name: SCREAMING_SNAKE_CASE = name.replace("""segmentation_head.classifier.classifier.""" , """segmentation_head.classifier.""" ) if "classifier.fc." in name: SCREAMING_SNAKE_CASE = name.replace("""classifier.fc.""" , """classifier.""" ) elif (not base_model) and ("segmentation_head." not in name): SCREAMING_SNAKE_CASE = """mobilevit.""" + name return name def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=False ) -> Dict: '''simple docstring''' if base_model: SCREAMING_SNAKE_CASE = """""" else: SCREAMING_SNAKE_CASE = """mobilevit.""" for key in orig_state_dict.copy().keys(): SCREAMING_SNAKE_CASE = orig_state_dict.pop(_SCREAMING_SNAKE_CASE ) if key[:8] == "encoder.": SCREAMING_SNAKE_CASE = key[8:] if "qkv" in key: SCREAMING_SNAKE_CASE = key.split(""".""" ) SCREAMING_SNAKE_CASE = int(key_split[0][6:] ) - 1 SCREAMING_SNAKE_CASE = int(key_split[3] ) SCREAMING_SNAKE_CASE = model.get_submodule(F"""{model_prefix}encoder.layer.{layer_num}""" ) SCREAMING_SNAKE_CASE = layer.transformer.layer[transformer_num].attention.attention.all_head_size SCREAMING_SNAKE_CASE = ( F"""{model_prefix}encoder.layer.{layer_num}.transformer.layer.{transformer_num}.attention.attention.""" ) if "weight" in key: SCREAMING_SNAKE_CASE = val[:dim, :] SCREAMING_SNAKE_CASE = val[dim : dim * 2, :] SCREAMING_SNAKE_CASE = val[-dim:, :] else: SCREAMING_SNAKE_CASE = val[:dim] SCREAMING_SNAKE_CASE = val[dim : dim * 2] SCREAMING_SNAKE_CASE = val[-dim:] else: SCREAMING_SNAKE_CASE = val return orig_state_dict def __lowercase ( ) -> str: '''simple docstring''' SCREAMING_SNAKE_CASE = """http://images.cocodataset.org/val2017/000000039769.jpg""" SCREAMING_SNAKE_CASE = Image.open(requests.get(_SCREAMING_SNAKE_CASE , stream=_SCREAMING_SNAKE_CASE ).raw ) return im @torch.no_grad() def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=False ) -> str: '''simple docstring''' SCREAMING_SNAKE_CASE = get_mobilevit_config(_SCREAMING_SNAKE_CASE ) # load original state_dict SCREAMING_SNAKE_CASE = torch.load(_SCREAMING_SNAKE_CASE , map_location="""cpu""" ) # load 🤗 model if mobilevit_name.startswith("""deeplabv3_""" ): SCREAMING_SNAKE_CASE = MobileViTForSemanticSegmentation(_SCREAMING_SNAKE_CASE ).eval() else: SCREAMING_SNAKE_CASE = MobileViTForImageClassification(_SCREAMING_SNAKE_CASE ).eval() SCREAMING_SNAKE_CASE = convert_state_dict(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) model.load_state_dict(_SCREAMING_SNAKE_CASE ) # Check outputs on an image, prepared by MobileViTImageProcessor SCREAMING_SNAKE_CASE = MobileViTImageProcessor(crop_size=config.image_size , size=config.image_size + 32 ) SCREAMING_SNAKE_CASE = image_processor(images=prepare_img() , return_tensors="""pt""" ) SCREAMING_SNAKE_CASE = model(**_SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE = outputs.logits if mobilevit_name.startswith("""deeplabv3_""" ): assert logits.shape == (1, 21, 32, 32) if mobilevit_name == "deeplabv3_mobilevit_s": SCREAMING_SNAKE_CASE = torch.tensor( [ [[6.2_065, 6.1_292, 6.2_070], [6.1_079, 6.1_254, 6.1_747], [6.0_042, 6.1_071, 6.1_034]], [[-6.9_253, -6.8_653, -7.0_398], [-7.3_218, -7.3_983, -7.3_670], [-7.1_961, -7.2_482, -7.1_569]], [[-4.4_723, -4.4_348, -4.3_769], [-5.3_629, -5.4_632, -5.4_598], [-5.1_587, -5.3_402, -5.5_059]], ] ) elif mobilevit_name == "deeplabv3_mobilevit_xs": SCREAMING_SNAKE_CASE = torch.tensor( [ [[5.4_449, 5.5_733, 5.6_314], [5.1_815, 5.3_930, 5.5_963], [5.1_656, 5.4_333, 5.4_853]], [[-9.4_423, -9.7_766, -9.6_714], [-9.1_581, -9.5_720, -9.5_519], [-9.1_006, -9.6_458, -9.5_703]], [[-7.7_721, -7.3_716, -7.1_583], [-8.4_599, -8.0_624, -7.7_944], [-8.4_172, -7.8_366, -7.5_025]], ] ) elif mobilevit_name == "deeplabv3_mobilevit_xxs": SCREAMING_SNAKE_CASE = torch.tensor( [ [[6.9_811, 6.9_743, 7.3_123], [7.1_777, 7.1_931, 7.3_938], [7.5_633, 7.8_050, 7.8_901]], [[-10.5_536, -10.2_332, -10.2_924], [-10.2_336, -9.8_624, -9.5_964], [-10.8_840, -10.8_158, -10.6_659]], [[-3.4_938, -3.0_631, -2.8_620], [-3.4_205, -2.8_135, -2.6_875], [-3.4_179, -2.7_945, -2.8_750]], ] ) else: raise ValueError(F"""Unknown mobilevit_name: {mobilevit_name}""" ) assert torch.allclose(logits[0, :3, :3, :3] , _SCREAMING_SNAKE_CASE , atol=1E-4 ) else: assert logits.shape == (1, 10_00) if mobilevit_name == "mobilevit_s": SCREAMING_SNAKE_CASE = torch.tensor([-0.9_866, 0.2_392, -1.1_241] ) elif mobilevit_name == "mobilevit_xs": SCREAMING_SNAKE_CASE = torch.tensor([-2.4_761, -0.9_399, -1.9_587] ) elif mobilevit_name == "mobilevit_xxs": SCREAMING_SNAKE_CASE = torch.tensor([-1.9_364, -1.2_327, -0.4_653] ) else: raise ValueError(F"""Unknown mobilevit_name: {mobilevit_name}""" ) assert torch.allclose(logits[0, :3] , _SCREAMING_SNAKE_CASE , atol=1E-4 ) Path(_SCREAMING_SNAKE_CASE ).mkdir(exist_ok=_SCREAMING_SNAKE_CASE ) print(F"""Saving model {mobilevit_name} to {pytorch_dump_folder_path}""" ) model.save_pretrained(_SCREAMING_SNAKE_CASE ) print(F"""Saving image processor to {pytorch_dump_folder_path}""" ) image_processor.save_pretrained(_SCREAMING_SNAKE_CASE ) if push_to_hub: SCREAMING_SNAKE_CASE = { """mobilevit_s""": """mobilevit-small""", """mobilevit_xs""": """mobilevit-x-small""", """mobilevit_xxs""": """mobilevit-xx-small""", """deeplabv3_mobilevit_s""": """deeplabv3-mobilevit-small""", """deeplabv3_mobilevit_xs""": """deeplabv3-mobilevit-x-small""", """deeplabv3_mobilevit_xxs""": """deeplabv3-mobilevit-xx-small""", } print("""Pushing to the hub...""" ) SCREAMING_SNAKE_CASE = model_mapping[mobilevit_name] image_processor.push_to_hub(_SCREAMING_SNAKE_CASE , organization="""apple""" ) model.push_to_hub(_SCREAMING_SNAKE_CASE , organization="""apple""" ) if __name__ == "__main__": SCREAMING_SNAKE_CASE_ = argparse.ArgumentParser() # Required parameters parser.add_argument( """--mobilevit_name""", default="""mobilevit_s""", type=str, help=( """Name of the MobileViT model you'd like to convert. Should be one of 'mobilevit_s', 'mobilevit_xs',""" """ 'mobilevit_xxs', 'deeplabv3_mobilevit_s', 'deeplabv3_mobilevit_xs', 'deeplabv3_mobilevit_xxs'.""" ), ) parser.add_argument( """--checkpoint_path""", required=True, type=str, help="""Path to the original state dict (.pt file).""" ) parser.add_argument( """--pytorch_dump_folder_path""", required=True, type=str, help="""Path to the output PyTorch model directory.""" ) parser.add_argument( """--push_to_hub""", action="""store_true""", help="""Whether or not to push the converted model to the 🤗 hub.""" ) SCREAMING_SNAKE_CASE_ = parser.parse_args() convert_movilevit_checkpoint( args.mobilevit_name, args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub )
296
1
def __lowercase ( _SCREAMING_SNAKE_CASE ) -> bool: '''simple docstring''' SCREAMING_SNAKE_CASE = (1 + 24 * n) ** 0.5 return ((1 + root) / 6) % 1 == 0 def __lowercase ( _SCREAMING_SNAKE_CASE = 50_00 ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE = [(i * (3 * i - 1)) // 2 for i in range(1 , _SCREAMING_SNAKE_CASE )] for i, pentagonal_i in enumerate(_SCREAMING_SNAKE_CASE ): for j in range(_SCREAMING_SNAKE_CASE , len(_SCREAMING_SNAKE_CASE ) ): SCREAMING_SNAKE_CASE = pentagonal_nums[j] SCREAMING_SNAKE_CASE = pentagonal_i + pentagonal_j SCREAMING_SNAKE_CASE = pentagonal_j - pentagonal_i if is_pentagonal(_SCREAMING_SNAKE_CASE ) and is_pentagonal(_SCREAMING_SNAKE_CASE ): return b return -1 if __name__ == "__main__": print(F'''{solution() = }''')
296
from collections import OrderedDict from ...utils import logging from .auto_factory import _BaseAutoModelClass, _LazyAutoMapping, auto_class_update from .configuration_auto import CONFIG_MAPPING_NAMES SCREAMING_SNAKE_CASE_ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE_ = 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"""), ] ) SCREAMING_SNAKE_CASE_ = 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"""), ] ) SCREAMING_SNAKE_CASE_ = 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"""), ] ) SCREAMING_SNAKE_CASE_ = 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"""), ] ) SCREAMING_SNAKE_CASE_ = OrderedDict( [ # Model for Image-classsification ("""beit""", """FlaxBeitForImageClassification"""), ("""regnet""", """FlaxRegNetForImageClassification"""), ("""resnet""", """FlaxResNetForImageClassification"""), ("""vit""", """FlaxViTForImageClassification"""), ] ) SCREAMING_SNAKE_CASE_ = OrderedDict( [ ("""vision-encoder-decoder""", """FlaxVisionEncoderDecoderModel"""), ] ) SCREAMING_SNAKE_CASE_ = 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"""), ] ) SCREAMING_SNAKE_CASE_ = 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"""), ] ) SCREAMING_SNAKE_CASE_ = 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"""), ] ) SCREAMING_SNAKE_CASE_ = 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"""), ] ) SCREAMING_SNAKE_CASE_ = 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"""), ] ) SCREAMING_SNAKE_CASE_ = OrderedDict( [ ("""bert""", """FlaxBertForNextSentencePrediction"""), ] ) SCREAMING_SNAKE_CASE_ = OrderedDict( [ ("""speech-encoder-decoder""", """FlaxSpeechEncoderDecoderModel"""), ("""whisper""", """FlaxWhisperForConditionalGeneration"""), ] ) SCREAMING_SNAKE_CASE_ = OrderedDict( [ ("""whisper""", """FlaxWhisperForAudioClassification"""), ] ) SCREAMING_SNAKE_CASE_ = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_MAPPING_NAMES) SCREAMING_SNAKE_CASE_ = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_PRETRAINING_MAPPING_NAMES) SCREAMING_SNAKE_CASE_ = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MASKED_LM_MAPPING_NAMES) SCREAMING_SNAKE_CASE_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES ) SCREAMING_SNAKE_CASE_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES ) SCREAMING_SNAKE_CASE_ = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES) SCREAMING_SNAKE_CASE_ = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_CAUSAL_LM_MAPPING_NAMES) SCREAMING_SNAKE_CASE_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES ) SCREAMING_SNAKE_CASE_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES ) SCREAMING_SNAKE_CASE_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES ) SCREAMING_SNAKE_CASE_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES ) SCREAMING_SNAKE_CASE_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING_NAMES ) SCREAMING_SNAKE_CASE_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES ) SCREAMING_SNAKE_CASE_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES ) class UpperCamelCase__ ( _BaseAutoModelClass ): '''simple docstring''' __snake_case : List[str] = FLAX_MODEL_MAPPING SCREAMING_SNAKE_CASE_ = auto_class_update(FlaxAutoModel) class UpperCamelCase__ ( _BaseAutoModelClass ): '''simple docstring''' __snake_case : Dict = FLAX_MODEL_FOR_PRETRAINING_MAPPING SCREAMING_SNAKE_CASE_ = auto_class_update(FlaxAutoModelForPreTraining, head_doc="""pretraining""") class UpperCamelCase__ ( _BaseAutoModelClass ): '''simple docstring''' __snake_case : Optional[Any] = FLAX_MODEL_FOR_CAUSAL_LM_MAPPING SCREAMING_SNAKE_CASE_ = auto_class_update(FlaxAutoModelForCausalLM, head_doc="""causal language modeling""") class UpperCamelCase__ ( _BaseAutoModelClass ): '''simple docstring''' __snake_case : Any = FLAX_MODEL_FOR_MASKED_LM_MAPPING SCREAMING_SNAKE_CASE_ = auto_class_update(FlaxAutoModelForMaskedLM, head_doc="""masked language modeling""") class UpperCamelCase__ ( _BaseAutoModelClass ): '''simple docstring''' __snake_case : int = FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING SCREAMING_SNAKE_CASE_ = auto_class_update( FlaxAutoModelForSeqaSeqLM, head_doc="""sequence-to-sequence language modeling""", checkpoint_for_example="""t5-base""" ) class UpperCamelCase__ ( _BaseAutoModelClass ): '''simple docstring''' __snake_case : Optional[int] = FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING SCREAMING_SNAKE_CASE_ = auto_class_update( FlaxAutoModelForSequenceClassification, head_doc="""sequence classification""" ) class UpperCamelCase__ ( _BaseAutoModelClass ): '''simple docstring''' __snake_case : List[Any] = FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING SCREAMING_SNAKE_CASE_ = auto_class_update(FlaxAutoModelForQuestionAnswering, head_doc="""question answering""") class UpperCamelCase__ ( _BaseAutoModelClass ): '''simple docstring''' __snake_case : Tuple = FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING SCREAMING_SNAKE_CASE_ = auto_class_update( FlaxAutoModelForTokenClassification, head_doc="""token classification""" ) class UpperCamelCase__ ( _BaseAutoModelClass ): '''simple docstring''' __snake_case : Union[str, Any] = FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING SCREAMING_SNAKE_CASE_ = auto_class_update(FlaxAutoModelForMultipleChoice, head_doc="""multiple choice""") class UpperCamelCase__ ( _BaseAutoModelClass ): '''simple docstring''' __snake_case : List[str] = FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING SCREAMING_SNAKE_CASE_ = auto_class_update( FlaxAutoModelForNextSentencePrediction, head_doc="""next sentence prediction""" ) class UpperCamelCase__ ( _BaseAutoModelClass ): '''simple docstring''' __snake_case : Dict = FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING SCREAMING_SNAKE_CASE_ = auto_class_update( FlaxAutoModelForImageClassification, head_doc="""image classification""" ) class UpperCamelCase__ ( _BaseAutoModelClass ): '''simple docstring''' __snake_case : Dict = FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING SCREAMING_SNAKE_CASE_ = auto_class_update(FlaxAutoModelForVisionaSeq, head_doc="""vision-to-text modeling""") class UpperCamelCase__ ( _BaseAutoModelClass ): '''simple docstring''' __snake_case : Optional[Any] = FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING SCREAMING_SNAKE_CASE_ = auto_class_update( FlaxAutoModelForSpeechSeqaSeq, head_doc="""sequence-to-sequence speech-to-text modeling""" )
296
1
import copy from collections import OrderedDict from typing import Dict, Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ..auto import CONFIG_MAPPING SCREAMING_SNAKE_CASE_ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE_ = { """facebook/detr-resnet-50""": """https://huggingface.co/facebook/detr-resnet-50/resolve/main/config.json""", # See all DETR models at https://huggingface.co/models?filter=detr } class UpperCamelCase__ ( lowerCAmelCase_ ): '''simple docstring''' __snake_case : Union[str, Any] = "detr" __snake_case : List[str] = ["past_key_values"] __snake_case : Union[str, Any] = { "hidden_size": "d_model", "num_attention_heads": "encoder_attention_heads", } def __init__( self : Any ,lowerCamelCase__ : Optional[Any]=True ,lowerCamelCase__ : List[str]=None ,lowerCamelCase__ : str=3 ,lowerCamelCase__ : Tuple=100 ,lowerCamelCase__ : List[Any]=6 ,lowerCamelCase__ : Dict=2048 ,lowerCamelCase__ : List[Any]=8 ,lowerCamelCase__ : List[Any]=6 ,lowerCamelCase__ : Union[str, Any]=2048 ,lowerCamelCase__ : Optional[Any]=8 ,lowerCamelCase__ : Union[str, Any]=0.0 ,lowerCamelCase__ : Tuple=0.0 ,lowerCamelCase__ : Optional[Any]=True ,lowerCamelCase__ : Tuple="relu" ,lowerCamelCase__ : Dict=256 ,lowerCamelCase__ : List[Any]=0.1 ,lowerCamelCase__ : Optional[Any]=0.0 ,lowerCamelCase__ : List[Any]=0.0 ,lowerCamelCase__ : int=0.02 ,lowerCamelCase__ : int=1.0 ,lowerCamelCase__ : int=False ,lowerCamelCase__ : str="sine" ,lowerCamelCase__ : Any="resnet50" ,lowerCamelCase__ : Any=True ,lowerCamelCase__ : str=False ,lowerCamelCase__ : Optional[int]=1 ,lowerCamelCase__ : str=5 ,lowerCamelCase__ : Any=2 ,lowerCamelCase__ : Any=1 ,lowerCamelCase__ : Optional[Any]=1 ,lowerCamelCase__ : Optional[Any]=5 ,lowerCamelCase__ : List[Any]=2 ,lowerCamelCase__ : Union[str, Any]=0.1 ,**lowerCamelCase__ : Union[str, Any] ,) -> int: '''simple docstring''' if backbone_config is not None and use_timm_backbone: raise ValueError("""You can't specify both `backbone_config` and `use_timm_backbone`.""" ) if not use_timm_backbone: if backbone_config is None: logger.info("""`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.""" ) SCREAMING_SNAKE_CASE = CONFIG_MAPPING["""resnet"""](out_features=["""stage4"""] ) elif isinstance(lowerCamelCase__ ,lowerCamelCase__ ): SCREAMING_SNAKE_CASE = backbone_config.get("""model_type""" ) SCREAMING_SNAKE_CASE = CONFIG_MAPPING[backbone_model_type] SCREAMING_SNAKE_CASE = config_class.from_dict(lowerCamelCase__ ) # set timm attributes to None SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE = None, None, None SCREAMING_SNAKE_CASE = use_timm_backbone SCREAMING_SNAKE_CASE = backbone_config SCREAMING_SNAKE_CASE = num_channels SCREAMING_SNAKE_CASE = num_queries SCREAMING_SNAKE_CASE = d_model SCREAMING_SNAKE_CASE = encoder_ffn_dim SCREAMING_SNAKE_CASE = encoder_layers SCREAMING_SNAKE_CASE = encoder_attention_heads SCREAMING_SNAKE_CASE = decoder_ffn_dim SCREAMING_SNAKE_CASE = decoder_layers SCREAMING_SNAKE_CASE = decoder_attention_heads SCREAMING_SNAKE_CASE = dropout SCREAMING_SNAKE_CASE = attention_dropout SCREAMING_SNAKE_CASE = activation_dropout SCREAMING_SNAKE_CASE = activation_function SCREAMING_SNAKE_CASE = init_std SCREAMING_SNAKE_CASE = init_xavier_std SCREAMING_SNAKE_CASE = encoder_layerdrop SCREAMING_SNAKE_CASE = decoder_layerdrop SCREAMING_SNAKE_CASE = encoder_layers SCREAMING_SNAKE_CASE = auxiliary_loss SCREAMING_SNAKE_CASE = position_embedding_type SCREAMING_SNAKE_CASE = backbone SCREAMING_SNAKE_CASE = use_pretrained_backbone SCREAMING_SNAKE_CASE = dilation # Hungarian matcher SCREAMING_SNAKE_CASE = class_cost SCREAMING_SNAKE_CASE = bbox_cost SCREAMING_SNAKE_CASE = giou_cost # Loss coefficients SCREAMING_SNAKE_CASE = mask_loss_coefficient SCREAMING_SNAKE_CASE = dice_loss_coefficient SCREAMING_SNAKE_CASE = bbox_loss_coefficient SCREAMING_SNAKE_CASE = giou_loss_coefficient SCREAMING_SNAKE_CASE = eos_coefficient super().__init__(is_encoder_decoder=lowerCamelCase__ ,**lowerCamelCase__ ) @property def SCREAMING_SNAKE_CASE__ ( self : List[str] ) -> int: '''simple docstring''' return self.encoder_attention_heads @property def SCREAMING_SNAKE_CASE__ ( self : str ) -> int: '''simple docstring''' return self.d_model @classmethod def SCREAMING_SNAKE_CASE__ ( cls : Dict ,lowerCamelCase__ : PretrainedConfig ,**lowerCamelCase__ : str ) -> Optional[Any]: '''simple docstring''' return cls(backbone_config=lowerCamelCase__ ,**lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( self : str ) -> Dict[str, any]: '''simple docstring''' SCREAMING_SNAKE_CASE = copy.deepcopy(self.__dict__ ) if output["backbone_config"] is not None: SCREAMING_SNAKE_CASE = self.backbone_config.to_dict() SCREAMING_SNAKE_CASE = self.__class__.model_type return output class UpperCamelCase__ ( lowerCAmelCase_ ): '''simple docstring''' __snake_case : Union[str, Any] = version.parse("1.11" ) @property def SCREAMING_SNAKE_CASE__ ( self : Tuple ) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' return OrderedDict( [ ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}), ("""pixel_mask""", {0: """batch"""}), ] ) @property def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ) -> float: '''simple docstring''' return 1e-5 @property def SCREAMING_SNAKE_CASE__ ( self : int ) -> int: '''simple docstring''' return 12
296
from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ..auto import CONFIG_MAPPING SCREAMING_SNAKE_CASE_ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE_ = { """microsoft/table-transformer-detection""": ( """https://huggingface.co/microsoft/table-transformer-detection/resolve/main/config.json""" ), } class UpperCamelCase__ ( lowerCAmelCase_ ): '''simple docstring''' __snake_case : Union[str, Any] = "table-transformer" __snake_case : Union[str, Any] = ["past_key_values"] __snake_case : List[Any] = { "hidden_size": "d_model", "num_attention_heads": "encoder_attention_heads", } def __init__( self : Optional[int] ,lowerCamelCase__ : Optional[Any]=True ,lowerCamelCase__ : Optional[Any]=None ,lowerCamelCase__ : List[Any]=3 ,lowerCamelCase__ : Optional[int]=100 ,lowerCamelCase__ : List[Any]=6 ,lowerCamelCase__ : Dict=2048 ,lowerCamelCase__ : List[Any]=8 ,lowerCamelCase__ : Dict=6 ,lowerCamelCase__ : Dict=2048 ,lowerCamelCase__ : Any=8 ,lowerCamelCase__ : Optional[int]=0.0 ,lowerCamelCase__ : int=0.0 ,lowerCamelCase__ : List[Any]=True ,lowerCamelCase__ : Optional[int]="relu" ,lowerCamelCase__ : Tuple=256 ,lowerCamelCase__ : Any=0.1 ,lowerCamelCase__ : Optional[Any]=0.0 ,lowerCamelCase__ : Tuple=0.0 ,lowerCamelCase__ : List[Any]=0.02 ,lowerCamelCase__ : int=1.0 ,lowerCamelCase__ : List[str]=False ,lowerCamelCase__ : Optional[Any]="sine" ,lowerCamelCase__ : List[str]="resnet50" ,lowerCamelCase__ : Optional[Any]=True ,lowerCamelCase__ : List[str]=False ,lowerCamelCase__ : int=1 ,lowerCamelCase__ : Dict=5 ,lowerCamelCase__ : Tuple=2 ,lowerCamelCase__ : Union[str, Any]=1 ,lowerCamelCase__ : str=1 ,lowerCamelCase__ : Any=5 ,lowerCamelCase__ : Tuple=2 ,lowerCamelCase__ : str=0.1 ,**lowerCamelCase__ : List[str] ,) -> Optional[int]: '''simple docstring''' if backbone_config is not None and use_timm_backbone: raise ValueError("""You can't specify both `backbone_config` and `use_timm_backbone`.""" ) if not use_timm_backbone: if backbone_config is None: logger.info("""`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.""" ) SCREAMING_SNAKE_CASE = CONFIG_MAPPING["""resnet"""](out_features=["""stage4"""] ) elif isinstance(lowerCamelCase__ ,lowerCamelCase__ ): SCREAMING_SNAKE_CASE = backbone_config.get("""model_type""" ) SCREAMING_SNAKE_CASE = CONFIG_MAPPING[backbone_model_type] SCREAMING_SNAKE_CASE = config_class.from_dict(lowerCamelCase__ ) # set timm attributes to None SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE = None, None, None SCREAMING_SNAKE_CASE = use_timm_backbone SCREAMING_SNAKE_CASE = backbone_config SCREAMING_SNAKE_CASE = num_channels SCREAMING_SNAKE_CASE = num_queries SCREAMING_SNAKE_CASE = d_model SCREAMING_SNAKE_CASE = encoder_ffn_dim SCREAMING_SNAKE_CASE = encoder_layers SCREAMING_SNAKE_CASE = encoder_attention_heads SCREAMING_SNAKE_CASE = decoder_ffn_dim SCREAMING_SNAKE_CASE = decoder_layers SCREAMING_SNAKE_CASE = decoder_attention_heads SCREAMING_SNAKE_CASE = dropout SCREAMING_SNAKE_CASE = attention_dropout SCREAMING_SNAKE_CASE = activation_dropout SCREAMING_SNAKE_CASE = activation_function SCREAMING_SNAKE_CASE = init_std SCREAMING_SNAKE_CASE = init_xavier_std SCREAMING_SNAKE_CASE = encoder_layerdrop SCREAMING_SNAKE_CASE = decoder_layerdrop SCREAMING_SNAKE_CASE = encoder_layers SCREAMING_SNAKE_CASE = auxiliary_loss SCREAMING_SNAKE_CASE = position_embedding_type SCREAMING_SNAKE_CASE = backbone SCREAMING_SNAKE_CASE = use_pretrained_backbone SCREAMING_SNAKE_CASE = dilation # Hungarian matcher SCREAMING_SNAKE_CASE = class_cost SCREAMING_SNAKE_CASE = bbox_cost SCREAMING_SNAKE_CASE = giou_cost # Loss coefficients SCREAMING_SNAKE_CASE = mask_loss_coefficient SCREAMING_SNAKE_CASE = dice_loss_coefficient SCREAMING_SNAKE_CASE = bbox_loss_coefficient SCREAMING_SNAKE_CASE = giou_loss_coefficient SCREAMING_SNAKE_CASE = eos_coefficient super().__init__(is_encoder_decoder=lowerCamelCase__ ,**lowerCamelCase__ ) @property def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ) -> int: '''simple docstring''' return self.encoder_attention_heads @property def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ) -> int: '''simple docstring''' return self.d_model class UpperCamelCase__ ( lowerCAmelCase_ ): '''simple docstring''' __snake_case : int = version.parse("1.11" ) @property def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' return OrderedDict( [ ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}), ("""pixel_mask""", {0: """batch"""}), ] ) @property def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ) -> float: '''simple docstring''' return 1e-5 @property def SCREAMING_SNAKE_CASE__ ( self : Any ) -> int: '''simple docstring''' return 12
296
1
from collections import OrderedDict from typing import TYPE_CHECKING, Any, Mapping, Optional, Union from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig, OnnxSeqaSeqConfigWithPast from ...utils import logging if TYPE_CHECKING: from ...feature_extraction_utils import FeatureExtractionMixin from ...tokenization_utils_base import PreTrainedTokenizerBase from ...utils import TensorType SCREAMING_SNAKE_CASE_ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE_ = { """openai/whisper-base""": """https://huggingface.co/openai/whisper-base/resolve/main/config.json""", } # fmt: off SCREAMING_SNAKE_CASE_ = [ 1, 2, 7, 8, 9, 1_0, 1_4, 2_5, 2_6, 2_7, 2_8, 2_9, 3_1, 5_8, 5_9, 6_0, 6_1, 6_2, 6_3, 9_0, 9_1, 9_2, 9_3, 3_5_7, 3_6_6, 4_3_8, 5_3_2, 6_8_5, 7_0_5, 7_9_6, 9_3_0, 1_0_5_8, 1_2_2_0, 1_2_6_7, 1_2_7_9, 1_3_0_3, 1_3_4_3, 1_3_7_7, 1_3_9_1, 1_6_3_5, 1_7_8_2, 1_8_7_5, 2_1_6_2, 2_3_6_1, 2_4_8_8, 3_4_6_7, 4_0_0_8, 4_2_1_1, 4_6_0_0, 4_8_0_8, 5_2_9_9, 5_8_5_5, 6_3_2_9, 7_2_0_3, 9_6_0_9, 9_9_5_9, 1_0_5_6_3, 1_0_7_8_6, 1_1_4_2_0, 1_1_7_0_9, 1_1_9_0_7, 1_3_1_6_3, 1_3_6_9_7, 1_3_7_0_0, 1_4_8_0_8, 1_5_3_0_6, 1_6_4_1_0, 1_6_7_9_1, 1_7_9_9_2, 1_9_2_0_3, 1_9_5_1_0, 2_0_7_2_4, 2_2_3_0_5, 2_2_9_3_5, 2_7_0_0_7, 3_0_1_0_9, 3_0_4_2_0, 3_3_4_0_9, 3_4_9_4_9, 4_0_2_8_3, 4_0_4_9_3, 4_0_5_4_9, 4_7_2_8_2, 4_9_1_4_6, 5_0_2_5_7, 5_0_3_5_9, 5_0_3_6_0, 5_0_3_6_1 ] SCREAMING_SNAKE_CASE_ = [ 1, 2, 7, 8, 9, 1_0, 1_4, 2_5, 2_6, 2_7, 2_8, 2_9, 3_1, 5_8, 5_9, 6_0, 6_1, 6_2, 6_3, 9_0, 9_1, 9_2, 9_3, 3_5_9, 5_0_3, 5_2_2, 5_4_2, 8_7_3, 8_9_3, 9_0_2, 9_1_8, 9_2_2, 9_3_1, 1_3_5_0, 1_8_5_3, 1_9_8_2, 2_4_6_0, 2_6_2_7, 3_2_4_6, 3_2_5_3, 3_2_6_8, 3_5_3_6, 3_8_4_6, 3_9_6_1, 4_1_8_3, 4_6_6_7, 6_5_8_5, 6_6_4_7, 7_2_7_3, 9_0_6_1, 9_3_8_3, 1_0_4_2_8, 1_0_9_2_9, 1_1_9_3_8, 1_2_0_3_3, 1_2_3_3_1, 1_2_5_6_2, 1_3_7_9_3, 1_4_1_5_7, 1_4_6_3_5, 1_5_2_6_5, 1_5_6_1_8, 1_6_5_5_3, 1_6_6_0_4, 1_8_3_6_2, 1_8_9_5_6, 2_0_0_7_5, 2_1_6_7_5, 2_2_5_2_0, 2_6_1_3_0, 2_6_1_6_1, 2_6_4_3_5, 2_8_2_7_9, 2_9_4_6_4, 3_1_6_5_0, 3_2_3_0_2, 3_2_4_7_0, 3_6_8_6_5, 4_2_8_6_3, 4_7_4_2_5, 4_9_8_7_0, 5_0_2_5_4, 5_0_2_5_8, 5_0_3_6_0, 5_0_3_6_1, 5_0_3_6_2 ] class UpperCamelCase__ ( lowerCAmelCase_ ): '''simple docstring''' __snake_case : Tuple = "whisper" __snake_case : str = ["past_key_values"] __snake_case : List[str] = {"num_attention_heads": "encoder_attention_heads", "hidden_size": "d_model"} def __init__( self : Union[str, Any] ,lowerCamelCase__ : Union[str, Any]=51865 ,lowerCamelCase__ : int=80 ,lowerCamelCase__ : List[str]=6 ,lowerCamelCase__ : Dict=4 ,lowerCamelCase__ : Optional[Any]=6 ,lowerCamelCase__ : Dict=4 ,lowerCamelCase__ : Tuple=1536 ,lowerCamelCase__ : Optional[int]=1536 ,lowerCamelCase__ : List[str]=0.0 ,lowerCamelCase__ : int=0.0 ,lowerCamelCase__ : List[str]=50257 ,lowerCamelCase__ : str=True ,lowerCamelCase__ : Optional[Any]=True ,lowerCamelCase__ : Any="gelu" ,lowerCamelCase__ : str=256 ,lowerCamelCase__ : str=0.0 ,lowerCamelCase__ : int=0.0 ,lowerCamelCase__ : Optional[Any]=0.0 ,lowerCamelCase__ : Dict=0.02 ,lowerCamelCase__ : Union[str, Any]=False ,lowerCamelCase__ : str=1500 ,lowerCamelCase__ : List[Any]=448 ,lowerCamelCase__ : Any=50256 ,lowerCamelCase__ : Union[str, Any]=50256 ,lowerCamelCase__ : List[Any]=50256 ,lowerCamelCase__ : int=None ,lowerCamelCase__ : List[str]=[220, 50256] ,lowerCamelCase__ : Optional[Any]=False ,lowerCamelCase__ : Tuple=256 ,lowerCamelCase__ : List[Any]=False ,lowerCamelCase__ : int=0.05 ,lowerCamelCase__ : Optional[int]=10 ,lowerCamelCase__ : str=2 ,lowerCamelCase__ : Tuple=0.0 ,lowerCamelCase__ : Optional[Any]=10 ,lowerCamelCase__ : int=0 ,lowerCamelCase__ : List[str]=7 ,**lowerCamelCase__ : List[str] ,) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE = vocab_size SCREAMING_SNAKE_CASE = num_mel_bins SCREAMING_SNAKE_CASE = d_model SCREAMING_SNAKE_CASE = encoder_layers SCREAMING_SNAKE_CASE = encoder_attention_heads SCREAMING_SNAKE_CASE = decoder_layers SCREAMING_SNAKE_CASE = decoder_attention_heads SCREAMING_SNAKE_CASE = decoder_ffn_dim SCREAMING_SNAKE_CASE = encoder_ffn_dim SCREAMING_SNAKE_CASE = dropout SCREAMING_SNAKE_CASE = attention_dropout SCREAMING_SNAKE_CASE = activation_dropout SCREAMING_SNAKE_CASE = activation_function SCREAMING_SNAKE_CASE = init_std SCREAMING_SNAKE_CASE = encoder_layerdrop SCREAMING_SNAKE_CASE = decoder_layerdrop SCREAMING_SNAKE_CASE = use_cache SCREAMING_SNAKE_CASE = encoder_layers SCREAMING_SNAKE_CASE = scale_embedding # scale factor will be sqrt(d_model) if True SCREAMING_SNAKE_CASE = max_source_positions SCREAMING_SNAKE_CASE = max_target_positions # Audio Classification-specific parameters. Feel free to ignore for other classes. SCREAMING_SNAKE_CASE = classifier_proj_size SCREAMING_SNAKE_CASE = use_weighted_layer_sum # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 SCREAMING_SNAKE_CASE = apply_spec_augment SCREAMING_SNAKE_CASE = mask_time_prob SCREAMING_SNAKE_CASE = mask_time_length SCREAMING_SNAKE_CASE = mask_time_min_masks SCREAMING_SNAKE_CASE = mask_feature_prob SCREAMING_SNAKE_CASE = mask_feature_length SCREAMING_SNAKE_CASE = mask_feature_min_masks SCREAMING_SNAKE_CASE = median_filter_width super().__init__( pad_token_id=lowerCamelCase__ ,bos_token_id=lowerCamelCase__ ,eos_token_id=lowerCamelCase__ ,is_encoder_decoder=lowerCamelCase__ ,decoder_start_token_id=lowerCamelCase__ ,suppress_tokens=lowerCamelCase__ ,begin_suppress_tokens=lowerCamelCase__ ,**lowerCamelCase__ ,) class UpperCamelCase__ ( lowerCAmelCase_ ): '''simple docstring''' @property def SCREAMING_SNAKE_CASE__ ( self : str ) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' SCREAMING_SNAKE_CASE = OrderedDict( [ ("""input_features""", {0: """batch""", 1: """feature_size""", 2: """encoder_sequence"""}), ] ) if self.use_past: SCREAMING_SNAKE_CASE = {0: """batch"""} else: SCREAMING_SNAKE_CASE = {0: """batch""", 1: """decoder_sequence"""} if self.use_past: self.fill_with_past_key_values_(lowerCamelCase__ ,direction="""inputs""" ) return common_inputs def SCREAMING_SNAKE_CASE__ ( self : str ,lowerCamelCase__ : Union["PreTrainedTokenizerBase", "FeatureExtractionMixin"] ,lowerCamelCase__ : int = -1 ,lowerCamelCase__ : int = -1 ,lowerCamelCase__ : bool = False ,lowerCamelCase__ : Optional["TensorType"] = None ,lowerCamelCase__ : int = 22050 ,lowerCamelCase__ : float = 5.0 ,lowerCamelCase__ : int = 220 ,) -> Mapping[str, Any]: '''simple docstring''' SCREAMING_SNAKE_CASE = OrderedDict() SCREAMING_SNAKE_CASE = OnnxConfig.generate_dummy_inputs( self ,preprocessor=preprocessor.feature_extractor ,batch_size=lowerCamelCase__ ,framework=lowerCamelCase__ ,sampling_rate=lowerCamelCase__ ,time_duration=lowerCamelCase__ ,frequency=lowerCamelCase__ ,) SCREAMING_SNAKE_CASE = encoder_inputs["""input_features"""].shape[2] SCREAMING_SNAKE_CASE = encoder_sequence_length // 2 if self.use_past else seq_length SCREAMING_SNAKE_CASE = super().generate_dummy_inputs( preprocessor.tokenizer ,lowerCamelCase__ ,lowerCamelCase__ ,lowerCamelCase__ ,lowerCamelCase__ ) SCREAMING_SNAKE_CASE = encoder_inputs.pop("""input_features""" ) SCREAMING_SNAKE_CASE = decoder_inputs.pop("""decoder_input_ids""" ) if "past_key_values" in decoder_inputs: SCREAMING_SNAKE_CASE = decoder_inputs.pop("""past_key_values""" ) return dummy_inputs @property def SCREAMING_SNAKE_CASE__ ( self : Tuple ) -> float: '''simple docstring''' return 1e-3
296
from collections import defaultdict from math import gcd def __lowercase ( _SCREAMING_SNAKE_CASE = 1_50_00_00 ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE = defaultdict(_SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE = 2 while 2 * euclid_m * (euclid_m + 1) <= limit: for euclid_n in range((euclid_m % 2) + 1 , _SCREAMING_SNAKE_CASE , 2 ): if gcd(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) > 1: continue SCREAMING_SNAKE_CASE = 2 * euclid_m * (euclid_m + euclid_n) for perimeter in range(_SCREAMING_SNAKE_CASE , limit + 1 , _SCREAMING_SNAKE_CASE ): frequencies[perimeter] += 1 euclid_m += 1 return sum(1 for frequency in frequencies.values() if frequency == 1 ) if __name__ == "__main__": print(F'''{solution() = }''')
296
1
import math def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE = len(_SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE = int(math.floor(math.sqrt(_SCREAMING_SNAKE_CASE ) ) ) SCREAMING_SNAKE_CASE = 0 while arr[min(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) - 1] < x: SCREAMING_SNAKE_CASE = step step += int(math.floor(math.sqrt(_SCREAMING_SNAKE_CASE ) ) ) if prev >= n: return -1 while arr[prev] < x: SCREAMING_SNAKE_CASE = prev + 1 if prev == min(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): return -1 if arr[prev] == x: return prev return -1 if __name__ == "__main__": SCREAMING_SNAKE_CASE_ = input("""Enter numbers separated by a comma:\n""").strip() SCREAMING_SNAKE_CASE_ = [int(item) for item in user_input.split(""",""")] SCREAMING_SNAKE_CASE_ = int(input("""Enter the number to be searched:\n""")) SCREAMING_SNAKE_CASE_ = jump_search(arr, x) if res == -1: print("""Number not found!""") else: print(F'''Number {x} is at index {res}''')
296
from argparse import ArgumentParser from .env import EnvironmentCommand def __lowercase ( ) -> Dict: '''simple docstring''' SCREAMING_SNAKE_CASE = ArgumentParser("""Diffusers CLI tool""" , usage="""diffusers-cli <command> [<args>]""" ) SCREAMING_SNAKE_CASE = parser.add_subparsers(help="""diffusers-cli command helpers""" ) # Register commands EnvironmentCommand.register_subcommand(_SCREAMING_SNAKE_CASE ) # Let's go SCREAMING_SNAKE_CASE = parser.parse_args() if not hasattr(_SCREAMING_SNAKE_CASE , """func""" ): parser.print_help() exit(1 ) # Run SCREAMING_SNAKE_CASE = args.func(_SCREAMING_SNAKE_CASE ) service.run() if __name__ == "__main__": main()
296
1
import doctest from collections import deque import numpy as np class UpperCamelCase__ : '''simple docstring''' def __init__( self : Any ) -> None: '''simple docstring''' SCREAMING_SNAKE_CASE = [2, 1, 2, -1] SCREAMING_SNAKE_CASE = [1, 2, 3, 4] def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ) -> list[float]: '''simple docstring''' SCREAMING_SNAKE_CASE = len(self.first_signal ) SCREAMING_SNAKE_CASE = len(self.second_signal ) SCREAMING_SNAKE_CASE = max(lowerCamelCase__ ,lowerCamelCase__ ) # create a zero matrix of max_length x max_length SCREAMING_SNAKE_CASE = [[0] * max_length for i in range(lowerCamelCase__ )] # fills the smaller signal with zeros to make both signals of same length if length_first_signal < length_second_signal: self.first_signal += [0] * (max_length - length_first_signal) elif length_first_signal > length_second_signal: self.second_signal += [0] * (max_length - length_second_signal) for i in range(lowerCamelCase__ ): SCREAMING_SNAKE_CASE = deque(self.second_signal ) rotated_signal.rotate(lowerCamelCase__ ) for j, item in enumerate(lowerCamelCase__ ): matrix[i][j] += item # multiply the matrix with the first signal SCREAMING_SNAKE_CASE = np.matmul(np.transpose(lowerCamelCase__ ) ,np.transpose(self.first_signal ) ) # rounding-off to two decimal places return [round(lowerCamelCase__ ,2 ) for i in final_signal] if __name__ == "__main__": doctest.testmod()
296
import argparse import json import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import AutoImageProcessor, SwinConfig, SwinForImageClassification def __lowercase ( _SCREAMING_SNAKE_CASE ) -> Union[str, Any]: '''simple docstring''' SCREAMING_SNAKE_CASE = SwinConfig() SCREAMING_SNAKE_CASE = swin_name.split("""_""" ) SCREAMING_SNAKE_CASE = name_split[1] SCREAMING_SNAKE_CASE = int(name_split[4] ) SCREAMING_SNAKE_CASE = int(name_split[3][-1] ) if model_size == "tiny": SCREAMING_SNAKE_CASE = 96 SCREAMING_SNAKE_CASE = (2, 2, 6, 2) SCREAMING_SNAKE_CASE = (3, 6, 12, 24) elif model_size == "small": SCREAMING_SNAKE_CASE = 96 SCREAMING_SNAKE_CASE = (2, 2, 18, 2) SCREAMING_SNAKE_CASE = (3, 6, 12, 24) elif model_size == "base": SCREAMING_SNAKE_CASE = 1_28 SCREAMING_SNAKE_CASE = (2, 2, 18, 2) SCREAMING_SNAKE_CASE = (4, 8, 16, 32) else: SCREAMING_SNAKE_CASE = 1_92 SCREAMING_SNAKE_CASE = (2, 2, 18, 2) SCREAMING_SNAKE_CASE = (6, 12, 24, 48) if "in22k" in swin_name: SCREAMING_SNAKE_CASE = 2_18_41 else: SCREAMING_SNAKE_CASE = 10_00 SCREAMING_SNAKE_CASE = """huggingface/label-files""" SCREAMING_SNAKE_CASE = """imagenet-1k-id2label.json""" SCREAMING_SNAKE_CASE = json.load(open(hf_hub_download(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , repo_type="""dataset""" ) , """r""" ) ) SCREAMING_SNAKE_CASE = {int(_SCREAMING_SNAKE_CASE ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE = idalabel SCREAMING_SNAKE_CASE = {v: k for k, v in idalabel.items()} SCREAMING_SNAKE_CASE = img_size SCREAMING_SNAKE_CASE = num_classes SCREAMING_SNAKE_CASE = embed_dim SCREAMING_SNAKE_CASE = depths SCREAMING_SNAKE_CASE = num_heads SCREAMING_SNAKE_CASE = window_size return config def __lowercase ( _SCREAMING_SNAKE_CASE ) -> Dict: '''simple docstring''' if "patch_embed.proj" in name: SCREAMING_SNAKE_CASE = name.replace("""patch_embed.proj""" , """embeddings.patch_embeddings.projection""" ) if "patch_embed.norm" in name: SCREAMING_SNAKE_CASE = name.replace("""patch_embed.norm""" , """embeddings.norm""" ) if "layers" in name: SCREAMING_SNAKE_CASE = """encoder.""" + name if "attn.proj" in name: SCREAMING_SNAKE_CASE = name.replace("""attn.proj""" , """attention.output.dense""" ) if "attn" in name: SCREAMING_SNAKE_CASE = name.replace("""attn""" , """attention.self""" ) if "norm1" in name: SCREAMING_SNAKE_CASE = name.replace("""norm1""" , """layernorm_before""" ) if "norm2" in name: SCREAMING_SNAKE_CASE = name.replace("""norm2""" , """layernorm_after""" ) if "mlp.fc1" in name: SCREAMING_SNAKE_CASE = name.replace("""mlp.fc1""" , """intermediate.dense""" ) if "mlp.fc2" in name: SCREAMING_SNAKE_CASE = name.replace("""mlp.fc2""" , """output.dense""" ) if name == "norm.weight": SCREAMING_SNAKE_CASE = """layernorm.weight""" if name == "norm.bias": SCREAMING_SNAKE_CASE = """layernorm.bias""" if "head" in name: SCREAMING_SNAKE_CASE = name.replace("""head""" , """classifier""" ) else: SCREAMING_SNAKE_CASE = """swin.""" + name return name def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Any: '''simple docstring''' for key in orig_state_dict.copy().keys(): SCREAMING_SNAKE_CASE = orig_state_dict.pop(_SCREAMING_SNAKE_CASE ) if "mask" in key: continue elif "qkv" in key: SCREAMING_SNAKE_CASE = key.split(""".""" ) SCREAMING_SNAKE_CASE = int(key_split[1] ) SCREAMING_SNAKE_CASE = int(key_split[3] ) SCREAMING_SNAKE_CASE = model.swin.encoder.layers[layer_num].blocks[block_num].attention.self.all_head_size if "weight" in key: SCREAMING_SNAKE_CASE = val[:dim, :] SCREAMING_SNAKE_CASE = val[ dim : dim * 2, : ] SCREAMING_SNAKE_CASE = val[-dim:, :] else: SCREAMING_SNAKE_CASE = val[ :dim ] SCREAMING_SNAKE_CASE = val[ dim : dim * 2 ] SCREAMING_SNAKE_CASE = val[ -dim: ] else: SCREAMING_SNAKE_CASE = val return orig_state_dict def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> List[str]: '''simple docstring''' SCREAMING_SNAKE_CASE = timm.create_model(_SCREAMING_SNAKE_CASE , pretrained=_SCREAMING_SNAKE_CASE ) timm_model.eval() SCREAMING_SNAKE_CASE = get_swin_config(_SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE = SwinForImageClassification(_SCREAMING_SNAKE_CASE ) model.eval() SCREAMING_SNAKE_CASE = convert_state_dict(timm_model.state_dict() , _SCREAMING_SNAKE_CASE ) model.load_state_dict(_SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE = """http://images.cocodataset.org/val2017/000000039769.jpg""" SCREAMING_SNAKE_CASE = AutoImageProcessor.from_pretrained("""microsoft/{}""".format(swin_name.replace("""_""" , """-""" ) ) ) SCREAMING_SNAKE_CASE = Image.open(requests.get(_SCREAMING_SNAKE_CASE , stream=_SCREAMING_SNAKE_CASE ).raw ) SCREAMING_SNAKE_CASE = image_processor(images=_SCREAMING_SNAKE_CASE , return_tensors="""pt""" ) SCREAMING_SNAKE_CASE = timm_model(inputs["""pixel_values"""] ) SCREAMING_SNAKE_CASE = model(**_SCREAMING_SNAKE_CASE ).logits assert torch.allclose(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , atol=1E-3 ) print(F"""Saving model {swin_name} to {pytorch_dump_folder_path}""" ) model.save_pretrained(_SCREAMING_SNAKE_CASE ) print(F"""Saving image processor to {pytorch_dump_folder_path}""" ) image_processor.save_pretrained(_SCREAMING_SNAKE_CASE ) if __name__ == "__main__": SCREAMING_SNAKE_CASE_ = argparse.ArgumentParser() # Required parameters parser.add_argument( """--swin_name""", default="""swin_tiny_patch4_window7_224""", type=str, help="""Name of the Swin timm model you'd like to convert.""", ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model directory.""" ) SCREAMING_SNAKE_CASE_ = parser.parse_args() convert_swin_checkpoint(args.swin_name, args.pytorch_dump_folder_path)
296
1
def __lowercase ( _SCREAMING_SNAKE_CASE ) -> Optional[Any]: '''simple docstring''' stooge(_SCREAMING_SNAKE_CASE , 0 , len(_SCREAMING_SNAKE_CASE ) - 1 ) return arr def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> str: '''simple docstring''' if i >= h: return # If first element is smaller than the last then swap them if arr[i] > arr[h]: SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE = arr[h], arr[i] # If there are more than 2 elements in the array if h - i + 1 > 2: SCREAMING_SNAKE_CASE = (int)((h - i + 1) / 3 ) # Recursively sort first 2/3 elements stooge(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , (h - t) ) # Recursively sort last 2/3 elements stooge(_SCREAMING_SNAKE_CASE , i + t , (_SCREAMING_SNAKE_CASE) ) # Recursively sort first 2/3 elements stooge(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , (h - t) ) if __name__ == "__main__": SCREAMING_SNAKE_CASE_ = input("""Enter numbers separated by a comma:\n""").strip() SCREAMING_SNAKE_CASE_ = [int(item) for item in user_input.split(""",""")] print(stooge_sort(unsorted))
296
import os from distutils.util import strtobool def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Tuple: '''simple docstring''' for e in env_keys: SCREAMING_SNAKE_CASE = int(os.environ.get(_SCREAMING_SNAKE_CASE , -1 ) ) if val >= 0: return val return default def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=False ) -> Optional[int]: '''simple docstring''' SCREAMING_SNAKE_CASE = os.environ.get(_SCREAMING_SNAKE_CASE , str(_SCREAMING_SNAKE_CASE ) ) return strtobool(_SCREAMING_SNAKE_CASE ) == 1 # As its name indicates `strtobool` actually returns an int... def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE="no" ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE = os.environ.get(_SCREAMING_SNAKE_CASE , str(_SCREAMING_SNAKE_CASE ) ) return value
296
1
from typing import Union from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging from .base import PIPELINE_INIT_ARGS, Pipeline if is_vision_available(): from PIL import Image from ..image_utils import load_image if is_torch_available(): from ..models.auto.modeling_auto import MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING SCREAMING_SNAKE_CASE_ = logging.get_logger(__name__) @add_end_docstrings(lowerCAmelCase_ ) class UpperCamelCase__ ( lowerCAmelCase_ ): '''simple docstring''' def __init__( self : Union[str, Any] ,*lowerCamelCase__ : Tuple ,**lowerCamelCase__ : Optional[Any] ) -> List[Any]: '''simple docstring''' super().__init__(*lowerCamelCase__ ,**lowerCamelCase__ ) self.check_model_type(lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ,lowerCamelCase__ : Union[str, Any]=None ,lowerCamelCase__ : List[str]=None ,lowerCamelCase__ : List[str]=None ,**lowerCamelCase__ : Union[str, Any] ) -> Tuple: '''simple docstring''' SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE = {}, {} if padding is not None: SCREAMING_SNAKE_CASE = padding if truncation is not None: SCREAMING_SNAKE_CASE = truncation if top_k is not None: SCREAMING_SNAKE_CASE = top_k return preprocess_params, {}, postprocess_params def __call__( self : Dict ,lowerCamelCase__ : Union["Image.Image", str] ,lowerCamelCase__ : str = None ,**lowerCamelCase__ : Any ) -> Tuple: '''simple docstring''' if isinstance(lowerCamelCase__ ,(Image.Image, str) ) and isinstance(lowerCamelCase__ ,lowerCamelCase__ ): SCREAMING_SNAKE_CASE = {"""image""": image, """question""": question} else: SCREAMING_SNAKE_CASE = image SCREAMING_SNAKE_CASE = super().__call__(lowerCamelCase__ ,**lowerCamelCase__ ) return results def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ,lowerCamelCase__ : Union[str, Any] ,lowerCamelCase__ : Any=False ,lowerCamelCase__ : Optional[Any]=False ) -> List[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE = load_image(inputs["""image"""] ) SCREAMING_SNAKE_CASE = self.tokenizer( inputs["""question"""] ,return_tensors=self.framework ,padding=lowerCamelCase__ ,truncation=lowerCamelCase__ ) SCREAMING_SNAKE_CASE = self.image_processor(images=lowerCamelCase__ ,return_tensors=self.framework ) model_inputs.update(lowerCamelCase__ ) return model_inputs def SCREAMING_SNAKE_CASE__ ( self : Tuple ,lowerCamelCase__ : List[Any] ) -> Optional[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE = self.model(**lowerCamelCase__ ) return model_outputs def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ,lowerCamelCase__ : Tuple ,lowerCamelCase__ : int=5 ) -> Dict: '''simple docstring''' if top_k > self.model.config.num_labels: SCREAMING_SNAKE_CASE = self.model.config.num_labels if self.framework == "pt": SCREAMING_SNAKE_CASE = model_outputs.logits.sigmoid()[0] SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE = probs.topk(lowerCamelCase__ ) else: raise ValueError(F"""Unsupported framework: {self.framework}""" ) SCREAMING_SNAKE_CASE = scores.tolist() SCREAMING_SNAKE_CASE = ids.tolist() return [{"score": score, "answer": self.model.config.idalabel[_id]} for score, _id in zip(lowerCamelCase__ ,lowerCamelCase__ )]
296
import dataclasses import json import warnings from dataclasses import dataclass, field from time import time from typing import List from ..utils import logging SCREAMING_SNAKE_CASE_ = logging.get_logger(__name__) def __lowercase ( _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None ) -> List[str]: '''simple docstring''' return field(default_factory=lambda: default , metadata=_SCREAMING_SNAKE_CASE ) @dataclass class UpperCamelCase__ : '''simple docstring''' __snake_case : 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" ) } , ) __snake_case : List[int] = list_field( default=[8] , metadata={"help": "List of batch sizes for which memory and time performance will be evaluated"} ) __snake_case : List[int] = list_field( default=[8, 32, 128, 512] , metadata={"help": "List of sequence lengths for which memory and time performance will be evaluated"} , ) __snake_case : bool = field( default=lowerCAmelCase_ , metadata={"help": "Whether to benchmark inference of model. Inference can be disabled via --no-inference."} , ) __snake_case : bool = field( default=lowerCAmelCase_ , metadata={"help": "Whether to run on available cuda devices. Cuda can be disabled via --no-cuda."} , ) __snake_case : bool = field( default=lowerCAmelCase_ , metadata={"help": "Whether to run on available tpu devices. TPU can be disabled via --no-tpu."} ) __snake_case : bool = field(default=lowerCAmelCase_ , metadata={"help": "Use FP16 to accelerate inference."} ) __snake_case : bool = field(default=lowerCAmelCase_ , metadata={"help": "Benchmark training of model"} ) __snake_case : bool = field(default=lowerCAmelCase_ , metadata={"help": "Verbose memory tracing"} ) __snake_case : bool = field( default=lowerCAmelCase_ , metadata={"help": "Whether to perform speed measurements. Speed measurements can be disabled via --no-speed."} , ) __snake_case : bool = field( default=lowerCAmelCase_ , metadata={ "help": "Whether to perform memory measurements. Memory measurements can be disabled via --no-memory" } , ) __snake_case : bool = field(default=lowerCAmelCase_ , metadata={"help": "Trace memory line by line"} ) __snake_case : bool = field(default=lowerCAmelCase_ , metadata={"help": "Save result to a CSV file"} ) __snake_case : bool = field(default=lowerCAmelCase_ , metadata={"help": "Save all print statements in a log file"} ) __snake_case : bool = field(default=lowerCAmelCase_ , metadata={"help": "Whether to print environment information"} ) __snake_case : bool = field( default=lowerCAmelCase_ , 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." ) } , ) __snake_case : str = field( default=F"inference_time_{round(time() )}.csv" , metadata={"help": "CSV filename used if saving time results to csv."} , ) __snake_case : str = field( default=F"inference_memory_{round(time() )}.csv" , metadata={"help": "CSV filename used if saving memory results to csv."} , ) __snake_case : str = field( default=F"train_time_{round(time() )}.csv" , metadata={"help": "CSV filename used if saving time results to csv for training."} , ) __snake_case : str = field( default=F"train_memory_{round(time() )}.csv" , metadata={"help": "CSV filename used if saving memory results to csv for training."} , ) __snake_case : str = field( default=F"env_info_{round(time() )}.csv" , metadata={"help": "CSV filename used if saving environment information."} , ) __snake_case : str = field( default=F"log_{round(time() )}.csv" , metadata={"help": "Log filename used if print statements are saved in log."} , ) __snake_case : int = field(default=3 , metadata={"help": "Times an experiment will be run."} ) __snake_case : bool = field( default=lowerCAmelCase_ , metadata={ "help": ( "Instead of loading the model as defined in `config.architectures` if exists, just load the pretrain" " model weights." ) } , ) def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ) -> Dict: '''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 SCREAMING_SNAKE_CASE__ ( self : Optional[int] ) -> Any: '''simple docstring''' return json.dumps(dataclasses.asdict(self ) ,indent=2 ) @property def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ) -> List[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 SCREAMING_SNAKE_CASE__ ( self : Optional[int] ) -> int: '''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
296
1
from math import isclose, sqrt def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> tuple[float, float, float]: '''simple docstring''' SCREAMING_SNAKE_CASE = point_y / 4 / point_x SCREAMING_SNAKE_CASE = 2 * normal_gradient / (1 + normal_gradient * normal_gradient) SCREAMING_SNAKE_CASE = (1 - normal_gradient * normal_gradient) / ( 1 + normal_gradient * normal_gradient ) SCREAMING_SNAKE_CASE = (sa - ca * incoming_gradient) / (ca + sa * incoming_gradient) # to find the next point, solve the simultaeneous equations: # y^2 + 4x^2 = 100 # y - b = m * (x - a) # ==> A x^2 + B x + C = 0 SCREAMING_SNAKE_CASE = outgoing_gradient**2 + 4 SCREAMING_SNAKE_CASE = 2 * outgoing_gradient * (point_y - outgoing_gradient * point_x) SCREAMING_SNAKE_CASE = (point_y - outgoing_gradient * point_x) ** 2 - 1_00 SCREAMING_SNAKE_CASE = ( -linear_term - sqrt(linear_term**2 - 4 * quadratic_term * constant_term ) ) / (2 * quadratic_term) SCREAMING_SNAKE_CASE = ( -linear_term + sqrt(linear_term**2 - 4 * quadratic_term * constant_term ) ) / (2 * quadratic_term) # two solutions, one of which is our input point SCREAMING_SNAKE_CASE = x_minus if isclose(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) else x_plus SCREAMING_SNAKE_CASE = point_y + outgoing_gradient * (next_x - point_x) return next_x, next_y, outgoing_gradient def __lowercase ( _SCREAMING_SNAKE_CASE = 1.4 , _SCREAMING_SNAKE_CASE = -9.6 ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = first_x_coord SCREAMING_SNAKE_CASE = first_y_coord SCREAMING_SNAKE_CASE = (10.1 - point_y) / (0.0 - point_x) while not (-0.01 <= point_x <= 0.01 and point_y > 0): SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE = next_point(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) num_reflections += 1 return num_reflections if __name__ == "__main__": print(F'''{solution() = }''')
296
import math import unittest def __lowercase ( _SCREAMING_SNAKE_CASE ) -> bool: '''simple docstring''' assert isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) and ( number >= 0 ), "'number' must been an int and positive" if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(math.sqrt(_SCREAMING_SNAKE_CASE ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True class UpperCamelCase__ ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE__ ( self : Dict ) -> Tuple: '''simple docstring''' self.assertTrue(is_prime(2 ) ) self.assertTrue(is_prime(3 ) ) self.assertTrue(is_prime(5 ) ) self.assertTrue(is_prime(7 ) ) self.assertTrue(is_prime(11 ) ) self.assertTrue(is_prime(13 ) ) self.assertTrue(is_prime(17 ) ) self.assertTrue(is_prime(19 ) ) self.assertTrue(is_prime(23 ) ) self.assertTrue(is_prime(29 ) ) def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ) -> Tuple: '''simple docstring''' with self.assertRaises(lowerCamelCase__ ): is_prime(-19 ) self.assertFalse( is_prime(0 ) ,"""Zero doesn't have any positive factors, primes must have exactly two.""" ,) self.assertFalse( is_prime(1 ) ,"""One only has 1 positive factor, primes must have exactly two.""" ,) self.assertFalse(is_prime(2 * 2 ) ) self.assertFalse(is_prime(2 * 3 ) ) self.assertFalse(is_prime(3 * 3 ) ) self.assertFalse(is_prime(3 * 5 ) ) self.assertFalse(is_prime(3 * 5 * 7 ) ) if __name__ == "__main__": unittest.main()
296
1
def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> float: '''simple docstring''' return round(float(moles / volume ) * nfactor ) def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> float: '''simple docstring''' return round(float((moles * 0.0_821 * temperature) / (volume) ) ) def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> float: '''simple docstring''' return round(float((moles * 0.0_821 * temperature) / (pressure) ) ) def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> float: '''simple docstring''' return round(float((pressure * volume) / (0.0_821 * moles) ) ) if __name__ == "__main__": import doctest doctest.testmod()
296
import random class UpperCamelCase__ : '''simple docstring''' @staticmethod def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ : str ) -> tuple[list[int], list[int]]: '''simple docstring''' SCREAMING_SNAKE_CASE = [ord(lowerCamelCase__ ) for i in text] SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = [] for i in plain: SCREAMING_SNAKE_CASE = random.randint(1 ,300 ) SCREAMING_SNAKE_CASE = (i + k) * k cipher.append(lowerCamelCase__ ) key.append(lowerCamelCase__ ) return cipher, key @staticmethod def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ : list[int] ,lowerCamelCase__ : list[int] ) -> str: '''simple docstring''' SCREAMING_SNAKE_CASE = [] for i in range(len(lowerCamelCase__ ) ): SCREAMING_SNAKE_CASE = int((cipher[i] - (key[i]) ** 2) / key[i] ) plain.append(chr(lowerCamelCase__ ) ) return "".join(lowerCamelCase__ ) if __name__ == "__main__": SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = Onepad().encrypt("""Hello""") print(c, k) print(Onepad().decrypt(c, k))
296
1
import os from distutils.util import strtobool def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Tuple: '''simple docstring''' for e in env_keys: SCREAMING_SNAKE_CASE = int(os.environ.get(_SCREAMING_SNAKE_CASE , -1 ) ) if val >= 0: return val return default def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=False ) -> Optional[int]: '''simple docstring''' SCREAMING_SNAKE_CASE = os.environ.get(_SCREAMING_SNAKE_CASE , str(_SCREAMING_SNAKE_CASE ) ) return strtobool(_SCREAMING_SNAKE_CASE ) == 1 # As its name indicates `strtobool` actually returns an int... def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE="no" ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE = os.environ.get(_SCREAMING_SNAKE_CASE , str(_SCREAMING_SNAKE_CASE ) ) return value
296
from typing import List from ...configuration_utils import PretrainedConfig from ...utils import logging SCREAMING_SNAKE_CASE_ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE_ = { """snap-research/efficientformer-l1-300""": ( """https://huggingface.co/snap-research/efficientformer-l1-300/resolve/main/config.json""" ), } class UpperCamelCase__ ( lowerCAmelCase_ ): '''simple docstring''' __snake_case : int = "efficientformer" def __init__( self : Optional[int] ,lowerCamelCase__ : List[int] = [3, 2, 6, 4] ,lowerCamelCase__ : List[int] = [48, 96, 224, 448] ,lowerCamelCase__ : List[bool] = [True, True, True, True] ,lowerCamelCase__ : int = 448 ,lowerCamelCase__ : int = 32 ,lowerCamelCase__ : int = 4 ,lowerCamelCase__ : int = 7 ,lowerCamelCase__ : int = 5 ,lowerCamelCase__ : int = 8 ,lowerCamelCase__ : int = 4 ,lowerCamelCase__ : float = 0.0 ,lowerCamelCase__ : int = 16 ,lowerCamelCase__ : int = 3 ,lowerCamelCase__ : int = 3 ,lowerCamelCase__ : int = 3 ,lowerCamelCase__ : int = 2 ,lowerCamelCase__ : int = 1 ,lowerCamelCase__ : float = 0.0 ,lowerCamelCase__ : int = 1 ,lowerCamelCase__ : bool = True ,lowerCamelCase__ : bool = True ,lowerCamelCase__ : float = 1e-5 ,lowerCamelCase__ : str = "gelu" ,lowerCamelCase__ : float = 0.02 ,lowerCamelCase__ : float = 1e-1_2 ,lowerCamelCase__ : int = 224 ,lowerCamelCase__ : float = 1e-0_5 ,**lowerCamelCase__ : str ,) -> None: '''simple docstring''' super().__init__(**lowerCamelCase__ ) SCREAMING_SNAKE_CASE = hidden_act SCREAMING_SNAKE_CASE = hidden_dropout_prob SCREAMING_SNAKE_CASE = hidden_sizes SCREAMING_SNAKE_CASE = num_hidden_layers SCREAMING_SNAKE_CASE = num_attention_heads SCREAMING_SNAKE_CASE = initializer_range SCREAMING_SNAKE_CASE = layer_norm_eps SCREAMING_SNAKE_CASE = patch_size SCREAMING_SNAKE_CASE = num_channels SCREAMING_SNAKE_CASE = depths SCREAMING_SNAKE_CASE = mlp_expansion_ratio SCREAMING_SNAKE_CASE = downsamples SCREAMING_SNAKE_CASE = dim SCREAMING_SNAKE_CASE = key_dim SCREAMING_SNAKE_CASE = attention_ratio SCREAMING_SNAKE_CASE = resolution SCREAMING_SNAKE_CASE = pool_size SCREAMING_SNAKE_CASE = downsample_patch_size SCREAMING_SNAKE_CASE = downsample_stride SCREAMING_SNAKE_CASE = downsample_pad SCREAMING_SNAKE_CASE = drop_path_rate SCREAMING_SNAKE_CASE = num_metaad_blocks SCREAMING_SNAKE_CASE = distillation SCREAMING_SNAKE_CASE = use_layer_scale SCREAMING_SNAKE_CASE = layer_scale_init_value SCREAMING_SNAKE_CASE = image_size SCREAMING_SNAKE_CASE = batch_norm_eps
296
1
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_big_bird import BigBirdTokenizer else: SCREAMING_SNAKE_CASE_ = None SCREAMING_SNAKE_CASE_ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE_ = {"""vocab_file""": """spiece.model""", """tokenizer_file""": """tokenizer.json"""} SCREAMING_SNAKE_CASE_ = { """vocab_file""": { """google/bigbird-roberta-base""": """https://huggingface.co/google/bigbird-roberta-base/resolve/main/spiece.model""", """google/bigbird-roberta-large""": ( """https://huggingface.co/google/bigbird-roberta-large/resolve/main/spiece.model""" ), """google/bigbird-base-trivia-itc""": ( """https://huggingface.co/google/bigbird-base-trivia-itc/resolve/main/spiece.model""" ), }, """tokenizer_file""": { """google/bigbird-roberta-base""": ( """https://huggingface.co/google/bigbird-roberta-base/resolve/main/tokenizer.json""" ), """google/bigbird-roberta-large""": ( """https://huggingface.co/google/bigbird-roberta-large/resolve/main/tokenizer.json""" ), """google/bigbird-base-trivia-itc""": ( """https://huggingface.co/google/bigbird-base-trivia-itc/resolve/main/tokenizer.json""" ), }, } SCREAMING_SNAKE_CASE_ = { """google/bigbird-roberta-base""": 4_0_9_6, """google/bigbird-roberta-large""": 4_0_9_6, """google/bigbird-base-trivia-itc""": 4_0_9_6, } SCREAMING_SNAKE_CASE_ = """▁""" class UpperCamelCase__ ( lowerCAmelCase_ ): '''simple docstring''' __snake_case : Union[str, Any] = VOCAB_FILES_NAMES __snake_case : List[Any] = PRETRAINED_VOCAB_FILES_MAP __snake_case : Any = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __snake_case : Dict = BigBirdTokenizer __snake_case : Any = ["input_ids", "attention_mask"] __snake_case : List[int] = [] def __init__( self : Union[str, Any] ,lowerCamelCase__ : int=None ,lowerCamelCase__ : int=None ,lowerCamelCase__ : Union[str, Any]="<unk>" ,lowerCamelCase__ : int="<s>" ,lowerCamelCase__ : List[str]="</s>" ,lowerCamelCase__ : List[Any]="<pad>" ,lowerCamelCase__ : Tuple="[SEP]" ,lowerCamelCase__ : Optional[Any]="[MASK]" ,lowerCamelCase__ : Dict="[CLS]" ,**lowerCamelCase__ : int ,) -> str: '''simple docstring''' SCREAMING_SNAKE_CASE = AddedToken(lowerCamelCase__ ,lstrip=lowerCamelCase__ ,rstrip=lowerCamelCase__ ) if isinstance(lowerCamelCase__ ,lowerCamelCase__ ) else bos_token SCREAMING_SNAKE_CASE = AddedToken(lowerCamelCase__ ,lstrip=lowerCamelCase__ ,rstrip=lowerCamelCase__ ) if isinstance(lowerCamelCase__ ,lowerCamelCase__ ) else eos_token SCREAMING_SNAKE_CASE = AddedToken(lowerCamelCase__ ,lstrip=lowerCamelCase__ ,rstrip=lowerCamelCase__ ) if isinstance(lowerCamelCase__ ,lowerCamelCase__ ) else unk_token SCREAMING_SNAKE_CASE = AddedToken(lowerCamelCase__ ,lstrip=lowerCamelCase__ ,rstrip=lowerCamelCase__ ) if isinstance(lowerCamelCase__ ,lowerCamelCase__ ) else pad_token SCREAMING_SNAKE_CASE = AddedToken(lowerCamelCase__ ,lstrip=lowerCamelCase__ ,rstrip=lowerCamelCase__ ) if isinstance(lowerCamelCase__ ,lowerCamelCase__ ) else cls_token SCREAMING_SNAKE_CASE = AddedToken(lowerCamelCase__ ,lstrip=lowerCamelCase__ ,rstrip=lowerCamelCase__ ) if isinstance(lowerCamelCase__ ,lowerCamelCase__ ) else sep_token # Mask token behave like a normal word, i.e. include the space before it SCREAMING_SNAKE_CASE = AddedToken(lowerCamelCase__ ,lstrip=lowerCamelCase__ ,rstrip=lowerCamelCase__ ) if isinstance(lowerCamelCase__ ,lowerCamelCase__ ) else mask_token super().__init__( lowerCamelCase__ ,tokenizer_file=lowerCamelCase__ ,bos_token=lowerCamelCase__ ,eos_token=lowerCamelCase__ ,unk_token=lowerCamelCase__ ,sep_token=lowerCamelCase__ ,pad_token=lowerCamelCase__ ,cls_token=lowerCamelCase__ ,mask_token=lowerCamelCase__ ,**lowerCamelCase__ ,) SCREAMING_SNAKE_CASE = vocab_file SCREAMING_SNAKE_CASE = False if not self.vocab_file else True def SCREAMING_SNAKE_CASE__ ( self : List[str] ,lowerCamelCase__ : List[int] ,lowerCamelCase__ : Optional[List[int]] = None ) -> List[int]: '''simple docstring''' SCREAMING_SNAKE_CASE = [self.sep_token_id] SCREAMING_SNAKE_CASE = [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 SCREAMING_SNAKE_CASE__ ( self : List[Any] ,lowerCamelCase__ : List[int] ,lowerCamelCase__ : Optional[List[int]] = None ,lowerCamelCase__ : bool = False ) -> List[int]: '''simple docstring''' if already_has_special_tokens: if token_ids_a is not None: raise ValueError( """You should not supply a second sequence if the provided sequence of """ """ids is already formatted with special tokens for the model.""" ) return [1 if x in [self.sep_token_id, self.cls_token_id] else 0 for x in token_ids_a] if token_ids_a is None: return [1] + ([0] * len(lowerCamelCase__ )) + [1] return [1] + ([0] * len(lowerCamelCase__ )) + [1] + ([0] * len(lowerCamelCase__ )) + [1] def SCREAMING_SNAKE_CASE__ ( self : Any ,lowerCamelCase__ : List[int] ,lowerCamelCase__ : Optional[List[int]] = None ) -> List[int]: '''simple docstring''' SCREAMING_SNAKE_CASE = [self.sep_token_id] SCREAMING_SNAKE_CASE = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def SCREAMING_SNAKE_CASE__ ( self : str ,lowerCamelCase__ : str ,lowerCamelCase__ : Optional[str] = None ) -> Tuple[str]: '''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(lowerCamelCase__ ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return SCREAMING_SNAKE_CASE = os.path.join( lowerCamelCase__ ,(filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(lowerCamelCase__ ): copyfile(self.vocab_file ,lowerCamelCase__ ) return (out_vocab_file,)
296
import importlib import shutil import threading import warnings from typing import List import fsspec import fsspec.asyn from . import compression from .hffilesystem import HfFileSystem SCREAMING_SNAKE_CASE_ = importlib.util.find_spec("""s3fs""") is not None if _has_safs: from .safilesystem import SaFileSystem # noqa: F401 SCREAMING_SNAKE_CASE_ = [ compression.BzaFileSystem, compression.GzipFileSystem, compression.LzaFileSystem, compression.XzFileSystem, compression.ZstdFileSystem, ] # Register custom filesystems for fs_class in COMPRESSION_FILESYSTEMS + [HfFileSystem]: if fs_class.protocol in fsspec.registry and fsspec.registry[fs_class.protocol] is not fs_class: warnings.warn(F'''A filesystem protocol was already set for {fs_class.protocol} and will be overwritten.''') fsspec.register_implementation(fs_class.protocol, fs_class, clobber=True) def __lowercase ( _SCREAMING_SNAKE_CASE ) -> str: '''simple docstring''' if "://" in dataset_path: SCREAMING_SNAKE_CASE = dataset_path.split("""://""" )[1] return dataset_path def __lowercase ( _SCREAMING_SNAKE_CASE ) -> bool: '''simple docstring''' if fs is not None and fs.protocol != "file": return True else: return False def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Dict: '''simple docstring''' SCREAMING_SNAKE_CASE = not is_remote_filesystem(_SCREAMING_SNAKE_CASE ) if is_local: # LocalFileSystem.mv does copy + rm, it is more efficient to simply move a local directory shutil.move(fs._strip_protocol(_SCREAMING_SNAKE_CASE ) , fs._strip_protocol(_SCREAMING_SNAKE_CASE ) ) else: fs.mv(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , recursive=_SCREAMING_SNAKE_CASE ) def __lowercase ( ) -> None: '''simple docstring''' if hasattr(fsspec.asyn , """reset_lock""" ): # for future fsspec>2022.05.0 fsspec.asyn.reset_lock() else: SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = threading.Lock()
296
1
from unittest import TestCase from datasets import Dataset from minhash_deduplication import deduplicate_dataset, make_duplicate_clusters def __lowercase ( ) -> Union[str, Any]: '''simple docstring''' SCREAMING_SNAKE_CASE = { """repo_name""": ["""test_repo1""", """test_repo2""", """test_repo3"""], """path""": ["""test_1.py""", """test_2.py""", """unit_test.py"""], """content""": ["""a """ * 20, """a """ * 30, """b """ * 7], } SCREAMING_SNAKE_CASE = Dataset.from_dict(_SCREAMING_SNAKE_CASE ) return dataset class UpperCamelCase__ ( lowerCAmelCase_ ): '''simple docstring''' def SCREAMING_SNAKE_CASE__ ( self : List[str] ) -> str: '''simple docstring''' SCREAMING_SNAKE_CASE = get_dataset() SCREAMING_SNAKE_CASE = make_duplicate_clusters(lowerCamelCase__ ,0.85 ) self.assertEqual(len(duplicate_clusters[0] ) ,2 ) def SCREAMING_SNAKE_CASE__ ( self : Tuple ) -> Dict: '''simple docstring''' SCREAMING_SNAKE_CASE = get_dataset() SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE = deduplicate_dataset(lowerCamelCase__ ) self.assertEqual(len(lowerCamelCase__ ) ,2 ) print(lowerCamelCase__ ) self.assertEqual(duplicate_clusters[0][0]["""copies"""] ,2 ) self.assertEqual(duplicate_clusters[0][0]["""is_extreme"""] ,lowerCamelCase__ )
296
import unittest import numpy as np import torch from diffusers import KarrasVePipeline, KarrasVeScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class UpperCamelCase__ ( unittest.TestCase ): '''simple docstring''' @property def SCREAMING_SNAKE_CASE__ ( self : str ) -> Optional[int]: '''simple docstring''' torch.manual_seed(0 ) SCREAMING_SNAKE_CASE = UNetaDModel( block_out_channels=(32, 64) ,layers_per_block=2 ,sample_size=32 ,in_channels=3 ,out_channels=3 ,down_block_types=("""DownBlock2D""", """AttnDownBlock2D""") ,up_block_types=("""AttnUpBlock2D""", """UpBlock2D""") ,) return model def SCREAMING_SNAKE_CASE__ ( self : Tuple ) -> Union[str, Any]: '''simple docstring''' SCREAMING_SNAKE_CASE = self.dummy_uncond_unet SCREAMING_SNAKE_CASE = KarrasVeScheduler() SCREAMING_SNAKE_CASE = KarrasVePipeline(unet=lowerCamelCase__ ,scheduler=lowerCamelCase__ ) pipe.to(lowerCamelCase__ ) pipe.set_progress_bar_config(disable=lowerCamelCase__ ) SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE = pipe(num_inference_steps=2 ,generator=lowerCamelCase__ ,output_type="""numpy""" ).images SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE = pipe(num_inference_steps=2 ,generator=lowerCamelCase__ ,output_type="""numpy""" ,return_dict=lowerCamelCase__ )[0] SCREAMING_SNAKE_CASE = image[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) SCREAMING_SNAKE_CASE = np.array([0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 @slow @require_torch class UpperCamelCase__ ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ) -> Optional[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE = """google/ncsnpp-celebahq-256""" SCREAMING_SNAKE_CASE = UNetaDModel.from_pretrained(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = KarrasVeScheduler() SCREAMING_SNAKE_CASE = KarrasVePipeline(unet=lowerCamelCase__ ,scheduler=lowerCamelCase__ ) pipe.to(lowerCamelCase__ ) pipe.set_progress_bar_config(disable=lowerCamelCase__ ) SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE = pipe(num_inference_steps=20 ,generator=lowerCamelCase__ ,output_type="""numpy""" ).images SCREAMING_SNAKE_CASE = image[0, -3:, -3:, -1] assert image.shape == (1, 256, 256, 3) SCREAMING_SNAKE_CASE = np.array([0.578, 0.5811, 0.5924, 0.5809, 0.587, 0.5886, 0.5861, 0.5802, 0.586] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
296
1
import collections.abc from typing import Optional, Tuple, Union import torch import torch.utils.checkpoint from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACTaFN from ...modeling_outputs import BaseModelOutputWithNoAttention, ImageClassifierOutputWithNoAttention from ...modeling_utils import PreTrainedModel from ...utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging from .configuration_poolformer import PoolFormerConfig SCREAMING_SNAKE_CASE_ = logging.get_logger(__name__) # General docstring SCREAMING_SNAKE_CASE_ = """PoolFormerConfig""" # Base docstring SCREAMING_SNAKE_CASE_ = """sail/poolformer_s12""" SCREAMING_SNAKE_CASE_ = [1, 5_1_2, 7, 7] # Image classification docstring SCREAMING_SNAKE_CASE_ = """sail/poolformer_s12""" SCREAMING_SNAKE_CASE_ = """tabby, tabby cat""" SCREAMING_SNAKE_CASE_ = [ """sail/poolformer_s12""", # See all PoolFormer models at https://huggingface.co/models?filter=poolformer ] def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = 0.0 , _SCREAMING_SNAKE_CASE = False ) -> Optional[int]: '''simple docstring''' if drop_prob == 0.0 or not training: return input SCREAMING_SNAKE_CASE = 1 - drop_prob SCREAMING_SNAKE_CASE = (input.shape[0],) + (1,) * (input.ndim - 1) # work with diff dim tensors, not just 2D ConvNets SCREAMING_SNAKE_CASE = keep_prob + torch.rand(_SCREAMING_SNAKE_CASE , dtype=input.dtype , device=input.device ) random_tensor.floor_() # binarize SCREAMING_SNAKE_CASE = input.div(_SCREAMING_SNAKE_CASE ) * random_tensor return output class UpperCamelCase__ ( nn.Module ): '''simple docstring''' def __init__( self : Dict ,lowerCamelCase__ : Optional[float] = None ) -> None: '''simple docstring''' super().__init__() SCREAMING_SNAKE_CASE = drop_prob def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ,lowerCamelCase__ : torch.Tensor ) -> torch.Tensor: '''simple docstring''' return drop_path(lowerCamelCase__ ,self.drop_prob ,self.training ) def SCREAMING_SNAKE_CASE__ ( self : List[Any] ) -> str: '''simple docstring''' return "p={}".format(self.drop_prob ) class UpperCamelCase__ ( nn.Module ): '''simple docstring''' def __init__( self : List[Any] ,lowerCamelCase__ : List[Any] ,lowerCamelCase__ : str ,lowerCamelCase__ : Optional[Any] ,lowerCamelCase__ : Dict ,lowerCamelCase__ : Any ,lowerCamelCase__ : str=None ) -> Tuple: '''simple docstring''' super().__init__() SCREAMING_SNAKE_CASE = patch_size if isinstance(lowerCamelCase__ ,collections.abc.Iterable ) else (patch_size, patch_size) SCREAMING_SNAKE_CASE = stride if isinstance(lowerCamelCase__ ,collections.abc.Iterable ) else (stride, stride) SCREAMING_SNAKE_CASE = padding if isinstance(lowerCamelCase__ ,collections.abc.Iterable ) else (padding, padding) SCREAMING_SNAKE_CASE = nn.Convad(lowerCamelCase__ ,lowerCamelCase__ ,kernel_size=lowerCamelCase__ ,stride=lowerCamelCase__ ,padding=lowerCamelCase__ ) SCREAMING_SNAKE_CASE = norm_layer(lowerCamelCase__ ) if norm_layer else nn.Identity() def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ,lowerCamelCase__ : Optional[Any] ) -> Optional[int]: '''simple docstring''' SCREAMING_SNAKE_CASE = self.projection(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = self.norm(lowerCamelCase__ ) return embeddings class UpperCamelCase__ ( nn.GroupNorm ): '''simple docstring''' def __init__( self : Optional[int] ,lowerCamelCase__ : int ,**lowerCamelCase__ : Union[str, Any] ) -> Dict: '''simple docstring''' super().__init__(1 ,lowerCamelCase__ ,**lowerCamelCase__ ) class UpperCamelCase__ ( nn.Module ): '''simple docstring''' def __init__( self : Any ,lowerCamelCase__ : Union[str, Any] ) -> List[Any]: '''simple docstring''' super().__init__() SCREAMING_SNAKE_CASE = nn.AvgPoolad(lowerCamelCase__ ,stride=1 ,padding=pool_size // 2 ,count_include_pad=lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( self : Tuple ,lowerCamelCase__ : Optional[int] ) -> Tuple: '''simple docstring''' return self.pool(lowerCamelCase__ ) - hidden_states class UpperCamelCase__ ( nn.Module ): '''simple docstring''' def __init__( self : List[str] ,lowerCamelCase__ : Optional[int] ,lowerCamelCase__ : int ,lowerCamelCase__ : Tuple ,lowerCamelCase__ : Optional[int] ) -> List[str]: '''simple docstring''' super().__init__() SCREAMING_SNAKE_CASE = nn.Convad(lowerCamelCase__ ,lowerCamelCase__ ,1 ) SCREAMING_SNAKE_CASE = nn.Convad(lowerCamelCase__ ,lowerCamelCase__ ,1 ) SCREAMING_SNAKE_CASE = PoolFormerDropPath(lowerCamelCase__ ) if isinstance(config.hidden_act ,lowerCamelCase__ ): SCREAMING_SNAKE_CASE = ACTaFN[config.hidden_act] else: SCREAMING_SNAKE_CASE = config.hidden_act def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ,lowerCamelCase__ : int ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE = self.conva(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = self.act_fn(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = self.drop(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = self.conva(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = self.drop(lowerCamelCase__ ) return hidden_states class UpperCamelCase__ ( nn.Module ): '''simple docstring''' def __init__( self : List[Any] ,lowerCamelCase__ : Dict ,lowerCamelCase__ : List[Any] ,lowerCamelCase__ : int ,lowerCamelCase__ : List[Any] ,lowerCamelCase__ : List[Any] ,lowerCamelCase__ : Dict ) -> Optional[Any]: '''simple docstring''' super().__init__() SCREAMING_SNAKE_CASE = PoolFormerPooling(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = PoolFormerOutput(lowerCamelCase__ ,lowerCamelCase__ ,lowerCamelCase__ ,lowerCamelCase__ ) SCREAMING_SNAKE_CASE = PoolFormerGroupNorm(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = PoolFormerGroupNorm(lowerCamelCase__ ) # Useful for training neural nets SCREAMING_SNAKE_CASE = PoolFormerDropPath(lowerCamelCase__ ) if drop_path > 0.0 else nn.Identity() SCREAMING_SNAKE_CASE = config.use_layer_scale if config.use_layer_scale: SCREAMING_SNAKE_CASE = nn.Parameter( config.layer_scale_init_value * torch.ones((lowerCamelCase__) ) ,requires_grad=lowerCamelCase__ ) SCREAMING_SNAKE_CASE = nn.Parameter( config.layer_scale_init_value * torch.ones((lowerCamelCase__) ) ,requires_grad=lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( self : List[str] ,lowerCamelCase__ : List[str] ) -> str: '''simple docstring''' if self.use_layer_scale: SCREAMING_SNAKE_CASE = self.pooling(self.before_norm(lowerCamelCase__ ) ) SCREAMING_SNAKE_CASE = self.layer_scale_a.unsqueeze(-1 ).unsqueeze(-1 ) * pooling_output # First residual connection SCREAMING_SNAKE_CASE = hidden_states + self.drop_path(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = () SCREAMING_SNAKE_CASE = self.output(self.after_norm(lowerCamelCase__ ) ) SCREAMING_SNAKE_CASE = self.layer_scale_a.unsqueeze(-1 ).unsqueeze(-1 ) * layer_output # Second residual connection SCREAMING_SNAKE_CASE = hidden_states + self.drop_path(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = (output,) + outputs return outputs else: SCREAMING_SNAKE_CASE = self.drop_path(self.pooling(self.before_norm(lowerCamelCase__ ) ) ) # First residual connection SCREAMING_SNAKE_CASE = pooling_output + hidden_states SCREAMING_SNAKE_CASE = () # Second residual connection inside the PoolFormerOutput block SCREAMING_SNAKE_CASE = self.drop_path(self.output(self.after_norm(lowerCamelCase__ ) ) ) SCREAMING_SNAKE_CASE = hidden_states + layer_output SCREAMING_SNAKE_CASE = (output,) + outputs return outputs class UpperCamelCase__ ( nn.Module ): '''simple docstring''' def __init__( self : Optional[Any] ,lowerCamelCase__ : Union[str, Any] ) -> str: '''simple docstring''' super().__init__() SCREAMING_SNAKE_CASE = config # stochastic depth decay rule SCREAMING_SNAKE_CASE = [x.item() for x in torch.linspace(0 ,config.drop_path_rate ,sum(config.depths ) )] # patch embeddings SCREAMING_SNAKE_CASE = [] for i in range(config.num_encoder_blocks ): embeddings.append( PoolFormerEmbeddings( patch_size=config.patch_sizes[i] ,stride=config.strides[i] ,padding=config.padding[i] ,num_channels=config.num_channels if i == 0 else config.hidden_sizes[i - 1] ,hidden_size=config.hidden_sizes[i] ,) ) SCREAMING_SNAKE_CASE = nn.ModuleList(lowerCamelCase__ ) # Transformer blocks SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = 0 for i in range(config.num_encoder_blocks ): # each block consists of layers SCREAMING_SNAKE_CASE = [] if i != 0: cur += config.depths[i - 1] for j in range(config.depths[i] ): layers.append( PoolFormerLayer( lowerCamelCase__ ,num_channels=config.hidden_sizes[i] ,pool_size=config.pool_size ,hidden_size=config.hidden_sizes[i] ,intermediate_size=int(config.hidden_sizes[i] * config.mlp_ratio ) ,drop_path=dpr[cur + j] ,) ) blocks.append(nn.ModuleList(lowerCamelCase__ ) ) SCREAMING_SNAKE_CASE = nn.ModuleList(lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ,lowerCamelCase__ : int ,lowerCamelCase__ : int=False ,lowerCamelCase__ : Optional[int]=True ) -> List[str]: '''simple docstring''' SCREAMING_SNAKE_CASE = () if output_hidden_states else None SCREAMING_SNAKE_CASE = pixel_values for idx, layers in enumerate(zip(self.patch_embeddings ,self.block ) ): SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE = layers # Get patch embeddings from hidden_states SCREAMING_SNAKE_CASE = embedding_layer(lowerCamelCase__ ) # Send the embeddings through the blocks for _, blk in enumerate(lowerCamelCase__ ): SCREAMING_SNAKE_CASE = blk(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = layer_outputs[0] if output_hidden_states: SCREAMING_SNAKE_CASE = all_hidden_states + (hidden_states,) if not return_dict: return tuple(v for v in [hidden_states, all_hidden_states] if v is not None ) return BaseModelOutputWithNoAttention(last_hidden_state=lowerCamelCase__ ,hidden_states=lowerCamelCase__ ) class UpperCamelCase__ ( lowerCAmelCase_ ): '''simple docstring''' __snake_case : Dict = PoolFormerConfig __snake_case : str = "poolformer" __snake_case : Union[str, Any] = "pixel_values" __snake_case : str = True def SCREAMING_SNAKE_CASE__ ( self : List[Any] ,lowerCamelCase__ : str ) -> Optional[int]: '''simple docstring''' if isinstance(lowerCamelCase__ ,(nn.Linear, nn.Convad) ): module.weight.data.normal_(mean=0.0 ,std=self.config.initializer_range ) if module.bias is not None: module.bias.data.zero_() elif isinstance(lowerCamelCase__ ,nn.LayerNorm ): module.bias.data.zero_() module.weight.data.fill_(1.0 ) def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ,lowerCamelCase__ : Any ,lowerCamelCase__ : Any=False ) -> Union[str, Any]: '''simple docstring''' if isinstance(lowerCamelCase__ ,lowerCamelCase__ ): SCREAMING_SNAKE_CASE = value SCREAMING_SNAKE_CASE_ = r""" This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior. Parameters: config ([`PoolFormerConfig`]): Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights. """ SCREAMING_SNAKE_CASE_ = r""" Args: pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`): Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See [`PoolFormerImageProcessor.__call__`] for details. """ @add_start_docstrings( "The bare PoolFormer Model transformer outputting raw hidden-states without any specific head on top." , lowerCAmelCase_ , ) class UpperCamelCase__ ( lowerCAmelCase_ ): '''simple docstring''' def __init__( self : List[Any] ,lowerCamelCase__ : str ) -> Dict: '''simple docstring''' super().__init__(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = config SCREAMING_SNAKE_CASE = PoolFormerEncoder(lowerCamelCase__ ) # Initialize weights and apply final processing self.post_init() def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ) -> str: '''simple docstring''' return self.embeddings.patch_embeddings @add_start_docstrings_to_model_forward(lowerCamelCase__ ) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC ,output_type=lowerCamelCase__ ,config_class=_CONFIG_FOR_DOC ,modality="""vision""" ,expected_output=_EXPECTED_OUTPUT_SHAPE ,) def SCREAMING_SNAKE_CASE__ ( self : List[Any] ,lowerCamelCase__ : Optional[torch.FloatTensor] = None ,lowerCamelCase__ : Optional[bool] = None ,lowerCamelCase__ : Optional[bool] = None ,) -> Union[Tuple, BaseModelOutputWithNoAttention]: '''simple docstring''' SCREAMING_SNAKE_CASE = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) SCREAMING_SNAKE_CASE = return_dict if return_dict is not None else self.config.use_return_dict if pixel_values is None: raise ValueError("""You have to specify pixel_values""" ) SCREAMING_SNAKE_CASE = self.encoder( lowerCamelCase__ ,output_hidden_states=lowerCamelCase__ ,return_dict=lowerCamelCase__ ,) SCREAMING_SNAKE_CASE = encoder_outputs[0] if not return_dict: return (sequence_output, None) + encoder_outputs[1:] return BaseModelOutputWithNoAttention( last_hidden_state=lowerCamelCase__ ,hidden_states=encoder_outputs.hidden_states ,) class UpperCamelCase__ ( nn.Module ): '''simple docstring''' def __init__( self : Dict ,lowerCamelCase__ : int ) -> int: '''simple docstring''' super().__init__() SCREAMING_SNAKE_CASE = nn.Linear(config.hidden_size ,config.hidden_size ) def SCREAMING_SNAKE_CASE__ ( self : List[Any] ,lowerCamelCase__ : List[Any] ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE = self.dense(lowerCamelCase__ ) return output @add_start_docstrings( "\n PoolFormer Model transformer with an image classification head on top\n " , lowerCAmelCase_ , ) class UpperCamelCase__ ( lowerCAmelCase_ ): '''simple docstring''' def __init__( self : List[Any] ,lowerCamelCase__ : str ) -> Any: '''simple docstring''' super().__init__(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = config.num_labels SCREAMING_SNAKE_CASE = PoolFormerModel(lowerCamelCase__ ) # Final norm SCREAMING_SNAKE_CASE = PoolFormerGroupNorm(config.hidden_sizes[-1] ) # Classifier head SCREAMING_SNAKE_CASE = ( nn.Linear(config.hidden_sizes[-1] ,config.num_labels ) if config.num_labels > 0 else nn.Identity() ) # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(lowerCamelCase__ ) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT ,output_type=lowerCamelCase__ ,config_class=_CONFIG_FOR_DOC ,expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT ,) def SCREAMING_SNAKE_CASE__ ( self : str ,lowerCamelCase__ : Optional[torch.FloatTensor] = None ,lowerCamelCase__ : Optional[torch.LongTensor] = None ,lowerCamelCase__ : Optional[bool] = None ,lowerCamelCase__ : Optional[bool] = None ,) -> Union[Tuple, ImageClassifierOutputWithNoAttention]: '''simple docstring''' SCREAMING_SNAKE_CASE = return_dict if return_dict is not None else self.config.use_return_dict SCREAMING_SNAKE_CASE = self.poolformer( lowerCamelCase__ ,output_hidden_states=lowerCamelCase__ ,return_dict=lowerCamelCase__ ,) SCREAMING_SNAKE_CASE = outputs[0] SCREAMING_SNAKE_CASE = self.classifier(self.norm(lowerCamelCase__ ).mean([-2, -1] ) ) SCREAMING_SNAKE_CASE = None if labels is not None: if self.config.problem_type is None: if self.num_labels == 1: SCREAMING_SNAKE_CASE = """regression""" elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int): SCREAMING_SNAKE_CASE = """single_label_classification""" else: SCREAMING_SNAKE_CASE = """multi_label_classification""" if self.config.problem_type == "regression": SCREAMING_SNAKE_CASE = MSELoss() if self.num_labels == 1: SCREAMING_SNAKE_CASE = loss_fct(logits.squeeze() ,labels.squeeze() ) else: SCREAMING_SNAKE_CASE = loss_fct(lowerCamelCase__ ,lowerCamelCase__ ) elif self.config.problem_type == "single_label_classification": SCREAMING_SNAKE_CASE = CrossEntropyLoss() SCREAMING_SNAKE_CASE = loss_fct(logits.view(-1 ,self.num_labels ) ,labels.view(-1 ) ) elif self.config.problem_type == "multi_label_classification": SCREAMING_SNAKE_CASE = BCEWithLogitsLoss() SCREAMING_SNAKE_CASE = loss_fct(lowerCamelCase__ ,lowerCamelCase__ ) if not return_dict: SCREAMING_SNAKE_CASE = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return ImageClassifierOutputWithNoAttention(loss=lowerCamelCase__ ,logits=lowerCamelCase__ ,hidden_states=outputs.hidden_states )
296
from typing import Callable, Optional from .. import Features from ..packaged_modules.generator.generator import Generator from .abc import AbstractDatasetInputStream class UpperCamelCase__ ( lowerCAmelCase_ ): '''simple docstring''' def __init__( self : Union[str, Any] ,lowerCamelCase__ : Callable ,lowerCamelCase__ : Optional[Features] = None ,lowerCamelCase__ : str = None ,lowerCamelCase__ : bool = False ,lowerCamelCase__ : bool = False ,lowerCamelCase__ : Optional[dict] = None ,lowerCamelCase__ : Optional[int] = None ,**lowerCamelCase__ : Optional[Any] ,) -> List[str]: '''simple docstring''' super().__init__( features=lowerCamelCase__ ,cache_dir=lowerCamelCase__ ,keep_in_memory=lowerCamelCase__ ,streaming=lowerCamelCase__ ,num_proc=lowerCamelCase__ ,**lowerCamelCase__ ,) SCREAMING_SNAKE_CASE = Generator( cache_dir=lowerCamelCase__ ,features=lowerCamelCase__ ,generator=lowerCamelCase__ ,gen_kwargs=lowerCamelCase__ ,**lowerCamelCase__ ,) def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ) -> Optional[Any]: '''simple docstring''' if self.streaming: SCREAMING_SNAKE_CASE = self.builder.as_streaming_dataset(split="""train""" ) # Build regular (map-style) dataset else: SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = None self.builder.download_and_prepare( download_config=lowerCamelCase__ ,download_mode=lowerCamelCase__ ,verification_mode=lowerCamelCase__ ,base_path=lowerCamelCase__ ,num_proc=self.num_proc ,) SCREAMING_SNAKE_CASE = self.builder.as_dataset( split="""train""" ,verification_mode=lowerCamelCase__ ,in_memory=self.keep_in_memory ) return dataset
296
1
import os import sys import unittest SCREAMING_SNAKE_CASE_ = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) sys.path.append(os.path.join(git_repo_path, """utils""")) import check_dummies # noqa: E402 from check_dummies import create_dummy_files, create_dummy_object, find_backend, read_init # noqa: E402 # Align TRANSFORMERS_PATH in check_dummies with the current path SCREAMING_SNAKE_CASE_ = os.path.join(git_repo_path, """src""", """transformers""") SCREAMING_SNAKE_CASE_ = """ {0} = None """ SCREAMING_SNAKE_CASE_ = """ class {0}(metaclass=DummyObject): _backends = {1} def __init__(self, *args, **kwargs): requires_backends(self, {1}) """ SCREAMING_SNAKE_CASE_ = """ def {0}(*args, **kwargs): requires_backends({0}, {1}) """ class UpperCamelCase__ ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE__ ( self : Tuple ) -> Union[str, Any]: '''simple docstring''' SCREAMING_SNAKE_CASE = find_backend(""" _import_structure[\"models.albert\"].append(\"AlbertTokenizerFast\")""" ) self.assertIsNone(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = find_backend(""" if not is_tokenizers_available():""" ) self.assertEqual(lowerCamelCase__ ,"""tokenizers""" ) SCREAMING_SNAKE_CASE = find_backend(""" if not is_tensorflow_text_available():""" ) self.assertEqual(lowerCamelCase__ ,"""tensorflow_text""" ) SCREAMING_SNAKE_CASE = find_backend(""" if not (is_sentencepiece_available() and is_tokenizers_available()):""" ) self.assertEqual(lowerCamelCase__ ,"""sentencepiece_and_tokenizers""" ) SCREAMING_SNAKE_CASE = find_backend( """ if not (is_sentencepiece_available() and is_tensorflow_text_available()):""" ) self.assertEqual(lowerCamelCase__ ,"""sentencepiece_and_tensorflow_text""" ) SCREAMING_SNAKE_CASE = find_backend( """ if not (is_sentencepiece_available() and is_tokenizers_available() and is_vision_available()):""" ) self.assertEqual(lowerCamelCase__ ,"""sentencepiece_and_tokenizers_and_vision""" ) def SCREAMING_SNAKE_CASE__ ( self : List[str] ) -> Union[str, Any]: '''simple docstring''' SCREAMING_SNAKE_CASE = read_init() # We don't assert on the exact list of keys to allow for smooth grow of backend-specific objects self.assertIn("""torch""" ,lowerCamelCase__ ) self.assertIn("""tensorflow_text""" ,lowerCamelCase__ ) self.assertIn("""sentencepiece_and_tokenizers""" ,lowerCamelCase__ ) # Likewise, we can't assert on the exact content of a key self.assertIn("""BertModel""" ,objects["""torch"""] ) self.assertIn("""TFBertModel""" ,objects["""tf"""] ) self.assertIn("""FlaxBertModel""" ,objects["""flax"""] ) self.assertIn("""BertModel""" ,objects["""torch"""] ) self.assertIn("""TFBertTokenizer""" ,objects["""tensorflow_text"""] ) self.assertIn("""convert_slow_tokenizer""" ,objects["""sentencepiece_and_tokenizers"""] ) def SCREAMING_SNAKE_CASE__ ( self : int ) -> str: '''simple docstring''' SCREAMING_SNAKE_CASE = create_dummy_object("""CONSTANT""" ,"""'torch'""" ) self.assertEqual(lowerCamelCase__ ,"""\nCONSTANT = None\n""" ) SCREAMING_SNAKE_CASE = create_dummy_object("""function""" ,"""'torch'""" ) self.assertEqual( lowerCamelCase__ ,"""\ndef function(*args, **kwargs):\n requires_backends(function, 'torch')\n""" ) SCREAMING_SNAKE_CASE = """ class FakeClass(metaclass=DummyObject): _backends = 'torch' def __init__(self, *args, **kwargs): requires_backends(self, 'torch') """ SCREAMING_SNAKE_CASE = create_dummy_object("""FakeClass""" ,"""'torch'""" ) self.assertEqual(lowerCamelCase__ ,lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE = """# This file is autogenerated by the command `make fix-copies`, do not edit. from ..utils import DummyObject, requires_backends CONSTANT = None def function(*args, **kwargs): requires_backends(function, [\"torch\"]) class FakeClass(metaclass=DummyObject): _backends = [\"torch\"] def __init__(self, *args, **kwargs): requires_backends(self, [\"torch\"]) """ SCREAMING_SNAKE_CASE = create_dummy_files({"""torch""": ["""CONSTANT""", """function""", """FakeClass"""]} ) self.assertEqual(dummy_files["""torch"""] ,lowerCamelCase__ )
296
import logging from dataclasses import dataclass, field from typing import Optional from seqaseq_trainer import arg_to_scheduler from transformers import TrainingArguments SCREAMING_SNAKE_CASE_ = logging.getLogger(__name__) @dataclass class UpperCamelCase__ ( lowerCAmelCase_ ): '''simple docstring''' __snake_case : Optional[float] = field( default=0.0 , metadata={"help": "The label smoothing epsilon to apply (if not zero)."} ) __snake_case : bool = field(default=lowerCAmelCase_ , metadata={"help": "Whether to SortishSamler or not."} ) __snake_case : bool = field( default=lowerCAmelCase_ , metadata={"help": "Whether to use generate to calculate generative metrics (ROUGE, BLEU)."} ) __snake_case : bool = field(default=lowerCAmelCase_ , metadata={"help": "whether to use adafactor"} ) __snake_case : Optional[float] = field( default=lowerCAmelCase_ , metadata={"help": "Encoder layer dropout probability. Goes into model.config."} ) __snake_case : Optional[float] = field( default=lowerCAmelCase_ , metadata={"help": "Decoder layer dropout probability. Goes into model.config."} ) __snake_case : Optional[float] = field(default=lowerCAmelCase_ , metadata={"help": "Dropout probability. Goes into model.config."} ) __snake_case : Optional[float] = field( default=lowerCAmelCase_ , metadata={"help": "Attention dropout probability. Goes into model.config."} ) __snake_case : Optional[str] = field( default="linear" , metadata={"help": F"Which lr scheduler to use. Selected in {sorted(arg_to_scheduler.keys() )}"} , )
296
1
import contextlib import csv import json import os import sqlitea import tarfile import textwrap import zipfile import pyarrow as pa import pyarrow.parquet as pq import pytest import datasets import datasets.config @pytest.fixture(scope="""session""" ) def __lowercase ( ) -> str: '''simple docstring''' SCREAMING_SNAKE_CASE = 10 SCREAMING_SNAKE_CASE = datasets.Features( { """tokens""": datasets.Sequence(datasets.Value("""string""" ) ), """labels""": datasets.Sequence(datasets.ClassLabel(names=["""negative""", """positive"""] ) ), """answers""": datasets.Sequence( { """text""": datasets.Value("""string""" ), """answer_start""": datasets.Value("""int32""" ), } ), """id""": datasets.Value("""int64""" ), } ) SCREAMING_SNAKE_CASE = datasets.Dataset.from_dict( { """tokens""": [["""foo"""] * 5] * n, """labels""": [[1] * 5] * n, """answers""": [{"""answer_start""": [97], """text""": ["""1976"""]}] * 10, """id""": list(range(_SCREAMING_SNAKE_CASE ) ), } , features=_SCREAMING_SNAKE_CASE , ) return dataset @pytest.fixture(scope="""session""" ) def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Optional[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE = str(tmp_path_factory.mktemp("""data""" ) / """file.arrow""" ) dataset.map(cache_file_name=_SCREAMING_SNAKE_CASE ) return filename # FILE_CONTENT + files SCREAMING_SNAKE_CASE_ = """\ Text data. Second line of data.""" @pytest.fixture(scope="""session""" ) def __lowercase ( _SCREAMING_SNAKE_CASE ) -> str: '''simple docstring''' SCREAMING_SNAKE_CASE = tmp_path_factory.mktemp("""data""" ) / """file.txt""" SCREAMING_SNAKE_CASE = FILE_CONTENT with open(_SCREAMING_SNAKE_CASE , """w""" ) as f: f.write(_SCREAMING_SNAKE_CASE ) return filename @pytest.fixture(scope="""session""" ) def __lowercase ( _SCREAMING_SNAKE_CASE ) -> Optional[Any]: '''simple docstring''' import bza SCREAMING_SNAKE_CASE = tmp_path_factory.mktemp("""data""" ) / """file.txt.bz2""" SCREAMING_SNAKE_CASE = bytes(_SCREAMING_SNAKE_CASE , """utf-8""" ) with bza.open(_SCREAMING_SNAKE_CASE , """wb""" ) as f: f.write(_SCREAMING_SNAKE_CASE ) return path @pytest.fixture(scope="""session""" ) def __lowercase ( _SCREAMING_SNAKE_CASE ) -> List[str]: '''simple docstring''' import gzip SCREAMING_SNAKE_CASE = str(tmp_path_factory.mktemp("""data""" ) / """file.txt.gz""" ) SCREAMING_SNAKE_CASE = bytes(_SCREAMING_SNAKE_CASE , """utf-8""" ) with gzip.open(_SCREAMING_SNAKE_CASE , """wb""" ) as f: f.write(_SCREAMING_SNAKE_CASE ) return path @pytest.fixture(scope="""session""" ) def __lowercase ( _SCREAMING_SNAKE_CASE ) -> Union[str, Any]: '''simple docstring''' if datasets.config.LZ4_AVAILABLE: import lza.frame SCREAMING_SNAKE_CASE = tmp_path_factory.mktemp("""data""" ) / """file.txt.lz4""" SCREAMING_SNAKE_CASE = bytes(_SCREAMING_SNAKE_CASE , """utf-8""" ) with lza.frame.open(_SCREAMING_SNAKE_CASE , """wb""" ) as f: f.write(_SCREAMING_SNAKE_CASE ) return path @pytest.fixture(scope="""session""" ) def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Union[str, Any]: '''simple docstring''' if datasets.config.PY7ZR_AVAILABLE: import pyazr SCREAMING_SNAKE_CASE = tmp_path_factory.mktemp("""data""" ) / """file.txt.7z""" with pyazr.SevenZipFile(_SCREAMING_SNAKE_CASE , """w""" ) as archive: archive.write(_SCREAMING_SNAKE_CASE , arcname=os.path.basename(_SCREAMING_SNAKE_CASE ) ) return path @pytest.fixture(scope="""session""" ) def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Any: '''simple docstring''' import tarfile SCREAMING_SNAKE_CASE = tmp_path_factory.mktemp("""data""" ) / """file.txt.tar""" with tarfile.TarFile(_SCREAMING_SNAKE_CASE , """w""" ) as f: f.add(_SCREAMING_SNAKE_CASE , arcname=os.path.basename(_SCREAMING_SNAKE_CASE ) ) return path @pytest.fixture(scope="""session""" ) def __lowercase ( _SCREAMING_SNAKE_CASE ) -> List[str]: '''simple docstring''' import lzma SCREAMING_SNAKE_CASE = tmp_path_factory.mktemp("""data""" ) / """file.txt.xz""" SCREAMING_SNAKE_CASE = bytes(_SCREAMING_SNAKE_CASE , """utf-8""" ) with lzma.open(_SCREAMING_SNAKE_CASE , """wb""" ) as f: f.write(_SCREAMING_SNAKE_CASE ) return path @pytest.fixture(scope="""session""" ) def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Tuple: '''simple docstring''' import zipfile SCREAMING_SNAKE_CASE = tmp_path_factory.mktemp("""data""" ) / """file.txt.zip""" with zipfile.ZipFile(_SCREAMING_SNAKE_CASE , """w""" ) as f: f.write(_SCREAMING_SNAKE_CASE , arcname=os.path.basename(_SCREAMING_SNAKE_CASE ) ) return path @pytest.fixture(scope="""session""" ) def __lowercase ( _SCREAMING_SNAKE_CASE ) -> int: '''simple docstring''' if datasets.config.ZSTANDARD_AVAILABLE: import zstandard as zstd SCREAMING_SNAKE_CASE = tmp_path_factory.mktemp("""data""" ) / """file.txt.zst""" SCREAMING_SNAKE_CASE = bytes(_SCREAMING_SNAKE_CASE , """utf-8""" ) with zstd.open(_SCREAMING_SNAKE_CASE , """wb""" ) as f: f.write(_SCREAMING_SNAKE_CASE ) return path @pytest.fixture(scope="""session""" ) def __lowercase ( _SCREAMING_SNAKE_CASE ) -> List[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE = tmp_path_factory.mktemp("""data""" ) / """file.xml""" SCREAMING_SNAKE_CASE = textwrap.dedent( """\ <?xml version=\"1.0\" encoding=\"UTF-8\" ?> <tmx version=\"1.4\"> <header segtype=\"sentence\" srclang=\"ca\" /> <body> <tu> <tuv xml:lang=\"ca\"><seg>Contingut 1</seg></tuv> <tuv xml:lang=\"en\"><seg>Content 1</seg></tuv> </tu> <tu> <tuv xml:lang=\"ca\"><seg>Contingut 2</seg></tuv> <tuv xml:lang=\"en\"><seg>Content 2</seg></tuv> </tu> <tu> <tuv xml:lang=\"ca\"><seg>Contingut 3</seg></tuv> <tuv xml:lang=\"en\"><seg>Content 3</seg></tuv> </tu> <tu> <tuv xml:lang=\"ca\"><seg>Contingut 4</seg></tuv> <tuv xml:lang=\"en\"><seg>Content 4</seg></tuv> </tu> <tu> <tuv xml:lang=\"ca\"><seg>Contingut 5</seg></tuv> <tuv xml:lang=\"en\"><seg>Content 5</seg></tuv> </tu> </body> </tmx>""" ) with open(_SCREAMING_SNAKE_CASE , """w""" ) as f: f.write(_SCREAMING_SNAKE_CASE ) return filename SCREAMING_SNAKE_CASE_ = [ {"""col_1""": """0""", """col_2""": 0, """col_3""": 0.0}, {"""col_1""": """1""", """col_2""": 1, """col_3""": 1.0}, {"""col_1""": """2""", """col_2""": 2, """col_3""": 2.0}, {"""col_1""": """3""", """col_2""": 3, """col_3""": 3.0}, ] SCREAMING_SNAKE_CASE_ = [ {"""col_1""": """4""", """col_2""": 4, """col_3""": 4.0}, {"""col_1""": """5""", """col_2""": 5, """col_3""": 5.0}, ] SCREAMING_SNAKE_CASE_ = { """col_1""": ["""0""", """1""", """2""", """3"""], """col_2""": [0, 1, 2, 3], """col_3""": [0.0, 1.0, 2.0, 3.0], } SCREAMING_SNAKE_CASE_ = [ {"""col_3""": 0.0, """col_1""": """0""", """col_2""": 0}, {"""col_3""": 1.0, """col_1""": """1""", """col_2""": 1}, ] SCREAMING_SNAKE_CASE_ = [ {"""col_1""": """s0""", """col_2""": 0, """col_3""": 0.0}, {"""col_1""": """s1""", """col_2""": 1, """col_3""": 1.0}, {"""col_1""": """s2""", """col_2""": 2, """col_3""": 2.0}, {"""col_1""": """s3""", """col_2""": 3, """col_3""": 3.0}, ] @pytest.fixture(scope="""session""" ) def __lowercase ( ) -> Optional[Any]: '''simple docstring''' return DATA_DICT_OF_LISTS @pytest.fixture(scope="""session""" ) def __lowercase ( _SCREAMING_SNAKE_CASE ) -> List[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE = datasets.Dataset.from_dict(_SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE = str(tmp_path_factory.mktemp("""data""" ) / """dataset.arrow""" ) dataset.map(cache_file_name=_SCREAMING_SNAKE_CASE ) return path @pytest.fixture(scope="""session""" ) def __lowercase ( _SCREAMING_SNAKE_CASE ) -> str: '''simple docstring''' SCREAMING_SNAKE_CASE = str(tmp_path_factory.mktemp("""data""" ) / """dataset.sqlite""" ) with contextlib.closing(sqlitea.connect(_SCREAMING_SNAKE_CASE ) ) as con: SCREAMING_SNAKE_CASE = con.cursor() cur.execute("""CREATE TABLE dataset(col_1 text, col_2 int, col_3 real)""" ) for item in DATA: cur.execute("""INSERT INTO dataset(col_1, col_2, col_3) VALUES (?, ?, ?)""" , tuple(item.values() ) ) con.commit() return path @pytest.fixture(scope="""session""" ) def __lowercase ( _SCREAMING_SNAKE_CASE ) -> Optional[int]: '''simple docstring''' SCREAMING_SNAKE_CASE = str(tmp_path_factory.mktemp("""data""" ) / """dataset.csv""" ) with open(_SCREAMING_SNAKE_CASE , """w""" , newline="""""" ) as f: SCREAMING_SNAKE_CASE = csv.DictWriter(_SCREAMING_SNAKE_CASE , fieldnames=["""col_1""", """col_2""", """col_3"""] ) writer.writeheader() for item in DATA: writer.writerow(_SCREAMING_SNAKE_CASE ) return path @pytest.fixture(scope="""session""" ) def __lowercase ( _SCREAMING_SNAKE_CASE ) -> List[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE = str(tmp_path_factory.mktemp("""data""" ) / """dataset2.csv""" ) with open(_SCREAMING_SNAKE_CASE , """w""" , newline="""""" ) as f: SCREAMING_SNAKE_CASE = csv.DictWriter(_SCREAMING_SNAKE_CASE , fieldnames=["""col_1""", """col_2""", """col_3"""] ) writer.writeheader() for item in DATA: writer.writerow(_SCREAMING_SNAKE_CASE ) return path @pytest.fixture(scope="""session""" ) def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Tuple: '''simple docstring''' import bza SCREAMING_SNAKE_CASE = tmp_path_factory.mktemp("""data""" ) / """dataset.csv.bz2""" with open(_SCREAMING_SNAKE_CASE , """rb""" ) as f: SCREAMING_SNAKE_CASE = f.read() # data = bytes(FILE_CONTENT, "utf-8") with bza.open(_SCREAMING_SNAKE_CASE , """wb""" ) as f: f.write(_SCREAMING_SNAKE_CASE ) return path @pytest.fixture(scope="""session""" ) def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Dict: '''simple docstring''' SCREAMING_SNAKE_CASE = tmp_path_factory.mktemp("""data""" ) / """dataset.csv.zip""" with zipfile.ZipFile(_SCREAMING_SNAKE_CASE , """w""" ) as f: f.write(_SCREAMING_SNAKE_CASE , arcname=os.path.basename(_SCREAMING_SNAKE_CASE ) ) f.write(_SCREAMING_SNAKE_CASE , arcname=os.path.basename(_SCREAMING_SNAKE_CASE ) ) return path @pytest.fixture(scope="""session""" ) def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Dict: '''simple docstring''' SCREAMING_SNAKE_CASE = tmp_path_factory.mktemp("""data""" ) / """dataset.csv.zip""" with zipfile.ZipFile(_SCREAMING_SNAKE_CASE , """w""" ) as f: f.write(_SCREAMING_SNAKE_CASE , arcname=os.path.basename(csv_path.replace(""".csv""" , """.CSV""" ) ) ) f.write(_SCREAMING_SNAKE_CASE , arcname=os.path.basename(csva_path.replace(""".csv""" , """.CSV""" ) ) ) return path @pytest.fixture(scope="""session""" ) def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE = tmp_path_factory.mktemp("""data""" ) / """dataset_with_dir.csv.zip""" with zipfile.ZipFile(_SCREAMING_SNAKE_CASE , """w""" ) as f: f.write(_SCREAMING_SNAKE_CASE , arcname=os.path.join("""main_dir""" , os.path.basename(_SCREAMING_SNAKE_CASE ) ) ) f.write(_SCREAMING_SNAKE_CASE , arcname=os.path.join("""main_dir""" , os.path.basename(_SCREAMING_SNAKE_CASE ) ) ) return path @pytest.fixture(scope="""session""" ) def __lowercase ( _SCREAMING_SNAKE_CASE ) -> Union[str, Any]: '''simple docstring''' SCREAMING_SNAKE_CASE = str(tmp_path_factory.mktemp("""data""" ) / """dataset.parquet""" ) SCREAMING_SNAKE_CASE = pa.schema( { """col_1""": pa.string(), """col_2""": pa.intaa(), """col_3""": pa.floataa(), } ) with open(_SCREAMING_SNAKE_CASE , """wb""" ) as f: SCREAMING_SNAKE_CASE = pq.ParquetWriter(_SCREAMING_SNAKE_CASE , schema=_SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE = pa.Table.from_pydict({k: [DATA[i][k] for i in range(len(_SCREAMING_SNAKE_CASE ) )] for k in DATA[0]} , schema=_SCREAMING_SNAKE_CASE ) writer.write_table(_SCREAMING_SNAKE_CASE ) writer.close() return path @pytest.fixture(scope="""session""" ) def __lowercase ( _SCREAMING_SNAKE_CASE ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE = str(tmp_path_factory.mktemp("""data""" ) / """dataset.json""" ) SCREAMING_SNAKE_CASE = {"""data""": DATA} with open(_SCREAMING_SNAKE_CASE , """w""" ) as f: json.dump(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) return path @pytest.fixture(scope="""session""" ) def __lowercase ( _SCREAMING_SNAKE_CASE ) -> List[str]: '''simple docstring''' SCREAMING_SNAKE_CASE = str(tmp_path_factory.mktemp("""data""" ) / """dataset.json""" ) SCREAMING_SNAKE_CASE = {"""data""": DATA_DICT_OF_LISTS} with open(_SCREAMING_SNAKE_CASE , """w""" ) as f: json.dump(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) return path @pytest.fixture(scope="""session""" ) def __lowercase ( _SCREAMING_SNAKE_CASE ) -> List[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE = str(tmp_path_factory.mktemp("""data""" ) / """dataset.jsonl""" ) with open(_SCREAMING_SNAKE_CASE , """w""" ) as f: for item in DATA: f.write(json.dumps(_SCREAMING_SNAKE_CASE ) + """\n""" ) return path @pytest.fixture(scope="""session""" ) def __lowercase ( _SCREAMING_SNAKE_CASE ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE = str(tmp_path_factory.mktemp("""data""" ) / """dataset2.jsonl""" ) with open(_SCREAMING_SNAKE_CASE , """w""" ) as f: for item in DATA: f.write(json.dumps(_SCREAMING_SNAKE_CASE ) + """\n""" ) return path @pytest.fixture(scope="""session""" ) def __lowercase ( _SCREAMING_SNAKE_CASE ) -> str: '''simple docstring''' SCREAMING_SNAKE_CASE = str(tmp_path_factory.mktemp("""data""" ) / """dataset_312.jsonl""" ) with open(_SCREAMING_SNAKE_CASE , """w""" ) as f: for item in DATA_312: f.write(json.dumps(_SCREAMING_SNAKE_CASE ) + """\n""" ) return path @pytest.fixture(scope="""session""" ) def __lowercase ( _SCREAMING_SNAKE_CASE ) -> Union[str, Any]: '''simple docstring''' SCREAMING_SNAKE_CASE = str(tmp_path_factory.mktemp("""data""" ) / """dataset-str.jsonl""" ) with open(_SCREAMING_SNAKE_CASE , """w""" ) as f: for item in DATA_STR: f.write(json.dumps(_SCREAMING_SNAKE_CASE ) + """\n""" ) return path @pytest.fixture(scope="""session""" ) def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> List[str]: '''simple docstring''' import gzip SCREAMING_SNAKE_CASE = str(tmp_path_factory.mktemp("""data""" ) / """dataset.txt.gz""" ) with open(_SCREAMING_SNAKE_CASE , """rb""" ) as orig_file: with gzip.open(_SCREAMING_SNAKE_CASE , """wb""" ) as zipped_file: zipped_file.writelines(_SCREAMING_SNAKE_CASE ) return path @pytest.fixture(scope="""session""" ) def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> str: '''simple docstring''' import gzip SCREAMING_SNAKE_CASE = str(tmp_path_factory.mktemp("""data""" ) / """dataset.jsonl.gz""" ) with open(_SCREAMING_SNAKE_CASE , """rb""" ) as orig_file: with gzip.open(_SCREAMING_SNAKE_CASE , """wb""" ) as zipped_file: zipped_file.writelines(_SCREAMING_SNAKE_CASE ) return path @pytest.fixture(scope="""session""" ) def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Union[str, Any]: '''simple docstring''' SCREAMING_SNAKE_CASE = tmp_path_factory.mktemp("""data""" ) / """dataset.jsonl.zip""" with zipfile.ZipFile(_SCREAMING_SNAKE_CASE , """w""" ) as f: f.write(_SCREAMING_SNAKE_CASE , arcname=os.path.basename(_SCREAMING_SNAKE_CASE ) ) f.write(_SCREAMING_SNAKE_CASE , arcname=os.path.basename(_SCREAMING_SNAKE_CASE ) ) return path @pytest.fixture(scope="""session""" ) def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Union[str, Any]: '''simple docstring''' SCREAMING_SNAKE_CASE = tmp_path_factory.mktemp("""data""" ) / """dataset_nested.jsonl.zip""" with zipfile.ZipFile(_SCREAMING_SNAKE_CASE , """w""" ) as f: f.write(_SCREAMING_SNAKE_CASE , arcname=os.path.join("""nested""" , os.path.basename(_SCREAMING_SNAKE_CASE ) ) ) return path @pytest.fixture(scope="""session""" ) def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Union[str, Any]: '''simple docstring''' SCREAMING_SNAKE_CASE = tmp_path_factory.mktemp("""data""" ) / """dataset_with_dir.jsonl.zip""" with zipfile.ZipFile(_SCREAMING_SNAKE_CASE , """w""" ) as f: f.write(_SCREAMING_SNAKE_CASE , arcname=os.path.join("""main_dir""" , os.path.basename(_SCREAMING_SNAKE_CASE ) ) ) f.write(_SCREAMING_SNAKE_CASE , arcname=os.path.join("""main_dir""" , os.path.basename(_SCREAMING_SNAKE_CASE ) ) ) return path @pytest.fixture(scope="""session""" ) def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> List[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE = tmp_path_factory.mktemp("""data""" ) / """dataset.jsonl.tar""" with tarfile.TarFile(_SCREAMING_SNAKE_CASE , """w""" ) as f: f.add(_SCREAMING_SNAKE_CASE , arcname=os.path.basename(_SCREAMING_SNAKE_CASE ) ) f.add(_SCREAMING_SNAKE_CASE , arcname=os.path.basename(_SCREAMING_SNAKE_CASE ) ) return path @pytest.fixture(scope="""session""" ) def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE = tmp_path_factory.mktemp("""data""" ) / """dataset_nested.jsonl.tar""" with tarfile.TarFile(_SCREAMING_SNAKE_CASE , """w""" ) as f: f.add(_SCREAMING_SNAKE_CASE , arcname=os.path.join("""nested""" , os.path.basename(_SCREAMING_SNAKE_CASE ) ) ) return path @pytest.fixture(scope="""session""" ) def __lowercase ( _SCREAMING_SNAKE_CASE ) -> Tuple: '''simple docstring''' SCREAMING_SNAKE_CASE = ["""0""", """1""", """2""", """3"""] SCREAMING_SNAKE_CASE = str(tmp_path_factory.mktemp("""data""" ) / """dataset.txt""" ) with open(_SCREAMING_SNAKE_CASE , """w""" ) as f: for item in data: f.write(item + """\n""" ) return path @pytest.fixture(scope="""session""" ) def __lowercase ( _SCREAMING_SNAKE_CASE ) -> str: '''simple docstring''' SCREAMING_SNAKE_CASE = ["""0""", """1""", """2""", """3"""] SCREAMING_SNAKE_CASE = str(tmp_path_factory.mktemp("""data""" ) / """dataset2.txt""" ) with open(_SCREAMING_SNAKE_CASE , """w""" ) as f: for item in data: f.write(item + """\n""" ) return path @pytest.fixture(scope="""session""" ) def __lowercase ( _SCREAMING_SNAKE_CASE ) -> Union[str, Any]: '''simple docstring''' SCREAMING_SNAKE_CASE = ["""0""", """1""", """2""", """3"""] SCREAMING_SNAKE_CASE = tmp_path_factory.mktemp("""data""" ) / """dataset.abc""" with open(_SCREAMING_SNAKE_CASE , """w""" ) as f: for item in data: f.write(item + """\n""" ) return path @pytest.fixture(scope="""session""" ) def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE = tmp_path_factory.mktemp("""data""" ) / """dataset.text.zip""" with zipfile.ZipFile(_SCREAMING_SNAKE_CASE , """w""" ) as f: f.write(_SCREAMING_SNAKE_CASE , arcname=os.path.basename(_SCREAMING_SNAKE_CASE ) ) f.write(_SCREAMING_SNAKE_CASE , arcname=os.path.basename(_SCREAMING_SNAKE_CASE ) ) return path @pytest.fixture(scope="""session""" ) def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Optional[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE = tmp_path_factory.mktemp("""data""" ) / """dataset_with_dir.text.zip""" with zipfile.ZipFile(_SCREAMING_SNAKE_CASE , """w""" ) as f: f.write(_SCREAMING_SNAKE_CASE , arcname=os.path.join("""main_dir""" , os.path.basename(_SCREAMING_SNAKE_CASE ) ) ) f.write(_SCREAMING_SNAKE_CASE , arcname=os.path.join("""main_dir""" , os.path.basename(_SCREAMING_SNAKE_CASE ) ) ) return path @pytest.fixture(scope="""session""" ) def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE = tmp_path_factory.mktemp("""data""" ) / """dataset.ext.zip""" with zipfile.ZipFile(_SCREAMING_SNAKE_CASE , """w""" ) as f: f.write(_SCREAMING_SNAKE_CASE , arcname=os.path.basename("""unsupported.ext""" ) ) f.write(_SCREAMING_SNAKE_CASE , arcname=os.path.basename("""unsupported_2.ext""" ) ) return path @pytest.fixture(scope="""session""" ) def __lowercase ( _SCREAMING_SNAKE_CASE ) -> str: '''simple docstring''' SCREAMING_SNAKE_CASE = """\n""".join(["""First""", """Second\u2029with Unicode new line""", """Third"""] ) SCREAMING_SNAKE_CASE = str(tmp_path_factory.mktemp("""data""" ) / """dataset_with_unicode_new_lines.txt""" ) with open(_SCREAMING_SNAKE_CASE , """w""" , encoding="""utf-8""" ) as f: f.write(_SCREAMING_SNAKE_CASE ) return path @pytest.fixture(scope="""session""" ) def __lowercase ( ) -> Tuple: '''simple docstring''' return os.path.join("""tests""" , """features""" , """data""" , """test_image_rgb.jpg""" ) @pytest.fixture(scope="""session""" ) def __lowercase ( ) -> List[str]: '''simple docstring''' return os.path.join("""tests""" , """features""" , """data""" , """test_audio_44100.wav""" ) @pytest.fixture(scope="""session""" ) def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Optional[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE = tmp_path_factory.mktemp("""data""" ) / """dataset.img.zip""" with zipfile.ZipFile(_SCREAMING_SNAKE_CASE , """w""" ) as f: f.write(_SCREAMING_SNAKE_CASE , arcname=os.path.basename(_SCREAMING_SNAKE_CASE ) ) f.write(_SCREAMING_SNAKE_CASE , arcname=os.path.basename(_SCREAMING_SNAKE_CASE ).replace(""".jpg""" , """2.jpg""" ) ) return path @pytest.fixture(scope="""session""" ) def __lowercase ( _SCREAMING_SNAKE_CASE ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE = tmp_path_factory.mktemp("""data_dir""" ) (data_dir / "subdir").mkdir() with open(data_dir / """subdir""" / """train.txt""" , """w""" ) as f: f.write("""foo\n""" * 10 ) with open(data_dir / """subdir""" / """test.txt""" , """w""" ) as f: f.write("""bar\n""" * 10 ) # hidden file with open(data_dir / """subdir""" / """.test.txt""" , """w""" ) as f: f.write("""bar\n""" * 10 ) # hidden directory (data_dir / ".subdir").mkdir() with open(data_dir / """.subdir""" / """train.txt""" , """w""" ) as f: f.write("""foo\n""" * 10 ) with open(data_dir / """.subdir""" / """test.txt""" , """w""" ) as f: f.write("""bar\n""" * 10 ) return data_dir
296
import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, DPMSolverMultistepScheduler, TextToVideoSDPipeline, UNetaDConditionModel, ) from diffusers.utils import is_xformers_available, load_numpy, skip_mps, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() @skip_mps class UpperCamelCase__ ( lowerCAmelCase_ , unittest.TestCase ): '''simple docstring''' __snake_case : List[str] = TextToVideoSDPipeline __snake_case : int = TEXT_TO_IMAGE_PARAMS __snake_case : Tuple = TEXT_TO_IMAGE_BATCH_PARAMS # No `output_type`. __snake_case : Dict = frozenset( [ "num_inference_steps", "generator", "latents", "return_dict", "callback", "callback_steps", ] ) def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ) -> Optional[int]: '''simple docstring''' torch.manual_seed(0 ) SCREAMING_SNAKE_CASE = UNetaDConditionModel( block_out_channels=(32, 64, 64, 64) ,layers_per_block=2 ,sample_size=32 ,in_channels=4 ,out_channels=4 ,down_block_types=("""CrossAttnDownBlock3D""", """CrossAttnDownBlock3D""", """CrossAttnDownBlock3D""", """DownBlock3D""") ,up_block_types=("""UpBlock3D""", """CrossAttnUpBlock3D""", """CrossAttnUpBlock3D""", """CrossAttnUpBlock3D""") ,cross_attention_dim=32 ,attention_head_dim=4 ,) SCREAMING_SNAKE_CASE = DDIMScheduler( beta_start=0.00085 ,beta_end=0.012 ,beta_schedule="""scaled_linear""" ,clip_sample=lowerCamelCase__ ,set_alpha_to_one=lowerCamelCase__ ,) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE = AutoencoderKL( block_out_channels=[32, 64] ,in_channels=3 ,out_channels=3 ,down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] ,up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] ,latent_channels=4 ,sample_size=128 ,) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE = CLIPTextConfig( bos_token_id=0 ,eos_token_id=2 ,hidden_size=32 ,intermediate_size=37 ,layer_norm_eps=1e-0_5 ,num_attention_heads=4 ,num_hidden_layers=5 ,pad_token_id=1 ,vocab_size=1000 ,hidden_act="""gelu""" ,projection_dim=512 ,) SCREAMING_SNAKE_CASE = CLIPTextModel(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) SCREAMING_SNAKE_CASE = { """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, } return components def SCREAMING_SNAKE_CASE__ ( self : int ,lowerCamelCase__ : Optional[Any] ,lowerCamelCase__ : int=0 ) -> List[Any]: '''simple docstring''' if str(lowerCamelCase__ ).startswith("""mps""" ): SCREAMING_SNAKE_CASE = torch.manual_seed(lowerCamelCase__ ) else: SCREAMING_SNAKE_CASE = torch.Generator(device=lowerCamelCase__ ).manual_seed(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = { """prompt""": """A painting of a squirrel eating a burger""", """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 6.0, """output_type""": """pt""", } return inputs def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ) -> List[str]: '''simple docstring''' SCREAMING_SNAKE_CASE = """cpu""" # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE = self.get_dummy_components() SCREAMING_SNAKE_CASE = TextToVideoSDPipeline(**lowerCamelCase__ ) SCREAMING_SNAKE_CASE = sd_pipe.to(lowerCamelCase__ ) sd_pipe.set_progress_bar_config(disable=lowerCamelCase__ ) SCREAMING_SNAKE_CASE = self.get_dummy_inputs(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = """np""" SCREAMING_SNAKE_CASE = sd_pipe(**lowerCamelCase__ ).frames SCREAMING_SNAKE_CASE = frames[0][-3:, -3:, -1] assert frames[0].shape == (64, 64, 3) SCREAMING_SNAKE_CASE = np.array([158.0, 160.0, 153.0, 125.0, 100.0, 121.0, 111.0, 93.0, 113.0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def SCREAMING_SNAKE_CASE__ ( self : Dict ) -> int: '''simple docstring''' self._test_attention_slicing_forward_pass(test_mean_pixel_difference=lowerCamelCase__ ,expected_max_diff=3e-3 ) @unittest.skipIf( torch_device != """cuda""" or not is_xformers_available() ,reason="""XFormers attention is only available with CUDA and `xformers` installed""" ,) def SCREAMING_SNAKE_CASE__ ( self : Tuple ) -> Any: '''simple docstring''' self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=lowerCamelCase__ ,expected_max_diff=1e-2 ) @unittest.skip(reason="""Batching needs to be properly figured out first for this pipeline.""" ) def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ) -> List[Any]: '''simple docstring''' pass @unittest.skip(reason="""Batching needs to be properly figured out first for this pipeline.""" ) def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ) -> Any: '''simple docstring''' pass @unittest.skip(reason="""`num_images_per_prompt` argument is not supported for this pipeline.""" ) def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ) -> Tuple: '''simple docstring''' pass def SCREAMING_SNAKE_CASE__ ( self : List[str] ) -> Optional[Any]: '''simple docstring''' return super().test_progress_bar() @slow @skip_mps class UpperCamelCase__ ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE__ ( self : Any ) -> Optional[int]: '''simple docstring''' SCREAMING_SNAKE_CASE = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/text_to_video/video.npy""" ) SCREAMING_SNAKE_CASE = TextToVideoSDPipeline.from_pretrained("""damo-vilab/text-to-video-ms-1.7b""" ) SCREAMING_SNAKE_CASE = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config ) SCREAMING_SNAKE_CASE = pipe.to("""cuda""" ) SCREAMING_SNAKE_CASE = """Spiderman is surfing""" SCREAMING_SNAKE_CASE = torch.Generator(device="""cpu""" ).manual_seed(0 ) SCREAMING_SNAKE_CASE = pipe(lowerCamelCase__ ,generator=lowerCamelCase__ ,num_inference_steps=25 ,output_type="""pt""" ).frames SCREAMING_SNAKE_CASE = video_frames.cpu().numpy() assert np.abs(expected_video - video ).mean() < 5e-2 def SCREAMING_SNAKE_CASE__ ( self : Any ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/text_to_video/video_2step.npy""" ) SCREAMING_SNAKE_CASE = TextToVideoSDPipeline.from_pretrained("""damo-vilab/text-to-video-ms-1.7b""" ) SCREAMING_SNAKE_CASE = pipe.to("""cuda""" ) SCREAMING_SNAKE_CASE = """Spiderman is surfing""" SCREAMING_SNAKE_CASE = torch.Generator(device="""cpu""" ).manual_seed(0 ) SCREAMING_SNAKE_CASE = pipe(lowerCamelCase__ ,generator=lowerCamelCase__ ,num_inference_steps=2 ,output_type="""pt""" ).frames SCREAMING_SNAKE_CASE = video_frames.cpu().numpy() assert np.abs(expected_video - video ).mean() < 5e-2
296
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) UpperCAmelCase__ = { "configuration_mobilevit": ["MOBILEVIT_PRETRAINED_CONFIG_ARCHIVE_MAP", "MobileViTConfig", "MobileViTOnnxConfig"], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ = ["MobileViTFeatureExtractor"] UpperCAmelCase__ = ["MobileViTImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ = [ "MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST", "MobileViTForImageClassification", "MobileViTForSemanticSegmentation", "MobileViTModel", "MobileViTPreTrainedModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ = [ "TF_MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST", "TFMobileViTForImageClassification", "TFMobileViTForSemanticSegmentation", "TFMobileViTModel", "TFMobileViTPreTrainedModel", ] if TYPE_CHECKING: from .configuration_mobilevit import MOBILEVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, MobileViTConfig, MobileViTOnnxConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_mobilevit import MobileViTFeatureExtractor from .image_processing_mobilevit import MobileViTImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mobilevit import ( MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST, MobileViTForImageClassification, MobileViTForSemanticSegmentation, MobileViTModel, MobileViTPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_mobilevit import ( TF_MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST, TFMobileViTForImageClassification, TFMobileViTForSemanticSegmentation, TFMobileViTModel, TFMobileViTPreTrainedModel, ) else: import sys UpperCAmelCase__ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
0
def __lowercase ( _SCREAMING_SNAKE_CASE = 10 ) -> str: '''simple docstring''' if not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) or n < 0: raise ValueError("""Invalid input""" ) SCREAMING_SNAKE_CASE = 10**n SCREAMING_SNAKE_CASE = 2_84_33 * (pow(2 , 7_83_04_57 , _SCREAMING_SNAKE_CASE )) + 1 return str(number % modulus ) if __name__ == "__main__": from doctest import testmod testmod() print(F'''{solution(1_0) = }''')
296
0
'''simple docstring''' import argparse import json from pathlib import Path import requests import torch from huggingface_hub import cached_download, hf_hub_download, hf_hub_url from PIL import Image from transformers import DetaConfig, DetaForObjectDetection, DetaImageProcessor, SwinConfig from transformers.utils import logging logging.set_verbosity_info() SCREAMING_SNAKE_CASE_: List[str] =logging.get_logger(__name__) def lowerCAmelCase_ ( snake_case_ : List[Any] ) -> Optional[int]: '''simple docstring''' UpperCAmelCase_ = SwinConfig( embed_dim=1_92 , depths=(2, 2, 18, 2) , num_heads=(6, 12, 24, 48) , window_size=12 , out_features=["stage2", "stage3", "stage4"] , ) UpperCAmelCase_ = DetaConfig( backbone_config=snake_case_ , num_queries=9_00 , encoder_ffn_dim=20_48 , decoder_ffn_dim=20_48 , num_feature_levels=5 , assign_first_stage=snake_case_ , with_box_refine=snake_case_ , two_stage=snake_case_ , ) # set labels UpperCAmelCase_ = "huggingface/label-files" if "o365" in model_name: UpperCAmelCase_ = 3_66 UpperCAmelCase_ = "object365-id2label.json" else: UpperCAmelCase_ = 91 UpperCAmelCase_ = "coco-detection-id2label.json" UpperCAmelCase_ = num_labels UpperCAmelCase_ = json.load(open(cached_download(hf_hub_url(snake_case_ , snake_case_ , repo_type="dataset" ) ) , "r" ) ) UpperCAmelCase_ = {int(snake_case_ ): v for k, v in idalabel.items()} UpperCAmelCase_ = idalabel UpperCAmelCase_ = {v: k for k, v in idalabel.items()} return config def lowerCAmelCase_ ( snake_case_ : int ) -> Optional[int]: '''simple docstring''' UpperCAmelCase_ = [] # stem # fmt: off rename_keys.append(("backbone.0.body.patch_embed.proj.weight", "model.backbone.model.embeddings.patch_embeddings.projection.weight") ) rename_keys.append(("backbone.0.body.patch_embed.proj.bias", "model.backbone.model.embeddings.patch_embeddings.projection.bias") ) rename_keys.append(("backbone.0.body.patch_embed.norm.weight", "model.backbone.model.embeddings.norm.weight") ) rename_keys.append(("backbone.0.body.patch_embed.norm.bias", "model.backbone.model.embeddings.norm.bias") ) # stages for i in range(len(config.backbone_config.depths ) ): for j in range(config.backbone_config.depths[i] ): rename_keys.append((f"""backbone.0.body.layers.{i}.blocks.{j}.norm1.weight""", f"""model.backbone.model.encoder.layers.{i}.blocks.{j}.layernorm_before.weight""") ) rename_keys.append((f"""backbone.0.body.layers.{i}.blocks.{j}.norm1.bias""", f"""model.backbone.model.encoder.layers.{i}.blocks.{j}.layernorm_before.bias""") ) rename_keys.append((f"""backbone.0.body.layers.{i}.blocks.{j}.attn.relative_position_bias_table""", f"""model.backbone.model.encoder.layers.{i}.blocks.{j}.attention.self.relative_position_bias_table""") ) rename_keys.append((f"""backbone.0.body.layers.{i}.blocks.{j}.attn.relative_position_index""", f"""model.backbone.model.encoder.layers.{i}.blocks.{j}.attention.self.relative_position_index""") ) rename_keys.append((f"""backbone.0.body.layers.{i}.blocks.{j}.attn.proj.weight""", f"""model.backbone.model.encoder.layers.{i}.blocks.{j}.attention.output.dense.weight""") ) rename_keys.append((f"""backbone.0.body.layers.{i}.blocks.{j}.attn.proj.bias""", f"""model.backbone.model.encoder.layers.{i}.blocks.{j}.attention.output.dense.bias""") ) rename_keys.append((f"""backbone.0.body.layers.{i}.blocks.{j}.norm2.weight""", f"""model.backbone.model.encoder.layers.{i}.blocks.{j}.layernorm_after.weight""") ) rename_keys.append((f"""backbone.0.body.layers.{i}.blocks.{j}.norm2.bias""", f"""model.backbone.model.encoder.layers.{i}.blocks.{j}.layernorm_after.bias""") ) rename_keys.append((f"""backbone.0.body.layers.{i}.blocks.{j}.mlp.fc1.weight""", f"""model.backbone.model.encoder.layers.{i}.blocks.{j}.intermediate.dense.weight""") ) rename_keys.append((f"""backbone.0.body.layers.{i}.blocks.{j}.mlp.fc1.bias""", f"""model.backbone.model.encoder.layers.{i}.blocks.{j}.intermediate.dense.bias""") ) rename_keys.append((f"""backbone.0.body.layers.{i}.blocks.{j}.mlp.fc2.weight""", f"""model.backbone.model.encoder.layers.{i}.blocks.{j}.output.dense.weight""") ) rename_keys.append((f"""backbone.0.body.layers.{i}.blocks.{j}.mlp.fc2.bias""", f"""model.backbone.model.encoder.layers.{i}.blocks.{j}.output.dense.bias""") ) if i < 3: rename_keys.append((f"""backbone.0.body.layers.{i}.downsample.reduction.weight""", f"""model.backbone.model.encoder.layers.{i}.downsample.reduction.weight""") ) rename_keys.append((f"""backbone.0.body.layers.{i}.downsample.norm.weight""", f"""model.backbone.model.encoder.layers.{i}.downsample.norm.weight""") ) rename_keys.append((f"""backbone.0.body.layers.{i}.downsample.norm.bias""", f"""model.backbone.model.encoder.layers.{i}.downsample.norm.bias""") ) rename_keys.append(("backbone.0.body.norm1.weight", "model.backbone.model.hidden_states_norms.stage2.weight") ) rename_keys.append(("backbone.0.body.norm1.bias", "model.backbone.model.hidden_states_norms.stage2.bias") ) rename_keys.append(("backbone.0.body.norm2.weight", "model.backbone.model.hidden_states_norms.stage3.weight") ) rename_keys.append(("backbone.0.body.norm2.bias", "model.backbone.model.hidden_states_norms.stage3.bias") ) rename_keys.append(("backbone.0.body.norm3.weight", "model.backbone.model.hidden_states_norms.stage4.weight") ) rename_keys.append(("backbone.0.body.norm3.bias", "model.backbone.model.hidden_states_norms.stage4.bias") ) # transformer encoder for i in range(config.encoder_layers ): rename_keys.append((f"""transformer.encoder.layers.{i}.self_attn.sampling_offsets.weight""", f"""model.encoder.layers.{i}.self_attn.sampling_offsets.weight""") ) rename_keys.append((f"""transformer.encoder.layers.{i}.self_attn.sampling_offsets.bias""", f"""model.encoder.layers.{i}.self_attn.sampling_offsets.bias""") ) rename_keys.append((f"""transformer.encoder.layers.{i}.self_attn.attention_weights.weight""", f"""model.encoder.layers.{i}.self_attn.attention_weights.weight""") ) rename_keys.append((f"""transformer.encoder.layers.{i}.self_attn.attention_weights.bias""", f"""model.encoder.layers.{i}.self_attn.attention_weights.bias""") ) rename_keys.append((f"""transformer.encoder.layers.{i}.self_attn.value_proj.weight""", f"""model.encoder.layers.{i}.self_attn.value_proj.weight""") ) rename_keys.append((f"""transformer.encoder.layers.{i}.self_attn.value_proj.bias""", f"""model.encoder.layers.{i}.self_attn.value_proj.bias""") ) rename_keys.append((f"""transformer.encoder.layers.{i}.self_attn.output_proj.weight""", f"""model.encoder.layers.{i}.self_attn.output_proj.weight""") ) rename_keys.append((f"""transformer.encoder.layers.{i}.self_attn.output_proj.bias""", f"""model.encoder.layers.{i}.self_attn.output_proj.bias""") ) rename_keys.append((f"""transformer.encoder.layers.{i}.norm1.weight""", f"""model.encoder.layers.{i}.self_attn_layer_norm.weight""") ) rename_keys.append((f"""transformer.encoder.layers.{i}.norm1.bias""", f"""model.encoder.layers.{i}.self_attn_layer_norm.bias""") ) rename_keys.append((f"""transformer.encoder.layers.{i}.linear1.weight""", f"""model.encoder.layers.{i}.fc1.weight""") ) rename_keys.append((f"""transformer.encoder.layers.{i}.linear1.bias""", f"""model.encoder.layers.{i}.fc1.bias""") ) rename_keys.append((f"""transformer.encoder.layers.{i}.linear2.weight""", f"""model.encoder.layers.{i}.fc2.weight""") ) rename_keys.append((f"""transformer.encoder.layers.{i}.linear2.bias""", f"""model.encoder.layers.{i}.fc2.bias""") ) rename_keys.append((f"""transformer.encoder.layers.{i}.norm2.weight""", f"""model.encoder.layers.{i}.final_layer_norm.weight""") ) rename_keys.append((f"""transformer.encoder.layers.{i}.norm2.bias""", f"""model.encoder.layers.{i}.final_layer_norm.bias""") ) # transformer decoder for i in range(config.decoder_layers ): rename_keys.append((f"""transformer.decoder.layers.{i}.cross_attn.sampling_offsets.weight""", f"""model.decoder.layers.{i}.encoder_attn.sampling_offsets.weight""") ) rename_keys.append((f"""transformer.decoder.layers.{i}.cross_attn.sampling_offsets.bias""", f"""model.decoder.layers.{i}.encoder_attn.sampling_offsets.bias""") ) rename_keys.append((f"""transformer.decoder.layers.{i}.cross_attn.attention_weights.weight""", f"""model.decoder.layers.{i}.encoder_attn.attention_weights.weight""") ) rename_keys.append((f"""transformer.decoder.layers.{i}.cross_attn.attention_weights.bias""", f"""model.decoder.layers.{i}.encoder_attn.attention_weights.bias""") ) rename_keys.append((f"""transformer.decoder.layers.{i}.cross_attn.value_proj.weight""", f"""model.decoder.layers.{i}.encoder_attn.value_proj.weight""") ) rename_keys.append((f"""transformer.decoder.layers.{i}.cross_attn.value_proj.bias""", f"""model.decoder.layers.{i}.encoder_attn.value_proj.bias""") ) rename_keys.append((f"""transformer.decoder.layers.{i}.cross_attn.output_proj.weight""", f"""model.decoder.layers.{i}.encoder_attn.output_proj.weight""") ) rename_keys.append((f"""transformer.decoder.layers.{i}.cross_attn.output_proj.bias""", f"""model.decoder.layers.{i}.encoder_attn.output_proj.bias""") ) rename_keys.append((f"""transformer.decoder.layers.{i}.norm1.weight""", f"""model.decoder.layers.{i}.encoder_attn_layer_norm.weight""") ) rename_keys.append((f"""transformer.decoder.layers.{i}.norm1.bias""", f"""model.decoder.layers.{i}.encoder_attn_layer_norm.bias""") ) rename_keys.append((f"""transformer.decoder.layers.{i}.self_attn.out_proj.weight""", f"""model.decoder.layers.{i}.self_attn.out_proj.weight""") ) rename_keys.append((f"""transformer.decoder.layers.{i}.self_attn.out_proj.bias""", f"""model.decoder.layers.{i}.self_attn.out_proj.bias""") ) rename_keys.append((f"""transformer.decoder.layers.{i}.norm2.weight""", f"""model.decoder.layers.{i}.self_attn_layer_norm.weight""") ) rename_keys.append((f"""transformer.decoder.layers.{i}.norm2.bias""", f"""model.decoder.layers.{i}.self_attn_layer_norm.bias""") ) rename_keys.append((f"""transformer.decoder.layers.{i}.linear1.weight""", f"""model.decoder.layers.{i}.fc1.weight""") ) rename_keys.append((f"""transformer.decoder.layers.{i}.linear1.bias""", f"""model.decoder.layers.{i}.fc1.bias""") ) rename_keys.append((f"""transformer.decoder.layers.{i}.linear2.weight""", f"""model.decoder.layers.{i}.fc2.weight""") ) rename_keys.append((f"""transformer.decoder.layers.{i}.linear2.bias""", f"""model.decoder.layers.{i}.fc2.bias""") ) rename_keys.append((f"""transformer.decoder.layers.{i}.norm3.weight""", f"""model.decoder.layers.{i}.final_layer_norm.weight""") ) rename_keys.append((f"""transformer.decoder.layers.{i}.norm3.bias""", f"""model.decoder.layers.{i}.final_layer_norm.bias""") ) # fmt: on return rename_keys def lowerCAmelCase_ ( snake_case_ : Tuple , snake_case_ : int , snake_case_ : Optional[int] ) -> int: '''simple docstring''' UpperCAmelCase_ = dct.pop(snake_case_ ) UpperCAmelCase_ = val def lowerCAmelCase_ ( snake_case_ : Union[str, Any] , snake_case_ : Optional[Any] ) -> List[str]: '''simple docstring''' UpperCAmelCase_ = [int(backbone_config.embed_dim * 2**i ) for i in range(len(backbone_config.depths ) )] for i in range(len(backbone_config.depths ) ): UpperCAmelCase_ = num_features[i] for j in range(backbone_config.depths[i] ): # fmt: off # read in weights + bias of input projection layer (in original implementation, this is a single matrix + bias) UpperCAmelCase_ = state_dict.pop(f"""backbone.0.body.layers.{i}.blocks.{j}.attn.qkv.weight""" ) UpperCAmelCase_ = state_dict.pop(f"""backbone.0.body.layers.{i}.blocks.{j}.attn.qkv.bias""" ) # next, add query, keys and values (in that order) to the state dict UpperCAmelCase_ = in_proj_weight[:dim, :] UpperCAmelCase_ = in_proj_bias[: dim] UpperCAmelCase_ = in_proj_weight[ dim : dim * 2, : ] UpperCAmelCase_ = in_proj_bias[ dim : dim * 2 ] UpperCAmelCase_ = in_proj_weight[ -dim :, : ] UpperCAmelCase_ = in_proj_bias[-dim :] # fmt: on def lowerCAmelCase_ ( snake_case_ : Union[str, Any] , snake_case_ : Dict ) -> List[str]: '''simple docstring''' UpperCAmelCase_ = config.d_model for i in range(config.decoder_layers ): # read in weights + bias of input projection layer of self-attention UpperCAmelCase_ = state_dict.pop(f"""transformer.decoder.layers.{i}.self_attn.in_proj_weight""" ) UpperCAmelCase_ = state_dict.pop(f"""transformer.decoder.layers.{i}.self_attn.in_proj_bias""" ) # next, add query, keys and values (in that order) to the state dict UpperCAmelCase_ = in_proj_weight[:hidden_size, :] UpperCAmelCase_ = in_proj_bias[:hidden_size] UpperCAmelCase_ = in_proj_weight[ hidden_size : hidden_size * 2, : ] UpperCAmelCase_ = in_proj_bias[hidden_size : hidden_size * 2] UpperCAmelCase_ = in_proj_weight[-hidden_size:, :] UpperCAmelCase_ = in_proj_bias[-hidden_size:] def lowerCAmelCase_ ( ) -> Dict: '''simple docstring''' UpperCAmelCase_ = "http://images.cocodataset.org/val2017/000000039769.jpg" UpperCAmelCase_ = Image.open(requests.get(snake_case_ , stream=snake_case_ ).raw ) return im @torch.no_grad() def lowerCAmelCase_ ( snake_case_ : List[Any] , snake_case_ : str , snake_case_ : str ) -> int: '''simple docstring''' UpperCAmelCase_ = get_deta_config(snake_case_ ) # load original state dict if model_name == "deta-swin-large": UpperCAmelCase_ = hf_hub_download(repo_id="nielsr/deta-checkpoints" , filename="adet_swin_ft.pth" ) elif model_name == "deta-swin-large-o365": UpperCAmelCase_ = hf_hub_download(repo_id="jozhang97/deta-swin-l-o365" , filename="deta_swin_pt_o365.pth" ) else: raise ValueError(f"""Model name {model_name} not supported""" ) UpperCAmelCase_ = torch.load(snake_case_ , map_location="cpu" )["model"] # original state dict for name, param in state_dict.items(): print(snake_case_ , param.shape ) # rename keys UpperCAmelCase_ = create_rename_keys(snake_case_ ) for src, dest in rename_keys: rename_key(snake_case_ , snake_case_ , snake_case_ ) read_in_swin_q_k_v(snake_case_ , config.backbone_config ) read_in_decoder_q_k_v(snake_case_ , snake_case_ ) # fix some prefixes for key in state_dict.copy().keys(): if "transformer.decoder.class_embed" in key or "transformer.decoder.bbox_embed" in key: UpperCAmelCase_ = state_dict.pop(snake_case_ ) UpperCAmelCase_ = val if "input_proj" in key: UpperCAmelCase_ = state_dict.pop(snake_case_ ) UpperCAmelCase_ = val if "level_embed" in key or "pos_trans" in key or "pix_trans" in key or "enc_output" in key: UpperCAmelCase_ = state_dict.pop(snake_case_ ) UpperCAmelCase_ = val # finally, create HuggingFace model and load state dict UpperCAmelCase_ = DetaForObjectDetection(snake_case_ ) model.load_state_dict(snake_case_ ) model.eval() UpperCAmelCase_ = "cuda" if torch.cuda.is_available() else "cpu" model.to(snake_case_ ) # load image processor UpperCAmelCase_ = DetaImageProcessor(format="coco_detection" ) # verify our conversion on image UpperCAmelCase_ = prepare_img() UpperCAmelCase_ = processor(images=snake_case_ , return_tensors="pt" ) UpperCAmelCase_ = encoding["pixel_values"] UpperCAmelCase_ = model(pixel_values.to(snake_case_ ) ) # verify logits print("Logits:" , outputs.logits[0, :3, :3] ) print("Boxes:" , outputs.pred_boxes[0, :3, :3] ) if model_name == "deta-swin-large": UpperCAmelCase_ = torch.tensor( [[-7.6308, -2.8485, -5.3737], [-7.2037, -4.5505, -4.8027], [-7.2943, -4.2611, -4.6617]] ) UpperCAmelCase_ = torch.tensor([[0.4987, 0.4969, 0.9999], [0.2549, 0.5498, 0.4805], [0.5498, 0.2757, 0.0569]] ) elif model_name == "deta-swin-large-o365": UpperCAmelCase_ = torch.tensor( [[-8.0122, -3.5720, -4.9717], [-8.1547, -3.6886, -4.6389], [-7.6610, -3.6194, -5.0134]] ) UpperCAmelCase_ = torch.tensor([[0.2523, 0.5549, 0.4881], [0.7715, 0.4149, 0.4601], [0.5503, 0.2753, 0.0575]] ) assert torch.allclose(outputs.logits[0, :3, :3] , expected_logits.to(snake_case_ ) , atol=1E-4 ) assert torch.allclose(outputs.pred_boxes[0, :3, :3] , expected_boxes.to(snake_case_ ) , atol=1E-4 ) print("Everything ok!" ) if pytorch_dump_folder_path: # Save model and processor logger.info(f"""Saving PyTorch model and processor to {pytorch_dump_folder_path}...""" ) Path(snake_case_ ).mkdir(exist_ok=snake_case_ ) model.save_pretrained(snake_case_ ) processor.save_pretrained(snake_case_ ) # Push to hub if push_to_hub: print("Pushing model and processor to hub..." ) model.push_to_hub(f"""jozhang97/{model_name}""" ) processor.push_to_hub(f"""jozhang97/{model_name}""" ) if __name__ == "__main__": SCREAMING_SNAKE_CASE_: Dict =argparse.ArgumentParser() parser.add_argument( '--model_name', type=str, default='deta-swin-large', choices=['deta-swin-large', 'deta-swin-large-o365'], help='Name of the model you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the folder to output PyTorch model.', ) parser.add_argument( '--push_to_hub', action='store_true', help='Whether or not to push the converted model to the 🤗 hub.' ) SCREAMING_SNAKE_CASE_: Optional[int] =parser.parse_args() convert_deta_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) SCREAMING_SNAKE_CASE_ = { """configuration_llama""": ["""LLAMA_PRETRAINED_CONFIG_ARCHIVE_MAP""", """LlamaConfig"""], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE_ = ["""LlamaTokenizer"""] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE_ = ["""LlamaTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE_ = [ """LlamaForCausalLM""", """LlamaModel""", """LlamaPreTrainedModel""", """LlamaForSequenceClassification""", ] if TYPE_CHECKING: from .configuration_llama import LLAMA_PRETRAINED_CONFIG_ARCHIVE_MAP, LlamaConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_llama import LlamaTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_llama_fast import LlamaTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_llama import LlamaForCausalLM, LlamaForSequenceClassification, LlamaModel, LlamaPreTrainedModel else: import sys SCREAMING_SNAKE_CASE_ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
296
0
'''simple docstring''' import torch import torch.nn as nn from transformers import CLIPConfig, CLIPVisionModel, PreTrainedModel from ...utils import logging lowerCamelCase : int = logging.get_logger(__name__) def _SCREAMING_SNAKE_CASE (A , A ) -> Optional[int]: """simple docstring""" lowercase__ = nn.functional.normalize(A ) lowercase__ = nn.functional.normalize(A ) return torch.mm(A , normalized_text_embeds.t() ) class __lowerCAmelCase (lowercase_ ): '''simple docstring''' lowerCAmelCase__ : Any = CLIPConfig lowerCAmelCase__ : Union[str, Any] = ["""CLIPEncoderLayer"""] def __init__(self : List[str] , UpperCamelCase : CLIPConfig ): '''simple docstring''' super().__init__(UpperCamelCase ) lowercase__ = CLIPVisionModel(config.vision_config ) lowercase__ = nn.Linear(config.vision_config.hidden_size , config.projection_dim , bias=UpperCamelCase ) lowercase__ = nn.Parameter(torch.ones(17 , config.projection_dim ) , requires_grad=UpperCamelCase ) lowercase__ = nn.Parameter(torch.ones(3 , config.projection_dim ) , requires_grad=UpperCamelCase ) lowercase__ = nn.Parameter(torch.ones(17 ) , requires_grad=UpperCamelCase ) lowercase__ = nn.Parameter(torch.ones(3 ) , requires_grad=UpperCamelCase ) @torch.no_grad() def UpperCamelCase__ (self : Union[str, Any] , UpperCamelCase : Dict , UpperCamelCase : int ): '''simple docstring''' lowercase__ = self.vision_model(UpperCamelCase )[1] # pooled_output lowercase__ = self.visual_projection(UpperCamelCase ) # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16 lowercase__ = cosine_distance(UpperCamelCase , self.special_care_embeds ).cpu().float().numpy() lowercase__ = cosine_distance(UpperCamelCase , self.concept_embeds ).cpu().float().numpy() lowercase__ = [] lowercase__ = image_embeds.shape[0] for i in range(UpperCamelCase ): lowercase__ = {'''special_scores''': {}, '''special_care''': [], '''concept_scores''': {}, '''bad_concepts''': []} # increase this value to create a stronger `nfsw` filter # at the cost of increasing the possibility of filtering benign images lowercase__ = 0.0 for concept_idx in range(len(special_cos_dist[0] ) ): lowercase__ = special_cos_dist[i][concept_idx] lowercase__ = self.special_care_embeds_weights[concept_idx].item() lowercase__ = round(concept_cos - concept_threshold + adjustment , 3 ) if result_img["special_scores"][concept_idx] > 0: result_img["special_care"].append({concept_idx, result_img['''special_scores'''][concept_idx]} ) lowercase__ = 0.01 for concept_idx in range(len(cos_dist[0] ) ): lowercase__ = cos_dist[i][concept_idx] lowercase__ = self.concept_embeds_weights[concept_idx].item() lowercase__ = round(concept_cos - concept_threshold + adjustment , 3 ) if result_img["concept_scores"][concept_idx] > 0: result_img["bad_concepts"].append(UpperCamelCase ) result.append(UpperCamelCase ) lowercase__ = [len(res['''bad_concepts'''] ) > 0 for res in result] return images, has_nsfw_concepts @torch.no_grad() def UpperCamelCase__ (self : Tuple , UpperCamelCase : torch.FloatTensor , UpperCamelCase : torch.FloatTensor ): '''simple docstring''' lowercase__ = self.vision_model(UpperCamelCase )[1] # pooled_output lowercase__ = self.visual_projection(UpperCamelCase ) lowercase__ = cosine_distance(UpperCamelCase , self.special_care_embeds ) lowercase__ = cosine_distance(UpperCamelCase , self.concept_embeds ) # increase this value to create a stronger `nsfw` filter # at the cost of increasing the possibility of filtering benign images lowercase__ = 0.0 lowercase__ = special_cos_dist - self.special_care_embeds_weights + adjustment # special_scores = special_scores.round(decimals=3) lowercase__ = torch.any(special_scores > 0 , dim=1 ) lowercase__ = special_care * 0.01 lowercase__ = special_adjustment.unsqueeze(1 ).expand(-1 , cos_dist.shape[1] ) lowercase__ = (cos_dist - self.concept_embeds_weights) + special_adjustment # concept_scores = concept_scores.round(decimals=3) lowercase__ = torch.any(concept_scores > 0 , dim=1 ) return images, has_nsfw_concepts
2
from pathlib import Path import fire def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> List[str]: '''simple docstring''' SCREAMING_SNAKE_CASE = Path(_SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE = Path(_SCREAMING_SNAKE_CASE ) dest_dir.mkdir(exist_ok=_SCREAMING_SNAKE_CASE ) for path in src_dir.iterdir(): SCREAMING_SNAKE_CASE = [x.rstrip() for x in list(path.open().readlines() )][:n] SCREAMING_SNAKE_CASE = dest_dir.joinpath(path.name ) print(_SCREAMING_SNAKE_CASE ) dest_path.open("""w""" ).write("""\n""".join(_SCREAMING_SNAKE_CASE ) ) if __name__ == "__main__": fire.Fire(minify)
296
0
'''simple docstring''' from ..utils import DummyObject, requires_backends class A ( metaclass=__snake_case ): __magic_name__ = ['''flax'''] def __init__( self , *SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) -> Any: """simple docstring""" requires_backends(self , ['''flax'''] ) @classmethod def __lowerCAmelCase ( cls , *SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) -> Tuple: """simple docstring""" requires_backends(cls , ['''flax'''] ) @classmethod def __lowerCAmelCase ( cls , *SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) -> Dict: """simple docstring""" requires_backends(cls , ['''flax'''] ) class A ( metaclass=__snake_case ): __magic_name__ = ['''flax'''] def __init__( self , *SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) -> Optional[int]: """simple docstring""" requires_backends(self , ['''flax'''] ) @classmethod def __lowerCAmelCase ( cls , *SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) -> Any: """simple docstring""" requires_backends(cls , ['''flax'''] ) @classmethod def __lowerCAmelCase ( cls , *SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) -> List[Any]: """simple docstring""" requires_backends(cls , ['''flax'''] ) class A ( metaclass=__snake_case ): __magic_name__ = ['''flax'''] def __init__( self , *SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) -> Optional[int]: """simple docstring""" requires_backends(self , ['''flax'''] ) @classmethod def __lowerCAmelCase ( cls , *SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) -> Union[str, Any]: """simple docstring""" requires_backends(cls , ['''flax'''] ) @classmethod def __lowerCAmelCase ( cls , *SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) -> List[Any]: """simple docstring""" requires_backends(cls , ['''flax'''] ) class A ( metaclass=__snake_case ): __magic_name__ = ['''flax'''] def __init__( self , *SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) -> Optional[Any]: """simple docstring""" requires_backends(self , ['''flax'''] ) @classmethod def __lowerCAmelCase ( cls , *SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) -> List[str]: """simple docstring""" requires_backends(cls , ['''flax'''] ) @classmethod def __lowerCAmelCase ( cls , *SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) -> Tuple: """simple docstring""" requires_backends(cls , ['''flax'''] ) class A ( metaclass=__snake_case ): __magic_name__ = ['''flax'''] def __init__( self , *SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) -> Tuple: """simple docstring""" requires_backends(self , ['''flax'''] ) @classmethod def __lowerCAmelCase ( cls , *SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) -> Tuple: """simple docstring""" requires_backends(cls , ['''flax'''] ) @classmethod def __lowerCAmelCase ( cls , *SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) -> Optional[int]: """simple docstring""" requires_backends(cls , ['''flax'''] ) class A ( metaclass=__snake_case ): __magic_name__ = ['''flax'''] def __init__( self , *SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) -> Optional[Any]: """simple docstring""" requires_backends(self , ['''flax'''] ) @classmethod def __lowerCAmelCase ( cls , *SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) -> Any: """simple docstring""" requires_backends(cls , ['''flax'''] ) @classmethod def __lowerCAmelCase ( cls , *SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) -> Optional[int]: """simple docstring""" requires_backends(cls , ['''flax'''] ) class A ( metaclass=__snake_case ): __magic_name__ = ['''flax'''] def __init__( self , *SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) -> Optional[int]: """simple docstring""" requires_backends(self , ['''flax'''] ) @classmethod def __lowerCAmelCase ( cls , *SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) -> Union[str, Any]: """simple docstring""" requires_backends(cls , ['''flax'''] ) @classmethod def __lowerCAmelCase ( cls , *SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) -> List[Any]: """simple docstring""" requires_backends(cls , ['''flax'''] ) class A ( metaclass=__snake_case ): __magic_name__ = ['''flax'''] def __init__( self , *SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) -> int: """simple docstring""" requires_backends(self , ['''flax'''] ) @classmethod def __lowerCAmelCase ( cls , *SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) -> List[Any]: """simple docstring""" requires_backends(cls , ['''flax'''] ) @classmethod def __lowerCAmelCase ( cls , *SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) -> str: """simple docstring""" requires_backends(cls , ['''flax'''] ) class A ( metaclass=__snake_case ): __magic_name__ = ['''flax'''] def __init__( self , *SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) -> Optional[int]: """simple docstring""" requires_backends(self , ['''flax'''] ) @classmethod def __lowerCAmelCase ( cls , *SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) -> List[Any]: """simple docstring""" requires_backends(cls , ['''flax'''] ) @classmethod def __lowerCAmelCase ( cls , *SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) -> Tuple: """simple docstring""" requires_backends(cls , ['''flax'''] ) class A ( metaclass=__snake_case ): __magic_name__ = ['''flax'''] def __init__( self , *SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) -> Optional[int]: """simple docstring""" requires_backends(self , ['''flax'''] ) @classmethod def __lowerCAmelCase ( cls , *SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) -> str: """simple docstring""" requires_backends(cls , ['''flax'''] ) @classmethod def __lowerCAmelCase ( cls , *SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) -> str: """simple docstring""" requires_backends(cls , ['''flax'''] ) class A ( metaclass=__snake_case ): __magic_name__ = ['''flax'''] def __init__( self , *SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) -> Tuple: """simple docstring""" requires_backends(self , ['''flax'''] ) @classmethod def __lowerCAmelCase ( cls , *SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) -> Dict: """simple docstring""" requires_backends(cls , ['''flax'''] ) @classmethod def __lowerCAmelCase ( cls , *SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) -> List[str]: """simple docstring""" requires_backends(cls , ['''flax'''] ) class A ( metaclass=__snake_case ): __magic_name__ = ['''flax'''] def __init__( self , *SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) -> Tuple: """simple docstring""" requires_backends(self , ['''flax'''] ) @classmethod def __lowerCAmelCase ( cls , *SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) -> Optional[Any]: """simple docstring""" requires_backends(cls , ['''flax'''] ) @classmethod def __lowerCAmelCase ( cls , *SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) -> int: """simple docstring""" requires_backends(cls , ['''flax'''] ) class A ( metaclass=__snake_case ): __magic_name__ = ['''flax'''] def __init__( self , *SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) -> Optional[int]: """simple docstring""" requires_backends(self , ['''flax'''] ) @classmethod def __lowerCAmelCase ( cls , *SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) -> Union[str, Any]: """simple docstring""" requires_backends(cls , ['''flax'''] ) @classmethod def __lowerCAmelCase ( cls , *SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) -> Any: """simple docstring""" requires_backends(cls , ['''flax'''] )
3
import importlib import json import os import sys import tempfile import unittest from pathlib import Path import transformers import transformers.models.auto from transformers.models.auto.configuration_auto import CONFIG_MAPPING, AutoConfig from transformers.models.bert.configuration_bert import BertConfig from transformers.models.roberta.configuration_roberta import RobertaConfig from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, get_tests_dir sys.path.append(str(Path(__file__).parent.parent.parent.parent / """utils""")) from test_module.custom_configuration import CustomConfig # noqa E402 SCREAMING_SNAKE_CASE_ = get_tests_dir("""fixtures/dummy-config.json""") class UpperCamelCase__ ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ) -> Optional[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE = 0 def SCREAMING_SNAKE_CASE__ ( self : Any ) -> str: '''simple docstring''' self.assertIsNotNone(transformers.models.auto.__spec__ ) self.assertIsNotNone(importlib.util.find_spec("""transformers.models.auto""" ) ) def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ) -> List[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained("""bert-base-uncased""" ) self.assertIsInstance(lowerCamelCase__ ,lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( self : int ) -> Optional[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained(lowerCamelCase__ ) self.assertIsInstance(lowerCamelCase__ ,lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ) -> List[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained(lowerCamelCase__ ) self.assertIsInstance(lowerCamelCase__ ,lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( self : Tuple ) -> Optional[int]: '''simple docstring''' SCREAMING_SNAKE_CASE = AutoConfig.for_model("""roberta""" ) self.assertIsInstance(lowerCamelCase__ ,lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( self : int ) -> int: '''simple docstring''' with tempfile.TemporaryDirectory() as tmp_dir: # This model name contains bert and roberta, but roberta ends up being picked. SCREAMING_SNAKE_CASE = os.path.join(lowerCamelCase__ ,"""fake-roberta""" ) os.makedirs(lowerCamelCase__ ,exist_ok=lowerCamelCase__ ) with open(os.path.join(lowerCamelCase__ ,"""config.json""" ) ,"""w""" ) as f: f.write(json.dumps({} ) ) SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained(lowerCamelCase__ ) self.assertEqual(type(lowerCamelCase__ ) ,lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( self : Dict ) -> str: '''simple docstring''' try: AutoConfig.register("""custom""" ,lowerCamelCase__ ) # Wrong model type will raise an error with self.assertRaises(lowerCamelCase__ ): AutoConfig.register("""model""" ,lowerCamelCase__ ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(lowerCamelCase__ ): AutoConfig.register("""bert""" ,lowerCamelCase__ ) # Now that the config is registered, it can be used as any other config with the auto-API SCREAMING_SNAKE_CASE = CustomConfig() with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained(lowerCamelCase__ ) self.assertIsInstance(lowerCamelCase__ ,lowerCamelCase__ ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] def SCREAMING_SNAKE_CASE__ ( self : str ) -> Dict: '''simple docstring''' with self.assertRaisesRegex( lowerCamelCase__ ,"""bert-base is not a local folder and is not a valid model identifier""" ): SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained("""bert-base""" ) def SCREAMING_SNAKE_CASE__ ( self : Dict ) -> str: '''simple docstring''' with self.assertRaisesRegex( lowerCamelCase__ ,R"""aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)""" ): SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained(lowerCamelCase__ ,revision="""aaaaaa""" ) def SCREAMING_SNAKE_CASE__ ( self : Tuple ) -> List[Any]: '''simple docstring''' with self.assertRaisesRegex( lowerCamelCase__ ,"""hf-internal-testing/no-config-test-repo does not appear to have a file named config.json.""" ,): SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained("""hf-internal-testing/no-config-test-repo""" ) def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ) -> Union[str, Any]: '''simple docstring''' with self.assertRaises(lowerCamelCase__ ): SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained("""hf-internal-testing/test_dynamic_model""" ) # If remote code is disabled, we can't load this config. with self.assertRaises(lowerCamelCase__ ): SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained("""hf-internal-testing/test_dynamic_model""" ,trust_remote_code=lowerCamelCase__ ) SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained("""hf-internal-testing/test_dynamic_model""" ,trust_remote_code=lowerCamelCase__ ) self.assertEqual(config.__class__.__name__ ,"""NewModelConfig""" ) # Test config can be reloaded. with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained(lowerCamelCase__ ,trust_remote_code=lowerCamelCase__ ) self.assertEqual(reloaded_config.__class__.__name__ ,"""NewModelConfig""" ) def SCREAMING_SNAKE_CASE__ ( self : Dict ) -> Union[str, Any]: '''simple docstring''' class UpperCamelCase__ ( lowerCAmelCase_ ): '''simple docstring''' __snake_case : Union[str, Any] = "new-model" try: AutoConfig.register("""new-model""" ,lowerCamelCase__ ) # If remote code is not set, the default is to use local SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained("""hf-internal-testing/test_dynamic_model""" ) self.assertEqual(config.__class__.__name__ ,"""NewModelConfigLocal""" ) # If remote code is disabled, we load the local one. SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained("""hf-internal-testing/test_dynamic_model""" ,trust_remote_code=lowerCamelCase__ ) self.assertEqual(config.__class__.__name__ ,"""NewModelConfigLocal""" ) # If remote is enabled, we load from the Hub SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained("""hf-internal-testing/test_dynamic_model""" ,trust_remote_code=lowerCamelCase__ ) self.assertEqual(config.__class__.__name__ ,"""NewModelConfig""" ) finally: if "new-model" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["new-model"]
296
0
'''simple docstring''' from math import factorial def a_ ( lowerCamelCase : int = 100 ): return sum(int(lowerCamelCase ) for x in str(factorial(lowerCamelCase ) ) ) if __name__ == "__main__": print(solution(int(input("""Enter the Number: """).strip())))
4
import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging SCREAMING_SNAKE_CASE_ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE_ = { """microsoft/git-base""": """https://huggingface.co/microsoft/git-base/resolve/main/config.json""", } class UpperCamelCase__ ( lowerCAmelCase_ ): '''simple docstring''' __snake_case : Dict = "git_vision_model" def __init__( self : List[Any] ,lowerCamelCase__ : Dict=768 ,lowerCamelCase__ : Union[str, Any]=3072 ,lowerCamelCase__ : Optional[int]=12 ,lowerCamelCase__ : Tuple=12 ,lowerCamelCase__ : Tuple=3 ,lowerCamelCase__ : Optional[Any]=224 ,lowerCamelCase__ : Union[str, Any]=16 ,lowerCamelCase__ : List[Any]="quick_gelu" ,lowerCamelCase__ : Optional[Any]=1e-5 ,lowerCamelCase__ : str=0.0 ,lowerCamelCase__ : Optional[int]=0.02 ,**lowerCamelCase__ : Union[str, Any] ,) -> Optional[int]: '''simple docstring''' super().__init__(**lowerCamelCase__ ) SCREAMING_SNAKE_CASE = hidden_size SCREAMING_SNAKE_CASE = intermediate_size SCREAMING_SNAKE_CASE = num_hidden_layers SCREAMING_SNAKE_CASE = num_attention_heads SCREAMING_SNAKE_CASE = num_channels SCREAMING_SNAKE_CASE = patch_size SCREAMING_SNAKE_CASE = image_size SCREAMING_SNAKE_CASE = initializer_range SCREAMING_SNAKE_CASE = attention_dropout SCREAMING_SNAKE_CASE = layer_norm_eps SCREAMING_SNAKE_CASE = hidden_act @classmethod def SCREAMING_SNAKE_CASE__ ( cls : Tuple ,lowerCamelCase__ : Union[str, os.PathLike] ,**lowerCamelCase__ : int ) -> "PretrainedConfig": '''simple docstring''' cls._set_token_in_kwargs(lowerCamelCase__ ) SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE = cls.get_config_dict(lowerCamelCase__ ,**lowerCamelCase__ ) # get the vision config dict if we are loading from GITConfig if config_dict.get("""model_type""" ) == "git": SCREAMING_SNAKE_CASE = config_dict["""vision_config"""] if "model_type" in config_dict and hasattr(cls ,"""model_type""" ) and config_dict["model_type"] != cls.model_type: logger.warning( F"""You are using a model of type {config_dict['model_type']} to instantiate a model of type """ F"""{cls.model_type}. This is not supported for all configurations of models and can yield errors.""" ) return cls.from_dict(lowerCamelCase__ ,**lowerCamelCase__ ) class UpperCamelCase__ ( lowerCAmelCase_ ): '''simple docstring''' __snake_case : Dict = "git" def __init__( self : Optional[int] ,lowerCamelCase__ : int=None ,lowerCamelCase__ : str=30522 ,lowerCamelCase__ : Tuple=768 ,lowerCamelCase__ : Union[str, Any]=6 ,lowerCamelCase__ : str=12 ,lowerCamelCase__ : List[str]=3072 ,lowerCamelCase__ : Dict="gelu" ,lowerCamelCase__ : Tuple=0.1 ,lowerCamelCase__ : Any=0.1 ,lowerCamelCase__ : List[str]=1024 ,lowerCamelCase__ : List[str]=0.02 ,lowerCamelCase__ : str=1e-1_2 ,lowerCamelCase__ : Optional[int]=0 ,lowerCamelCase__ : Optional[int]="absolute" ,lowerCamelCase__ : Optional[Any]=True ,lowerCamelCase__ : str=False ,lowerCamelCase__ : int=101 ,lowerCamelCase__ : int=102 ,lowerCamelCase__ : Dict=None ,**lowerCamelCase__ : List[Any] ,) -> Optional[Any]: '''simple docstring''' super().__init__(bos_token_id=lowerCamelCase__ ,eos_token_id=lowerCamelCase__ ,pad_token_id=lowerCamelCase__ ,**lowerCamelCase__ ) if vision_config is None: SCREAMING_SNAKE_CASE = {} logger.info("""vision_config is None. initializing the GitVisionConfig with default values.""" ) SCREAMING_SNAKE_CASE = GitVisionConfig(**lowerCamelCase__ ) SCREAMING_SNAKE_CASE = vocab_size SCREAMING_SNAKE_CASE = hidden_size SCREAMING_SNAKE_CASE = num_hidden_layers SCREAMING_SNAKE_CASE = num_attention_heads SCREAMING_SNAKE_CASE = hidden_act SCREAMING_SNAKE_CASE = intermediate_size SCREAMING_SNAKE_CASE = hidden_dropout_prob SCREAMING_SNAKE_CASE = attention_probs_dropout_prob SCREAMING_SNAKE_CASE = max_position_embeddings SCREAMING_SNAKE_CASE = initializer_range SCREAMING_SNAKE_CASE = layer_norm_eps SCREAMING_SNAKE_CASE = position_embedding_type SCREAMING_SNAKE_CASE = use_cache SCREAMING_SNAKE_CASE = tie_word_embeddings SCREAMING_SNAKE_CASE = num_image_with_embedding SCREAMING_SNAKE_CASE = bos_token_id SCREAMING_SNAKE_CASE = eos_token_id def SCREAMING_SNAKE_CASE__ ( self : Dict ) -> Optional[int]: '''simple docstring''' SCREAMING_SNAKE_CASE = copy.deepcopy(self.__dict__ ) SCREAMING_SNAKE_CASE = self.vision_config.to_dict() SCREAMING_SNAKE_CASE = self.__class__.model_type return output
296
0
import argparse import json import torch from diffusers import DDPMScheduler, LDMPipeline, UNetaDModel, VQModel def UpperCAmelCase_ ( __snake_case , __snake_case=1 ) -> Any: """simple docstring""" if n_shave_prefix_segments >= 0: return ".".join(path.split('''.''' )[n_shave_prefix_segments:] ) else: return ".".join(path.split('''.''' )[:n_shave_prefix_segments] ) def UpperCAmelCase_ ( __snake_case , __snake_case=0 ) -> str: """simple docstring""" _lowercase =[] for old_item in old_list: _lowercase =old_item.replace('''in_layers.0''' , '''norm1''' ) _lowercase =new_item.replace('''in_layers.2''' , '''conv1''' ) _lowercase =new_item.replace('''out_layers.0''' , '''norm2''' ) _lowercase =new_item.replace('''out_layers.3''' , '''conv2''' ) _lowercase =new_item.replace('''emb_layers.1''' , '''time_emb_proj''' ) _lowercase =new_item.replace('''skip_connection''' , '''conv_shortcut''' ) _lowercase =shave_segments(__snake_case , n_shave_prefix_segments=__snake_case ) mapping.append({'''old''': old_item, '''new''': new_item} ) return mapping def UpperCAmelCase_ ( __snake_case , __snake_case=0 ) -> Tuple: """simple docstring""" _lowercase =[] for old_item in old_list: _lowercase =old_item _lowercase =new_item.replace('''norm.weight''' , '''group_norm.weight''' ) _lowercase =new_item.replace('''norm.bias''' , '''group_norm.bias''' ) _lowercase =new_item.replace('''proj_out.weight''' , '''proj_attn.weight''' ) _lowercase =new_item.replace('''proj_out.bias''' , '''proj_attn.bias''' ) _lowercase =shave_segments(__snake_case , n_shave_prefix_segments=__snake_case ) mapping.append({'''old''': old_item, '''new''': new_item} ) return mapping def UpperCAmelCase_ ( __snake_case , __snake_case , __snake_case , __snake_case=None , __snake_case=None , __snake_case=None ) -> Any: """simple docstring""" assert isinstance(__snake_case , __snake_case ), "Paths should be a list of dicts containing 'old' and 'new' keys." # Splits the attention layers into three variables. if attention_paths_to_split is not None: for path, path_map in attention_paths_to_split.items(): _lowercase =old_checkpoint[path] _lowercase =old_tensor.shape[0] // 3 _lowercase =(-1, channels) if len(old_tensor.shape ) == 3 else (-1) _lowercase =old_tensor.shape[0] // config['''num_head_channels'''] // 3 _lowercase =old_tensor.reshape((num_heads, 3 * channels // num_heads) + old_tensor.shape[1:] ) _lowercase , _lowercase , _lowercase =old_tensor.split(channels // num_heads , dim=1 ) _lowercase =query.reshape(__snake_case ) _lowercase =key.reshape(__snake_case ) _lowercase =value.reshape(__snake_case ) for path in paths: _lowercase =path['''new'''] # These have already been assigned if attention_paths_to_split is not None and new_path in attention_paths_to_split: continue # Global renaming happens here _lowercase =new_path.replace('''middle_block.0''' , '''mid_block.resnets.0''' ) _lowercase =new_path.replace('''middle_block.1''' , '''mid_block.attentions.0''' ) _lowercase =new_path.replace('''middle_block.2''' , '''mid_block.resnets.1''' ) if additional_replacements is not None: for replacement in additional_replacements: _lowercase =new_path.replace(replacement['''old'''] , replacement['''new'''] ) # proj_attn.weight has to be converted from conv 1D to linear if "proj_attn.weight" in new_path: _lowercase =old_checkpoint[path['''old''']][:, :, 0] else: _lowercase =old_checkpoint[path['''old''']] def UpperCAmelCase_ ( __snake_case , __snake_case ) -> str: """simple docstring""" _lowercase ={} _lowercase =checkpoint['''time_embed.0.weight'''] _lowercase =checkpoint['''time_embed.0.bias'''] _lowercase =checkpoint['''time_embed.2.weight'''] _lowercase =checkpoint['''time_embed.2.bias'''] _lowercase =checkpoint['''input_blocks.0.0.weight'''] _lowercase =checkpoint['''input_blocks.0.0.bias'''] _lowercase =checkpoint['''out.0.weight'''] _lowercase =checkpoint['''out.0.bias'''] _lowercase =checkpoint['''out.2.weight'''] _lowercase =checkpoint['''out.2.bias'''] # Retrieves the keys for the input blocks only _lowercase =len({'''.'''.join(layer.split('''.''' )[:2] ) for layer in checkpoint if '''input_blocks''' in layer} ) _lowercase ={ layer_id: [key for key in checkpoint if F"input_blocks.{layer_id}" in key] for layer_id in range(__snake_case ) } # Retrieves the keys for the middle blocks only _lowercase =len({'''.'''.join(layer.split('''.''' )[:2] ) for layer in checkpoint if '''middle_block''' in layer} ) _lowercase ={ layer_id: [key for key in checkpoint if F"middle_block.{layer_id}" in key] for layer_id in range(__snake_case ) } # Retrieves the keys for the output blocks only _lowercase =len({'''.'''.join(layer.split('''.''' )[:2] ) for layer in checkpoint if '''output_blocks''' in layer} ) _lowercase ={ layer_id: [key for key in checkpoint if F"output_blocks.{layer_id}" in key] for layer_id in range(__snake_case ) } for i in range(1 , __snake_case ): _lowercase =(i - 1) // (config['''num_res_blocks'''] + 1) _lowercase =(i - 1) % (config['''num_res_blocks'''] + 1) _lowercase =[key for key in input_blocks[i] if F"input_blocks.{i}.0" in key] _lowercase =[key for key in input_blocks[i] if F"input_blocks.{i}.1" in key] if F"input_blocks.{i}.0.op.weight" in checkpoint: _lowercase =checkpoint[ F"input_blocks.{i}.0.op.weight" ] _lowercase =checkpoint[ F"input_blocks.{i}.0.op.bias" ] continue _lowercase =renew_resnet_paths(__snake_case ) _lowercase ={'''old''': F"input_blocks.{i}.0", '''new''': F"down_blocks.{block_id}.resnets.{layer_in_block_id}"} _lowercase ={'''old''': '''resnets.2.op''', '''new''': '''downsamplers.0.op'''} assign_to_checkpoint( __snake_case , __snake_case , __snake_case , additional_replacements=[meta_path, resnet_op] , config=__snake_case ) if len(__snake_case ): _lowercase =renew_attention_paths(__snake_case ) _lowercase ={ '''old''': F"input_blocks.{i}.1", '''new''': F"down_blocks.{block_id}.attentions.{layer_in_block_id}", } _lowercase ={ F"input_blocks.{i}.1.qkv.bias": { '''key''': F"down_blocks.{block_id}.attentions.{layer_in_block_id}.key.bias", '''query''': F"down_blocks.{block_id}.attentions.{layer_in_block_id}.query.bias", '''value''': F"down_blocks.{block_id}.attentions.{layer_in_block_id}.value.bias", }, F"input_blocks.{i}.1.qkv.weight": { '''key''': F"down_blocks.{block_id}.attentions.{layer_in_block_id}.key.weight", '''query''': F"down_blocks.{block_id}.attentions.{layer_in_block_id}.query.weight", '''value''': F"down_blocks.{block_id}.attentions.{layer_in_block_id}.value.weight", }, } assign_to_checkpoint( __snake_case , __snake_case , __snake_case , additional_replacements=[meta_path] , attention_paths_to_split=__snake_case , config=__snake_case , ) _lowercase =middle_blocks[0] _lowercase =middle_blocks[1] _lowercase =middle_blocks[2] _lowercase =renew_resnet_paths(__snake_case ) assign_to_checkpoint(__snake_case , __snake_case , __snake_case , config=__snake_case ) _lowercase =renew_resnet_paths(__snake_case ) assign_to_checkpoint(__snake_case , __snake_case , __snake_case , config=__snake_case ) _lowercase =renew_attention_paths(__snake_case ) _lowercase ={ '''middle_block.1.qkv.bias''': { '''key''': '''mid_block.attentions.0.key.bias''', '''query''': '''mid_block.attentions.0.query.bias''', '''value''': '''mid_block.attentions.0.value.bias''', }, '''middle_block.1.qkv.weight''': { '''key''': '''mid_block.attentions.0.key.weight''', '''query''': '''mid_block.attentions.0.query.weight''', '''value''': '''mid_block.attentions.0.value.weight''', }, } assign_to_checkpoint( __snake_case , __snake_case , __snake_case , attention_paths_to_split=__snake_case , config=__snake_case ) for i in range(__snake_case ): _lowercase =i // (config['''num_res_blocks'''] + 1) _lowercase =i % (config['''num_res_blocks'''] + 1) _lowercase =[shave_segments(__snake_case , 2 ) for name in output_blocks[i]] _lowercase ={} for layer in output_block_layers: _lowercase , _lowercase =layer.split('''.''' )[0], shave_segments(__snake_case , 1 ) if layer_id in output_block_list: output_block_list[layer_id].append(__snake_case ) else: _lowercase =[layer_name] if len(__snake_case ) > 1: _lowercase =[key for key in output_blocks[i] if F"output_blocks.{i}.0" in key] _lowercase =[key for key in output_blocks[i] if F"output_blocks.{i}.1" in key] _lowercase =renew_resnet_paths(__snake_case ) _lowercase =renew_resnet_paths(__snake_case ) _lowercase ={'''old''': F"output_blocks.{i}.0", '''new''': F"up_blocks.{block_id}.resnets.{layer_in_block_id}"} assign_to_checkpoint(__snake_case , __snake_case , __snake_case , additional_replacements=[meta_path] , config=__snake_case ) if ["conv.weight", "conv.bias"] in output_block_list.values(): _lowercase =list(output_block_list.values() ).index(['''conv.weight''', '''conv.bias'''] ) _lowercase =checkpoint[ F"output_blocks.{i}.{index}.conv.weight" ] _lowercase =checkpoint[ F"output_blocks.{i}.{index}.conv.bias" ] # Clear attentions as they have been attributed above. if len(__snake_case ) == 2: _lowercase =[] if len(__snake_case ): _lowercase =renew_attention_paths(__snake_case ) _lowercase ={ '''old''': F"output_blocks.{i}.1", '''new''': F"up_blocks.{block_id}.attentions.{layer_in_block_id}", } _lowercase ={ F"output_blocks.{i}.1.qkv.bias": { '''key''': F"up_blocks.{block_id}.attentions.{layer_in_block_id}.key.bias", '''query''': F"up_blocks.{block_id}.attentions.{layer_in_block_id}.query.bias", '''value''': F"up_blocks.{block_id}.attentions.{layer_in_block_id}.value.bias", }, F"output_blocks.{i}.1.qkv.weight": { '''key''': F"up_blocks.{block_id}.attentions.{layer_in_block_id}.key.weight", '''query''': F"up_blocks.{block_id}.attentions.{layer_in_block_id}.query.weight", '''value''': F"up_blocks.{block_id}.attentions.{layer_in_block_id}.value.weight", }, } assign_to_checkpoint( __snake_case , __snake_case , __snake_case , additional_replacements=[meta_path] , attention_paths_to_split=to_split if any('''qkv''' in key for key in attentions ) else None , config=__snake_case , ) else: _lowercase =renew_resnet_paths(__snake_case , n_shave_prefix_segments=1 ) for path in resnet_0_paths: _lowercase ='''.'''.join(['''output_blocks''', str(__snake_case ), path['''old''']] ) _lowercase ='''.'''.join(['''up_blocks''', str(__snake_case ), '''resnets''', str(__snake_case ), path['''new''']] ) _lowercase =checkpoint[old_path] return new_checkpoint if __name__ == "__main__": UpperCAmelCase__ = argparse.ArgumentParser() parser.add_argument( '''--checkpoint_path''', default=None, type=str, required=True, help='''Path to the checkpoint to convert.''' ) parser.add_argument( '''--config_file''', default=None, type=str, required=True, help='''The config json file corresponding to the architecture.''', ) parser.add_argument('''--dump_path''', default=None, type=str, required=True, help='''Path to the output model.''') UpperCAmelCase__ = parser.parse_args() UpperCAmelCase__ = torch.load(args.checkpoint_path) with open(args.config_file) as f: UpperCAmelCase__ = json.loads(f.read()) UpperCAmelCase__ = convert_ldm_checkpoint(checkpoint, config) if "ldm" in config: del config["ldm"] UpperCAmelCase__ = UNetaDModel(**config) model.load_state_dict(converted_checkpoint) try: UpperCAmelCase__ = DDPMScheduler.from_config('''/'''.join(args.checkpoint_path.split('''/''')[:-1])) UpperCAmelCase__ = VQModel.from_pretrained('''/'''.join(args.checkpoint_path.split('''/''')[:-1])) UpperCAmelCase__ = LDMPipeline(unet=model, scheduler=scheduler, vae=vqvae) pipe.save_pretrained(args.dump_path) except: # noqa: E722 model.save_pretrained(args.dump_path)
5
import itertools import os import random import tempfile import unittest import numpy as np from transformers import TvltFeatureExtractor, is_datasets_available from transformers.testing_utils import check_json_file_has_correct_format, require_torch, require_torchaudio from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin if is_torch_available(): import torch if is_datasets_available(): from datasets import load_dataset SCREAMING_SNAKE_CASE_ = random.Random() def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=1.0 , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None ) -> Tuple: '''simple docstring''' if rng is None: SCREAMING_SNAKE_CASE = global_rng SCREAMING_SNAKE_CASE = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values class UpperCamelCase__ ( unittest.TestCase ): '''simple docstring''' def __init__( self : List[Any] ,lowerCamelCase__ : str ,lowerCamelCase__ : Optional[int]=7 ,lowerCamelCase__ : Optional[Any]=400 ,lowerCamelCase__ : List[str]=2000 ,lowerCamelCase__ : List[str]=2048 ,lowerCamelCase__ : Any=128 ,lowerCamelCase__ : List[str]=1 ,lowerCamelCase__ : str=512 ,lowerCamelCase__ : Optional[Any]=30 ,lowerCamelCase__ : Tuple=44100 ,) -> Tuple: '''simple docstring''' SCREAMING_SNAKE_CASE = parent SCREAMING_SNAKE_CASE = batch_size SCREAMING_SNAKE_CASE = min_seq_length SCREAMING_SNAKE_CASE = max_seq_length SCREAMING_SNAKE_CASE = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) SCREAMING_SNAKE_CASE = spectrogram_length SCREAMING_SNAKE_CASE = feature_size SCREAMING_SNAKE_CASE = num_audio_channels SCREAMING_SNAKE_CASE = hop_length SCREAMING_SNAKE_CASE = chunk_length SCREAMING_SNAKE_CASE = sampling_rate def SCREAMING_SNAKE_CASE__ ( self : List[Any] ) -> Optional[int]: '''simple docstring''' return { "spectrogram_length": self.spectrogram_length, "feature_size": self.feature_size, "num_audio_channels": self.num_audio_channels, "hop_length": self.hop_length, "chunk_length": self.chunk_length, "sampling_rate": self.sampling_rate, } def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ,lowerCamelCase__ : Tuple=False ,lowerCamelCase__ : Union[str, Any]=False ) -> str: '''simple docstring''' def _flatten(lowerCamelCase__ : List[Any] ): return list(itertools.chain(*lowerCamelCase__ ) ) if equal_length: SCREAMING_SNAKE_CASE = [floats_list((self.max_seq_length, self.feature_size) ) for _ in range(self.batch_size )] else: # make sure that inputs increase in size SCREAMING_SNAKE_CASE = [ floats_list((x, self.feature_size) ) for x in range(self.min_seq_length ,self.max_seq_length ,self.seq_length_diff ) ] if numpify: SCREAMING_SNAKE_CASE = [np.asarray(lowerCamelCase__ ) for x in speech_inputs] return speech_inputs @require_torch @require_torchaudio class UpperCamelCase__ ( lowerCAmelCase_ , unittest.TestCase ): '''simple docstring''' __snake_case : List[Any] = TvltFeatureExtractor def SCREAMING_SNAKE_CASE__ ( self : str ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE = TvltFeatureExtractionTester(self ) def SCREAMING_SNAKE_CASE__ ( self : List[Any] ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_dict ) self.assertTrue(hasattr(lowerCamelCase__ ,"""spectrogram_length""" ) ) self.assertTrue(hasattr(lowerCamelCase__ ,"""feature_size""" ) ) self.assertTrue(hasattr(lowerCamelCase__ ,"""num_audio_channels""" ) ) self.assertTrue(hasattr(lowerCamelCase__ ,"""hop_length""" ) ) self.assertTrue(hasattr(lowerCamelCase__ ,"""chunk_length""" ) ) self.assertTrue(hasattr(lowerCamelCase__ ,"""sampling_rate""" ) ) def SCREAMING_SNAKE_CASE__ ( self : str ) -> Union[str, Any]: '''simple docstring''' SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: SCREAMING_SNAKE_CASE = feat_extract_first.save_pretrained(lowerCamelCase__ )[0] check_json_file_has_correct_format(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = self.feature_extraction_class.from_pretrained(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = feat_extract_first.to_dict() SCREAMING_SNAKE_CASE = feat_extract_second.to_dict() SCREAMING_SNAKE_CASE = dict_first.pop("""mel_filters""" ) SCREAMING_SNAKE_CASE = dict_second.pop("""mel_filters""" ) self.assertTrue(np.allclose(lowerCamelCase__ ,lowerCamelCase__ ) ) self.assertEqual(lowerCamelCase__ ,lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( self : Any ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: SCREAMING_SNAKE_CASE = os.path.join(lowerCamelCase__ ,"""feat_extract.json""" ) feat_extract_first.to_json_file(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = self.feature_extraction_class.from_json_file(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = feat_extract_first.to_dict() SCREAMING_SNAKE_CASE = feat_extract_second.to_dict() SCREAMING_SNAKE_CASE = dict_first.pop("""mel_filters""" ) SCREAMING_SNAKE_CASE = dict_second.pop("""mel_filters""" ) self.assertTrue(np.allclose(lowerCamelCase__ ,lowerCamelCase__ ) ) self.assertEqual(lowerCamelCase__ ,lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( self : str ) -> Optional[int]: '''simple docstring''' SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_dict ) # create three inputs of length 800, 1000, and 1200 SCREAMING_SNAKE_CASE = [floats_list((1, x) )[0] for x in range(800 ,1400 ,200 )] SCREAMING_SNAKE_CASE = [np.asarray(lowerCamelCase__ ) for speech_input in speech_inputs] # Test not batched input SCREAMING_SNAKE_CASE = feature_extractor(np_speech_inputs[0] ,return_tensors="""np""" ,sampling_rate=44100 ).audio_values self.assertTrue(encoded_audios.ndim == 4 ) self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size ) self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length ) self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels ) # Test batched SCREAMING_SNAKE_CASE = feature_extractor(lowerCamelCase__ ,return_tensors="""np""" ,sampling_rate=44100 ).audio_values self.assertTrue(encoded_audios.ndim == 4 ) self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size ) self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length ) self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels ) # Test audio masking SCREAMING_SNAKE_CASE = feature_extractor( lowerCamelCase__ ,return_tensors="""np""" ,sampling_rate=44100 ,mask_audio=lowerCamelCase__ ).audio_values self.assertTrue(encoded_audios.ndim == 4 ) self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size ) self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length ) self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels ) # Test 2-D numpy arrays are batched. SCREAMING_SNAKE_CASE = [floats_list((1, x) )[0] for x in (800, 800, 800)] SCREAMING_SNAKE_CASE = np.asarray(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = feature_extractor(lowerCamelCase__ ,return_tensors="""np""" ,sampling_rate=44100 ).audio_values self.assertTrue(encoded_audios.ndim == 4 ) self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size ) self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length ) self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels ) def SCREAMING_SNAKE_CASE__ ( self : Any ,lowerCamelCase__ : str ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE = load_dataset("""hf-internal-testing/librispeech_asr_dummy""" ,"""clean""" ,split="""validation""" ) # automatic decoding with librispeech SCREAMING_SNAKE_CASE = ds.sort("""id""" ).select(range(lowerCamelCase__ ) )[:num_samples]["""audio"""] return [x["array"] for x in speech_samples] def SCREAMING_SNAKE_CASE__ ( self : Tuple ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE = self._load_datasamples(1 ) SCREAMING_SNAKE_CASE = TvltFeatureExtractor() SCREAMING_SNAKE_CASE = feature_extractor(lowerCamelCase__ ,return_tensors="""pt""" ).audio_values self.assertEquals(audio_values.shape ,(1, 1, 192, 128) ) SCREAMING_SNAKE_CASE = torch.tensor([[-0.3032, -0.2708], [-0.4434, -0.4007]] ) self.assertTrue(torch.allclose(audio_values[0, 0, :2, :2] ,lowerCamelCase__ ,atol=1e-4 ) )
296
0
import copy from ...configuration_utils import PretrainedConfig from ...utils import logging A : Dict = logging.get_logger(__name__) class __A( a ): snake_case_ = '''encoder-decoder''' snake_case_ = True def __init__( self , **_snake_case ) -> str: '''simple docstring''' super().__init__(**_snake_case ) assert ( "encoder" in kwargs and "decoder" in kwargs ), "Config has to be initialized with encoder and decoder config" __a = kwargs.pop('''encoder''' ) __a = encoder_config.pop('''model_type''' ) __a = kwargs.pop('''decoder''' ) __a = decoder_config.pop('''model_type''' ) from ..auto.configuration_auto import AutoConfig __a = AutoConfig.for_model(_snake_case , **_snake_case ) __a = AutoConfig.for_model(_snake_case , **_snake_case ) __a = True @classmethod def SCREAMING_SNAKE_CASE_ ( cls , _snake_case , _snake_case , **_snake_case ) -> PretrainedConfig: '''simple docstring''' logger.info('''Set `config.is_decoder=True` and `config.add_cross_attention=True` for decoder_config''' ) __a = True __a = True return cls(encoder=encoder_config.to_dict() , decoder=decoder_config.to_dict() , **_snake_case ) def SCREAMING_SNAKE_CASE_ ( self ) -> Optional[Any]: '''simple docstring''' __a = copy.deepcopy(self.__dict__ ) __a = self.encoder.to_dict() __a = self.decoder.to_dict() __a = self.__class__.model_type return output
6
import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( MobileViTConfig, MobileViTForImageClassification, MobileViTForSemanticSegmentation, MobileViTImageProcessor, ) from transformers.utils import logging logging.set_verbosity_info() SCREAMING_SNAKE_CASE_ = logging.get_logger(__name__) def __lowercase ( _SCREAMING_SNAKE_CASE ) -> Optional[int]: '''simple docstring''' SCREAMING_SNAKE_CASE = MobileViTConfig() # size of the architecture if "mobilevit_s" in mobilevit_name: SCREAMING_SNAKE_CASE = [1_44, 1_92, 2_40] SCREAMING_SNAKE_CASE = [16, 32, 64, 96, 1_28, 1_60, 6_40] elif "mobilevit_xs" in mobilevit_name: SCREAMING_SNAKE_CASE = [96, 1_20, 1_44] SCREAMING_SNAKE_CASE = [16, 32, 48, 64, 80, 96, 3_84] elif "mobilevit_xxs" in mobilevit_name: SCREAMING_SNAKE_CASE = [64, 80, 96] SCREAMING_SNAKE_CASE = [16, 16, 24, 48, 64, 80, 3_20] SCREAMING_SNAKE_CASE = 0.05 SCREAMING_SNAKE_CASE = 2.0 if mobilevit_name.startswith("""deeplabv3_""" ): SCREAMING_SNAKE_CASE = 5_12 SCREAMING_SNAKE_CASE = 16 SCREAMING_SNAKE_CASE = 21 SCREAMING_SNAKE_CASE = """pascal-voc-id2label.json""" else: SCREAMING_SNAKE_CASE = 10_00 SCREAMING_SNAKE_CASE = """imagenet-1k-id2label.json""" SCREAMING_SNAKE_CASE = """huggingface/label-files""" SCREAMING_SNAKE_CASE = json.load(open(hf_hub_download(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , repo_type="""dataset""" ) , """r""" ) ) SCREAMING_SNAKE_CASE = {int(_SCREAMING_SNAKE_CASE ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE = idalabel SCREAMING_SNAKE_CASE = {v: k for k, v in idalabel.items()} return config def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=False ) -> str: '''simple docstring''' for i in range(1 , 6 ): if F"""layer_{i}.""" in name: SCREAMING_SNAKE_CASE = name.replace(F"""layer_{i}.""" , F"""encoder.layer.{i - 1}.""" ) if "conv_1." in name: SCREAMING_SNAKE_CASE = name.replace("""conv_1.""" , """conv_stem.""" ) if ".block." in name: SCREAMING_SNAKE_CASE = name.replace(""".block.""" , """.""" ) if "exp_1x1" in name: SCREAMING_SNAKE_CASE = name.replace("""exp_1x1""" , """expand_1x1""" ) if "red_1x1" in name: SCREAMING_SNAKE_CASE = name.replace("""red_1x1""" , """reduce_1x1""" ) if ".local_rep.conv_3x3." in name: SCREAMING_SNAKE_CASE = name.replace(""".local_rep.conv_3x3.""" , """.conv_kxk.""" ) if ".local_rep.conv_1x1." in name: SCREAMING_SNAKE_CASE = name.replace(""".local_rep.conv_1x1.""" , """.conv_1x1.""" ) if ".norm." in name: SCREAMING_SNAKE_CASE = name.replace(""".norm.""" , """.normalization.""" ) if ".conv." in name: SCREAMING_SNAKE_CASE = name.replace(""".conv.""" , """.convolution.""" ) if ".conv_proj." in name: SCREAMING_SNAKE_CASE = name.replace(""".conv_proj.""" , """.conv_projection.""" ) for i in range(0 , 2 ): for j in range(0 , 4 ): if F""".{i}.{j}.""" in name: SCREAMING_SNAKE_CASE = name.replace(F""".{i}.{j}.""" , F""".{i}.layer.{j}.""" ) for i in range(2 , 6 ): for j in range(0 , 4 ): if F""".{i}.{j}.""" in name: SCREAMING_SNAKE_CASE = name.replace(F""".{i}.{j}.""" , F""".{i}.""" ) if "expand_1x1" in name: SCREAMING_SNAKE_CASE = name.replace("""expand_1x1""" , """downsampling_layer.expand_1x1""" ) if "conv_3x3" in name: SCREAMING_SNAKE_CASE = name.replace("""conv_3x3""" , """downsampling_layer.conv_3x3""" ) if "reduce_1x1" in name: SCREAMING_SNAKE_CASE = name.replace("""reduce_1x1""" , """downsampling_layer.reduce_1x1""" ) for i in range(2 , 5 ): if F""".global_rep.{i}.weight""" in name: SCREAMING_SNAKE_CASE = name.replace(F""".global_rep.{i}.weight""" , """.layernorm.weight""" ) if F""".global_rep.{i}.bias""" in name: SCREAMING_SNAKE_CASE = name.replace(F""".global_rep.{i}.bias""" , """.layernorm.bias""" ) if ".global_rep." in name: SCREAMING_SNAKE_CASE = name.replace(""".global_rep.""" , """.transformer.""" ) if ".pre_norm_mha.0." in name: SCREAMING_SNAKE_CASE = name.replace(""".pre_norm_mha.0.""" , """.layernorm_before.""" ) if ".pre_norm_mha.1.out_proj." in name: SCREAMING_SNAKE_CASE = name.replace(""".pre_norm_mha.1.out_proj.""" , """.attention.output.dense.""" ) if ".pre_norm_ffn.0." in name: SCREAMING_SNAKE_CASE = name.replace(""".pre_norm_ffn.0.""" , """.layernorm_after.""" ) if ".pre_norm_ffn.1." in name: SCREAMING_SNAKE_CASE = name.replace(""".pre_norm_ffn.1.""" , """.intermediate.dense.""" ) if ".pre_norm_ffn.4." in name: SCREAMING_SNAKE_CASE = name.replace(""".pre_norm_ffn.4.""" , """.output.dense.""" ) if ".transformer." in name: SCREAMING_SNAKE_CASE = name.replace(""".transformer.""" , """.transformer.layer.""" ) if ".aspp_layer." in name: SCREAMING_SNAKE_CASE = name.replace(""".aspp_layer.""" , """.""" ) if ".aspp_pool." in name: SCREAMING_SNAKE_CASE = name.replace(""".aspp_pool.""" , """.""" ) if "seg_head." in name: SCREAMING_SNAKE_CASE = name.replace("""seg_head.""" , """segmentation_head.""" ) if "segmentation_head.classifier.classifier." in name: SCREAMING_SNAKE_CASE = name.replace("""segmentation_head.classifier.classifier.""" , """segmentation_head.classifier.""" ) if "classifier.fc." in name: SCREAMING_SNAKE_CASE = name.replace("""classifier.fc.""" , """classifier.""" ) elif (not base_model) and ("segmentation_head." not in name): SCREAMING_SNAKE_CASE = """mobilevit.""" + name return name def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=False ) -> Dict: '''simple docstring''' if base_model: SCREAMING_SNAKE_CASE = """""" else: SCREAMING_SNAKE_CASE = """mobilevit.""" for key in orig_state_dict.copy().keys(): SCREAMING_SNAKE_CASE = orig_state_dict.pop(_SCREAMING_SNAKE_CASE ) if key[:8] == "encoder.": SCREAMING_SNAKE_CASE = key[8:] if "qkv" in key: SCREAMING_SNAKE_CASE = key.split(""".""" ) SCREAMING_SNAKE_CASE = int(key_split[0][6:] ) - 1 SCREAMING_SNAKE_CASE = int(key_split[3] ) SCREAMING_SNAKE_CASE = model.get_submodule(F"""{model_prefix}encoder.layer.{layer_num}""" ) SCREAMING_SNAKE_CASE = layer.transformer.layer[transformer_num].attention.attention.all_head_size SCREAMING_SNAKE_CASE = ( F"""{model_prefix}encoder.layer.{layer_num}.transformer.layer.{transformer_num}.attention.attention.""" ) if "weight" in key: SCREAMING_SNAKE_CASE = val[:dim, :] SCREAMING_SNAKE_CASE = val[dim : dim * 2, :] SCREAMING_SNAKE_CASE = val[-dim:, :] else: SCREAMING_SNAKE_CASE = val[:dim] SCREAMING_SNAKE_CASE = val[dim : dim * 2] SCREAMING_SNAKE_CASE = val[-dim:] else: SCREAMING_SNAKE_CASE = val return orig_state_dict def __lowercase ( ) -> str: '''simple docstring''' SCREAMING_SNAKE_CASE = """http://images.cocodataset.org/val2017/000000039769.jpg""" SCREAMING_SNAKE_CASE = Image.open(requests.get(_SCREAMING_SNAKE_CASE , stream=_SCREAMING_SNAKE_CASE ).raw ) return im @torch.no_grad() def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=False ) -> str: '''simple docstring''' SCREAMING_SNAKE_CASE = get_mobilevit_config(_SCREAMING_SNAKE_CASE ) # load original state_dict SCREAMING_SNAKE_CASE = torch.load(_SCREAMING_SNAKE_CASE , map_location="""cpu""" ) # load 🤗 model if mobilevit_name.startswith("""deeplabv3_""" ): SCREAMING_SNAKE_CASE = MobileViTForSemanticSegmentation(_SCREAMING_SNAKE_CASE ).eval() else: SCREAMING_SNAKE_CASE = MobileViTForImageClassification(_SCREAMING_SNAKE_CASE ).eval() SCREAMING_SNAKE_CASE = convert_state_dict(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) model.load_state_dict(_SCREAMING_SNAKE_CASE ) # Check outputs on an image, prepared by MobileViTImageProcessor SCREAMING_SNAKE_CASE = MobileViTImageProcessor(crop_size=config.image_size , size=config.image_size + 32 ) SCREAMING_SNAKE_CASE = image_processor(images=prepare_img() , return_tensors="""pt""" ) SCREAMING_SNAKE_CASE = model(**_SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE = outputs.logits if mobilevit_name.startswith("""deeplabv3_""" ): assert logits.shape == (1, 21, 32, 32) if mobilevit_name == "deeplabv3_mobilevit_s": SCREAMING_SNAKE_CASE = torch.tensor( [ [[6.2_065, 6.1_292, 6.2_070], [6.1_079, 6.1_254, 6.1_747], [6.0_042, 6.1_071, 6.1_034]], [[-6.9_253, -6.8_653, -7.0_398], [-7.3_218, -7.3_983, -7.3_670], [-7.1_961, -7.2_482, -7.1_569]], [[-4.4_723, -4.4_348, -4.3_769], [-5.3_629, -5.4_632, -5.4_598], [-5.1_587, -5.3_402, -5.5_059]], ] ) elif mobilevit_name == "deeplabv3_mobilevit_xs": SCREAMING_SNAKE_CASE = torch.tensor( [ [[5.4_449, 5.5_733, 5.6_314], [5.1_815, 5.3_930, 5.5_963], [5.1_656, 5.4_333, 5.4_853]], [[-9.4_423, -9.7_766, -9.6_714], [-9.1_581, -9.5_720, -9.5_519], [-9.1_006, -9.6_458, -9.5_703]], [[-7.7_721, -7.3_716, -7.1_583], [-8.4_599, -8.0_624, -7.7_944], [-8.4_172, -7.8_366, -7.5_025]], ] ) elif mobilevit_name == "deeplabv3_mobilevit_xxs": SCREAMING_SNAKE_CASE = torch.tensor( [ [[6.9_811, 6.9_743, 7.3_123], [7.1_777, 7.1_931, 7.3_938], [7.5_633, 7.8_050, 7.8_901]], [[-10.5_536, -10.2_332, -10.2_924], [-10.2_336, -9.8_624, -9.5_964], [-10.8_840, -10.8_158, -10.6_659]], [[-3.4_938, -3.0_631, -2.8_620], [-3.4_205, -2.8_135, -2.6_875], [-3.4_179, -2.7_945, -2.8_750]], ] ) else: raise ValueError(F"""Unknown mobilevit_name: {mobilevit_name}""" ) assert torch.allclose(logits[0, :3, :3, :3] , _SCREAMING_SNAKE_CASE , atol=1E-4 ) else: assert logits.shape == (1, 10_00) if mobilevit_name == "mobilevit_s": SCREAMING_SNAKE_CASE = torch.tensor([-0.9_866, 0.2_392, -1.1_241] ) elif mobilevit_name == "mobilevit_xs": SCREAMING_SNAKE_CASE = torch.tensor([-2.4_761, -0.9_399, -1.9_587] ) elif mobilevit_name == "mobilevit_xxs": SCREAMING_SNAKE_CASE = torch.tensor([-1.9_364, -1.2_327, -0.4_653] ) else: raise ValueError(F"""Unknown mobilevit_name: {mobilevit_name}""" ) assert torch.allclose(logits[0, :3] , _SCREAMING_SNAKE_CASE , atol=1E-4 ) Path(_SCREAMING_SNAKE_CASE ).mkdir(exist_ok=_SCREAMING_SNAKE_CASE ) print(F"""Saving model {mobilevit_name} to {pytorch_dump_folder_path}""" ) model.save_pretrained(_SCREAMING_SNAKE_CASE ) print(F"""Saving image processor to {pytorch_dump_folder_path}""" ) image_processor.save_pretrained(_SCREAMING_SNAKE_CASE ) if push_to_hub: SCREAMING_SNAKE_CASE = { """mobilevit_s""": """mobilevit-small""", """mobilevit_xs""": """mobilevit-x-small""", """mobilevit_xxs""": """mobilevit-xx-small""", """deeplabv3_mobilevit_s""": """deeplabv3-mobilevit-small""", """deeplabv3_mobilevit_xs""": """deeplabv3-mobilevit-x-small""", """deeplabv3_mobilevit_xxs""": """deeplabv3-mobilevit-xx-small""", } print("""Pushing to the hub...""" ) SCREAMING_SNAKE_CASE = model_mapping[mobilevit_name] image_processor.push_to_hub(_SCREAMING_SNAKE_CASE , organization="""apple""" ) model.push_to_hub(_SCREAMING_SNAKE_CASE , organization="""apple""" ) if __name__ == "__main__": SCREAMING_SNAKE_CASE_ = argparse.ArgumentParser() # Required parameters parser.add_argument( """--mobilevit_name""", default="""mobilevit_s""", type=str, help=( """Name of the MobileViT model you'd like to convert. Should be one of 'mobilevit_s', 'mobilevit_xs',""" """ 'mobilevit_xxs', 'deeplabv3_mobilevit_s', 'deeplabv3_mobilevit_xs', 'deeplabv3_mobilevit_xxs'.""" ), ) parser.add_argument( """--checkpoint_path""", required=True, type=str, help="""Path to the original state dict (.pt file).""" ) parser.add_argument( """--pytorch_dump_folder_path""", required=True, type=str, help="""Path to the output PyTorch model directory.""" ) parser.add_argument( """--push_to_hub""", action="""store_true""", help="""Whether or not to push the converted model to the 🤗 hub.""" ) SCREAMING_SNAKE_CASE_ = parser.parse_args() convert_movilevit_checkpoint( args.mobilevit_name, args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub )
296
0
import unittest from transformers import ( MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING, TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING, TextaTextGenerationPipeline, pipeline, ) from transformers.testing_utils import is_pipeline_test, require_tf, require_torch from transformers.utils import is_torch_available from .test_pipelines_common import ANY if is_torch_available(): import torch @is_pipeline_test class A ( unittest.TestCase ): """simple docstring""" lowerCamelCase = MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING lowerCamelCase = TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING def snake_case__ ( self : List[Any],lowercase_ : Union[str, Any],lowercase_ : int,lowercase_ : Dict )-> Any: '''simple docstring''' A__ = TextaTextGenerationPipeline(model=lowercase_,tokenizer=lowercase_ ) return generator, ["Something to write", "Something else"] def snake_case__ ( self : int,lowercase_ : List[str],lowercase_ : List[Any] )-> Optional[int]: '''simple docstring''' A__ = generator('Something there' ) self.assertEqual(lowercase_,[{'generated_text': ANY(lowercase_ )}] ) # These are encoder decoder, they don't just append to incoming string self.assertFalse(outputs[0]['generated_text'].startswith('Something there' ) ) A__ = generator(['This is great !', 'Something else'],num_return_sequences=2,do_sample=lowercase_ ) self.assertEqual( lowercase_,[ [{'generated_text': ANY(lowercase_ )}, {'generated_text': ANY(lowercase_ )}], [{'generated_text': ANY(lowercase_ )}, {'generated_text': ANY(lowercase_ )}], ],) A__ = generator( ['This is great !', 'Something else'],num_return_sequences=2,batch_size=2,do_sample=lowercase_ ) self.assertEqual( lowercase_,[ [{'generated_text': ANY(lowercase_ )}, {'generated_text': ANY(lowercase_ )}], [{'generated_text': ANY(lowercase_ )}, {'generated_text': ANY(lowercase_ )}], ],) with self.assertRaises(lowercase_ ): generator(4 ) @require_torch def snake_case__ ( self : Tuple )-> List[Any]: '''simple docstring''' A__ = pipeline('text2text-generation',model='patrickvonplaten/t5-tiny-random',framework='pt' ) # do_sample=False necessary for reproducibility A__ = generator('Something there',do_sample=lowercase_ ) self.assertEqual(lowercase_,[{'generated_text': ''}] ) A__ = 3 A__ = generator( 'Something there',num_return_sequences=lowercase_,num_beams=lowercase_,) A__ = [ {'generated_text': 'Beide Beide Beide Beide Beide Beide Beide Beide Beide'}, {'generated_text': 'Beide Beide Beide Beide Beide Beide Beide Beide'}, {'generated_text': ''}, ] self.assertEqual(lowercase_,lowercase_ ) A__ = generator('This is a test',do_sample=lowercase_,num_return_sequences=2,return_tensors=lowercase_ ) self.assertEqual( lowercase_,[ {'generated_token_ids': ANY(torch.Tensor )}, {'generated_token_ids': ANY(torch.Tensor )}, ],) A__ = generator.model.config.eos_token_id A__ = '<pad>' A__ = generator( ['This is a test', 'This is a second test'],do_sample=lowercase_,num_return_sequences=2,batch_size=2,return_tensors=lowercase_,) self.assertEqual( lowercase_,[ [ {'generated_token_ids': ANY(torch.Tensor )}, {'generated_token_ids': ANY(torch.Tensor )}, ], [ {'generated_token_ids': ANY(torch.Tensor )}, {'generated_token_ids': ANY(torch.Tensor )}, ], ],) @require_tf def snake_case__ ( self : List[str] )-> List[str]: '''simple docstring''' A__ = pipeline('text2text-generation',model='patrickvonplaten/t5-tiny-random',framework='tf' ) # do_sample=False necessary for reproducibility A__ = generator('Something there',do_sample=lowercase_ ) self.assertEqual(lowercase_,[{'generated_text': ''}] )
7
from collections import OrderedDict from ...utils import logging from .auto_factory import _BaseAutoModelClass, _LazyAutoMapping, auto_class_update from .configuration_auto import CONFIG_MAPPING_NAMES SCREAMING_SNAKE_CASE_ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE_ = 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"""), ] ) SCREAMING_SNAKE_CASE_ = 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"""), ] ) SCREAMING_SNAKE_CASE_ = 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"""), ] ) SCREAMING_SNAKE_CASE_ = 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"""), ] ) SCREAMING_SNAKE_CASE_ = OrderedDict( [ # Model for Image-classsification ("""beit""", """FlaxBeitForImageClassification"""), ("""regnet""", """FlaxRegNetForImageClassification"""), ("""resnet""", """FlaxResNetForImageClassification"""), ("""vit""", """FlaxViTForImageClassification"""), ] ) SCREAMING_SNAKE_CASE_ = OrderedDict( [ ("""vision-encoder-decoder""", """FlaxVisionEncoderDecoderModel"""), ] ) SCREAMING_SNAKE_CASE_ = 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"""), ] ) SCREAMING_SNAKE_CASE_ = 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"""), ] ) SCREAMING_SNAKE_CASE_ = 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"""), ] ) SCREAMING_SNAKE_CASE_ = 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"""), ] ) SCREAMING_SNAKE_CASE_ = 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"""), ] ) SCREAMING_SNAKE_CASE_ = OrderedDict( [ ("""bert""", """FlaxBertForNextSentencePrediction"""), ] ) SCREAMING_SNAKE_CASE_ = OrderedDict( [ ("""speech-encoder-decoder""", """FlaxSpeechEncoderDecoderModel"""), ("""whisper""", """FlaxWhisperForConditionalGeneration"""), ] ) SCREAMING_SNAKE_CASE_ = OrderedDict( [ ("""whisper""", """FlaxWhisperForAudioClassification"""), ] ) SCREAMING_SNAKE_CASE_ = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_MAPPING_NAMES) SCREAMING_SNAKE_CASE_ = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_PRETRAINING_MAPPING_NAMES) SCREAMING_SNAKE_CASE_ = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MASKED_LM_MAPPING_NAMES) SCREAMING_SNAKE_CASE_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES ) SCREAMING_SNAKE_CASE_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES ) SCREAMING_SNAKE_CASE_ = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES) SCREAMING_SNAKE_CASE_ = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_CAUSAL_LM_MAPPING_NAMES) SCREAMING_SNAKE_CASE_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES ) SCREAMING_SNAKE_CASE_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES ) SCREAMING_SNAKE_CASE_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES ) SCREAMING_SNAKE_CASE_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES ) SCREAMING_SNAKE_CASE_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING_NAMES ) SCREAMING_SNAKE_CASE_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES ) SCREAMING_SNAKE_CASE_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES ) class UpperCamelCase__ ( _BaseAutoModelClass ): '''simple docstring''' __snake_case : List[str] = FLAX_MODEL_MAPPING SCREAMING_SNAKE_CASE_ = auto_class_update(FlaxAutoModel) class UpperCamelCase__ ( _BaseAutoModelClass ): '''simple docstring''' __snake_case : Dict = FLAX_MODEL_FOR_PRETRAINING_MAPPING SCREAMING_SNAKE_CASE_ = auto_class_update(FlaxAutoModelForPreTraining, head_doc="""pretraining""") class UpperCamelCase__ ( _BaseAutoModelClass ): '''simple docstring''' __snake_case : Optional[Any] = FLAX_MODEL_FOR_CAUSAL_LM_MAPPING SCREAMING_SNAKE_CASE_ = auto_class_update(FlaxAutoModelForCausalLM, head_doc="""causal language modeling""") class UpperCamelCase__ ( _BaseAutoModelClass ): '''simple docstring''' __snake_case : Any = FLAX_MODEL_FOR_MASKED_LM_MAPPING SCREAMING_SNAKE_CASE_ = auto_class_update(FlaxAutoModelForMaskedLM, head_doc="""masked language modeling""") class UpperCamelCase__ ( _BaseAutoModelClass ): '''simple docstring''' __snake_case : int = FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING SCREAMING_SNAKE_CASE_ = auto_class_update( FlaxAutoModelForSeqaSeqLM, head_doc="""sequence-to-sequence language modeling""", checkpoint_for_example="""t5-base""" ) class UpperCamelCase__ ( _BaseAutoModelClass ): '''simple docstring''' __snake_case : Optional[int] = FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING SCREAMING_SNAKE_CASE_ = auto_class_update( FlaxAutoModelForSequenceClassification, head_doc="""sequence classification""" ) class UpperCamelCase__ ( _BaseAutoModelClass ): '''simple docstring''' __snake_case : List[Any] = FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING SCREAMING_SNAKE_CASE_ = auto_class_update(FlaxAutoModelForQuestionAnswering, head_doc="""question answering""") class UpperCamelCase__ ( _BaseAutoModelClass ): '''simple docstring''' __snake_case : Tuple = FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING SCREAMING_SNAKE_CASE_ = auto_class_update( FlaxAutoModelForTokenClassification, head_doc="""token classification""" ) class UpperCamelCase__ ( _BaseAutoModelClass ): '''simple docstring''' __snake_case : Union[str, Any] = FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING SCREAMING_SNAKE_CASE_ = auto_class_update(FlaxAutoModelForMultipleChoice, head_doc="""multiple choice""") class UpperCamelCase__ ( _BaseAutoModelClass ): '''simple docstring''' __snake_case : List[str] = FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING SCREAMING_SNAKE_CASE_ = auto_class_update( FlaxAutoModelForNextSentencePrediction, head_doc="""next sentence prediction""" ) class UpperCamelCase__ ( _BaseAutoModelClass ): '''simple docstring''' __snake_case : Dict = FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING SCREAMING_SNAKE_CASE_ = auto_class_update( FlaxAutoModelForImageClassification, head_doc="""image classification""" ) class UpperCamelCase__ ( _BaseAutoModelClass ): '''simple docstring''' __snake_case : Dict = FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING SCREAMING_SNAKE_CASE_ = auto_class_update(FlaxAutoModelForVisionaSeq, head_doc="""vision-to-text modeling""") class UpperCamelCase__ ( _BaseAutoModelClass ): '''simple docstring''' __snake_case : Optional[Any] = FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING SCREAMING_SNAKE_CASE_ = auto_class_update( FlaxAutoModelForSpeechSeqaSeq, head_doc="""sequence-to-sequence speech-to-text modeling""" )
296
0
import sys lowerCAmelCase_ = ( '''73167176531330624919225119674426574742355349194934''' '''96983520312774506326239578318016984801869478851843''' '''85861560789112949495459501737958331952853208805511''' '''12540698747158523863050715693290963295227443043557''' '''66896648950445244523161731856403098711121722383113''' '''62229893423380308135336276614282806444486645238749''' '''30358907296290491560440772390713810515859307960866''' '''70172427121883998797908792274921901699720888093776''' '''65727333001053367881220235421809751254540594752243''' '''52584907711670556013604839586446706324415722155397''' '''53697817977846174064955149290862569321978468622482''' '''83972241375657056057490261407972968652414535100474''' '''82166370484403199890008895243450658541227588666881''' '''16427171479924442928230863465674813919123162824586''' '''17866458359124566529476545682848912883142607690042''' '''24219022671055626321111109370544217506941658960408''' '''07198403850962455444362981230987879927244284909188''' '''84580156166097919133875499200524063689912560717606''' '''05886116467109405077541002256983155200055935729725''' '''71636269561882670428252483600823257530420752963450''' ) def __SCREAMING_SNAKE_CASE (SCREAMING_SNAKE_CASE__ = N ): snake_case_ = -sys.maxsize - 1 for i in range(len(SCREAMING_SNAKE_CASE__ ) - 12 ): snake_case_ = 1 for j in range(13 ): product *= int(n[i + j] ) if product > largest_product: snake_case_ = product return largest_product if __name__ == "__main__": print(f"""{solution() = }""")
8
from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ..auto import CONFIG_MAPPING SCREAMING_SNAKE_CASE_ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE_ = { """microsoft/table-transformer-detection""": ( """https://huggingface.co/microsoft/table-transformer-detection/resolve/main/config.json""" ), } class UpperCamelCase__ ( lowerCAmelCase_ ): '''simple docstring''' __snake_case : Union[str, Any] = "table-transformer" __snake_case : Union[str, Any] = ["past_key_values"] __snake_case : List[Any] = { "hidden_size": "d_model", "num_attention_heads": "encoder_attention_heads", } def __init__( self : Optional[int] ,lowerCamelCase__ : Optional[Any]=True ,lowerCamelCase__ : Optional[Any]=None ,lowerCamelCase__ : List[Any]=3 ,lowerCamelCase__ : Optional[int]=100 ,lowerCamelCase__ : List[Any]=6 ,lowerCamelCase__ : Dict=2048 ,lowerCamelCase__ : List[Any]=8 ,lowerCamelCase__ : Dict=6 ,lowerCamelCase__ : Dict=2048 ,lowerCamelCase__ : Any=8 ,lowerCamelCase__ : Optional[int]=0.0 ,lowerCamelCase__ : int=0.0 ,lowerCamelCase__ : List[Any]=True ,lowerCamelCase__ : Optional[int]="relu" ,lowerCamelCase__ : Tuple=256 ,lowerCamelCase__ : Any=0.1 ,lowerCamelCase__ : Optional[Any]=0.0 ,lowerCamelCase__ : Tuple=0.0 ,lowerCamelCase__ : List[Any]=0.02 ,lowerCamelCase__ : int=1.0 ,lowerCamelCase__ : List[str]=False ,lowerCamelCase__ : Optional[Any]="sine" ,lowerCamelCase__ : List[str]="resnet50" ,lowerCamelCase__ : Optional[Any]=True ,lowerCamelCase__ : List[str]=False ,lowerCamelCase__ : int=1 ,lowerCamelCase__ : Dict=5 ,lowerCamelCase__ : Tuple=2 ,lowerCamelCase__ : Union[str, Any]=1 ,lowerCamelCase__ : str=1 ,lowerCamelCase__ : Any=5 ,lowerCamelCase__ : Tuple=2 ,lowerCamelCase__ : str=0.1 ,**lowerCamelCase__ : List[str] ,) -> Optional[int]: '''simple docstring''' if backbone_config is not None and use_timm_backbone: raise ValueError("""You can't specify both `backbone_config` and `use_timm_backbone`.""" ) if not use_timm_backbone: if backbone_config is None: logger.info("""`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.""" ) SCREAMING_SNAKE_CASE = CONFIG_MAPPING["""resnet"""](out_features=["""stage4"""] ) elif isinstance(lowerCamelCase__ ,lowerCamelCase__ ): SCREAMING_SNAKE_CASE = backbone_config.get("""model_type""" ) SCREAMING_SNAKE_CASE = CONFIG_MAPPING[backbone_model_type] SCREAMING_SNAKE_CASE = config_class.from_dict(lowerCamelCase__ ) # set timm attributes to None SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE = None, None, None SCREAMING_SNAKE_CASE = use_timm_backbone SCREAMING_SNAKE_CASE = backbone_config SCREAMING_SNAKE_CASE = num_channels SCREAMING_SNAKE_CASE = num_queries SCREAMING_SNAKE_CASE = d_model SCREAMING_SNAKE_CASE = encoder_ffn_dim SCREAMING_SNAKE_CASE = encoder_layers SCREAMING_SNAKE_CASE = encoder_attention_heads SCREAMING_SNAKE_CASE = decoder_ffn_dim SCREAMING_SNAKE_CASE = decoder_layers SCREAMING_SNAKE_CASE = decoder_attention_heads SCREAMING_SNAKE_CASE = dropout SCREAMING_SNAKE_CASE = attention_dropout SCREAMING_SNAKE_CASE = activation_dropout SCREAMING_SNAKE_CASE = activation_function SCREAMING_SNAKE_CASE = init_std SCREAMING_SNAKE_CASE = init_xavier_std SCREAMING_SNAKE_CASE = encoder_layerdrop SCREAMING_SNAKE_CASE = decoder_layerdrop SCREAMING_SNAKE_CASE = encoder_layers SCREAMING_SNAKE_CASE = auxiliary_loss SCREAMING_SNAKE_CASE = position_embedding_type SCREAMING_SNAKE_CASE = backbone SCREAMING_SNAKE_CASE = use_pretrained_backbone SCREAMING_SNAKE_CASE = dilation # Hungarian matcher SCREAMING_SNAKE_CASE = class_cost SCREAMING_SNAKE_CASE = bbox_cost SCREAMING_SNAKE_CASE = giou_cost # Loss coefficients SCREAMING_SNAKE_CASE = mask_loss_coefficient SCREAMING_SNAKE_CASE = dice_loss_coefficient SCREAMING_SNAKE_CASE = bbox_loss_coefficient SCREAMING_SNAKE_CASE = giou_loss_coefficient SCREAMING_SNAKE_CASE = eos_coefficient super().__init__(is_encoder_decoder=lowerCamelCase__ ,**lowerCamelCase__ ) @property def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ) -> int: '''simple docstring''' return self.encoder_attention_heads @property def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ) -> int: '''simple docstring''' return self.d_model class UpperCamelCase__ ( lowerCAmelCase_ ): '''simple docstring''' __snake_case : int = version.parse("1.11" ) @property def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' return OrderedDict( [ ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}), ("""pixel_mask""", {0: """batch"""}), ] ) @property def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ) -> float: '''simple docstring''' return 1e-5 @property def SCREAMING_SNAKE_CASE__ ( self : Any ) -> int: '''simple docstring''' return 12
296
0
import multiprocessing from typing import TYPE_CHECKING, Optional, Union from .. import Dataset, Features, config from ..formatting import query_table from ..packaged_modules.sql.sql import Sql from ..utils import logging from .abc import AbstractDatasetInputStream if TYPE_CHECKING: import sqlitea import sqlalchemy class _lowercase ( A__ ): '''simple docstring''' def __init__( self :int , lowerCAmelCase__ :Union[str, "sqlalchemy.sql.Selectable"] , lowerCAmelCase__ :Union[str, "sqlalchemy.engine.Connection", "sqlalchemy.engine.Engine", "sqlite3.Connection"] , lowerCAmelCase__ :Optional[Features] = None , lowerCAmelCase__ :str = None , lowerCAmelCase__ :bool = False , **lowerCAmelCase__ :Union[str, Any] , ) -> Optional[int]: super().__init__(features=lowerCAmelCase__ , cache_dir=lowerCAmelCase__ , keep_in_memory=lowerCAmelCase__ , **lowerCAmelCase__ ) __SCREAMING_SNAKE_CASE : Any = Sql( cache_dir=lowerCAmelCase__ , features=lowerCAmelCase__ , sql=lowerCAmelCase__ , con=lowerCAmelCase__ , **lowerCAmelCase__ , ) def __magic_name__( self :List[Any] ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE : Optional[int] = None __SCREAMING_SNAKE_CASE : int = None __SCREAMING_SNAKE_CASE : Optional[Any] = None __SCREAMING_SNAKE_CASE : Dict = None self.builder.download_and_prepare( download_config=lowerCAmelCase__ , download_mode=lowerCAmelCase__ , verification_mode=lowerCAmelCase__ , base_path=lowerCAmelCase__ , ) # Build dataset for splits __SCREAMING_SNAKE_CASE : List[Any] = self.builder.as_dataset( split='''train''' , verification_mode=lowerCAmelCase__ , in_memory=self.keep_in_memory ) return dataset class _lowercase : '''simple docstring''' def __init__( self :int , lowerCAmelCase__ :Dataset , lowerCAmelCase__ :str , lowerCAmelCase__ :Union[str, "sqlalchemy.engine.Connection", "sqlalchemy.engine.Engine", "sqlite3.Connection"] , lowerCAmelCase__ :Optional[int] = None , lowerCAmelCase__ :Optional[int] = None , **lowerCAmelCase__ :Union[str, Any] , ) -> int: if num_proc is not None and num_proc <= 0: raise ValueError(f'''num_proc {num_proc} must be an integer > 0.''' ) __SCREAMING_SNAKE_CASE : List[Any] = dataset __SCREAMING_SNAKE_CASE : Tuple = name __SCREAMING_SNAKE_CASE : Optional[Any] = con __SCREAMING_SNAKE_CASE : Union[str, Any] = batch_size if batch_size else config.DEFAULT_MAX_BATCH_SIZE __SCREAMING_SNAKE_CASE : List[Any] = num_proc __SCREAMING_SNAKE_CASE : Optional[int] = to_sql_kwargs def __magic_name__( self :Tuple ) -> int: __SCREAMING_SNAKE_CASE : Optional[int] = self.to_sql_kwargs.pop('''sql''' , lowerCAmelCase__ ) __SCREAMING_SNAKE_CASE : Optional[int] = self.to_sql_kwargs.pop('''con''' , lowerCAmelCase__ ) __SCREAMING_SNAKE_CASE : int = self.to_sql_kwargs.pop('''index''' , lowerCAmelCase__ ) __SCREAMING_SNAKE_CASE : int = self._write(index=lowerCAmelCase__ , **self.to_sql_kwargs ) return written def __magic_name__( self :Dict , lowerCAmelCase__ :List[Any] ) -> Optional[Any]: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[str] = args __SCREAMING_SNAKE_CASE : Union[str, Any] = {**to_sql_kwargs, '''if_exists''': '''append'''} if offset > 0 else to_sql_kwargs __SCREAMING_SNAKE_CASE : List[str] = query_table( table=self.dataset.data , key=slice(lowerCAmelCase__ , offset + self.batch_size ) , indices=self.dataset._indices , ) __SCREAMING_SNAKE_CASE : Union[str, Any] = batch.to_pandas() __SCREAMING_SNAKE_CASE : Union[str, Any] = df.to_sql(self.name , self.con , index=lowerCAmelCase__ , **lowerCAmelCase__ ) return num_rows or len(lowerCAmelCase__ ) def __magic_name__( self :str , lowerCAmelCase__ :str , **lowerCAmelCase__ :Tuple ) -> int: __SCREAMING_SNAKE_CASE : str = 0 if self.num_proc is None or self.num_proc == 1: for offset in logging.tqdm( range(0 , len(self.dataset ) , self.batch_size ) , unit='''ba''' , disable=not logging.is_progress_bar_enabled() , desc='''Creating SQL from Arrow format''' , ): written += self._batch_sql((offset, index, to_sql_kwargs) ) else: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[int] = len(self.dataset ), self.batch_size with multiprocessing.Pool(self.num_proc ) as pool: for num_rows in logging.tqdm( pool.imap( self._batch_sql , [(offset, index, to_sql_kwargs) for offset in range(0 , lowerCAmelCase__ , lowerCAmelCase__ )] , ) , total=(num_rows // batch_size) + 1 if num_rows % batch_size else num_rows // batch_size , unit='''ba''' , disable=not logging.is_progress_bar_enabled() , desc='''Creating SQL from Arrow format''' , ): written += num_rows return written
9
from collections import defaultdict from math import gcd def __lowercase ( _SCREAMING_SNAKE_CASE = 1_50_00_00 ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE = defaultdict(_SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE = 2 while 2 * euclid_m * (euclid_m + 1) <= limit: for euclid_n in range((euclid_m % 2) + 1 , _SCREAMING_SNAKE_CASE , 2 ): if gcd(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) > 1: continue SCREAMING_SNAKE_CASE = 2 * euclid_m * (euclid_m + euclid_n) for perimeter in range(_SCREAMING_SNAKE_CASE , limit + 1 , _SCREAMING_SNAKE_CASE ): frequencies[perimeter] += 1 euclid_m += 1 return sum(1 for frequency in frequencies.values() if frequency == 1 ) if __name__ == "__main__": print(F'''{solution() = }''')
296
0
import torch from diffusers import DDPMParallelScheduler from .test_schedulers import SchedulerCommonTest class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowercase_ = (DDPMParallelScheduler,) def SCREAMING_SNAKE_CASE_ (self : Any , **UpperCAmelCase_ : Any) ->Any: '''simple docstring''' lowerCamelCase__: Any ={ "num_train_timesteps": 1_000, "beta_start": 0.0001, "beta_end": 0.02, "beta_schedule": "linear", "variance_type": "fixed_small", "clip_sample": True, } config.update(**UpperCAmelCase_) return config def SCREAMING_SNAKE_CASE_ (self : int) ->Dict: '''simple docstring''' for timesteps in [1, 5, 100, 1_000]: self.check_over_configs(num_train_timesteps=UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : int) ->Optional[int]: '''simple docstring''' for beta_start, beta_end in zip([0.0001, 0.001, 0.01, 0.1] , [0.002, 0.02, 0.2, 2]): self.check_over_configs(beta_start=UpperCAmelCase_ , beta_end=UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Optional[Any]) ->Any: '''simple docstring''' for schedule in ["linear", "squaredcos_cap_v2"]: self.check_over_configs(beta_schedule=UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : int) ->Optional[int]: '''simple docstring''' for variance in ["fixed_small", "fixed_large", "other"]: self.check_over_configs(variance_type=UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Optional[int]) ->Optional[Any]: '''simple docstring''' for clip_sample in [True, False]: self.check_over_configs(clip_sample=UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Any) ->Tuple: '''simple docstring''' self.check_over_configs(thresholding=UpperCAmelCase_) for threshold in [0.5, 1.0, 2.0]: for prediction_type in ["epsilon", "sample", "v_prediction"]: self.check_over_configs( thresholding=UpperCAmelCase_ , prediction_type=UpperCAmelCase_ , sample_max_value=UpperCAmelCase_ , ) def SCREAMING_SNAKE_CASE_ (self : Any) ->Optional[int]: '''simple docstring''' for prediction_type in ["epsilon", "sample", "v_prediction"]: self.check_over_configs(prediction_type=UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : int) ->int: '''simple docstring''' for t in [0, 500, 999]: self.check_over_forward(time_step=UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Optional[Any]) ->str: '''simple docstring''' lowerCamelCase__: Dict =self.scheduler_classes[0] lowerCamelCase__: Tuple =self.get_scheduler_config() lowerCamelCase__: Any =scheduler_class(**UpperCAmelCase_) assert torch.sum(torch.abs(scheduler._get_variance(0) - 0.0)) < 1E-5 assert torch.sum(torch.abs(scheduler._get_variance(487) - 0.0_0979)) < 1E-5 assert torch.sum(torch.abs(scheduler._get_variance(999) - 0.02)) < 1E-5 def SCREAMING_SNAKE_CASE_ (self : Any) ->str: '''simple docstring''' lowerCamelCase__: int =self.scheduler_classes[0] lowerCamelCase__: Tuple =self.get_scheduler_config() lowerCamelCase__: Tuple =scheduler_class(**UpperCAmelCase_) lowerCamelCase__: str =len(UpperCAmelCase_) lowerCamelCase__: Optional[int] =self.dummy_model() lowerCamelCase__: int =self.dummy_sample_deter lowerCamelCase__: Union[str, Any] =self.dummy_sample_deter + 0.1 lowerCamelCase__: Optional[Any] =self.dummy_sample_deter - 0.1 lowerCamelCase__: Optional[Any] =samplea.shape[0] lowerCamelCase__: List[Any] =torch.stack([samplea, samplea, samplea] , dim=0) lowerCamelCase__: Union[str, Any] =torch.arange(UpperCAmelCase_)[0:3, None].repeat(1 , UpperCAmelCase_) lowerCamelCase__: Optional[int] =model(samples.flatten(0 , 1) , timesteps.flatten(0 , 1)) lowerCamelCase__: Tuple =scheduler.batch_step_no_noise(UpperCAmelCase_ , timesteps.flatten(0 , 1) , samples.flatten(0 , 1)) lowerCamelCase__: List[str] =torch.sum(torch.abs(UpperCAmelCase_)) lowerCamelCase__: Any =torch.mean(torch.abs(UpperCAmelCase_)) assert abs(result_sum.item() - 1153.1833) < 1E-2 assert abs(result_mean.item() - 0.5005) < 1E-3 def SCREAMING_SNAKE_CASE_ (self : Optional[Any]) ->Union[str, Any]: '''simple docstring''' lowerCamelCase__: Any =self.scheduler_classes[0] lowerCamelCase__: Optional[Any] =self.get_scheduler_config() lowerCamelCase__: Optional[int] =scheduler_class(**UpperCAmelCase_) lowerCamelCase__: Union[str, Any] =len(UpperCAmelCase_) lowerCamelCase__: Union[str, Any] =self.dummy_model() lowerCamelCase__: List[Any] =self.dummy_sample_deter lowerCamelCase__: int =torch.manual_seed(0) for t in reversed(range(UpperCAmelCase_)): # 1. predict noise residual lowerCamelCase__: Tuple =model(UpperCAmelCase_ , UpperCAmelCase_) # 2. predict previous mean of sample x_t-1 lowerCamelCase__: Optional[Any] =scheduler.step(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , generator=UpperCAmelCase_).prev_sample lowerCamelCase__: Any =pred_prev_sample lowerCamelCase__: Any =torch.sum(torch.abs(UpperCAmelCase_)) lowerCamelCase__: List[str] =torch.mean(torch.abs(UpperCAmelCase_)) assert abs(result_sum.item() - 258.9606) < 1E-2 assert abs(result_mean.item() - 0.3372) < 1E-3 def SCREAMING_SNAKE_CASE_ (self : int) ->Any: '''simple docstring''' lowerCamelCase__: Tuple =self.scheduler_classes[0] lowerCamelCase__: Any =self.get_scheduler_config(prediction_type="v_prediction") lowerCamelCase__: Any =scheduler_class(**UpperCAmelCase_) lowerCamelCase__: str =len(UpperCAmelCase_) lowerCamelCase__: str =self.dummy_model() lowerCamelCase__: str =self.dummy_sample_deter lowerCamelCase__: Dict =torch.manual_seed(0) for t in reversed(range(UpperCAmelCase_)): # 1. predict noise residual lowerCamelCase__: Union[str, Any] =model(UpperCAmelCase_ , UpperCAmelCase_) # 2. predict previous mean of sample x_t-1 lowerCamelCase__: Dict =scheduler.step(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , generator=UpperCAmelCase_).prev_sample lowerCamelCase__: List[str] =pred_prev_sample lowerCamelCase__: List[Any] =torch.sum(torch.abs(UpperCAmelCase_)) lowerCamelCase__: Tuple =torch.mean(torch.abs(UpperCAmelCase_)) assert abs(result_sum.item() - 202.0296) < 1E-2 assert abs(result_mean.item() - 0.2631) < 1E-3 def SCREAMING_SNAKE_CASE_ (self : Tuple) ->Optional[int]: '''simple docstring''' lowerCamelCase__: str =self.scheduler_classes[0] lowerCamelCase__: Union[str, Any] =self.get_scheduler_config() lowerCamelCase__: Any =scheduler_class(**UpperCAmelCase_) lowerCamelCase__: List[Any] =[100, 87, 50, 1, 0] scheduler.set_timesteps(timesteps=UpperCAmelCase_) lowerCamelCase__: Union[str, Any] =scheduler.timesteps for i, timestep in enumerate(UpperCAmelCase_): if i == len(UpperCAmelCase_) - 1: lowerCamelCase__: Dict =-1 else: lowerCamelCase__: Union[str, Any] =timesteps[i + 1] lowerCamelCase__: Tuple =scheduler.previous_timestep(UpperCAmelCase_) lowerCamelCase__: str =prev_t.item() self.assertEqual(UpperCAmelCase_ , UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Union[str, Any]) ->Union[str, Any]: '''simple docstring''' lowerCamelCase__: Tuple =self.scheduler_classes[0] lowerCamelCase__: List[Any] =self.get_scheduler_config() lowerCamelCase__: Dict =scheduler_class(**UpperCAmelCase_) lowerCamelCase__: Optional[Any] =[100, 87, 50, 51, 0] with self.assertRaises(UpperCAmelCase_ , msg="`custom_timesteps` must be in descending order."): scheduler.set_timesteps(timesteps=UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : List[Any]) ->List[Any]: '''simple docstring''' lowerCamelCase__: Dict =self.scheduler_classes[0] lowerCamelCase__: Any =self.get_scheduler_config() lowerCamelCase__: int =scheduler_class(**UpperCAmelCase_) lowerCamelCase__: Optional[int] =[100, 87, 50, 1, 0] lowerCamelCase__: int =len(UpperCAmelCase_) with self.assertRaises(UpperCAmelCase_ , msg="Can only pass one of `num_inference_steps` or `custom_timesteps`."): scheduler.set_timesteps(num_inference_steps=UpperCAmelCase_ , timesteps=UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Optional[Any]) ->Any: '''simple docstring''' lowerCamelCase__: Tuple =self.scheduler_classes[0] lowerCamelCase__: Optional[Any] =self.get_scheduler_config() lowerCamelCase__: Optional[Any] =scheduler_class(**UpperCAmelCase_) lowerCamelCase__: Dict =[scheduler.config.num_train_timesteps] with self.assertRaises( UpperCAmelCase_ , msg="`timesteps` must start before `self.config.train_timesteps`: {scheduler.config.num_train_timesteps}}" , ): scheduler.set_timesteps(timesteps=UpperCAmelCase_)
10
from argparse import ArgumentParser from .env import EnvironmentCommand def __lowercase ( ) -> Dict: '''simple docstring''' SCREAMING_SNAKE_CASE = ArgumentParser("""Diffusers CLI tool""" , usage="""diffusers-cli <command> [<args>]""" ) SCREAMING_SNAKE_CASE = parser.add_subparsers(help="""diffusers-cli command helpers""" ) # Register commands EnvironmentCommand.register_subcommand(_SCREAMING_SNAKE_CASE ) # Let's go SCREAMING_SNAKE_CASE = parser.parse_args() if not hasattr(_SCREAMING_SNAKE_CASE , """func""" ): parser.print_help() exit(1 ) # Run SCREAMING_SNAKE_CASE = args.func(_SCREAMING_SNAKE_CASE ) service.run() if __name__ == "__main__": main()
296
0
from collections.abc import Sequence from queue import Queue class lowerCAmelCase__ : '''simple docstring''' def __init__( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase=None , __lowerCamelCase=None) -> Union[str, Any]: _A : str = start _A : Optional[int] = end _A : List[str] = val _A : Tuple = (start + end) // 2 _A : Any = left _A : List[Any] = right def __repr__( self) -> Any: return F"SegmentTreeNode(start={self.start}, end={self.end}, val={self.val})" class lowerCAmelCase__ : '''simple docstring''' def __init__( self , __lowerCamelCase , __lowerCamelCase) -> List[str]: _A : str = collection _A : Optional[Any] = function if self.collection: _A : Optional[int] = self._build_tree(0 , len(__lowerCamelCase) - 1) def _lowerCamelCase ( self , __lowerCamelCase , __lowerCamelCase) -> Tuple: self._update_tree(self.root , __lowerCamelCase , __lowerCamelCase) def _lowerCamelCase ( self , __lowerCamelCase , __lowerCamelCase) -> List[str]: return self._query_range(self.root , __lowerCamelCase , __lowerCamelCase) def _lowerCamelCase ( self , __lowerCamelCase , __lowerCamelCase) -> List[str]: if start == end: return SegmentTreeNode(__lowerCamelCase , __lowerCamelCase , self.collection[start]) _A : List[Any] = (start + end) // 2 _A : int = self._build_tree(__lowerCamelCase , __lowerCamelCase) _A : Optional[Any] = self._build_tree(mid + 1 , __lowerCamelCase) return SegmentTreeNode(__lowerCamelCase , __lowerCamelCase , self.fn(left.val , right.val) , __lowerCamelCase , __lowerCamelCase) def _lowerCamelCase ( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase) -> int: if node.start == i and node.end == i: _A : List[str] = val return if i <= node.mid: self._update_tree(node.left , __lowerCamelCase , __lowerCamelCase) else: self._update_tree(node.right , __lowerCamelCase , __lowerCamelCase) _A : str = self.fn(node.left.val , node.right.val) def _lowerCamelCase ( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase) -> str: if node.start == i and node.end == j: return node.val if i <= node.mid: if j <= node.mid: # range in left child tree return self._query_range(node.left , __lowerCamelCase , __lowerCamelCase) else: # range in left child tree and right child tree return self.fn( self._query_range(node.left , __lowerCamelCase , node.mid) , self._query_range(node.right , node.mid + 1 , __lowerCamelCase) , ) else: # range in right child tree return self._query_range(node.right , __lowerCamelCase , __lowerCamelCase) def _lowerCamelCase ( self) -> Dict: if self.root is not None: _A : Optional[int] = Queue() queue.put(self.root) while not queue.empty(): _A : Tuple = queue.get() yield node if node.left is not None: queue.put(node.left) if node.right is not None: queue.put(node.right) if __name__ == "__main__": import operator for fn in [operator.add, max, min]: print('*' * 50) lowerCAmelCase__ = SegmentTree([2, 1, 5, 3, 4], fn) for node in arr.traverse(): print(node) print() arr.update(1, 5) for node in arr.traverse(): print(node) print() print(arr.query_range(3, 4)) # 7 print(arr.query_range(2, 2)) # 5 print(arr.query_range(1, 3)) # 13 print()
11
import argparse import json import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import AutoImageProcessor, SwinConfig, SwinForImageClassification def __lowercase ( _SCREAMING_SNAKE_CASE ) -> Union[str, Any]: '''simple docstring''' SCREAMING_SNAKE_CASE = SwinConfig() SCREAMING_SNAKE_CASE = swin_name.split("""_""" ) SCREAMING_SNAKE_CASE = name_split[1] SCREAMING_SNAKE_CASE = int(name_split[4] ) SCREAMING_SNAKE_CASE = int(name_split[3][-1] ) if model_size == "tiny": SCREAMING_SNAKE_CASE = 96 SCREAMING_SNAKE_CASE = (2, 2, 6, 2) SCREAMING_SNAKE_CASE = (3, 6, 12, 24) elif model_size == "small": SCREAMING_SNAKE_CASE = 96 SCREAMING_SNAKE_CASE = (2, 2, 18, 2) SCREAMING_SNAKE_CASE = (3, 6, 12, 24) elif model_size == "base": SCREAMING_SNAKE_CASE = 1_28 SCREAMING_SNAKE_CASE = (2, 2, 18, 2) SCREAMING_SNAKE_CASE = (4, 8, 16, 32) else: SCREAMING_SNAKE_CASE = 1_92 SCREAMING_SNAKE_CASE = (2, 2, 18, 2) SCREAMING_SNAKE_CASE = (6, 12, 24, 48) if "in22k" in swin_name: SCREAMING_SNAKE_CASE = 2_18_41 else: SCREAMING_SNAKE_CASE = 10_00 SCREAMING_SNAKE_CASE = """huggingface/label-files""" SCREAMING_SNAKE_CASE = """imagenet-1k-id2label.json""" SCREAMING_SNAKE_CASE = json.load(open(hf_hub_download(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , repo_type="""dataset""" ) , """r""" ) ) SCREAMING_SNAKE_CASE = {int(_SCREAMING_SNAKE_CASE ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE = idalabel SCREAMING_SNAKE_CASE = {v: k for k, v in idalabel.items()} SCREAMING_SNAKE_CASE = img_size SCREAMING_SNAKE_CASE = num_classes SCREAMING_SNAKE_CASE = embed_dim SCREAMING_SNAKE_CASE = depths SCREAMING_SNAKE_CASE = num_heads SCREAMING_SNAKE_CASE = window_size return config def __lowercase ( _SCREAMING_SNAKE_CASE ) -> Dict: '''simple docstring''' if "patch_embed.proj" in name: SCREAMING_SNAKE_CASE = name.replace("""patch_embed.proj""" , """embeddings.patch_embeddings.projection""" ) if "patch_embed.norm" in name: SCREAMING_SNAKE_CASE = name.replace("""patch_embed.norm""" , """embeddings.norm""" ) if "layers" in name: SCREAMING_SNAKE_CASE = """encoder.""" + name if "attn.proj" in name: SCREAMING_SNAKE_CASE = name.replace("""attn.proj""" , """attention.output.dense""" ) if "attn" in name: SCREAMING_SNAKE_CASE = name.replace("""attn""" , """attention.self""" ) if "norm1" in name: SCREAMING_SNAKE_CASE = name.replace("""norm1""" , """layernorm_before""" ) if "norm2" in name: SCREAMING_SNAKE_CASE = name.replace("""norm2""" , """layernorm_after""" ) if "mlp.fc1" in name: SCREAMING_SNAKE_CASE = name.replace("""mlp.fc1""" , """intermediate.dense""" ) if "mlp.fc2" in name: SCREAMING_SNAKE_CASE = name.replace("""mlp.fc2""" , """output.dense""" ) if name == "norm.weight": SCREAMING_SNAKE_CASE = """layernorm.weight""" if name == "norm.bias": SCREAMING_SNAKE_CASE = """layernorm.bias""" if "head" in name: SCREAMING_SNAKE_CASE = name.replace("""head""" , """classifier""" ) else: SCREAMING_SNAKE_CASE = """swin.""" + name return name def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Any: '''simple docstring''' for key in orig_state_dict.copy().keys(): SCREAMING_SNAKE_CASE = orig_state_dict.pop(_SCREAMING_SNAKE_CASE ) if "mask" in key: continue elif "qkv" in key: SCREAMING_SNAKE_CASE = key.split(""".""" ) SCREAMING_SNAKE_CASE = int(key_split[1] ) SCREAMING_SNAKE_CASE = int(key_split[3] ) SCREAMING_SNAKE_CASE = model.swin.encoder.layers[layer_num].blocks[block_num].attention.self.all_head_size if "weight" in key: SCREAMING_SNAKE_CASE = val[:dim, :] SCREAMING_SNAKE_CASE = val[ dim : dim * 2, : ] SCREAMING_SNAKE_CASE = val[-dim:, :] else: SCREAMING_SNAKE_CASE = val[ :dim ] SCREAMING_SNAKE_CASE = val[ dim : dim * 2 ] SCREAMING_SNAKE_CASE = val[ -dim: ] else: SCREAMING_SNAKE_CASE = val return orig_state_dict def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> List[str]: '''simple docstring''' SCREAMING_SNAKE_CASE = timm.create_model(_SCREAMING_SNAKE_CASE , pretrained=_SCREAMING_SNAKE_CASE ) timm_model.eval() SCREAMING_SNAKE_CASE = get_swin_config(_SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE = SwinForImageClassification(_SCREAMING_SNAKE_CASE ) model.eval() SCREAMING_SNAKE_CASE = convert_state_dict(timm_model.state_dict() , _SCREAMING_SNAKE_CASE ) model.load_state_dict(_SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE = """http://images.cocodataset.org/val2017/000000039769.jpg""" SCREAMING_SNAKE_CASE = AutoImageProcessor.from_pretrained("""microsoft/{}""".format(swin_name.replace("""_""" , """-""" ) ) ) SCREAMING_SNAKE_CASE = Image.open(requests.get(_SCREAMING_SNAKE_CASE , stream=_SCREAMING_SNAKE_CASE ).raw ) SCREAMING_SNAKE_CASE = image_processor(images=_SCREAMING_SNAKE_CASE , return_tensors="""pt""" ) SCREAMING_SNAKE_CASE = timm_model(inputs["""pixel_values"""] ) SCREAMING_SNAKE_CASE = model(**_SCREAMING_SNAKE_CASE ).logits assert torch.allclose(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , atol=1E-3 ) print(F"""Saving model {swin_name} to {pytorch_dump_folder_path}""" ) model.save_pretrained(_SCREAMING_SNAKE_CASE ) print(F"""Saving image processor to {pytorch_dump_folder_path}""" ) image_processor.save_pretrained(_SCREAMING_SNAKE_CASE ) if __name__ == "__main__": SCREAMING_SNAKE_CASE_ = argparse.ArgumentParser() # Required parameters parser.add_argument( """--swin_name""", default="""swin_tiny_patch4_window7_224""", type=str, help="""Name of the Swin timm model you'd like to convert.""", ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model directory.""" ) SCREAMING_SNAKE_CASE_ = parser.parse_args() convert_swin_checkpoint(args.swin_name, args.pytorch_dump_folder_path)
296
0
import os import re import shutil import sys import tempfile import unittest import black UpperCAmelCase_ = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) sys.path.append(os.path.join(git_repo_path, 'utils')) import check_copies # noqa: E402 # This is the reference code that will be used in the tests. # If BertLMPredictionHead is changed in modeling_bert.py, this code needs to be manually updated. UpperCAmelCase_ = ' def __init__(self, config):\n super().__init__()\n self.transform = BertPredictionHeadTransform(config)\n\n # The output weights are the same as the input embeddings, but there is\n # an output-only bias for each token.\n self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False)\n\n self.bias = nn.Parameter(torch.zeros(config.vocab_size))\n\n # Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings`\n self.decoder.bias = self.bias\n\n def forward(self, hidden_states):\n hidden_states = self.transform(hidden_states)\n hidden_states = self.decoder(hidden_states)\n return hidden_states\n' class lowerCamelCase__( unittest.TestCase): def lowerCAmelCase__ ( self: List[str] ): __lowerCamelCase = tempfile.mkdtemp() os.makedirs(os.path.join(self.transformer_dir , """models/bert/""" ) ) __lowerCamelCase = self.transformer_dir shutil.copy( os.path.join(UpperCamelCase_ , """src/transformers/models/bert/modeling_bert.py""" ) , os.path.join(self.transformer_dir , """models/bert/modeling_bert.py""" ) , ) def lowerCAmelCase__ ( self: int ): __lowerCamelCase = """src/transformers""" shutil.rmtree(self.transformer_dir ) def lowerCAmelCase__ ( self: List[Any] , UpperCamelCase_: List[str] , UpperCamelCase_: Any , UpperCamelCase_: List[Any] , UpperCamelCase_: List[str]=None ): __lowerCamelCase = comment + F'\nclass {class_name}(nn.Module):\n' + class_code if overwrite_result is not None: __lowerCamelCase = comment + F'\nclass {class_name}(nn.Module):\n' + overwrite_result __lowerCamelCase = black.Mode(target_versions={black.TargetVersion.PYaa} , line_length=1_19 ) __lowerCamelCase = black.format_str(UpperCamelCase_ , mode=UpperCamelCase_ ) __lowerCamelCase = os.path.join(self.transformer_dir , """new_code.py""" ) with open(UpperCamelCase_ , """w""" , newline="""\n""" ) as f: f.write(UpperCamelCase_ ) if overwrite_result is None: self.assertTrue(len(check_copies.is_copy_consistent(UpperCamelCase_ ) ) == 0 ) else: check_copies.is_copy_consistent(f.name , overwrite=UpperCamelCase_ ) with open(UpperCamelCase_ , """r""" ) as f: self.assertTrue(f.read() , UpperCamelCase_ ) def lowerCAmelCase__ ( self: Union[str, Any] ): __lowerCamelCase = check_copies.find_code_in_transformers("""models.bert.modeling_bert.BertLMPredictionHead""" ) self.assertEqual(UpperCamelCase_ , UpperCamelCase_ ) def lowerCAmelCase__ ( self: Dict ): # Base copy consistency self.check_copy_consistency( """# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead""" , """BertLMPredictionHead""" , REFERENCE_CODE + """\n""" , ) # With no empty line at the end self.check_copy_consistency( """# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead""" , """BertLMPredictionHead""" , UpperCamelCase_ , ) # Copy consistency with rename self.check_copy_consistency( """# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead with Bert->TestModel""" , """TestModelLMPredictionHead""" , re.sub("""Bert""" , """TestModel""" , UpperCamelCase_ ) , ) # Copy consistency with a really long name __lowerCamelCase = """TestModelWithAReallyLongNameBecauseSomePeopleLikeThatForSomeReason""" self.check_copy_consistency( F'# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead with Bert->{long_class_name}' , F'{long_class_name}LMPredictionHead' , re.sub("""Bert""" , UpperCamelCase_ , UpperCamelCase_ ) , ) # Copy consistency with overwrite self.check_copy_consistency( """# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead with Bert->TestModel""" , """TestModelLMPredictionHead""" , UpperCamelCase_ , overwrite_result=re.sub("""Bert""" , """TestModel""" , UpperCamelCase_ ) , ) def lowerCAmelCase__ ( self: Dict ): __lowerCamelCase = check_copies.LOCALIZED_READMES["""README_zh-hans.md"""] __lowerCamelCase = ( """1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (from Google Research and the""" """ Toyota Technological Institute at Chicago) released with the paper [ALBERT: A Lite BERT for""" """ Self-supervised Learning of Language Representations](https://arxiv.org/abs/1909.11942), by Zhenzhong""" """ Lan, Mingda Chen, Sebastian Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut.\n1.""" """ **[DistilBERT](https://huggingface.co/transformers/model_doc/distilbert.html)** (from HuggingFace),""" """ released together with the paper [DistilBERT, a distilled version of BERT: smaller, faster, cheaper and""" """ lighter](https://arxiv.org/abs/1910.01108) by Victor Sanh, Lysandre Debut and Thomas Wolf. The same""" """ method has been applied to compress GPT2 into""" """ [DistilGPT2](https://github.com/huggingface/transformers/tree/main/examples/distillation), RoBERTa into""" """ [DistilRoBERTa](https://github.com/huggingface/transformers/tree/main/examples/distillation),""" """ Multilingual BERT into""" """ [DistilmBERT](https://github.com/huggingface/transformers/tree/main/examples/distillation) and a German""" """ version of DistilBERT.\n1. **[ELECTRA](https://huggingface.co/transformers/model_doc/electra.html)**""" """ (from Google Research/Stanford University) released with the paper [ELECTRA: Pre-training text encoders""" """ as discriminators rather than generators](https://arxiv.org/abs/2003.10555) by Kevin Clark, Minh-Thang""" """ Luong, Quoc V. Le, Christopher D. Manning.""" ) __lowerCamelCase = ( """1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (来自 Google Research and the""" """ Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of""" """ Language Representations](https://arxiv.org/abs/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian""" """ Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n""" ) __lowerCamelCase = ( """1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (来自 Google Research and the""" """ Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of""" """ Language Representations](https://arxiv.org/abs/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian""" """ Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n1.""" """ **[DistilBERT](https://huggingface.co/transformers/model_doc/distilbert.html)** (来自 HuggingFace) 伴随论文""" """ [DistilBERT, a distilled version of BERT: smaller, faster, cheaper and""" """ lighter](https://arxiv.org/abs/1910.01108) 由 Victor Sanh, Lysandre Debut and Thomas Wolf 发布。 The same""" """ method has been applied to compress GPT2 into""" """ [DistilGPT2](https://github.com/huggingface/transformers/tree/main/examples/distillation), RoBERTa into""" """ [DistilRoBERTa](https://github.com/huggingface/transformers/tree/main/examples/distillation),""" """ Multilingual BERT into""" """ [DistilmBERT](https://github.com/huggingface/transformers/tree/main/examples/distillation) and a German""" """ version of DistilBERT.\n1. **[ELECTRA](https://huggingface.co/transformers/model_doc/electra.html)** (来自""" """ Google Research/Stanford University) 伴随论文 [ELECTRA: Pre-training text encoders as discriminators rather""" """ than generators](https://arxiv.org/abs/2003.10555) 由 Kevin Clark, Minh-Thang Luong, Quoc V. Le,""" """ Christopher D. Manning 发布。\n""" ) __lowerCamelCase, __lowerCamelCase = check_copies.convert_to_localized_md( UpperCamelCase_ , UpperCamelCase_ , localized_readme["""format_model_list"""] ) self.assertFalse(UpperCamelCase_ ) self.assertEqual(UpperCamelCase_ , UpperCamelCase_ ) __lowerCamelCase, __lowerCamelCase = check_copies.convert_to_localized_md( UpperCamelCase_ , UpperCamelCase_ , localized_readme["""format_model_list"""] ) # Check whether the number of models is equal to README.md after conversion. self.assertTrue(UpperCamelCase_ ) __lowerCamelCase = ( """1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (from Google Research and the""" """ Toyota Technological Institute at Chicago) released with the paper [ALBERT: A Lite BERT for""" """ Self-supervised Learning of Language Representations](https://arxiv.org/abs/1909.11942), by Zhenzhong""" """ Lan, Mingda Chen, Sebastian Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut.""" ) __lowerCamelCase = ( """1. **[ALBERT](https://huggingface.co/transformers/main/model_doc/albert.html)** (来自 Google Research and""" """ the Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of""" """ Language Representations](https://arxiv.org/abs/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian""" """ Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n""" ) __lowerCamelCase = ( """1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (来自 Google Research and the""" """ Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of""" """ Language Representations](https://arxiv.org/abs/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian""" """ Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n""" ) __lowerCamelCase, __lowerCamelCase = check_copies.convert_to_localized_md( UpperCamelCase_ , UpperCamelCase_ , localized_readme["""format_model_list"""] ) # Check if the model link is synchronized. self.assertEqual(UpperCamelCase_ , UpperCamelCase_ )
12
import os from distutils.util import strtobool def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Tuple: '''simple docstring''' for e in env_keys: SCREAMING_SNAKE_CASE = int(os.environ.get(_SCREAMING_SNAKE_CASE , -1 ) ) if val >= 0: return val return default def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=False ) -> Optional[int]: '''simple docstring''' SCREAMING_SNAKE_CASE = os.environ.get(_SCREAMING_SNAKE_CASE , str(_SCREAMING_SNAKE_CASE ) ) return strtobool(_SCREAMING_SNAKE_CASE ) == 1 # As its name indicates `strtobool` actually returns an int... def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE="no" ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE = os.environ.get(_SCREAMING_SNAKE_CASE , str(_SCREAMING_SNAKE_CASE ) ) return value
296
0
# We ignore warnings about stepping the scheduler since we step it ourselves during gradient accumulation import warnings from .state import AcceleratorState, GradientState warnings.filterwarnings("""ignore""", category=UserWarning, module="""torch.optim.lr_scheduler""") class __lowercase : """simple docstring""" def __init__( self : Tuple , lowerCAmelCase__ : Optional[int] , lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : bool = True , lowerCAmelCase__ : bool = False): SCREAMING_SNAKE_CASE_: Any = scheduler SCREAMING_SNAKE_CASE_: List[str] = optimizers if isinstance(lowerCAmelCase__ , (list, tuple)) else [optimizers] SCREAMING_SNAKE_CASE_: str = split_batches SCREAMING_SNAKE_CASE_: Optional[Any] = step_with_optimizer SCREAMING_SNAKE_CASE_: Dict = GradientState() def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] , *lowerCAmelCase__ : Tuple , **lowerCAmelCase__ : List[Any]): if not self.step_with_optimizer: # No link between scheduler and optimizer -> just step self.scheduler.step(*lowerCAmelCase__ , **lowerCAmelCase__) return # Otherwise, first make sure the optimizer was stepped. if not self.gradient_state.sync_gradients: if self.gradient_state.adjust_scheduler: self.scheduler._step_count += 1 return for opt in self.optimizers: if opt.step_was_skipped: return if self.split_batches: # Split batches -> the training dataloader batch size is not changed so one step per training step self.scheduler.step(*lowerCAmelCase__ , **lowerCAmelCase__) else: # Otherwise the training dataloader batch size was multiplied by `num_processes`, so we need to do # num_processes steps per training step SCREAMING_SNAKE_CASE_: Union[str, Any] = AcceleratorState().num_processes for _ in range(lowerCAmelCase__): # Special case when using OneCycle and `drop_last` was not used if hasattr(self.scheduler , "total_steps"): if self.scheduler._step_count <= self.scheduler.total_steps: self.scheduler.step(*lowerCAmelCase__ , **lowerCAmelCase__) else: self.scheduler.step(*lowerCAmelCase__ , **lowerCAmelCase__) def _SCREAMING_SNAKE_CASE ( self : str): return self.scheduler.get_last_lr() def _SCREAMING_SNAKE_CASE ( self : Dict): return self.scheduler.state_dict() def _SCREAMING_SNAKE_CASE ( self : Dict , lowerCAmelCase__ : Optional[Any]): self.scheduler.load_state_dict(lowerCAmelCase__) def _SCREAMING_SNAKE_CASE ( self : List[Any]): return self.scheduler.get_lr() def _SCREAMING_SNAKE_CASE ( self : Optional[int] , *lowerCAmelCase__ : List[str] , **lowerCAmelCase__ : Optional[int]): return self.scheduler.print_lr(*lowerCAmelCase__ , **lowerCAmelCase__)
13
import dataclasses import json import warnings from dataclasses import dataclass, field from time import time from typing import List from ..utils import logging SCREAMING_SNAKE_CASE_ = logging.get_logger(__name__) def __lowercase ( _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None ) -> List[str]: '''simple docstring''' return field(default_factory=lambda: default , metadata=_SCREAMING_SNAKE_CASE ) @dataclass class UpperCamelCase__ : '''simple docstring''' __snake_case : 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" ) } , ) __snake_case : List[int] = list_field( default=[8] , metadata={"help": "List of batch sizes for which memory and time performance will be evaluated"} ) __snake_case : List[int] = list_field( default=[8, 32, 128, 512] , metadata={"help": "List of sequence lengths for which memory and time performance will be evaluated"} , ) __snake_case : bool = field( default=lowerCAmelCase_ , metadata={"help": "Whether to benchmark inference of model. Inference can be disabled via --no-inference."} , ) __snake_case : bool = field( default=lowerCAmelCase_ , metadata={"help": "Whether to run on available cuda devices. Cuda can be disabled via --no-cuda."} , ) __snake_case : bool = field( default=lowerCAmelCase_ , metadata={"help": "Whether to run on available tpu devices. TPU can be disabled via --no-tpu."} ) __snake_case : bool = field(default=lowerCAmelCase_ , metadata={"help": "Use FP16 to accelerate inference."} ) __snake_case : bool = field(default=lowerCAmelCase_ , metadata={"help": "Benchmark training of model"} ) __snake_case : bool = field(default=lowerCAmelCase_ , metadata={"help": "Verbose memory tracing"} ) __snake_case : bool = field( default=lowerCAmelCase_ , metadata={"help": "Whether to perform speed measurements. Speed measurements can be disabled via --no-speed."} , ) __snake_case : bool = field( default=lowerCAmelCase_ , metadata={ "help": "Whether to perform memory measurements. Memory measurements can be disabled via --no-memory" } , ) __snake_case : bool = field(default=lowerCAmelCase_ , metadata={"help": "Trace memory line by line"} ) __snake_case : bool = field(default=lowerCAmelCase_ , metadata={"help": "Save result to a CSV file"} ) __snake_case : bool = field(default=lowerCAmelCase_ , metadata={"help": "Save all print statements in a log file"} ) __snake_case : bool = field(default=lowerCAmelCase_ , metadata={"help": "Whether to print environment information"} ) __snake_case : bool = field( default=lowerCAmelCase_ , 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." ) } , ) __snake_case : str = field( default=F"inference_time_{round(time() )}.csv" , metadata={"help": "CSV filename used if saving time results to csv."} , ) __snake_case : str = field( default=F"inference_memory_{round(time() )}.csv" , metadata={"help": "CSV filename used if saving memory results to csv."} , ) __snake_case : str = field( default=F"train_time_{round(time() )}.csv" , metadata={"help": "CSV filename used if saving time results to csv for training."} , ) __snake_case : str = field( default=F"train_memory_{round(time() )}.csv" , metadata={"help": "CSV filename used if saving memory results to csv for training."} , ) __snake_case : str = field( default=F"env_info_{round(time() )}.csv" , metadata={"help": "CSV filename used if saving environment information."} , ) __snake_case : str = field( default=F"log_{round(time() )}.csv" , metadata={"help": "Log filename used if print statements are saved in log."} , ) __snake_case : int = field(default=3 , metadata={"help": "Times an experiment will be run."} ) __snake_case : bool = field( default=lowerCAmelCase_ , metadata={ "help": ( "Instead of loading the model as defined in `config.architectures` if exists, just load the pretrain" " model weights." ) } , ) def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ) -> Dict: '''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 SCREAMING_SNAKE_CASE__ ( self : Optional[int] ) -> Any: '''simple docstring''' return json.dumps(dataclasses.asdict(self ) ,indent=2 ) @property def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ) -> List[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 SCREAMING_SNAKE_CASE__ ( self : Optional[int] ) -> int: '''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
296
0
import argparse import os import re _lowerCamelCase : List[str] = """src/transformers""" # Pattern that looks at the indentation in a line. _lowerCamelCase : Optional[Any] = re.compile(r"""^(\s*)\S""") # Pattern that matches `"key":" and puts `key` in group 0. _lowerCamelCase : Tuple = re.compile(r"""^\s*\"([^\"]+)\":""") # Pattern that matches `_import_structure["key"]` and puts `key` in group 0. _lowerCamelCase : List[str] = re.compile(r"""^\s*_import_structure\[\"([^\"]+)\"\]""") # Pattern that matches `"key",` and puts `key` in group 0. _lowerCamelCase : str = re.compile(r"""^\s*\"([^\"]+)\",\s*$""") # Pattern that matches any `[stuff]` and puts `stuff` in group 0. _lowerCamelCase : Any = re.compile(r"""\[([^\]]+)\]""") def SCREAMING_SNAKE_CASE ( lowercase_ ) -> int: """simple docstring""" A__ = _re_indent.search(lowercase_ ) return "" if search is None else search.groups()[0] def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_="" , lowercase_=None , lowercase_=None ) -> List[str]: """simple docstring""" A__ = 0 A__ = code.split('''\n''' ) if start_prompt is not None: while not lines[index].startswith(lowercase_ ): index += 1 A__ = ['''\n'''.join(lines[:index] )] else: A__ = [] # We split into blocks until we get to the `end_prompt` (or the end of the block). A__ = [lines[index]] index += 1 while index < len(lowercase_ ) and (end_prompt is None or not lines[index].startswith(lowercase_ )): if len(lines[index] ) > 0 and get_indent(lines[index] ) == indent_level: if len(lowercase_ ) > 0 and get_indent(current_block[-1] ).startswith(indent_level + ''' ''' ): current_block.append(lines[index] ) blocks.append('''\n'''.join(lowercase_ ) ) if index < len(lowercase_ ) - 1: A__ = [lines[index + 1]] index += 1 else: A__ = [] else: blocks.append('''\n'''.join(lowercase_ ) ) A__ = [lines[index]] else: current_block.append(lines[index] ) index += 1 # Adds current block if it's nonempty. if len(lowercase_ ) > 0: blocks.append('''\n'''.join(lowercase_ ) ) # Add final block after end_prompt if provided. if end_prompt is not None and index < len(lowercase_ ): blocks.append('''\n'''.join(lines[index:] ) ) return blocks def SCREAMING_SNAKE_CASE ( lowercase_ ) -> Tuple: """simple docstring""" def _inner(lowercase_ ): return key(lowercase_ ).lower().replace('''_''' , '''''' ) return _inner def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_=None ) -> int: """simple docstring""" def noop(lowercase_ ): return x if key is None: A__ = noop # Constants are all uppercase, they go first. A__ = [obj for obj in objects if key(lowercase_ ).isupper()] # Classes are not all uppercase but start with a capital, they go second. A__ = [obj for obj in objects if key(lowercase_ )[0].isupper() and not key(lowercase_ ).isupper()] # Functions begin with a lowercase, they go last. A__ = [obj for obj in objects if not key(lowercase_ )[0].isupper()] A__ = ignore_underscore(lowercase_ ) return sorted(lowercase_ , key=lowercase_ ) + sorted(lowercase_ , key=lowercase_ ) + sorted(lowercase_ , key=lowercase_ ) def SCREAMING_SNAKE_CASE ( lowercase_ ) -> Tuple: """simple docstring""" def _replace(lowercase_ ): A__ = match.groups()[0] if "," not in imports: return f"""[{imports}]""" A__ = [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__ = keys[:-1] return "[" + ", ".join([f"""\"{k}\"""" for k in sort_objects(lowercase_ )] ) + "]" A__ = import_statement.split('''\n''' ) if len(lowercase_ ) > 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__ = 2 if lines[1].strip() == '''[''' else 1 A__ = [(i, _re_strip_line.search(lowercase_ ).groups()[0]) for i, line in enumerate(lines[idx:-idx] )] A__ = sort_objects(lowercase_ , key=lambda lowercase_ : x[1] ) A__ = [lines[x[0] + idx] for x in sorted_indices] return "\n".join(lines[:idx] + sorted_lines + lines[-idx:] ) elif len(lowercase_ ) == 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__ = _re_bracket_content.sub(_replace , lines[1] ) else: A__ = [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__ = keys[:-1] A__ = get_indent(lines[1] ) + ''', '''.join([f"""\"{k}\"""" for k in sort_objects(lowercase_ )] ) return "\n".join(lowercase_ ) else: # Finally we have to deal with imports fitting on one line A__ = _re_bracket_content.sub(_replace , lowercase_ ) return import_statement def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_=True ) -> Dict: """simple docstring""" with open(lowercase_ , encoding='''utf-8''' ) as f: A__ = f.read() if "_import_structure" not in code: return # Blocks of indent level 0 A__ = split_code_in_indented_blocks( lowercase_ , 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(lowercase_ ) - 1 ): # Check if the block contains some `_import_structure`s thingy to sort. A__ = main_blocks[block_idx] A__ = block.split('''\n''' ) # Get to the start of the imports. A__ = 0 while line_idx < len(lowercase_ ) and "_import_structure" not in block_lines[line_idx]: # Skip dummy import blocks if "import dummy" in block_lines[line_idx]: A__ = len(lowercase_ ) else: line_idx += 1 if line_idx >= len(lowercase_ ): continue # Ignore beginning and last line: they don't contain anything. A__ = '''\n'''.join(block_lines[line_idx:-1] ) A__ = get_indent(block_lines[1] ) # Slit the internal block into blocks of indent level 1. A__ = split_code_in_indented_blocks(lowercase_ , indent_level=lowercase_ ) # We have two categories of import key: list or _import_structure[key].append/extend A__ = _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__ = [(pattern.search(lowercase_ ).groups()[0] if pattern.search(lowercase_ ) is not None else None) for b in internal_blocks] # We only sort the lines with a key. A__ = [(i, key) for i, key in enumerate(lowercase_ ) if key is not None] A__ = [x[0] for x in sorted(lowercase_ , key=lambda lowercase_ : x[1] )] # We reorder the blocks by leaving empty lines/comments as they were and reorder the rest. A__ = 0 A__ = [] for i in range(len(lowercase_ ) ): if keys[i] is None: reorderded_blocks.append(internal_blocks[i] ) else: A__ = sort_objects_in_import(internal_blocks[sorted_indices[count]] ) reorderded_blocks.append(lowercase_ ) count += 1 # And we put our main block back together with its first and last line. A__ = '''\n'''.join(block_lines[:line_idx] + reorderded_blocks + [block_lines[-1]] ) if code != "\n".join(lowercase_ ): if check_only: return True else: print(f"""Overwriting {file}.""" ) with open(lowercase_ , '''w''' , encoding='''utf-8''' ) as f: f.write('''\n'''.join(lowercase_ ) ) def SCREAMING_SNAKE_CASE ( lowercase_=True ) -> int: """simple docstring""" A__ = [] for root, _, files in os.walk(lowercase_ ): if "__init__.py" in files: A__ = sort_imports(os.path.join(lowercase_ , '''__init__.py''' ) , check_only=lowercase_ ) if result: A__ = [os.path.join(lowercase_ , '''__init__.py''' )] if len(lowercase_ ) > 0: raise ValueError(f"""Would overwrite {len(lowercase_ )} files, run `make style`.""" ) if __name__ == "__main__": _lowerCamelCase : Optional[Any] = argparse.ArgumentParser() parser.add_argument("""--check_only""", action="""store_true""", help="""Whether to only check or fix style.""") _lowerCamelCase : Optional[Any] = parser.parse_args() sort_imports_in_all_inits(check_only=args.check_only)
14
import math import unittest def __lowercase ( _SCREAMING_SNAKE_CASE ) -> bool: '''simple docstring''' assert isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) and ( number >= 0 ), "'number' must been an int and positive" if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(math.sqrt(_SCREAMING_SNAKE_CASE ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True class UpperCamelCase__ ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE__ ( self : Dict ) -> Tuple: '''simple docstring''' self.assertTrue(is_prime(2 ) ) self.assertTrue(is_prime(3 ) ) self.assertTrue(is_prime(5 ) ) self.assertTrue(is_prime(7 ) ) self.assertTrue(is_prime(11 ) ) self.assertTrue(is_prime(13 ) ) self.assertTrue(is_prime(17 ) ) self.assertTrue(is_prime(19 ) ) self.assertTrue(is_prime(23 ) ) self.assertTrue(is_prime(29 ) ) def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ) -> Tuple: '''simple docstring''' with self.assertRaises(lowerCamelCase__ ): is_prime(-19 ) self.assertFalse( is_prime(0 ) ,"""Zero doesn't have any positive factors, primes must have exactly two.""" ,) self.assertFalse( is_prime(1 ) ,"""One only has 1 positive factor, primes must have exactly two.""" ,) self.assertFalse(is_prime(2 * 2 ) ) self.assertFalse(is_prime(2 * 3 ) ) self.assertFalse(is_prime(3 * 3 ) ) self.assertFalse(is_prime(3 * 5 ) ) self.assertFalse(is_prime(3 * 5 * 7 ) ) if __name__ == "__main__": unittest.main()
296
0
# Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available SCREAMING_SNAKE_CASE :List[str] = {'configuration_mra': ['MRA_PRETRAINED_CONFIG_ARCHIVE_MAP', 'MraConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE :List[str] = [ 'MRA_PRETRAINED_MODEL_ARCHIVE_LIST', 'MraForMaskedLM', 'MraForMultipleChoice', 'MraForQuestionAnswering', 'MraForSequenceClassification', 'MraForTokenClassification', 'MraLayer', 'MraModel', 'MraPreTrainedModel', ] if TYPE_CHECKING: from .configuration_mra import MRA_PRETRAINED_CONFIG_ARCHIVE_MAP, MraConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mra import ( MRA_PRETRAINED_MODEL_ARCHIVE_LIST, MraForMaskedLM, MraForMultipleChoice, MraForQuestionAnswering, MraForSequenceClassification, MraForTokenClassification, MraLayer, MraModel, MraPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE :List[str] = _LazyModule(__name__, globals()['__file__'], _import_structure)
15
import random class UpperCamelCase__ : '''simple docstring''' @staticmethod def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ : str ) -> tuple[list[int], list[int]]: '''simple docstring''' SCREAMING_SNAKE_CASE = [ord(lowerCamelCase__ ) for i in text] SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = [] for i in plain: SCREAMING_SNAKE_CASE = random.randint(1 ,300 ) SCREAMING_SNAKE_CASE = (i + k) * k cipher.append(lowerCamelCase__ ) key.append(lowerCamelCase__ ) return cipher, key @staticmethod def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ : list[int] ,lowerCamelCase__ : list[int] ) -> str: '''simple docstring''' SCREAMING_SNAKE_CASE = [] for i in range(len(lowerCamelCase__ ) ): SCREAMING_SNAKE_CASE = int((cipher[i] - (key[i]) ** 2) / key[i] ) plain.append(chr(lowerCamelCase__ ) ) return "".join(lowerCamelCase__ ) if __name__ == "__main__": SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = Onepad().encrypt("""Hello""") print(c, k) print(Onepad().decrypt(c, k))
296
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, is_vision_available, ) lowerCAmelCase_ = { 'configuration_owlvit': [ 'OWLVIT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'OwlViTConfig', 'OwlViTOnnxConfig', 'OwlViTTextConfig', 'OwlViTVisionConfig', ], 'processing_owlvit': ['OwlViTProcessor'], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ = ['OwlViTFeatureExtractor'] lowerCAmelCase_ = ['OwlViTImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ = [ 'OWLVIT_PRETRAINED_MODEL_ARCHIVE_LIST', 'OwlViTModel', 'OwlViTPreTrainedModel', 'OwlViTTextModel', 'OwlViTVisionModel', 'OwlViTForObjectDetection', ] if TYPE_CHECKING: from .configuration_owlvit import ( OWLVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, OwlViTConfig, OwlViTOnnxConfig, OwlViTTextConfig, OwlViTVisionConfig, ) from .processing_owlvit import OwlViTProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_owlvit import OwlViTFeatureExtractor from .image_processing_owlvit import OwlViTImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_owlvit import ( OWLVIT_PRETRAINED_MODEL_ARCHIVE_LIST, OwlViTForObjectDetection, OwlViTModel, OwlViTPreTrainedModel, OwlViTTextModel, OwlViTVisionModel, ) else: import sys lowerCAmelCase_ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
16
from typing import List from ...configuration_utils import PretrainedConfig from ...utils import logging SCREAMING_SNAKE_CASE_ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE_ = { """snap-research/efficientformer-l1-300""": ( """https://huggingface.co/snap-research/efficientformer-l1-300/resolve/main/config.json""" ), } class UpperCamelCase__ ( lowerCAmelCase_ ): '''simple docstring''' __snake_case : int = "efficientformer" def __init__( self : Optional[int] ,lowerCamelCase__ : List[int] = [3, 2, 6, 4] ,lowerCamelCase__ : List[int] = [48, 96, 224, 448] ,lowerCamelCase__ : List[bool] = [True, True, True, True] ,lowerCamelCase__ : int = 448 ,lowerCamelCase__ : int = 32 ,lowerCamelCase__ : int = 4 ,lowerCamelCase__ : int = 7 ,lowerCamelCase__ : int = 5 ,lowerCamelCase__ : int = 8 ,lowerCamelCase__ : int = 4 ,lowerCamelCase__ : float = 0.0 ,lowerCamelCase__ : int = 16 ,lowerCamelCase__ : int = 3 ,lowerCamelCase__ : int = 3 ,lowerCamelCase__ : int = 3 ,lowerCamelCase__ : int = 2 ,lowerCamelCase__ : int = 1 ,lowerCamelCase__ : float = 0.0 ,lowerCamelCase__ : int = 1 ,lowerCamelCase__ : bool = True ,lowerCamelCase__ : bool = True ,lowerCamelCase__ : float = 1e-5 ,lowerCamelCase__ : str = "gelu" ,lowerCamelCase__ : float = 0.02 ,lowerCamelCase__ : float = 1e-1_2 ,lowerCamelCase__ : int = 224 ,lowerCamelCase__ : float = 1e-0_5 ,**lowerCamelCase__ : str ,) -> None: '''simple docstring''' super().__init__(**lowerCamelCase__ ) SCREAMING_SNAKE_CASE = hidden_act SCREAMING_SNAKE_CASE = hidden_dropout_prob SCREAMING_SNAKE_CASE = hidden_sizes SCREAMING_SNAKE_CASE = num_hidden_layers SCREAMING_SNAKE_CASE = num_attention_heads SCREAMING_SNAKE_CASE = initializer_range SCREAMING_SNAKE_CASE = layer_norm_eps SCREAMING_SNAKE_CASE = patch_size SCREAMING_SNAKE_CASE = num_channels SCREAMING_SNAKE_CASE = depths SCREAMING_SNAKE_CASE = mlp_expansion_ratio SCREAMING_SNAKE_CASE = downsamples SCREAMING_SNAKE_CASE = dim SCREAMING_SNAKE_CASE = key_dim SCREAMING_SNAKE_CASE = attention_ratio SCREAMING_SNAKE_CASE = resolution SCREAMING_SNAKE_CASE = pool_size SCREAMING_SNAKE_CASE = downsample_patch_size SCREAMING_SNAKE_CASE = downsample_stride SCREAMING_SNAKE_CASE = downsample_pad SCREAMING_SNAKE_CASE = drop_path_rate SCREAMING_SNAKE_CASE = num_metaad_blocks SCREAMING_SNAKE_CASE = distillation SCREAMING_SNAKE_CASE = use_layer_scale SCREAMING_SNAKE_CASE = layer_scale_init_value SCREAMING_SNAKE_CASE = image_size SCREAMING_SNAKE_CASE = batch_norm_eps
296
0
"""simple docstring""" from ...configuration_utils import PretrainedConfig _a = { '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 ( lowercase ): """simple docstring""" __UpperCAmelCase : Union[str, Any] = "tapas" def __init__( self : int, UpperCAmelCase__ : List[Any]=3_0_5_2_2, UpperCAmelCase__ : Any=7_6_8, UpperCAmelCase__ : Tuple=1_2, UpperCAmelCase__ : str=1_2, UpperCAmelCase__ : Union[str, Any]=3_0_7_2, UpperCAmelCase__ : Union[str, Any]="gelu", UpperCAmelCase__ : Dict=0.1, UpperCAmelCase__ : Union[str, Any]=0.1, UpperCAmelCase__ : Optional[int]=1_0_2_4, UpperCAmelCase__ : Optional[Any]=[3, 2_5_6, 2_5_6, 2, 2_5_6, 2_5_6, 1_0], UpperCAmelCase__ : Dict=0.02, UpperCAmelCase__ : str=1E-12, UpperCAmelCase__ : int=0, UpperCAmelCase__ : Optional[Any]=10.0, UpperCAmelCase__ : Union[str, Any]=0, UpperCAmelCase__ : Any=1.0, UpperCAmelCase__ : List[Any]=None, UpperCAmelCase__ : Any=1.0, UpperCAmelCase__ : Union[str, Any]=False, UpperCAmelCase__ : Union[str, Any]=None, UpperCAmelCase__ : Union[str, Any]=1.0, UpperCAmelCase__ : Optional[Any]=1.0, UpperCAmelCase__ : Optional[Any]=False, UpperCAmelCase__ : str=False, UpperCAmelCase__ : List[str]="ratio", UpperCAmelCase__ : Optional[Any]=None, UpperCAmelCase__ : Dict=None, UpperCAmelCase__ : Optional[Any]=6_4, UpperCAmelCase__ : Dict=3_2, UpperCAmelCase__ : Any=False, UpperCAmelCase__ : List[str]=True, UpperCAmelCase__ : Optional[Any]=False, UpperCAmelCase__ : Optional[Any]=False, UpperCAmelCase__ : Any=True, UpperCAmelCase__ : Union[str, Any]=False, UpperCAmelCase__ : str=None, UpperCAmelCase__ : int=None, **UpperCAmelCase__ : Optional[int], ): super().__init__(pad_token_id=UpperCAmelCase__, **UpperCAmelCase__ ) # BERT hyperparameters (with updated max_position_embeddings and type_vocab_sizes) __lowercase = vocab_size __lowercase = hidden_size __lowercase = num_hidden_layers __lowercase = num_attention_heads __lowercase = hidden_act __lowercase = intermediate_size __lowercase = hidden_dropout_prob __lowercase = attention_probs_dropout_prob __lowercase = max_position_embeddings __lowercase = type_vocab_sizes __lowercase = initializer_range __lowercase = layer_norm_eps # Fine-tuning task hyperparameters __lowercase = positive_label_weight __lowercase = num_aggregation_labels __lowercase = aggregation_loss_weight __lowercase = use_answer_as_supervision __lowercase = answer_loss_importance __lowercase = use_normalized_answer_loss __lowercase = huber_loss_delta __lowercase = temperature __lowercase = aggregation_temperature __lowercase = use_gumbel_for_cells __lowercase = use_gumbel_for_aggregation __lowercase = average_approximation_function __lowercase = cell_selection_preference __lowercase = answer_loss_cutoff __lowercase = max_num_rows __lowercase = max_num_columns __lowercase = average_logits_per_cell __lowercase = select_one_column __lowercase = allow_empty_column_selection __lowercase = init_cell_selection_weights_to_zero __lowercase = reset_position_index_per_cell __lowercase = disable_per_token_loss # Aggregation hyperparameters __lowercase = aggregation_labels __lowercase = no_aggregation_label_index if isinstance(self.aggregation_labels, UpperCAmelCase__ ): __lowercase = {int(UpperCAmelCase__ ): v for k, v in aggregation_labels.items()}
17
import importlib import shutil import threading import warnings from typing import List import fsspec import fsspec.asyn from . import compression from .hffilesystem import HfFileSystem SCREAMING_SNAKE_CASE_ = importlib.util.find_spec("""s3fs""") is not None if _has_safs: from .safilesystem import SaFileSystem # noqa: F401 SCREAMING_SNAKE_CASE_ = [ compression.BzaFileSystem, compression.GzipFileSystem, compression.LzaFileSystem, compression.XzFileSystem, compression.ZstdFileSystem, ] # Register custom filesystems for fs_class in COMPRESSION_FILESYSTEMS + [HfFileSystem]: if fs_class.protocol in fsspec.registry and fsspec.registry[fs_class.protocol] is not fs_class: warnings.warn(F'''A filesystem protocol was already set for {fs_class.protocol} and will be overwritten.''') fsspec.register_implementation(fs_class.protocol, fs_class, clobber=True) def __lowercase ( _SCREAMING_SNAKE_CASE ) -> str: '''simple docstring''' if "://" in dataset_path: SCREAMING_SNAKE_CASE = dataset_path.split("""://""" )[1] return dataset_path def __lowercase ( _SCREAMING_SNAKE_CASE ) -> bool: '''simple docstring''' if fs is not None and fs.protocol != "file": return True else: return False def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Dict: '''simple docstring''' SCREAMING_SNAKE_CASE = not is_remote_filesystem(_SCREAMING_SNAKE_CASE ) if is_local: # LocalFileSystem.mv does copy + rm, it is more efficient to simply move a local directory shutil.move(fs._strip_protocol(_SCREAMING_SNAKE_CASE ) , fs._strip_protocol(_SCREAMING_SNAKE_CASE ) ) else: fs.mv(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , recursive=_SCREAMING_SNAKE_CASE ) def __lowercase ( ) -> None: '''simple docstring''' if hasattr(fsspec.asyn , """reset_lock""" ): # for future fsspec>2022.05.0 fsspec.asyn.reset_lock() else: SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = threading.Lock()
296
0
import math def _snake_case ( lowerCAmelCase : float , lowerCAmelCase : float ): """simple docstring""" if initial_intensity < 0: raise ValueError("The value of intensity cannot be negative" ) # handling of negative values of initial intensity if angle < 0 or angle > 3_6_0: raise ValueError("In Malus Law, the angle is in the range 0-360 degrees" ) # handling of values out of allowed range return initial_intensity * (math.cos(math.radians(lowerCAmelCase ) ) ** 2) if __name__ == "__main__": import doctest doctest.testmod(name='''malus_law''')
18
import unittest import numpy as np import torch from diffusers import KarrasVePipeline, KarrasVeScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class UpperCamelCase__ ( unittest.TestCase ): '''simple docstring''' @property def SCREAMING_SNAKE_CASE__ ( self : str ) -> Optional[int]: '''simple docstring''' torch.manual_seed(0 ) SCREAMING_SNAKE_CASE = UNetaDModel( block_out_channels=(32, 64) ,layers_per_block=2 ,sample_size=32 ,in_channels=3 ,out_channels=3 ,down_block_types=("""DownBlock2D""", """AttnDownBlock2D""") ,up_block_types=("""AttnUpBlock2D""", """UpBlock2D""") ,) return model def SCREAMING_SNAKE_CASE__ ( self : Tuple ) -> Union[str, Any]: '''simple docstring''' SCREAMING_SNAKE_CASE = self.dummy_uncond_unet SCREAMING_SNAKE_CASE = KarrasVeScheduler() SCREAMING_SNAKE_CASE = KarrasVePipeline(unet=lowerCamelCase__ ,scheduler=lowerCamelCase__ ) pipe.to(lowerCamelCase__ ) pipe.set_progress_bar_config(disable=lowerCamelCase__ ) SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE = pipe(num_inference_steps=2 ,generator=lowerCamelCase__ ,output_type="""numpy""" ).images SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE = pipe(num_inference_steps=2 ,generator=lowerCamelCase__ ,output_type="""numpy""" ,return_dict=lowerCamelCase__ )[0] SCREAMING_SNAKE_CASE = image[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) SCREAMING_SNAKE_CASE = np.array([0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 @slow @require_torch class UpperCamelCase__ ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ) -> Optional[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE = """google/ncsnpp-celebahq-256""" SCREAMING_SNAKE_CASE = UNetaDModel.from_pretrained(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = KarrasVeScheduler() SCREAMING_SNAKE_CASE = KarrasVePipeline(unet=lowerCamelCase__ ,scheduler=lowerCamelCase__ ) pipe.to(lowerCamelCase__ ) pipe.set_progress_bar_config(disable=lowerCamelCase__ ) SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE = pipe(num_inference_steps=20 ,generator=lowerCamelCase__ ,output_type="""numpy""" ).images SCREAMING_SNAKE_CASE = image[0, -3:, -3:, -1] assert image.shape == (1, 256, 256, 3) SCREAMING_SNAKE_CASE = np.array([0.578, 0.5811, 0.5924, 0.5809, 0.587, 0.5886, 0.5861, 0.5802, 0.586] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
296
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) __A ={ '''configuration_blenderbot''': [ '''BLENDERBOT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''BlenderbotConfig''', '''BlenderbotOnnxConfig''', ], '''tokenization_blenderbot''': ['''BlenderbotTokenizer'''], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A =['''BlenderbotTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A =[ '''BLENDERBOT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''BlenderbotForCausalLM''', '''BlenderbotForConditionalGeneration''', '''BlenderbotModel''', '''BlenderbotPreTrainedModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A =[ '''TFBlenderbotForConditionalGeneration''', '''TFBlenderbotModel''', '''TFBlenderbotPreTrainedModel''', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A =[ '''FlaxBlenderbotForConditionalGeneration''', '''FlaxBlenderbotModel''', '''FlaxBlenderbotPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_blenderbot import ( BLENDERBOT_PRETRAINED_CONFIG_ARCHIVE_MAP, BlenderbotConfig, BlenderbotOnnxConfig, ) from .tokenization_blenderbot import BlenderbotTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_blenderbot_fast import BlenderbotTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_blenderbot import ( BLENDERBOT_PRETRAINED_MODEL_ARCHIVE_LIST, BlenderbotForCausalLM, BlenderbotForConditionalGeneration, BlenderbotModel, BlenderbotPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_blenderbot import ( TFBlenderbotForConditionalGeneration, TFBlenderbotModel, TFBlenderbotPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_blenderbot import ( FlaxBlenderbotForConditionalGeneration, FlaxBlenderbotModel, FlaxBlenderbotPreTrainedModel, ) else: import sys __A =_LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
19
from typing import Callable, Optional from .. import Features from ..packaged_modules.generator.generator import Generator from .abc import AbstractDatasetInputStream class UpperCamelCase__ ( lowerCAmelCase_ ): '''simple docstring''' def __init__( self : Union[str, Any] ,lowerCamelCase__ : Callable ,lowerCamelCase__ : Optional[Features] = None ,lowerCamelCase__ : str = None ,lowerCamelCase__ : bool = False ,lowerCamelCase__ : bool = False ,lowerCamelCase__ : Optional[dict] = None ,lowerCamelCase__ : Optional[int] = None ,**lowerCamelCase__ : Optional[Any] ,) -> List[str]: '''simple docstring''' super().__init__( features=lowerCamelCase__ ,cache_dir=lowerCamelCase__ ,keep_in_memory=lowerCamelCase__ ,streaming=lowerCamelCase__ ,num_proc=lowerCamelCase__ ,**lowerCamelCase__ ,) SCREAMING_SNAKE_CASE = Generator( cache_dir=lowerCamelCase__ ,features=lowerCamelCase__ ,generator=lowerCamelCase__ ,gen_kwargs=lowerCamelCase__ ,**lowerCamelCase__ ,) def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ) -> Optional[Any]: '''simple docstring''' if self.streaming: SCREAMING_SNAKE_CASE = self.builder.as_streaming_dataset(split="""train""" ) # Build regular (map-style) dataset else: SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = None self.builder.download_and_prepare( download_config=lowerCamelCase__ ,download_mode=lowerCamelCase__ ,verification_mode=lowerCamelCase__ ,base_path=lowerCamelCase__ ,num_proc=self.num_proc ,) SCREAMING_SNAKE_CASE = self.builder.as_dataset( split="""train""" ,verification_mode=lowerCamelCase__ ,in_memory=self.keep_in_memory ) return dataset
296
0
import logging import os from .state import PartialState class __snake_case ( logging.LoggerAdapter ): @staticmethod def _SCREAMING_SNAKE_CASE ( snake_case ): '''simple docstring''' lowercase : str = PartialState() return not main_process_only or (main_process_only and state.is_main_process) def _SCREAMING_SNAKE_CASE ( self ,snake_case ,snake_case ,*snake_case ,**snake_case ): '''simple docstring''' if PartialState._shared_state == {}: raise RuntimeError( """You must initialize the accelerate state by calling either `PartialState()` or `Accelerator()` before using the logging utility.""" ) lowercase : Any = kwargs.pop("""main_process_only""" ,snake_case ) lowercase : Any = kwargs.pop("""in_order""" ,snake_case ) if self.isEnabledFor(snake_case ): if self._should_log(snake_case ): lowercase , lowercase : Optional[int] = self.process(snake_case ,snake_case ) self.logger.log(snake_case ,snake_case ,*snake_case ,**snake_case ) elif in_order: lowercase : Any = PartialState() for i in range(state.num_processes ): if i == state.process_index: lowercase , lowercase : Union[str, Any] = self.process(snake_case ,snake_case ) self.logger.log(snake_case ,snake_case ,*snake_case ,**snake_case ) state.wait_for_everyone() def _snake_case( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = None ) -> Dict: if log_level is None: lowercase : Dict = os.environ.get("""ACCELERATE_LOG_LEVEL""" , SCREAMING_SNAKE_CASE__ ) lowercase : int = logging.getLogger(SCREAMING_SNAKE_CASE__ ) if log_level is not None: logger.setLevel(log_level.upper() ) logger.root.setLevel(log_level.upper() ) return MultiProcessAdapter(SCREAMING_SNAKE_CASE__ , {} )
20
import logging from dataclasses import dataclass, field from typing import Optional from seqaseq_trainer import arg_to_scheduler from transformers import TrainingArguments SCREAMING_SNAKE_CASE_ = logging.getLogger(__name__) @dataclass class UpperCamelCase__ ( lowerCAmelCase_ ): '''simple docstring''' __snake_case : Optional[float] = field( default=0.0 , metadata={"help": "The label smoothing epsilon to apply (if not zero)."} ) __snake_case : bool = field(default=lowerCAmelCase_ , metadata={"help": "Whether to SortishSamler or not."} ) __snake_case : bool = field( default=lowerCAmelCase_ , metadata={"help": "Whether to use generate to calculate generative metrics (ROUGE, BLEU)."} ) __snake_case : bool = field(default=lowerCAmelCase_ , metadata={"help": "whether to use adafactor"} ) __snake_case : Optional[float] = field( default=lowerCAmelCase_ , metadata={"help": "Encoder layer dropout probability. Goes into model.config."} ) __snake_case : Optional[float] = field( default=lowerCAmelCase_ , metadata={"help": "Decoder layer dropout probability. Goes into model.config."} ) __snake_case : Optional[float] = field(default=lowerCAmelCase_ , metadata={"help": "Dropout probability. Goes into model.config."} ) __snake_case : Optional[float] = field( default=lowerCAmelCase_ , metadata={"help": "Attention dropout probability. Goes into model.config."} ) __snake_case : Optional[str] = field( default="linear" , metadata={"help": F"Which lr scheduler to use. Selected in {sorted(arg_to_scheduler.keys() )}"} , )
296
0
import argparse import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType ######################################################################## # This is a fully working simple example to use Accelerate # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## SCREAMING_SNAKE_CASE : Optional[int] = 16 SCREAMING_SNAKE_CASE : List[Any] = 32 def UpperCamelCase_( lowerCamelCase_ , lowerCamelCase_ = 16 ) -> Optional[Any]: _lowercase : Optional[Any] = AutoTokenizer.from_pretrained('bert-base-cased' ) _lowercase : Any = load_dataset('glue' , 'mrpc' ) def tokenize_function(lowerCamelCase_ ): # max_length=None => use the model max length (it's actually the default) _lowercase : Any = tokenizer(examples['sentence1'] , examples['sentence2'] , truncation=lowerCamelCase_ , max_length=lowerCamelCase_ ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): _lowercase : Union[str, Any] = datasets.map( lowerCamelCase_ , batched=lowerCamelCase_ , remove_columns=['idx', 'sentence1', 'sentence2'] , ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library _lowercase : Tuple = tokenized_datasets.rename_column('label' , 'labels' ) def collate_fn(lowerCamelCase_ ): # On TPU it's best to pad everything to the same length or training will be very slow. _lowercase : str = 128 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": _lowercase : Union[str, Any] = 16 elif accelerator.mixed_precision != "no": _lowercase : Any = 8 else: _lowercase : List[Any] = None return tokenizer.pad( lowerCamelCase_ , padding='longest' , max_length=lowerCamelCase_ , pad_to_multiple_of=lowerCamelCase_ , return_tensors='pt' , ) # Instantiate dataloaders. _lowercase : str = DataLoader( tokenized_datasets['train'] , shuffle=lowerCamelCase_ , collate_fn=lowerCamelCase_ , batch_size=lowerCamelCase_ , drop_last=lowerCamelCase_ ) _lowercase : str = DataLoader( tokenized_datasets['validation'] , shuffle=lowerCamelCase_ , collate_fn=lowerCamelCase_ , batch_size=lowerCamelCase_ , drop_last=(accelerator.mixed_precision == 'fp8') , ) return train_dataloader, eval_dataloader def UpperCamelCase_( lowerCamelCase_ , lowerCamelCase_ ) -> Optional[int]: # Initialize accelerator _lowercase : Union[str, Any] = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs _lowercase : Tuple = config['lr'] _lowercase : Any = int(config['num_epochs'] ) _lowercase : Optional[int] = int(config['seed'] ) _lowercase : List[str] = int(config['batch_size'] ) _lowercase : List[Any] = evaluate.load('glue' , 'mrpc' ) # If the batch size is too big we use gradient accumulation _lowercase : Any = 1 if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU: _lowercase : List[str] = batch_size // MAX_GPU_BATCH_SIZE _lowercase : Any = MAX_GPU_BATCH_SIZE set_seed(lowerCamelCase_ ) _lowercase , _lowercase : Optional[int] = get_dataloaders(lowerCamelCase_ , lowerCamelCase_ ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) _lowercase : List[Any] = AutoModelForSequenceClassification.from_pretrained('bert-base-cased' , return_dict=lowerCamelCase_ ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). _lowercase : Optional[Any] = model.to(accelerator.device ) # Instantiate optimizer _lowercase : str = AdamW(params=model.parameters() , lr=lowerCamelCase_ ) # Instantiate scheduler _lowercase : Optional[Any] = get_linear_schedule_with_warmup( optimizer=lowerCamelCase_ , num_warmup_steps=100 , num_training_steps=(len(lowerCamelCase_ ) * num_epochs) // gradient_accumulation_steps , ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. _lowercase , _lowercase , _lowercase , _lowercase , _lowercase : int = accelerator.prepare( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) # Now we train the model for epoch in range(lowerCamelCase_ ): model.train() for step, batch in enumerate(lowerCamelCase_ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) _lowercase : str = model(**lowerCamelCase_ ) _lowercase : Tuple = outputs.loss _lowercase : str = loss / gradient_accumulation_steps accelerator.backward(lowerCamelCase_ ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(lowerCamelCase_ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): _lowercase : List[str] = model(**lowerCamelCase_ ) _lowercase : Dict = outputs.logits.argmax(dim=-1 ) _lowercase , _lowercase : str = accelerator.gather_for_metrics((predictions, batch['labels']) ) metric.add_batch( predictions=lowerCamelCase_ , references=lowerCamelCase_ , ) _lowercase : Any = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F'''epoch {epoch}:''' , lowerCamelCase_ ) def UpperCamelCase_( ) -> Tuple: _lowercase : List[Any] = argparse.ArgumentParser(description='Simple example of training script.' ) parser.add_argument( '--mixed_precision' , type=lowerCamelCase_ , default=lowerCamelCase_ , choices=['no', 'fp16', 'bf16', 'fp8'] , help='Whether to use mixed precision. Choose' 'between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.' 'and an Nvidia Ampere GPU.' , ) parser.add_argument('--cpu' , action='store_true' , help='If passed, will train on the CPU.' ) _lowercase : Optional[int] = parser.parse_args() _lowercase : Dict = {'lr': 2e-5, 'num_epochs': 3, 'seed': 42, 'batch_size': 16} training_function(lowerCamelCase_ , lowerCamelCase_ ) if __name__ == "__main__": main()
21
import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, DPMSolverMultistepScheduler, TextToVideoSDPipeline, UNetaDConditionModel, ) from diffusers.utils import is_xformers_available, load_numpy, skip_mps, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() @skip_mps class UpperCamelCase__ ( lowerCAmelCase_ , unittest.TestCase ): '''simple docstring''' __snake_case : List[str] = TextToVideoSDPipeline __snake_case : int = TEXT_TO_IMAGE_PARAMS __snake_case : Tuple = TEXT_TO_IMAGE_BATCH_PARAMS # No `output_type`. __snake_case : Dict = frozenset( [ "num_inference_steps", "generator", "latents", "return_dict", "callback", "callback_steps", ] ) def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ) -> Optional[int]: '''simple docstring''' torch.manual_seed(0 ) SCREAMING_SNAKE_CASE = UNetaDConditionModel( block_out_channels=(32, 64, 64, 64) ,layers_per_block=2 ,sample_size=32 ,in_channels=4 ,out_channels=4 ,down_block_types=("""CrossAttnDownBlock3D""", """CrossAttnDownBlock3D""", """CrossAttnDownBlock3D""", """DownBlock3D""") ,up_block_types=("""UpBlock3D""", """CrossAttnUpBlock3D""", """CrossAttnUpBlock3D""", """CrossAttnUpBlock3D""") ,cross_attention_dim=32 ,attention_head_dim=4 ,) SCREAMING_SNAKE_CASE = DDIMScheduler( beta_start=0.00085 ,beta_end=0.012 ,beta_schedule="""scaled_linear""" ,clip_sample=lowerCamelCase__ ,set_alpha_to_one=lowerCamelCase__ ,) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE = AutoencoderKL( block_out_channels=[32, 64] ,in_channels=3 ,out_channels=3 ,down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] ,up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] ,latent_channels=4 ,sample_size=128 ,) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE = CLIPTextConfig( bos_token_id=0 ,eos_token_id=2 ,hidden_size=32 ,intermediate_size=37 ,layer_norm_eps=1e-0_5 ,num_attention_heads=4 ,num_hidden_layers=5 ,pad_token_id=1 ,vocab_size=1000 ,hidden_act="""gelu""" ,projection_dim=512 ,) SCREAMING_SNAKE_CASE = CLIPTextModel(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) SCREAMING_SNAKE_CASE = { """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, } return components def SCREAMING_SNAKE_CASE__ ( self : int ,lowerCamelCase__ : Optional[Any] ,lowerCamelCase__ : int=0 ) -> List[Any]: '''simple docstring''' if str(lowerCamelCase__ ).startswith("""mps""" ): SCREAMING_SNAKE_CASE = torch.manual_seed(lowerCamelCase__ ) else: SCREAMING_SNAKE_CASE = torch.Generator(device=lowerCamelCase__ ).manual_seed(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = { """prompt""": """A painting of a squirrel eating a burger""", """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 6.0, """output_type""": """pt""", } return inputs def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ) -> List[str]: '''simple docstring''' SCREAMING_SNAKE_CASE = """cpu""" # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE = self.get_dummy_components() SCREAMING_SNAKE_CASE = TextToVideoSDPipeline(**lowerCamelCase__ ) SCREAMING_SNAKE_CASE = sd_pipe.to(lowerCamelCase__ ) sd_pipe.set_progress_bar_config(disable=lowerCamelCase__ ) SCREAMING_SNAKE_CASE = self.get_dummy_inputs(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = """np""" SCREAMING_SNAKE_CASE = sd_pipe(**lowerCamelCase__ ).frames SCREAMING_SNAKE_CASE = frames[0][-3:, -3:, -1] assert frames[0].shape == (64, 64, 3) SCREAMING_SNAKE_CASE = np.array([158.0, 160.0, 153.0, 125.0, 100.0, 121.0, 111.0, 93.0, 113.0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def SCREAMING_SNAKE_CASE__ ( self : Dict ) -> int: '''simple docstring''' self._test_attention_slicing_forward_pass(test_mean_pixel_difference=lowerCamelCase__ ,expected_max_diff=3e-3 ) @unittest.skipIf( torch_device != """cuda""" or not is_xformers_available() ,reason="""XFormers attention is only available with CUDA and `xformers` installed""" ,) def SCREAMING_SNAKE_CASE__ ( self : Tuple ) -> Any: '''simple docstring''' self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=lowerCamelCase__ ,expected_max_diff=1e-2 ) @unittest.skip(reason="""Batching needs to be properly figured out first for this pipeline.""" ) def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ) -> List[Any]: '''simple docstring''' pass @unittest.skip(reason="""Batching needs to be properly figured out first for this pipeline.""" ) def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ) -> Any: '''simple docstring''' pass @unittest.skip(reason="""`num_images_per_prompt` argument is not supported for this pipeline.""" ) def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ) -> Tuple: '''simple docstring''' pass def SCREAMING_SNAKE_CASE__ ( self : List[str] ) -> Optional[Any]: '''simple docstring''' return super().test_progress_bar() @slow @skip_mps class UpperCamelCase__ ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE__ ( self : Any ) -> Optional[int]: '''simple docstring''' SCREAMING_SNAKE_CASE = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/text_to_video/video.npy""" ) SCREAMING_SNAKE_CASE = TextToVideoSDPipeline.from_pretrained("""damo-vilab/text-to-video-ms-1.7b""" ) SCREAMING_SNAKE_CASE = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config ) SCREAMING_SNAKE_CASE = pipe.to("""cuda""" ) SCREAMING_SNAKE_CASE = """Spiderman is surfing""" SCREAMING_SNAKE_CASE = torch.Generator(device="""cpu""" ).manual_seed(0 ) SCREAMING_SNAKE_CASE = pipe(lowerCamelCase__ ,generator=lowerCamelCase__ ,num_inference_steps=25 ,output_type="""pt""" ).frames SCREAMING_SNAKE_CASE = video_frames.cpu().numpy() assert np.abs(expected_video - video ).mean() < 5e-2 def SCREAMING_SNAKE_CASE__ ( self : Any ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/text_to_video/video_2step.npy""" ) SCREAMING_SNAKE_CASE = TextToVideoSDPipeline.from_pretrained("""damo-vilab/text-to-video-ms-1.7b""" ) SCREAMING_SNAKE_CASE = pipe.to("""cuda""" ) SCREAMING_SNAKE_CASE = """Spiderman is surfing""" SCREAMING_SNAKE_CASE = torch.Generator(device="""cpu""" ).manual_seed(0 ) SCREAMING_SNAKE_CASE = pipe(lowerCamelCase__ ,generator=lowerCamelCase__ ,num_inference_steps=2 ,output_type="""pt""" ).frames SCREAMING_SNAKE_CASE = video_frames.cpu().numpy() assert np.abs(expected_video - video ).mean() < 5e-2
296
0
'''simple docstring''' import warnings from ...utils import logging from .image_processing_deit import DeiTImageProcessor __SCREAMING_SNAKE_CASE :Union[str, Any] = logging.get_logger(__name__) class A_ ( lowerCAmelCase_ ): def __init__( self : Tuple , *snake_case_ : str , **snake_case_ : Union[str, Any] ): warnings.warn( "The class DeiTFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please" " use DeiTImageProcessor instead." , snake_case_ , ) super().__init__(*snake_case_ , **snake_case_ )
22
def __lowercase ( _SCREAMING_SNAKE_CASE = 10 ) -> str: '''simple docstring''' if not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) or n < 0: raise ValueError("""Invalid input""" ) SCREAMING_SNAKE_CASE = 10**n SCREAMING_SNAKE_CASE = 2_84_33 * (pow(2 , 7_83_04_57 , _SCREAMING_SNAKE_CASE )) + 1 return str(number % modulus ) if __name__ == "__main__": from doctest import testmod testmod() print(F'''{solution(1_0) = }''')
296
0
'''simple docstring''' import argparse from pathlib import Path from typing import Dict, OrderedDict, Tuple import torch from audiocraft.models import MusicGen from transformers import ( AutoFeatureExtractor, AutoTokenizer, EncodecModel, MusicgenDecoderConfig, MusicgenForConditionalGeneration, MusicgenProcessor, TaEncoderModel, ) from transformers.models.musicgen.modeling_musicgen import MusicgenForCausalLM from transformers.utils import logging logging.set_verbosity_info() UpperCamelCase__: Dict = logging.get_logger(__name__) UpperCamelCase__: Optional[Any] = ["model.decoder.embed_positions.weights"] def snake_case_ ( _lowerCAmelCase : str ) -> Tuple: if "emb" in name: UpperCAmelCase : int = name.replace('''emb''' , '''model.decoder.embed_tokens''' ) if "transformer" in name: UpperCAmelCase : Optional[Any] = name.replace('''transformer''' , '''model.decoder''' ) if "cross_attention" in name: UpperCAmelCase : int = name.replace('''cross_attention''' , '''encoder_attn''' ) if "linear1" in name: UpperCAmelCase : List[str] = name.replace('''linear1''' , '''fc1''' ) if "linear2" in name: UpperCAmelCase : Any = name.replace('''linear2''' , '''fc2''' ) if "norm1" in name: UpperCAmelCase : str = name.replace('''norm1''' , '''self_attn_layer_norm''' ) if "norm_cross" in name: UpperCAmelCase : str = name.replace('''norm_cross''' , '''encoder_attn_layer_norm''' ) if "norm2" in name: UpperCAmelCase : List[str] = name.replace('''norm2''' , '''final_layer_norm''' ) if "out_norm" in name: UpperCAmelCase : Dict = name.replace('''out_norm''' , '''model.decoder.layer_norm''' ) if "linears" in name: UpperCAmelCase : Optional[int] = name.replace('''linears''' , '''lm_heads''' ) if "condition_provider.conditioners.description.output_proj" in name: UpperCAmelCase : List[str] = name.replace('''condition_provider.conditioners.description.output_proj''' , '''enc_to_dec_proj''' ) return name def snake_case_ ( _lowerCAmelCase : OrderedDict , _lowerCAmelCase : int ) -> Tuple[Dict, Dict]: UpperCAmelCase : int = list(state_dict.keys() ) UpperCAmelCase : Tuple = {} for key in keys: UpperCAmelCase : Optional[int] = state_dict.pop(_lowerCAmelCase ) UpperCAmelCase : Union[str, Any] = rename_keys(_lowerCAmelCase ) if "in_proj_weight" in key: # split fused qkv proj UpperCAmelCase : Union[str, Any] = val[:hidden_size, :] UpperCAmelCase : str = val[hidden_size : 2 * hidden_size, :] UpperCAmelCase : str = val[-hidden_size:, :] elif "enc_to_dec_proj" in key: UpperCAmelCase : Tuple = val else: UpperCAmelCase : int = val return state_dict, enc_dec_proj_state_dict def snake_case_ ( _lowerCAmelCase : str ) -> MusicgenDecoderConfig: if checkpoint == "small": # default config values UpperCAmelCase : Optional[int] = 1024 UpperCAmelCase : List[Any] = 24 UpperCAmelCase : List[Any] = 16 elif checkpoint == "medium": UpperCAmelCase : Tuple = 1536 UpperCAmelCase : Union[str, Any] = 48 UpperCAmelCase : Tuple = 24 elif checkpoint == "large": UpperCAmelCase : Tuple = 2048 UpperCAmelCase : List[Any] = 48 UpperCAmelCase : List[Any] = 32 else: raise ValueError(f"""Checkpoint should be one of `['small', 'medium', 'large']`, got {checkpoint}.""" ) UpperCAmelCase : List[Any] = MusicgenDecoderConfig( hidden_size=_lowerCAmelCase , ffn_dim=hidden_size * 4 , num_hidden_layers=_lowerCAmelCase , num_attention_heads=_lowerCAmelCase , ) return config @torch.no_grad() def snake_case_ ( _lowerCAmelCase : List[str] , _lowerCAmelCase : List[Any]=None , _lowerCAmelCase : Optional[Any]=None , _lowerCAmelCase : Dict="cpu" ) -> str: UpperCAmelCase : List[str] = MusicGen.get_pretrained(_lowerCAmelCase , device=_lowerCAmelCase ) UpperCAmelCase : Dict = decoder_config_from_checkpoint(_lowerCAmelCase ) UpperCAmelCase : Any = fairseq_model.lm.state_dict() UpperCAmelCase , UpperCAmelCase : Optional[int] = rename_state_dict( _lowerCAmelCase , hidden_size=decoder_config.hidden_size ) UpperCAmelCase : Tuple = TaEncoderModel.from_pretrained('''t5-base''' ) UpperCAmelCase : Dict = EncodecModel.from_pretrained('''facebook/encodec_32khz''' ) UpperCAmelCase : Optional[int] = MusicgenForCausalLM(_lowerCAmelCase ).eval() # load all decoder weights - expect that we'll be missing embeddings and enc-dec projection UpperCAmelCase , UpperCAmelCase : Optional[int] = decoder.load_state_dict(_lowerCAmelCase , strict=_lowerCAmelCase ) for key in missing_keys.copy(): if key.startswith(('''text_encoder''', '''audio_encoder''') ) or key in EXPECTED_MISSING_KEYS: missing_keys.remove(_lowerCAmelCase ) if len(_lowerCAmelCase ) > 0: raise ValueError(f"""Missing key(s) in state_dict: {missing_keys}""" ) if len(_lowerCAmelCase ) > 0: raise ValueError(f"""Unexpected key(s) in state_dict: {unexpected_keys}""" ) # init the composite model UpperCAmelCase : Any = MusicgenForConditionalGeneration(text_encoder=_lowerCAmelCase , audio_encoder=_lowerCAmelCase , decoder=_lowerCAmelCase ) # load the pre-trained enc-dec projection (from the decoder state dict) model.enc_to_dec_proj.load_state_dict(_lowerCAmelCase ) # check we can do a forward pass UpperCAmelCase : Union[str, Any] = torch.arange(0 , 8 , dtype=torch.long ).reshape(2 , -1 ) UpperCAmelCase : List[Any] = input_ids.reshape(2 * 4 , -1 ) with torch.no_grad(): UpperCAmelCase : List[str] = model(input_ids=_lowerCAmelCase , decoder_input_ids=_lowerCAmelCase ).logits if logits.shape != (8, 1, 2048): raise ValueError('''Incorrect shape for logits''' ) # now construct the processor UpperCAmelCase : Any = AutoTokenizer.from_pretrained('''t5-base''' ) UpperCAmelCase : Optional[Any] = AutoFeatureExtractor.from_pretrained('''facebook/encodec_32khz''' , padding_side='''left''' ) UpperCAmelCase : int = MusicgenProcessor(feature_extractor=_lowerCAmelCase , tokenizer=_lowerCAmelCase ) # set the appropriate bos/pad token ids UpperCAmelCase : Optional[int] = 2048 UpperCAmelCase : List[Any] = 2048 # set other default generation config params UpperCAmelCase : Tuple = int(30 * audio_encoder.config.frame_rate ) UpperCAmelCase : Optional[Any] = True UpperCAmelCase : str = 3.0 if pytorch_dump_folder is not None: Path(_lowerCAmelCase ).mkdir(exist_ok=_lowerCAmelCase ) logger.info(f"""Saving model {checkpoint} to {pytorch_dump_folder}""" ) model.save_pretrained(_lowerCAmelCase ) processor.save_pretrained(_lowerCAmelCase ) if repo_id: logger.info(f"""Pushing model {checkpoint} to {repo_id}""" ) model.push_to_hub(_lowerCAmelCase ) processor.push_to_hub(_lowerCAmelCase ) if __name__ == "__main__": UpperCamelCase__: Dict = argparse.ArgumentParser() # Required parameters parser.add_argument( "--checkpoint", default="small", type=str, help="Checkpoint size of the MusicGen model you'd like to convert. Can be one of: `['small', 'medium', 'large']`.", ) parser.add_argument( "--pytorch_dump_folder", required=True, default=None, type=str, help="Path to the output PyTorch model directory.", ) parser.add_argument( "--push_to_hub", default=None, type=str, help="Where to upload the converted model on the 🤗 hub." ) parser.add_argument( "--device", default="cpu", type=str, help="Torch device to run the conversion, either cpu or cuda." ) UpperCamelCase__: Optional[int] = parser.parse_args() convert_musicgen_checkpoint(args.checkpoint, args.pytorch_dump_folder, args.push_to_hub)
23
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) SCREAMING_SNAKE_CASE_ = { """configuration_llama""": ["""LLAMA_PRETRAINED_CONFIG_ARCHIVE_MAP""", """LlamaConfig"""], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE_ = ["""LlamaTokenizer"""] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE_ = ["""LlamaTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE_ = [ """LlamaForCausalLM""", """LlamaModel""", """LlamaPreTrainedModel""", """LlamaForSequenceClassification""", ] if TYPE_CHECKING: from .configuration_llama import LLAMA_PRETRAINED_CONFIG_ARCHIVE_MAP, LlamaConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_llama import LlamaTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_llama_fast import LlamaTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_llama import LlamaForCausalLM, LlamaForSequenceClassification, LlamaModel, LlamaPreTrainedModel else: import sys SCREAMING_SNAKE_CASE_ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
296
0
def lowerCamelCase__ ( snake_case_ : int ) -> int: if not isinstance(snake_case_ , snake_case_ ) or number < 0: raise ValueError('''Input must be a non-negative integer''' ) __snake_case = 0 while number: # This way we arrive at next set bit (next 1) instead of looping # through each bit and checking for 1s hence the # loop won't run 32 times it will only run the number of `1` times number &= number - 1 count += 1 return count if __name__ == "__main__": import doctest doctest.testmod()
24
from pathlib import Path import fire def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> List[str]: '''simple docstring''' SCREAMING_SNAKE_CASE = Path(_SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE = Path(_SCREAMING_SNAKE_CASE ) dest_dir.mkdir(exist_ok=_SCREAMING_SNAKE_CASE ) for path in src_dir.iterdir(): SCREAMING_SNAKE_CASE = [x.rstrip() for x in list(path.open().readlines() )][:n] SCREAMING_SNAKE_CASE = dest_dir.joinpath(path.name ) print(_SCREAMING_SNAKE_CASE ) dest_path.open("""w""" ).write("""\n""".join(_SCREAMING_SNAKE_CASE ) ) if __name__ == "__main__": fire.Fire(minify)
296
0
"""simple docstring""" from __future__ import annotations def lowercase_ ( _snake_case ,_snake_case ,_snake_case ,_snake_case ,_snake_case ,): SCREAMING_SNAKE_CASE__ : Any = len(_snake_case ) # If row is equal to the size of the board it means there are a queen in each row in # the current board (possible_board) if row == n: # We convert the variable possible_board that looks like this: [1, 3, 0, 2] to # this: ['. Q . . ', '. . . Q ', 'Q . . . ', '. . Q . '] boards.append([""". """ * i + """Q """ + """. """ * (n - 1 - i) for i in possible_board] ) return # We iterate each column in the row to find all possible results in each row for col in range(_snake_case ): # We apply that we learned previously. First we check that in the current board # (possible_board) there are not other same value because if there is it means # that there are a collision in vertical. Then we apply the two formulas we # learned before: # # 45º: y - x = b or 45: row - col = b # 135º: y + x = b or row + col = b. # # And we verify if the results of this two formulas not exist in their variables # respectively. (diagonal_right_collisions, diagonal_left_collisions) # # If any or these are True it means there is a collision so we continue to the # next value in the for loop. if ( col in possible_board or row - col in diagonal_right_collisions or row + col in diagonal_left_collisions ): continue # If it is False we call dfs function again and we update the inputs depth_first_search( [*possible_board, col] ,[*diagonal_right_collisions, row - col] ,[*diagonal_left_collisions, row + col] ,_snake_case ,_snake_case ,) def lowercase_ ( _snake_case ): SCREAMING_SNAKE_CASE__ : list[list[str]] = [] depth_first_search([] ,[] ,[] ,_snake_case ,_snake_case ) # Print all the boards for board in boards: for column in board: print(_snake_case ) print("""""" ) print(len(_snake_case ) ,"""solutions were found.""" ) if __name__ == "__main__": import doctest doctest.testmod() n_queens_solution(4)
25
import importlib import json import os import sys import tempfile import unittest from pathlib import Path import transformers import transformers.models.auto from transformers.models.auto.configuration_auto import CONFIG_MAPPING, AutoConfig from transformers.models.bert.configuration_bert import BertConfig from transformers.models.roberta.configuration_roberta import RobertaConfig from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, get_tests_dir sys.path.append(str(Path(__file__).parent.parent.parent.parent / """utils""")) from test_module.custom_configuration import CustomConfig # noqa E402 SCREAMING_SNAKE_CASE_ = get_tests_dir("""fixtures/dummy-config.json""") class UpperCamelCase__ ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ) -> Optional[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE = 0 def SCREAMING_SNAKE_CASE__ ( self : Any ) -> str: '''simple docstring''' self.assertIsNotNone(transformers.models.auto.__spec__ ) self.assertIsNotNone(importlib.util.find_spec("""transformers.models.auto""" ) ) def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ) -> List[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained("""bert-base-uncased""" ) self.assertIsInstance(lowerCamelCase__ ,lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( self : int ) -> Optional[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained(lowerCamelCase__ ) self.assertIsInstance(lowerCamelCase__ ,lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ) -> List[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained(lowerCamelCase__ ) self.assertIsInstance(lowerCamelCase__ ,lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( self : Tuple ) -> Optional[int]: '''simple docstring''' SCREAMING_SNAKE_CASE = AutoConfig.for_model("""roberta""" ) self.assertIsInstance(lowerCamelCase__ ,lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( self : int ) -> int: '''simple docstring''' with tempfile.TemporaryDirectory() as tmp_dir: # This model name contains bert and roberta, but roberta ends up being picked. SCREAMING_SNAKE_CASE = os.path.join(lowerCamelCase__ ,"""fake-roberta""" ) os.makedirs(lowerCamelCase__ ,exist_ok=lowerCamelCase__ ) with open(os.path.join(lowerCamelCase__ ,"""config.json""" ) ,"""w""" ) as f: f.write(json.dumps({} ) ) SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained(lowerCamelCase__ ) self.assertEqual(type(lowerCamelCase__ ) ,lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( self : Dict ) -> str: '''simple docstring''' try: AutoConfig.register("""custom""" ,lowerCamelCase__ ) # Wrong model type will raise an error with self.assertRaises(lowerCamelCase__ ): AutoConfig.register("""model""" ,lowerCamelCase__ ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(lowerCamelCase__ ): AutoConfig.register("""bert""" ,lowerCamelCase__ ) # Now that the config is registered, it can be used as any other config with the auto-API SCREAMING_SNAKE_CASE = CustomConfig() with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained(lowerCamelCase__ ) self.assertIsInstance(lowerCamelCase__ ,lowerCamelCase__ ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] def SCREAMING_SNAKE_CASE__ ( self : str ) -> Dict: '''simple docstring''' with self.assertRaisesRegex( lowerCamelCase__ ,"""bert-base is not a local folder and is not a valid model identifier""" ): SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained("""bert-base""" ) def SCREAMING_SNAKE_CASE__ ( self : Dict ) -> str: '''simple docstring''' with self.assertRaisesRegex( lowerCamelCase__ ,R"""aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)""" ): SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained(lowerCamelCase__ ,revision="""aaaaaa""" ) def SCREAMING_SNAKE_CASE__ ( self : Tuple ) -> List[Any]: '''simple docstring''' with self.assertRaisesRegex( lowerCamelCase__ ,"""hf-internal-testing/no-config-test-repo does not appear to have a file named config.json.""" ,): SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained("""hf-internal-testing/no-config-test-repo""" ) def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ) -> Union[str, Any]: '''simple docstring''' with self.assertRaises(lowerCamelCase__ ): SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained("""hf-internal-testing/test_dynamic_model""" ) # If remote code is disabled, we can't load this config. with self.assertRaises(lowerCamelCase__ ): SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained("""hf-internal-testing/test_dynamic_model""" ,trust_remote_code=lowerCamelCase__ ) SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained("""hf-internal-testing/test_dynamic_model""" ,trust_remote_code=lowerCamelCase__ ) self.assertEqual(config.__class__.__name__ ,"""NewModelConfig""" ) # Test config can be reloaded. with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained(lowerCamelCase__ ,trust_remote_code=lowerCamelCase__ ) self.assertEqual(reloaded_config.__class__.__name__ ,"""NewModelConfig""" ) def SCREAMING_SNAKE_CASE__ ( self : Dict ) -> Union[str, Any]: '''simple docstring''' class UpperCamelCase__ ( lowerCAmelCase_ ): '''simple docstring''' __snake_case : Union[str, Any] = "new-model" try: AutoConfig.register("""new-model""" ,lowerCamelCase__ ) # If remote code is not set, the default is to use local SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained("""hf-internal-testing/test_dynamic_model""" ) self.assertEqual(config.__class__.__name__ ,"""NewModelConfigLocal""" ) # If remote code is disabled, we load the local one. SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained("""hf-internal-testing/test_dynamic_model""" ,trust_remote_code=lowerCamelCase__ ) self.assertEqual(config.__class__.__name__ ,"""NewModelConfigLocal""" ) # If remote is enabled, we load from the Hub SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained("""hf-internal-testing/test_dynamic_model""" ,trust_remote_code=lowerCamelCase__ ) self.assertEqual(config.__class__.__name__ ,"""NewModelConfig""" ) finally: if "new-model" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["new-model"]
296
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _snake_case = { "configuration_x_clip": [ "XCLIP_PRETRAINED_CONFIG_ARCHIVE_MAP", "XCLIPConfig", "XCLIPTextConfig", "XCLIPVisionConfig", ], "processing_x_clip": ["XCLIPProcessor"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _snake_case = [ "XCLIP_PRETRAINED_MODEL_ARCHIVE_LIST", "XCLIPModel", "XCLIPPreTrainedModel", "XCLIPTextModel", "XCLIPVisionModel", ] if TYPE_CHECKING: from .configuration_x_clip import ( XCLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, XCLIPConfig, XCLIPTextConfig, XCLIPVisionConfig, ) from .processing_x_clip import XCLIPProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_x_clip import ( XCLIP_PRETRAINED_MODEL_ARCHIVE_LIST, XCLIPModel, XCLIPPreTrainedModel, XCLIPTextModel, XCLIPVisionModel, ) else: import sys _snake_case = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
26
import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging SCREAMING_SNAKE_CASE_ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE_ = { """microsoft/git-base""": """https://huggingface.co/microsoft/git-base/resolve/main/config.json""", } class UpperCamelCase__ ( lowerCAmelCase_ ): '''simple docstring''' __snake_case : Dict = "git_vision_model" def __init__( self : List[Any] ,lowerCamelCase__ : Dict=768 ,lowerCamelCase__ : Union[str, Any]=3072 ,lowerCamelCase__ : Optional[int]=12 ,lowerCamelCase__ : Tuple=12 ,lowerCamelCase__ : Tuple=3 ,lowerCamelCase__ : Optional[Any]=224 ,lowerCamelCase__ : Union[str, Any]=16 ,lowerCamelCase__ : List[Any]="quick_gelu" ,lowerCamelCase__ : Optional[Any]=1e-5 ,lowerCamelCase__ : str=0.0 ,lowerCamelCase__ : Optional[int]=0.02 ,**lowerCamelCase__ : Union[str, Any] ,) -> Optional[int]: '''simple docstring''' super().__init__(**lowerCamelCase__ ) SCREAMING_SNAKE_CASE = hidden_size SCREAMING_SNAKE_CASE = intermediate_size SCREAMING_SNAKE_CASE = num_hidden_layers SCREAMING_SNAKE_CASE = num_attention_heads SCREAMING_SNAKE_CASE = num_channels SCREAMING_SNAKE_CASE = patch_size SCREAMING_SNAKE_CASE = image_size SCREAMING_SNAKE_CASE = initializer_range SCREAMING_SNAKE_CASE = attention_dropout SCREAMING_SNAKE_CASE = layer_norm_eps SCREAMING_SNAKE_CASE = hidden_act @classmethod def SCREAMING_SNAKE_CASE__ ( cls : Tuple ,lowerCamelCase__ : Union[str, os.PathLike] ,**lowerCamelCase__ : int ) -> "PretrainedConfig": '''simple docstring''' cls._set_token_in_kwargs(lowerCamelCase__ ) SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE = cls.get_config_dict(lowerCamelCase__ ,**lowerCamelCase__ ) # get the vision config dict if we are loading from GITConfig if config_dict.get("""model_type""" ) == "git": SCREAMING_SNAKE_CASE = config_dict["""vision_config"""] if "model_type" in config_dict and hasattr(cls ,"""model_type""" ) and config_dict["model_type"] != cls.model_type: logger.warning( F"""You are using a model of type {config_dict['model_type']} to instantiate a model of type """ F"""{cls.model_type}. This is not supported for all configurations of models and can yield errors.""" ) return cls.from_dict(lowerCamelCase__ ,**lowerCamelCase__ ) class UpperCamelCase__ ( lowerCAmelCase_ ): '''simple docstring''' __snake_case : Dict = "git" def __init__( self : Optional[int] ,lowerCamelCase__ : int=None ,lowerCamelCase__ : str=30522 ,lowerCamelCase__ : Tuple=768 ,lowerCamelCase__ : Union[str, Any]=6 ,lowerCamelCase__ : str=12 ,lowerCamelCase__ : List[str]=3072 ,lowerCamelCase__ : Dict="gelu" ,lowerCamelCase__ : Tuple=0.1 ,lowerCamelCase__ : Any=0.1 ,lowerCamelCase__ : List[str]=1024 ,lowerCamelCase__ : List[str]=0.02 ,lowerCamelCase__ : str=1e-1_2 ,lowerCamelCase__ : Optional[int]=0 ,lowerCamelCase__ : Optional[int]="absolute" ,lowerCamelCase__ : Optional[Any]=True ,lowerCamelCase__ : str=False ,lowerCamelCase__ : int=101 ,lowerCamelCase__ : int=102 ,lowerCamelCase__ : Dict=None ,**lowerCamelCase__ : List[Any] ,) -> Optional[Any]: '''simple docstring''' super().__init__(bos_token_id=lowerCamelCase__ ,eos_token_id=lowerCamelCase__ ,pad_token_id=lowerCamelCase__ ,**lowerCamelCase__ ) if vision_config is None: SCREAMING_SNAKE_CASE = {} logger.info("""vision_config is None. initializing the GitVisionConfig with default values.""" ) SCREAMING_SNAKE_CASE = GitVisionConfig(**lowerCamelCase__ ) SCREAMING_SNAKE_CASE = vocab_size SCREAMING_SNAKE_CASE = hidden_size SCREAMING_SNAKE_CASE = num_hidden_layers SCREAMING_SNAKE_CASE = num_attention_heads SCREAMING_SNAKE_CASE = hidden_act SCREAMING_SNAKE_CASE = intermediate_size SCREAMING_SNAKE_CASE = hidden_dropout_prob SCREAMING_SNAKE_CASE = attention_probs_dropout_prob SCREAMING_SNAKE_CASE = max_position_embeddings SCREAMING_SNAKE_CASE = initializer_range SCREAMING_SNAKE_CASE = layer_norm_eps SCREAMING_SNAKE_CASE = position_embedding_type SCREAMING_SNAKE_CASE = use_cache SCREAMING_SNAKE_CASE = tie_word_embeddings SCREAMING_SNAKE_CASE = num_image_with_embedding SCREAMING_SNAKE_CASE = bos_token_id SCREAMING_SNAKE_CASE = eos_token_id def SCREAMING_SNAKE_CASE__ ( self : Dict ) -> Optional[int]: '''simple docstring''' SCREAMING_SNAKE_CASE = copy.deepcopy(self.__dict__ ) SCREAMING_SNAKE_CASE = self.vision_config.to_dict() SCREAMING_SNAKE_CASE = self.__class__.model_type return output
296
0
'''simple docstring''' import requests __lowercase : Tuple = '' # <-- Put your OpenWeatherMap appid here! __lowercase : Tuple = 'https://api.openweathermap.org/data/2.5/' def lowerCamelCase (_SCREAMING_SNAKE_CASE : str = "Chicago" , _SCREAMING_SNAKE_CASE : str = APPID ): return requests.get(URL_BASE + 'weather' , params=locals() ).json() def lowerCamelCase (_SCREAMING_SNAKE_CASE : str = "Kolkata, India" , _SCREAMING_SNAKE_CASE : str = APPID ): return requests.get(URL_BASE + 'forecast' , params=locals() ).json() def lowerCamelCase (_SCREAMING_SNAKE_CASE : float = 5_5.6_8 , _SCREAMING_SNAKE_CASE : float = 1_2.5_7 , _SCREAMING_SNAKE_CASE : str = APPID ): return requests.get(URL_BASE + 'onecall' , params=locals() ).json() if __name__ == "__main__": from pprint import pprint while True: __lowercase : Dict = input('Enter a location:').strip() if location: pprint(current_weather(location)) else: break
27
import itertools import os import random import tempfile import unittest import numpy as np from transformers import TvltFeatureExtractor, is_datasets_available from transformers.testing_utils import check_json_file_has_correct_format, require_torch, require_torchaudio from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin if is_torch_available(): import torch if is_datasets_available(): from datasets import load_dataset SCREAMING_SNAKE_CASE_ = random.Random() def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=1.0 , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None ) -> Tuple: '''simple docstring''' if rng is None: SCREAMING_SNAKE_CASE = global_rng SCREAMING_SNAKE_CASE = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values class UpperCamelCase__ ( unittest.TestCase ): '''simple docstring''' def __init__( self : List[Any] ,lowerCamelCase__ : str ,lowerCamelCase__ : Optional[int]=7 ,lowerCamelCase__ : Optional[Any]=400 ,lowerCamelCase__ : List[str]=2000 ,lowerCamelCase__ : List[str]=2048 ,lowerCamelCase__ : Any=128 ,lowerCamelCase__ : List[str]=1 ,lowerCamelCase__ : str=512 ,lowerCamelCase__ : Optional[Any]=30 ,lowerCamelCase__ : Tuple=44100 ,) -> Tuple: '''simple docstring''' SCREAMING_SNAKE_CASE = parent SCREAMING_SNAKE_CASE = batch_size SCREAMING_SNAKE_CASE = min_seq_length SCREAMING_SNAKE_CASE = max_seq_length SCREAMING_SNAKE_CASE = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) SCREAMING_SNAKE_CASE = spectrogram_length SCREAMING_SNAKE_CASE = feature_size SCREAMING_SNAKE_CASE = num_audio_channels SCREAMING_SNAKE_CASE = hop_length SCREAMING_SNAKE_CASE = chunk_length SCREAMING_SNAKE_CASE = sampling_rate def SCREAMING_SNAKE_CASE__ ( self : List[Any] ) -> Optional[int]: '''simple docstring''' return { "spectrogram_length": self.spectrogram_length, "feature_size": self.feature_size, "num_audio_channels": self.num_audio_channels, "hop_length": self.hop_length, "chunk_length": self.chunk_length, "sampling_rate": self.sampling_rate, } def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ,lowerCamelCase__ : Tuple=False ,lowerCamelCase__ : Union[str, Any]=False ) -> str: '''simple docstring''' def _flatten(lowerCamelCase__ : List[Any] ): return list(itertools.chain(*lowerCamelCase__ ) ) if equal_length: SCREAMING_SNAKE_CASE = [floats_list((self.max_seq_length, self.feature_size) ) for _ in range(self.batch_size )] else: # make sure that inputs increase in size SCREAMING_SNAKE_CASE = [ floats_list((x, self.feature_size) ) for x in range(self.min_seq_length ,self.max_seq_length ,self.seq_length_diff ) ] if numpify: SCREAMING_SNAKE_CASE = [np.asarray(lowerCamelCase__ ) for x in speech_inputs] return speech_inputs @require_torch @require_torchaudio class UpperCamelCase__ ( lowerCAmelCase_ , unittest.TestCase ): '''simple docstring''' __snake_case : List[Any] = TvltFeatureExtractor def SCREAMING_SNAKE_CASE__ ( self : str ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE = TvltFeatureExtractionTester(self ) def SCREAMING_SNAKE_CASE__ ( self : List[Any] ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_dict ) self.assertTrue(hasattr(lowerCamelCase__ ,"""spectrogram_length""" ) ) self.assertTrue(hasattr(lowerCamelCase__ ,"""feature_size""" ) ) self.assertTrue(hasattr(lowerCamelCase__ ,"""num_audio_channels""" ) ) self.assertTrue(hasattr(lowerCamelCase__ ,"""hop_length""" ) ) self.assertTrue(hasattr(lowerCamelCase__ ,"""chunk_length""" ) ) self.assertTrue(hasattr(lowerCamelCase__ ,"""sampling_rate""" ) ) def SCREAMING_SNAKE_CASE__ ( self : str ) -> Union[str, Any]: '''simple docstring''' SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: SCREAMING_SNAKE_CASE = feat_extract_first.save_pretrained(lowerCamelCase__ )[0] check_json_file_has_correct_format(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = self.feature_extraction_class.from_pretrained(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = feat_extract_first.to_dict() SCREAMING_SNAKE_CASE = feat_extract_second.to_dict() SCREAMING_SNAKE_CASE = dict_first.pop("""mel_filters""" ) SCREAMING_SNAKE_CASE = dict_second.pop("""mel_filters""" ) self.assertTrue(np.allclose(lowerCamelCase__ ,lowerCamelCase__ ) ) self.assertEqual(lowerCamelCase__ ,lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( self : Any ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: SCREAMING_SNAKE_CASE = os.path.join(lowerCamelCase__ ,"""feat_extract.json""" ) feat_extract_first.to_json_file(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = self.feature_extraction_class.from_json_file(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = feat_extract_first.to_dict() SCREAMING_SNAKE_CASE = feat_extract_second.to_dict() SCREAMING_SNAKE_CASE = dict_first.pop("""mel_filters""" ) SCREAMING_SNAKE_CASE = dict_second.pop("""mel_filters""" ) self.assertTrue(np.allclose(lowerCamelCase__ ,lowerCamelCase__ ) ) self.assertEqual(lowerCamelCase__ ,lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( self : str ) -> Optional[int]: '''simple docstring''' SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_dict ) # create three inputs of length 800, 1000, and 1200 SCREAMING_SNAKE_CASE = [floats_list((1, x) )[0] for x in range(800 ,1400 ,200 )] SCREAMING_SNAKE_CASE = [np.asarray(lowerCamelCase__ ) for speech_input in speech_inputs] # Test not batched input SCREAMING_SNAKE_CASE = feature_extractor(np_speech_inputs[0] ,return_tensors="""np""" ,sampling_rate=44100 ).audio_values self.assertTrue(encoded_audios.ndim == 4 ) self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size ) self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length ) self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels ) # Test batched SCREAMING_SNAKE_CASE = feature_extractor(lowerCamelCase__ ,return_tensors="""np""" ,sampling_rate=44100 ).audio_values self.assertTrue(encoded_audios.ndim == 4 ) self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size ) self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length ) self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels ) # Test audio masking SCREAMING_SNAKE_CASE = feature_extractor( lowerCamelCase__ ,return_tensors="""np""" ,sampling_rate=44100 ,mask_audio=lowerCamelCase__ ).audio_values self.assertTrue(encoded_audios.ndim == 4 ) self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size ) self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length ) self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels ) # Test 2-D numpy arrays are batched. SCREAMING_SNAKE_CASE = [floats_list((1, x) )[0] for x in (800, 800, 800)] SCREAMING_SNAKE_CASE = np.asarray(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = feature_extractor(lowerCamelCase__ ,return_tensors="""np""" ,sampling_rate=44100 ).audio_values self.assertTrue(encoded_audios.ndim == 4 ) self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size ) self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length ) self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels ) def SCREAMING_SNAKE_CASE__ ( self : Any ,lowerCamelCase__ : str ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE = load_dataset("""hf-internal-testing/librispeech_asr_dummy""" ,"""clean""" ,split="""validation""" ) # automatic decoding with librispeech SCREAMING_SNAKE_CASE = ds.sort("""id""" ).select(range(lowerCamelCase__ ) )[:num_samples]["""audio"""] return [x["array"] for x in speech_samples] def SCREAMING_SNAKE_CASE__ ( self : Tuple ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE = self._load_datasamples(1 ) SCREAMING_SNAKE_CASE = TvltFeatureExtractor() SCREAMING_SNAKE_CASE = feature_extractor(lowerCamelCase__ ,return_tensors="""pt""" ).audio_values self.assertEquals(audio_values.shape ,(1, 1, 192, 128) ) SCREAMING_SNAKE_CASE = torch.tensor([[-0.3032, -0.2708], [-0.4434, -0.4007]] ) self.assertTrue(torch.allclose(audio_values[0, 0, :2, :2] ,lowerCamelCase__ ,atol=1e-4 ) )
296
0
'''simple docstring''' _lowerCamelCase : Any = "\n# Transformers installation\n! pip install transformers datasets\n# To install from source instead of the last release, comment the command above and uncomment the following one.\n# ! pip install git+https://github.com/huggingface/transformers.git\n" _lowerCamelCase : Dict = [{"type": "code", "content": INSTALL_CONTENT}] _lowerCamelCase : List[Any] = { "{processor_class}": "FakeProcessorClass", "{model_class}": "FakeModelClass", "{object_class}": "FakeObjectClass", }
28
import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( MobileViTConfig, MobileViTForImageClassification, MobileViTForSemanticSegmentation, MobileViTImageProcessor, ) from transformers.utils import logging logging.set_verbosity_info() SCREAMING_SNAKE_CASE_ = logging.get_logger(__name__) def __lowercase ( _SCREAMING_SNAKE_CASE ) -> Optional[int]: '''simple docstring''' SCREAMING_SNAKE_CASE = MobileViTConfig() # size of the architecture if "mobilevit_s" in mobilevit_name: SCREAMING_SNAKE_CASE = [1_44, 1_92, 2_40] SCREAMING_SNAKE_CASE = [16, 32, 64, 96, 1_28, 1_60, 6_40] elif "mobilevit_xs" in mobilevit_name: SCREAMING_SNAKE_CASE = [96, 1_20, 1_44] SCREAMING_SNAKE_CASE = [16, 32, 48, 64, 80, 96, 3_84] elif "mobilevit_xxs" in mobilevit_name: SCREAMING_SNAKE_CASE = [64, 80, 96] SCREAMING_SNAKE_CASE = [16, 16, 24, 48, 64, 80, 3_20] SCREAMING_SNAKE_CASE = 0.05 SCREAMING_SNAKE_CASE = 2.0 if mobilevit_name.startswith("""deeplabv3_""" ): SCREAMING_SNAKE_CASE = 5_12 SCREAMING_SNAKE_CASE = 16 SCREAMING_SNAKE_CASE = 21 SCREAMING_SNAKE_CASE = """pascal-voc-id2label.json""" else: SCREAMING_SNAKE_CASE = 10_00 SCREAMING_SNAKE_CASE = """imagenet-1k-id2label.json""" SCREAMING_SNAKE_CASE = """huggingface/label-files""" SCREAMING_SNAKE_CASE = json.load(open(hf_hub_download(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , repo_type="""dataset""" ) , """r""" ) ) SCREAMING_SNAKE_CASE = {int(_SCREAMING_SNAKE_CASE ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE = idalabel SCREAMING_SNAKE_CASE = {v: k for k, v in idalabel.items()} return config def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=False ) -> str: '''simple docstring''' for i in range(1 , 6 ): if F"""layer_{i}.""" in name: SCREAMING_SNAKE_CASE = name.replace(F"""layer_{i}.""" , F"""encoder.layer.{i - 1}.""" ) if "conv_1." in name: SCREAMING_SNAKE_CASE = name.replace("""conv_1.""" , """conv_stem.""" ) if ".block." in name: SCREAMING_SNAKE_CASE = name.replace(""".block.""" , """.""" ) if "exp_1x1" in name: SCREAMING_SNAKE_CASE = name.replace("""exp_1x1""" , """expand_1x1""" ) if "red_1x1" in name: SCREAMING_SNAKE_CASE = name.replace("""red_1x1""" , """reduce_1x1""" ) if ".local_rep.conv_3x3." in name: SCREAMING_SNAKE_CASE = name.replace(""".local_rep.conv_3x3.""" , """.conv_kxk.""" ) if ".local_rep.conv_1x1." in name: SCREAMING_SNAKE_CASE = name.replace(""".local_rep.conv_1x1.""" , """.conv_1x1.""" ) if ".norm." in name: SCREAMING_SNAKE_CASE = name.replace(""".norm.""" , """.normalization.""" ) if ".conv." in name: SCREAMING_SNAKE_CASE = name.replace(""".conv.""" , """.convolution.""" ) if ".conv_proj." in name: SCREAMING_SNAKE_CASE = name.replace(""".conv_proj.""" , """.conv_projection.""" ) for i in range(0 , 2 ): for j in range(0 , 4 ): if F""".{i}.{j}.""" in name: SCREAMING_SNAKE_CASE = name.replace(F""".{i}.{j}.""" , F""".{i}.layer.{j}.""" ) for i in range(2 , 6 ): for j in range(0 , 4 ): if F""".{i}.{j}.""" in name: SCREAMING_SNAKE_CASE = name.replace(F""".{i}.{j}.""" , F""".{i}.""" ) if "expand_1x1" in name: SCREAMING_SNAKE_CASE = name.replace("""expand_1x1""" , """downsampling_layer.expand_1x1""" ) if "conv_3x3" in name: SCREAMING_SNAKE_CASE = name.replace("""conv_3x3""" , """downsampling_layer.conv_3x3""" ) if "reduce_1x1" in name: SCREAMING_SNAKE_CASE = name.replace("""reduce_1x1""" , """downsampling_layer.reduce_1x1""" ) for i in range(2 , 5 ): if F""".global_rep.{i}.weight""" in name: SCREAMING_SNAKE_CASE = name.replace(F""".global_rep.{i}.weight""" , """.layernorm.weight""" ) if F""".global_rep.{i}.bias""" in name: SCREAMING_SNAKE_CASE = name.replace(F""".global_rep.{i}.bias""" , """.layernorm.bias""" ) if ".global_rep." in name: SCREAMING_SNAKE_CASE = name.replace(""".global_rep.""" , """.transformer.""" ) if ".pre_norm_mha.0." in name: SCREAMING_SNAKE_CASE = name.replace(""".pre_norm_mha.0.""" , """.layernorm_before.""" ) if ".pre_norm_mha.1.out_proj." in name: SCREAMING_SNAKE_CASE = name.replace(""".pre_norm_mha.1.out_proj.""" , """.attention.output.dense.""" ) if ".pre_norm_ffn.0." in name: SCREAMING_SNAKE_CASE = name.replace(""".pre_norm_ffn.0.""" , """.layernorm_after.""" ) if ".pre_norm_ffn.1." in name: SCREAMING_SNAKE_CASE = name.replace(""".pre_norm_ffn.1.""" , """.intermediate.dense.""" ) if ".pre_norm_ffn.4." in name: SCREAMING_SNAKE_CASE = name.replace(""".pre_norm_ffn.4.""" , """.output.dense.""" ) if ".transformer." in name: SCREAMING_SNAKE_CASE = name.replace(""".transformer.""" , """.transformer.layer.""" ) if ".aspp_layer." in name: SCREAMING_SNAKE_CASE = name.replace(""".aspp_layer.""" , """.""" ) if ".aspp_pool." in name: SCREAMING_SNAKE_CASE = name.replace(""".aspp_pool.""" , """.""" ) if "seg_head." in name: SCREAMING_SNAKE_CASE = name.replace("""seg_head.""" , """segmentation_head.""" ) if "segmentation_head.classifier.classifier." in name: SCREAMING_SNAKE_CASE = name.replace("""segmentation_head.classifier.classifier.""" , """segmentation_head.classifier.""" ) if "classifier.fc." in name: SCREAMING_SNAKE_CASE = name.replace("""classifier.fc.""" , """classifier.""" ) elif (not base_model) and ("segmentation_head." not in name): SCREAMING_SNAKE_CASE = """mobilevit.""" + name return name def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=False ) -> Dict: '''simple docstring''' if base_model: SCREAMING_SNAKE_CASE = """""" else: SCREAMING_SNAKE_CASE = """mobilevit.""" for key in orig_state_dict.copy().keys(): SCREAMING_SNAKE_CASE = orig_state_dict.pop(_SCREAMING_SNAKE_CASE ) if key[:8] == "encoder.": SCREAMING_SNAKE_CASE = key[8:] if "qkv" in key: SCREAMING_SNAKE_CASE = key.split(""".""" ) SCREAMING_SNAKE_CASE = int(key_split[0][6:] ) - 1 SCREAMING_SNAKE_CASE = int(key_split[3] ) SCREAMING_SNAKE_CASE = model.get_submodule(F"""{model_prefix}encoder.layer.{layer_num}""" ) SCREAMING_SNAKE_CASE = layer.transformer.layer[transformer_num].attention.attention.all_head_size SCREAMING_SNAKE_CASE = ( F"""{model_prefix}encoder.layer.{layer_num}.transformer.layer.{transformer_num}.attention.attention.""" ) if "weight" in key: SCREAMING_SNAKE_CASE = val[:dim, :] SCREAMING_SNAKE_CASE = val[dim : dim * 2, :] SCREAMING_SNAKE_CASE = val[-dim:, :] else: SCREAMING_SNAKE_CASE = val[:dim] SCREAMING_SNAKE_CASE = val[dim : dim * 2] SCREAMING_SNAKE_CASE = val[-dim:] else: SCREAMING_SNAKE_CASE = val return orig_state_dict def __lowercase ( ) -> str: '''simple docstring''' SCREAMING_SNAKE_CASE = """http://images.cocodataset.org/val2017/000000039769.jpg""" SCREAMING_SNAKE_CASE = Image.open(requests.get(_SCREAMING_SNAKE_CASE , stream=_SCREAMING_SNAKE_CASE ).raw ) return im @torch.no_grad() def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=False ) -> str: '''simple docstring''' SCREAMING_SNAKE_CASE = get_mobilevit_config(_SCREAMING_SNAKE_CASE ) # load original state_dict SCREAMING_SNAKE_CASE = torch.load(_SCREAMING_SNAKE_CASE , map_location="""cpu""" ) # load 🤗 model if mobilevit_name.startswith("""deeplabv3_""" ): SCREAMING_SNAKE_CASE = MobileViTForSemanticSegmentation(_SCREAMING_SNAKE_CASE ).eval() else: SCREAMING_SNAKE_CASE = MobileViTForImageClassification(_SCREAMING_SNAKE_CASE ).eval() SCREAMING_SNAKE_CASE = convert_state_dict(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) model.load_state_dict(_SCREAMING_SNAKE_CASE ) # Check outputs on an image, prepared by MobileViTImageProcessor SCREAMING_SNAKE_CASE = MobileViTImageProcessor(crop_size=config.image_size , size=config.image_size + 32 ) SCREAMING_SNAKE_CASE = image_processor(images=prepare_img() , return_tensors="""pt""" ) SCREAMING_SNAKE_CASE = model(**_SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE = outputs.logits if mobilevit_name.startswith("""deeplabv3_""" ): assert logits.shape == (1, 21, 32, 32) if mobilevit_name == "deeplabv3_mobilevit_s": SCREAMING_SNAKE_CASE = torch.tensor( [ [[6.2_065, 6.1_292, 6.2_070], [6.1_079, 6.1_254, 6.1_747], [6.0_042, 6.1_071, 6.1_034]], [[-6.9_253, -6.8_653, -7.0_398], [-7.3_218, -7.3_983, -7.3_670], [-7.1_961, -7.2_482, -7.1_569]], [[-4.4_723, -4.4_348, -4.3_769], [-5.3_629, -5.4_632, -5.4_598], [-5.1_587, -5.3_402, -5.5_059]], ] ) elif mobilevit_name == "deeplabv3_mobilevit_xs": SCREAMING_SNAKE_CASE = torch.tensor( [ [[5.4_449, 5.5_733, 5.6_314], [5.1_815, 5.3_930, 5.5_963], [5.1_656, 5.4_333, 5.4_853]], [[-9.4_423, -9.7_766, -9.6_714], [-9.1_581, -9.5_720, -9.5_519], [-9.1_006, -9.6_458, -9.5_703]], [[-7.7_721, -7.3_716, -7.1_583], [-8.4_599, -8.0_624, -7.7_944], [-8.4_172, -7.8_366, -7.5_025]], ] ) elif mobilevit_name == "deeplabv3_mobilevit_xxs": SCREAMING_SNAKE_CASE = torch.tensor( [ [[6.9_811, 6.9_743, 7.3_123], [7.1_777, 7.1_931, 7.3_938], [7.5_633, 7.8_050, 7.8_901]], [[-10.5_536, -10.2_332, -10.2_924], [-10.2_336, -9.8_624, -9.5_964], [-10.8_840, -10.8_158, -10.6_659]], [[-3.4_938, -3.0_631, -2.8_620], [-3.4_205, -2.8_135, -2.6_875], [-3.4_179, -2.7_945, -2.8_750]], ] ) else: raise ValueError(F"""Unknown mobilevit_name: {mobilevit_name}""" ) assert torch.allclose(logits[0, :3, :3, :3] , _SCREAMING_SNAKE_CASE , atol=1E-4 ) else: assert logits.shape == (1, 10_00) if mobilevit_name == "mobilevit_s": SCREAMING_SNAKE_CASE = torch.tensor([-0.9_866, 0.2_392, -1.1_241] ) elif mobilevit_name == "mobilevit_xs": SCREAMING_SNAKE_CASE = torch.tensor([-2.4_761, -0.9_399, -1.9_587] ) elif mobilevit_name == "mobilevit_xxs": SCREAMING_SNAKE_CASE = torch.tensor([-1.9_364, -1.2_327, -0.4_653] ) else: raise ValueError(F"""Unknown mobilevit_name: {mobilevit_name}""" ) assert torch.allclose(logits[0, :3] , _SCREAMING_SNAKE_CASE , atol=1E-4 ) Path(_SCREAMING_SNAKE_CASE ).mkdir(exist_ok=_SCREAMING_SNAKE_CASE ) print(F"""Saving model {mobilevit_name} to {pytorch_dump_folder_path}""" ) model.save_pretrained(_SCREAMING_SNAKE_CASE ) print(F"""Saving image processor to {pytorch_dump_folder_path}""" ) image_processor.save_pretrained(_SCREAMING_SNAKE_CASE ) if push_to_hub: SCREAMING_SNAKE_CASE = { """mobilevit_s""": """mobilevit-small""", """mobilevit_xs""": """mobilevit-x-small""", """mobilevit_xxs""": """mobilevit-xx-small""", """deeplabv3_mobilevit_s""": """deeplabv3-mobilevit-small""", """deeplabv3_mobilevit_xs""": """deeplabv3-mobilevit-x-small""", """deeplabv3_mobilevit_xxs""": """deeplabv3-mobilevit-xx-small""", } print("""Pushing to the hub...""" ) SCREAMING_SNAKE_CASE = model_mapping[mobilevit_name] image_processor.push_to_hub(_SCREAMING_SNAKE_CASE , organization="""apple""" ) model.push_to_hub(_SCREAMING_SNAKE_CASE , organization="""apple""" ) if __name__ == "__main__": SCREAMING_SNAKE_CASE_ = argparse.ArgumentParser() # Required parameters parser.add_argument( """--mobilevit_name""", default="""mobilevit_s""", type=str, help=( """Name of the MobileViT model you'd like to convert. Should be one of 'mobilevit_s', 'mobilevit_xs',""" """ 'mobilevit_xxs', 'deeplabv3_mobilevit_s', 'deeplabv3_mobilevit_xs', 'deeplabv3_mobilevit_xxs'.""" ), ) parser.add_argument( """--checkpoint_path""", required=True, type=str, help="""Path to the original state dict (.pt file).""" ) parser.add_argument( """--pytorch_dump_folder_path""", required=True, type=str, help="""Path to the output PyTorch model directory.""" ) parser.add_argument( """--push_to_hub""", action="""store_true""", help="""Whether or not to push the converted model to the 🤗 hub.""" ) SCREAMING_SNAKE_CASE_ = parser.parse_args() convert_movilevit_checkpoint( args.mobilevit_name, args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub )
296
0
def lowercase__ ( __snake_case : int = 600_851_475_143 ): '''simple docstring''' try: UpperCAmelCase_ : Tuple = int(__snake_case ) except (TypeError, ValueError): raise TypeError('Parameter n must be int or castable to int.' ) if n <= 0: raise ValueError('Parameter n must be greater than or equal to one.' ) UpperCAmelCase_ : List[Any] = 2 UpperCAmelCase_ : str = 0 if n == 2: return 2 while n > 2: while n % i != 0: i += 1 UpperCAmelCase_ : str = i while n % i == 0: UpperCAmelCase_ : List[Any] = n // i i += 1 return int(__snake_case ) if __name__ == "__main__": print(F'{solution() = }')
29
from collections import OrderedDict from ...utils import logging from .auto_factory import _BaseAutoModelClass, _LazyAutoMapping, auto_class_update from .configuration_auto import CONFIG_MAPPING_NAMES SCREAMING_SNAKE_CASE_ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE_ = 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"""), ] ) SCREAMING_SNAKE_CASE_ = 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"""), ] ) SCREAMING_SNAKE_CASE_ = 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"""), ] ) SCREAMING_SNAKE_CASE_ = 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"""), ] ) SCREAMING_SNAKE_CASE_ = OrderedDict( [ # Model for Image-classsification ("""beit""", """FlaxBeitForImageClassification"""), ("""regnet""", """FlaxRegNetForImageClassification"""), ("""resnet""", """FlaxResNetForImageClassification"""), ("""vit""", """FlaxViTForImageClassification"""), ] ) SCREAMING_SNAKE_CASE_ = OrderedDict( [ ("""vision-encoder-decoder""", """FlaxVisionEncoderDecoderModel"""), ] ) SCREAMING_SNAKE_CASE_ = 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"""), ] ) SCREAMING_SNAKE_CASE_ = 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"""), ] ) SCREAMING_SNAKE_CASE_ = 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"""), ] ) SCREAMING_SNAKE_CASE_ = 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"""), ] ) SCREAMING_SNAKE_CASE_ = 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"""), ] ) SCREAMING_SNAKE_CASE_ = OrderedDict( [ ("""bert""", """FlaxBertForNextSentencePrediction"""), ] ) SCREAMING_SNAKE_CASE_ = OrderedDict( [ ("""speech-encoder-decoder""", """FlaxSpeechEncoderDecoderModel"""), ("""whisper""", """FlaxWhisperForConditionalGeneration"""), ] ) SCREAMING_SNAKE_CASE_ = OrderedDict( [ ("""whisper""", """FlaxWhisperForAudioClassification"""), ] ) SCREAMING_SNAKE_CASE_ = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_MAPPING_NAMES) SCREAMING_SNAKE_CASE_ = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_PRETRAINING_MAPPING_NAMES) SCREAMING_SNAKE_CASE_ = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MASKED_LM_MAPPING_NAMES) SCREAMING_SNAKE_CASE_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES ) SCREAMING_SNAKE_CASE_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES ) SCREAMING_SNAKE_CASE_ = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES) SCREAMING_SNAKE_CASE_ = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_CAUSAL_LM_MAPPING_NAMES) SCREAMING_SNAKE_CASE_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES ) SCREAMING_SNAKE_CASE_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES ) SCREAMING_SNAKE_CASE_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES ) SCREAMING_SNAKE_CASE_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES ) SCREAMING_SNAKE_CASE_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING_NAMES ) SCREAMING_SNAKE_CASE_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES ) SCREAMING_SNAKE_CASE_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES ) class UpperCamelCase__ ( _BaseAutoModelClass ): '''simple docstring''' __snake_case : List[str] = FLAX_MODEL_MAPPING SCREAMING_SNAKE_CASE_ = auto_class_update(FlaxAutoModel) class UpperCamelCase__ ( _BaseAutoModelClass ): '''simple docstring''' __snake_case : Dict = FLAX_MODEL_FOR_PRETRAINING_MAPPING SCREAMING_SNAKE_CASE_ = auto_class_update(FlaxAutoModelForPreTraining, head_doc="""pretraining""") class UpperCamelCase__ ( _BaseAutoModelClass ): '''simple docstring''' __snake_case : Optional[Any] = FLAX_MODEL_FOR_CAUSAL_LM_MAPPING SCREAMING_SNAKE_CASE_ = auto_class_update(FlaxAutoModelForCausalLM, head_doc="""causal language modeling""") class UpperCamelCase__ ( _BaseAutoModelClass ): '''simple docstring''' __snake_case : Any = FLAX_MODEL_FOR_MASKED_LM_MAPPING SCREAMING_SNAKE_CASE_ = auto_class_update(FlaxAutoModelForMaskedLM, head_doc="""masked language modeling""") class UpperCamelCase__ ( _BaseAutoModelClass ): '''simple docstring''' __snake_case : int = FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING SCREAMING_SNAKE_CASE_ = auto_class_update( FlaxAutoModelForSeqaSeqLM, head_doc="""sequence-to-sequence language modeling""", checkpoint_for_example="""t5-base""" ) class UpperCamelCase__ ( _BaseAutoModelClass ): '''simple docstring''' __snake_case : Optional[int] = FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING SCREAMING_SNAKE_CASE_ = auto_class_update( FlaxAutoModelForSequenceClassification, head_doc="""sequence classification""" ) class UpperCamelCase__ ( _BaseAutoModelClass ): '''simple docstring''' __snake_case : List[Any] = FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING SCREAMING_SNAKE_CASE_ = auto_class_update(FlaxAutoModelForQuestionAnswering, head_doc="""question answering""") class UpperCamelCase__ ( _BaseAutoModelClass ): '''simple docstring''' __snake_case : Tuple = FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING SCREAMING_SNAKE_CASE_ = auto_class_update( FlaxAutoModelForTokenClassification, head_doc="""token classification""" ) class UpperCamelCase__ ( _BaseAutoModelClass ): '''simple docstring''' __snake_case : Union[str, Any] = FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING SCREAMING_SNAKE_CASE_ = auto_class_update(FlaxAutoModelForMultipleChoice, head_doc="""multiple choice""") class UpperCamelCase__ ( _BaseAutoModelClass ): '''simple docstring''' __snake_case : List[str] = FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING SCREAMING_SNAKE_CASE_ = auto_class_update( FlaxAutoModelForNextSentencePrediction, head_doc="""next sentence prediction""" ) class UpperCamelCase__ ( _BaseAutoModelClass ): '''simple docstring''' __snake_case : Dict = FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING SCREAMING_SNAKE_CASE_ = auto_class_update( FlaxAutoModelForImageClassification, head_doc="""image classification""" ) class UpperCamelCase__ ( _BaseAutoModelClass ): '''simple docstring''' __snake_case : Dict = FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING SCREAMING_SNAKE_CASE_ = auto_class_update(FlaxAutoModelForVisionaSeq, head_doc="""vision-to-text modeling""") class UpperCamelCase__ ( _BaseAutoModelClass ): '''simple docstring''' __snake_case : Optional[Any] = FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING SCREAMING_SNAKE_CASE_ = auto_class_update( FlaxAutoModelForSpeechSeqaSeq, head_doc="""sequence-to-sequence speech-to-text modeling""" )
296
0
def a ( snake_case__: int , snake_case__: int ): '''simple docstring''' return base * power(snake_case__ , (exponent - 1) ) if exponent else 1 if __name__ == "__main__": print('Raise base to the power of exponent using recursion...') __a = int(input('Enter the base: ').strip()) __a = int(input('Enter the exponent: ').strip()) __a = power(base, abs(exponent)) if exponent < 0: # power() does not properly deal w/ negative exponents __a = 1 / result print(f"{base} to the power of {exponent} is {result}")
30
from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ..auto import CONFIG_MAPPING SCREAMING_SNAKE_CASE_ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE_ = { """microsoft/table-transformer-detection""": ( """https://huggingface.co/microsoft/table-transformer-detection/resolve/main/config.json""" ), } class UpperCamelCase__ ( lowerCAmelCase_ ): '''simple docstring''' __snake_case : Union[str, Any] = "table-transformer" __snake_case : Union[str, Any] = ["past_key_values"] __snake_case : List[Any] = { "hidden_size": "d_model", "num_attention_heads": "encoder_attention_heads", } def __init__( self : Optional[int] ,lowerCamelCase__ : Optional[Any]=True ,lowerCamelCase__ : Optional[Any]=None ,lowerCamelCase__ : List[Any]=3 ,lowerCamelCase__ : Optional[int]=100 ,lowerCamelCase__ : List[Any]=6 ,lowerCamelCase__ : Dict=2048 ,lowerCamelCase__ : List[Any]=8 ,lowerCamelCase__ : Dict=6 ,lowerCamelCase__ : Dict=2048 ,lowerCamelCase__ : Any=8 ,lowerCamelCase__ : Optional[int]=0.0 ,lowerCamelCase__ : int=0.0 ,lowerCamelCase__ : List[Any]=True ,lowerCamelCase__ : Optional[int]="relu" ,lowerCamelCase__ : Tuple=256 ,lowerCamelCase__ : Any=0.1 ,lowerCamelCase__ : Optional[Any]=0.0 ,lowerCamelCase__ : Tuple=0.0 ,lowerCamelCase__ : List[Any]=0.02 ,lowerCamelCase__ : int=1.0 ,lowerCamelCase__ : List[str]=False ,lowerCamelCase__ : Optional[Any]="sine" ,lowerCamelCase__ : List[str]="resnet50" ,lowerCamelCase__ : Optional[Any]=True ,lowerCamelCase__ : List[str]=False ,lowerCamelCase__ : int=1 ,lowerCamelCase__ : Dict=5 ,lowerCamelCase__ : Tuple=2 ,lowerCamelCase__ : Union[str, Any]=1 ,lowerCamelCase__ : str=1 ,lowerCamelCase__ : Any=5 ,lowerCamelCase__ : Tuple=2 ,lowerCamelCase__ : str=0.1 ,**lowerCamelCase__ : List[str] ,) -> Optional[int]: '''simple docstring''' if backbone_config is not None and use_timm_backbone: raise ValueError("""You can't specify both `backbone_config` and `use_timm_backbone`.""" ) if not use_timm_backbone: if backbone_config is None: logger.info("""`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.""" ) SCREAMING_SNAKE_CASE = CONFIG_MAPPING["""resnet"""](out_features=["""stage4"""] ) elif isinstance(lowerCamelCase__ ,lowerCamelCase__ ): SCREAMING_SNAKE_CASE = backbone_config.get("""model_type""" ) SCREAMING_SNAKE_CASE = CONFIG_MAPPING[backbone_model_type] SCREAMING_SNAKE_CASE = config_class.from_dict(lowerCamelCase__ ) # set timm attributes to None SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE = None, None, None SCREAMING_SNAKE_CASE = use_timm_backbone SCREAMING_SNAKE_CASE = backbone_config SCREAMING_SNAKE_CASE = num_channels SCREAMING_SNAKE_CASE = num_queries SCREAMING_SNAKE_CASE = d_model SCREAMING_SNAKE_CASE = encoder_ffn_dim SCREAMING_SNAKE_CASE = encoder_layers SCREAMING_SNAKE_CASE = encoder_attention_heads SCREAMING_SNAKE_CASE = decoder_ffn_dim SCREAMING_SNAKE_CASE = decoder_layers SCREAMING_SNAKE_CASE = decoder_attention_heads SCREAMING_SNAKE_CASE = dropout SCREAMING_SNAKE_CASE = attention_dropout SCREAMING_SNAKE_CASE = activation_dropout SCREAMING_SNAKE_CASE = activation_function SCREAMING_SNAKE_CASE = init_std SCREAMING_SNAKE_CASE = init_xavier_std SCREAMING_SNAKE_CASE = encoder_layerdrop SCREAMING_SNAKE_CASE = decoder_layerdrop SCREAMING_SNAKE_CASE = encoder_layers SCREAMING_SNAKE_CASE = auxiliary_loss SCREAMING_SNAKE_CASE = position_embedding_type SCREAMING_SNAKE_CASE = backbone SCREAMING_SNAKE_CASE = use_pretrained_backbone SCREAMING_SNAKE_CASE = dilation # Hungarian matcher SCREAMING_SNAKE_CASE = class_cost SCREAMING_SNAKE_CASE = bbox_cost SCREAMING_SNAKE_CASE = giou_cost # Loss coefficients SCREAMING_SNAKE_CASE = mask_loss_coefficient SCREAMING_SNAKE_CASE = dice_loss_coefficient SCREAMING_SNAKE_CASE = bbox_loss_coefficient SCREAMING_SNAKE_CASE = giou_loss_coefficient SCREAMING_SNAKE_CASE = eos_coefficient super().__init__(is_encoder_decoder=lowerCamelCase__ ,**lowerCamelCase__ ) @property def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ) -> int: '''simple docstring''' return self.encoder_attention_heads @property def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ) -> int: '''simple docstring''' return self.d_model class UpperCamelCase__ ( lowerCAmelCase_ ): '''simple docstring''' __snake_case : int = version.parse("1.11" ) @property def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' return OrderedDict( [ ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}), ("""pixel_mask""", {0: """batch"""}), ] ) @property def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ) -> float: '''simple docstring''' return 1e-5 @property def SCREAMING_SNAKE_CASE__ ( self : Any ) -> int: '''simple docstring''' return 12
296
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available __SCREAMING_SNAKE_CASE : Optional[int] = { """configuration_altclip""": [ """ALTCLIP_PRETRAINED_CONFIG_ARCHIVE_MAP""", """AltCLIPConfig""", """AltCLIPTextConfig""", """AltCLIPVisionConfig""", ], """processing_altclip""": ["""AltCLIPProcessor"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __SCREAMING_SNAKE_CASE : str = [ """ALTCLIP_PRETRAINED_MODEL_ARCHIVE_LIST""", """AltCLIPPreTrainedModel""", """AltCLIPModel""", """AltCLIPTextModel""", """AltCLIPVisionModel""", ] if TYPE_CHECKING: from .configuration_altclip import ( ALTCLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, AltCLIPConfig, AltCLIPTextConfig, AltCLIPVisionConfig, ) from .processing_altclip import AltCLIPProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_altclip import ( ALTCLIP_PRETRAINED_MODEL_ARCHIVE_LIST, AltCLIPModel, AltCLIPPreTrainedModel, AltCLIPTextModel, AltCLIPVisionModel, ) else: import sys __SCREAMING_SNAKE_CASE : Optional[Any] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
31
from collections import defaultdict from math import gcd def __lowercase ( _SCREAMING_SNAKE_CASE = 1_50_00_00 ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE = defaultdict(_SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE = 2 while 2 * euclid_m * (euclid_m + 1) <= limit: for euclid_n in range((euclid_m % 2) + 1 , _SCREAMING_SNAKE_CASE , 2 ): if gcd(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) > 1: continue SCREAMING_SNAKE_CASE = 2 * euclid_m * (euclid_m + euclid_n) for perimeter in range(_SCREAMING_SNAKE_CASE , limit + 1 , _SCREAMING_SNAKE_CASE ): frequencies[perimeter] += 1 euclid_m += 1 return sum(1 for frequency in frequencies.values() if frequency == 1 ) if __name__ == "__main__": print(F'''{solution() = }''')
296
0
import coval # From: git+https://github.com/ns-moosavi/coval.git # noqa: F401 from coval.conll import reader, util from coval.eval import evaluator import datasets UpperCAmelCase_ : Union[str, Any] = datasets.logging.get_logger(__name__) UpperCAmelCase_ : Dict = '\\n@InProceedings{moosavi2019minimum,\n author = { Nafise Sadat Moosavi, Leo Born, Massimo Poesio and Michael Strube},\n title = {Using Automatically Extracted Minimum Spans to Disentangle Coreference Evaluation from Boundary Detection},\n year = {2019},\n booktitle = {Proceedings of the 57th Annual Meeting of\n the Association for Computational Linguistics (Volume 1: Long Papers)},\n publisher = {Association for Computational Linguistics},\n address = {Florence, Italy},\n}\n\n@inproceedings{10.3115/1072399.1072405,\nauthor = {Vilain, Marc and Burger, John and Aberdeen, John and Connolly, Dennis and Hirschman, Lynette},\ntitle = {A Model-Theoretic Coreference Scoring Scheme},\nyear = {1995},\nisbn = {1558604022},\npublisher = {Association for Computational Linguistics},\naddress = {USA},\nurl = {https://doi.org/10.3115/1072399.1072405},\ndoi = {10.3115/1072399.1072405},\nbooktitle = {Proceedings of the 6th Conference on Message Understanding},\npages = {45–52},\nnumpages = {8},\nlocation = {Columbia, Maryland},\nseries = {MUC6 ’95}\n}\n\n@INPROCEEDINGS{Bagga98algorithmsfor,\n author = {Amit Bagga and Breck Baldwin},\n title = {Algorithms for Scoring Coreference Chains},\n booktitle = {In The First International Conference on Language Resources and Evaluation Workshop on Linguistics Coreference},\n year = {1998},\n pages = {563--566}\n}\n\n@INPROCEEDINGS{Luo05oncoreference,\n author = {Xiaoqiang Luo},\n title = {On coreference resolution performance metrics},\n booktitle = {In Proc. of HLT/EMNLP},\n year = {2005},\n pages = {25--32},\n publisher = {URL}\n}\n\n@inproceedings{moosavi-strube-2016-coreference,\n title = "Which Coreference Evaluation Metric Do You Trust? A Proposal for a Link-based Entity Aware Metric",\n author = "Moosavi, Nafise Sadat and\n Strube, Michael",\n booktitle = "Proceedings of the 54th Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers)",\n month = aug,\n year = "2016",\n address = "Berlin, Germany",\n publisher = "Association for Computational Linguistics",\n url = "https://www.aclweb.org/anthology/P16-1060",\n doi = "10.18653/v1/P16-1060",\n pages = "632--642",\n}\n\n' UpperCAmelCase_ : str = '\\nCoVal is a coreference evaluation tool for the CoNLL and ARRAU datasets which\nimplements of the common evaluation metrics including MUC [Vilain et al, 1995],\nB-cubed [Bagga and Baldwin, 1998], CEAFe [Luo et al., 2005],\nLEA [Moosavi and Strube, 2016] and the averaged CoNLL score\n(the average of the F1 values of MUC, B-cubed and CEAFe)\n[Denis and Baldridge, 2009a; Pradhan et al., 2011].\n\nThis wrapper of CoVal currently only work with CoNLL line format:\nThe CoNLL format has one word per line with all the annotation for this word in column separated by spaces:\nColumn Type Description\n1 Document ID This is a variation on the document filename\n2 Part number Some files are divided into multiple parts numbered as 000, 001, 002, ... etc.\n3 Word number\n4 Word itself This is the token as segmented/tokenized in the Treebank. Initially the *_skel file contain the placeholder [WORD] which gets replaced by the actual token from the Treebank which is part of the OntoNotes release.\n5 Part-of-Speech\n6 Parse bit This is the bracketed structure broken before the first open parenthesis in the parse, and the word/part-of-speech leaf replaced with a *. The full parse can be created by substituting the asterix with the "([pos] [word])" string (or leaf) and concatenating the items in the rows of that column.\n7 Predicate lemma The predicate lemma is mentioned for the rows for which we have semantic role information. All other rows are marked with a "-"\n8 Predicate Frameset ID This is the PropBank frameset ID of the predicate in Column 7.\n9 Word sense This is the word sense of the word in Column 3.\n10 Speaker/Author This is the speaker or author name where available. Mostly in Broadcast Conversation and Web Log data.\n11 Named Entities These columns identifies the spans representing various named entities.\n12:N Predicate Arguments There is one column each of predicate argument structure information for the predicate mentioned in Column 7.\nN Coreference Coreference chain information encoded in a parenthesis structure.\nMore informations on the format can be found here (section "*_conll File Format"): http://www.conll.cemantix.org/2012/data.html\n\nDetails on the evaluation on CoNLL can be found here: https://github.com/ns-moosavi/coval/blob/master/conll/README.md\n\nCoVal code was written by @ns-moosavi.\nSome parts are borrowed from https://github.com/clarkkev/deep-coref/blob/master/evaluation.py\nThe test suite is taken from https://github.com/conll/reference-coreference-scorers/\nMention evaluation and the test suite are added by @andreasvc.\nParsing CoNLL files is developed by Leo Born.\n' UpperCAmelCase_ : int = '\nCalculates coreference evaluation metrics.\nArgs:\n predictions: list of sentences. Each sentence is a list of word predictions to score in the CoNLL format.\n Each prediction is a word with its annotations as a string made of columns joined with spaces.\n Only columns 4, 5, 6 and the last column are used (word, POS, Pars and coreference annotation)\n See the details on the format in the description of the metric.\n references: list of sentences. Each sentence is a list of word reference to score in the CoNLL format.\n Each reference is a word with its annotations as a string made of columns joined with spaces.\n Only columns 4, 5, 6 and the last column are used (word, POS, Pars and coreference annotation)\n See the details on the format in the description of the metric.\n keep_singletons: After extracting all mentions of key or system files,\n mentions whose corresponding coreference chain is of size one,\n are considered as singletons. The default evaluation mode will include\n singletons in evaluations if they are included in the key or the system files.\n By setting \'keep_singletons=False\', all singletons in the key and system files\n will be excluded from the evaluation.\n NP_only: Most of the recent coreference resolvers only resolve NP mentions and\n leave out the resolution of VPs. By setting the \'NP_only\' option, the scorer will only evaluate the resolution of NPs.\n min_span: By setting \'min_span\', the scorer reports the results based on automatically detected minimum spans.\n Minimum spans are determined using the MINA algorithm.\n\nReturns:\n \'mentions\': mentions\n \'muc\': MUC metric [Vilain et al, 1995]\n \'bcub\': B-cubed [Bagga and Baldwin, 1998]\n \'ceafe\': CEAFe [Luo et al., 2005]\n \'lea\': LEA [Moosavi and Strube, 2016]\n \'conll_score\': averaged CoNLL score (the average of the F1 values of MUC, B-cubed and CEAFe)\n\nExamples:\n\n >>> coval = datasets.load_metric(\'coval\')\n >>> words = [\'bc/cctv/00/cctv_0005 0 0 Thank VBP (TOP(S(VP* thank 01 1 Xu_li * (V*) * -\',\n ... \'bc/cctv/00/cctv_0005 0 1 you PRP (NP*) - - - Xu_li * (ARG1*) (ARG0*) (116)\',\n ... \'bc/cctv/00/cctv_0005 0 2 everyone NN (NP*) - - - Xu_li * (ARGM-DIS*) * (116)\',\n ... \'bc/cctv/00/cctv_0005 0 3 for IN (PP* - - - Xu_li * (ARG2* * -\',\n ... \'bc/cctv/00/cctv_0005 0 4 watching VBG (S(VP*)))) watch 01 1 Xu_li * *) (V*) -\',\n ... \'bc/cctv/00/cctv_0005 0 5 . . *)) - - - Xu_li * * * -\']\n >>> references = [words]\n >>> predictions = [words]\n >>> results = coval.compute(predictions=predictions, references=references)\n >>> print(results) # doctest:+ELLIPSIS\n {\'mentions/recall\': 1.0,[...] \'conll_score\': 100.0}\n' def SCREAMING_SNAKE_CASE_ ( __A : Optional[int] , __A : List[str] , __A : List[Any]=False , __A : Tuple=False , __A : Union[str, Any]=True , __A : List[str]=False , __A : Optional[int]="dummy_doc" ) -> Any: """simple docstring""" a_ : Any = {doc: key_lines} a_ : List[Any] = {doc: sys_lines} a_ : Union[str, Any] = {} a_ : int = 0 a_ : List[Any] = 0 a_ : Union[str, Any] = 0 a_ : Union[str, Any] = 0 a_ : int = 0 a_ : Optional[int] = 0 a_ , a_ : Optional[int] = reader.get_doc_mentions(__A , key_doc_lines[doc] , __A ) key_singletons_num += singletons_num if NP_only or min_span: a_ : List[Any] = reader.set_annotated_parse_trees(__A , key_doc_lines[doc] , __A , __A ) a_ , a_ : List[str] = reader.get_doc_mentions(__A , sys_doc_lines[doc] , __A ) sys_singletons_num += singletons_num if NP_only or min_span: a_ : int = reader.set_annotated_parse_trees(__A , key_doc_lines[doc] , __A , __A ) if remove_nested: a_ , a_ : Union[str, Any] = reader.remove_nested_coref_mentions(__A , __A ) key_nested_coref_num += nested_mentions key_removed_nested_clusters += removed_clusters a_ , a_ : Union[str, Any] = reader.remove_nested_coref_mentions(__A , __A ) sys_nested_coref_num += nested_mentions sys_removed_nested_clusters += removed_clusters a_ : Any = reader.get_mention_assignments(__A , __A ) a_ : List[str] = reader.get_mention_assignments(__A , __A ) a_ : Dict = (key_clusters, sys_clusters, key_mention_sys_cluster, sys_mention_key_cluster) if remove_nested: logger.info( 'Number of removed nested coreferring mentions in the key ' F"""annotation: {key_nested_coref_num}; and system annotation: {sys_nested_coref_num}""" ) logger.info( 'Number of resulting singleton clusters in the key ' F"""annotation: {key_removed_nested_clusters}; and system annotation: {sys_removed_nested_clusters}""" ) if not keep_singletons: logger.info( F"""{key_singletons_num:d} and {sys_singletons_num:d} singletons are removed from the key and system """ 'files, respectively' ) return doc_coref_infos def SCREAMING_SNAKE_CASE_ ( __A : List[Any] , __A : str , __A : str , __A : List[str] , __A : Any , __A : Optional[int] , __A : Dict ) -> Optional[int]: """simple docstring""" a_ : Tuple = get_coref_infos(__A , __A , __A , __A , __A , __A ) a_ : Optional[int] = {} a_ : Union[str, Any] = 0 a_ : str = 0 for name, metric in metrics: a_ , a_ , a_ : Any = evaluator.evaluate_documents(__A , __A , beta=1 ) if name in ["muc", "bcub", "ceafe"]: conll += fa conll_subparts_num += 1 output_scores.update({F"""{name}/recall""": recall, F"""{name}/precision""": precision, F"""{name}/f1""": fa} ) logger.info( name.ljust(10 ) , F"""Recall: {recall * 1_00:.2f}""" , F""" Precision: {precision * 1_00:.2f}""" , F""" F1: {fa * 1_00:.2f}""" , ) if conll_subparts_num == 3: a_ : List[Any] = (conll / 3) * 1_00 logger.info(F"""CoNLL score: {conll:.2f}""" ) output_scores.update({'conll_score': conll} ) return output_scores def SCREAMING_SNAKE_CASE_ ( __A : Tuple ) -> Union[str, Any]: """simple docstring""" a_ : Union[str, Any] = False for line in key_lines: if not line.startswith('#' ): if len(line.split() ) > 6: a_ : str = line.split()[5] if not parse_col == "-": a_ : Optional[int] = True break else: break return has_gold_parse @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class SCREAMING_SNAKE_CASE__ ( datasets.Metric ): def SCREAMING_SNAKE_CASE ( self : Dict ) -> List[Any]: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { 'predictions': datasets.Sequence(datasets.Value('string' ) ), 'references': datasets.Sequence(datasets.Value('string' ) ), } ) , codebase_urls=['https://github.com/ns-moosavi/coval'] , reference_urls=[ 'https://github.com/ns-moosavi/coval', 'https://www.aclweb.org/anthology/P16-1060', 'http://www.conll.cemantix.org/2012/data.html', ] , ) def SCREAMING_SNAKE_CASE ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Dict=True , SCREAMING_SNAKE_CASE__ : str=False , SCREAMING_SNAKE_CASE__ : Optional[Any]=False , SCREAMING_SNAKE_CASE__ : List[str]=False ) -> List[str]: a_ : str = [ ('mentions', evaluator.mentions), ('muc', evaluator.muc), ('bcub', evaluator.b_cubed), ('ceafe', evaluator.ceafe), ('lea', evaluator.lea), ] if min_span: a_ : Tuple = util.check_gold_parse_annotation(SCREAMING_SNAKE_CASE__ ) if not has_gold_parse: raise NotImplementedError('References should have gold parse annotation to use \'min_span\'.' ) # util.parse_key_file(key_file) # key_file = key_file + ".parsed" a_ : List[str] = evaluate( key_lines=SCREAMING_SNAKE_CASE__ , sys_lines=SCREAMING_SNAKE_CASE__ , metrics=SCREAMING_SNAKE_CASE__ , NP_only=SCREAMING_SNAKE_CASE__ , remove_nested=SCREAMING_SNAKE_CASE__ , keep_singletons=SCREAMING_SNAKE_CASE__ , min_span=SCREAMING_SNAKE_CASE__ , ) return score
32
from argparse import ArgumentParser from .env import EnvironmentCommand def __lowercase ( ) -> Dict: '''simple docstring''' SCREAMING_SNAKE_CASE = ArgumentParser("""Diffusers CLI tool""" , usage="""diffusers-cli <command> [<args>]""" ) SCREAMING_SNAKE_CASE = parser.add_subparsers(help="""diffusers-cli command helpers""" ) # Register commands EnvironmentCommand.register_subcommand(_SCREAMING_SNAKE_CASE ) # Let's go SCREAMING_SNAKE_CASE = parser.parse_args() if not hasattr(_SCREAMING_SNAKE_CASE , """func""" ): parser.print_help() exit(1 ) # Run SCREAMING_SNAKE_CASE = args.func(_SCREAMING_SNAKE_CASE ) service.run() if __name__ == "__main__": main()
296
0
"""simple docstring""" from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import Features, Sequence, Value from .base import TaskTemplate @dataclass(frozen=_A ) class _UpperCAmelCase ( _A ): # `task` is not a ClassVar since we want it to be part of the `asdict` output for JSON serialization SCREAMING_SNAKE_CASE_ : str = field(default="question-answering-extractive" , metadata={"include_in_asdict_even_if_is_default": True} ) SCREAMING_SNAKE_CASE_ : ClassVar[Features] = Features({"question": Value("string" ), "context": Value("string" )} ) SCREAMING_SNAKE_CASE_ : ClassVar[Features] = Features( { "answers": Sequence( { "text": Value("string" ), "answer_start": Value("int32" ), } ) } ) SCREAMING_SNAKE_CASE_ : str = "question" SCREAMING_SNAKE_CASE_ : str = "context" SCREAMING_SNAKE_CASE_ : str = "answers" @property def A ( self : Any ) -> Dict[str, str]: return {self.question_column: "question", self.context_column: "context", self.answers_column: "answers"}
33
import argparse import json import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import AutoImageProcessor, SwinConfig, SwinForImageClassification def __lowercase ( _SCREAMING_SNAKE_CASE ) -> Union[str, Any]: '''simple docstring''' SCREAMING_SNAKE_CASE = SwinConfig() SCREAMING_SNAKE_CASE = swin_name.split("""_""" ) SCREAMING_SNAKE_CASE = name_split[1] SCREAMING_SNAKE_CASE = int(name_split[4] ) SCREAMING_SNAKE_CASE = int(name_split[3][-1] ) if model_size == "tiny": SCREAMING_SNAKE_CASE = 96 SCREAMING_SNAKE_CASE = (2, 2, 6, 2) SCREAMING_SNAKE_CASE = (3, 6, 12, 24) elif model_size == "small": SCREAMING_SNAKE_CASE = 96 SCREAMING_SNAKE_CASE = (2, 2, 18, 2) SCREAMING_SNAKE_CASE = (3, 6, 12, 24) elif model_size == "base": SCREAMING_SNAKE_CASE = 1_28 SCREAMING_SNAKE_CASE = (2, 2, 18, 2) SCREAMING_SNAKE_CASE = (4, 8, 16, 32) else: SCREAMING_SNAKE_CASE = 1_92 SCREAMING_SNAKE_CASE = (2, 2, 18, 2) SCREAMING_SNAKE_CASE = (6, 12, 24, 48) if "in22k" in swin_name: SCREAMING_SNAKE_CASE = 2_18_41 else: SCREAMING_SNAKE_CASE = 10_00 SCREAMING_SNAKE_CASE = """huggingface/label-files""" SCREAMING_SNAKE_CASE = """imagenet-1k-id2label.json""" SCREAMING_SNAKE_CASE = json.load(open(hf_hub_download(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , repo_type="""dataset""" ) , """r""" ) ) SCREAMING_SNAKE_CASE = {int(_SCREAMING_SNAKE_CASE ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE = idalabel SCREAMING_SNAKE_CASE = {v: k for k, v in idalabel.items()} SCREAMING_SNAKE_CASE = img_size SCREAMING_SNAKE_CASE = num_classes SCREAMING_SNAKE_CASE = embed_dim SCREAMING_SNAKE_CASE = depths SCREAMING_SNAKE_CASE = num_heads SCREAMING_SNAKE_CASE = window_size return config def __lowercase ( _SCREAMING_SNAKE_CASE ) -> Dict: '''simple docstring''' if "patch_embed.proj" in name: SCREAMING_SNAKE_CASE = name.replace("""patch_embed.proj""" , """embeddings.patch_embeddings.projection""" ) if "patch_embed.norm" in name: SCREAMING_SNAKE_CASE = name.replace("""patch_embed.norm""" , """embeddings.norm""" ) if "layers" in name: SCREAMING_SNAKE_CASE = """encoder.""" + name if "attn.proj" in name: SCREAMING_SNAKE_CASE = name.replace("""attn.proj""" , """attention.output.dense""" ) if "attn" in name: SCREAMING_SNAKE_CASE = name.replace("""attn""" , """attention.self""" ) if "norm1" in name: SCREAMING_SNAKE_CASE = name.replace("""norm1""" , """layernorm_before""" ) if "norm2" in name: SCREAMING_SNAKE_CASE = name.replace("""norm2""" , """layernorm_after""" ) if "mlp.fc1" in name: SCREAMING_SNAKE_CASE = name.replace("""mlp.fc1""" , """intermediate.dense""" ) if "mlp.fc2" in name: SCREAMING_SNAKE_CASE = name.replace("""mlp.fc2""" , """output.dense""" ) if name == "norm.weight": SCREAMING_SNAKE_CASE = """layernorm.weight""" if name == "norm.bias": SCREAMING_SNAKE_CASE = """layernorm.bias""" if "head" in name: SCREAMING_SNAKE_CASE = name.replace("""head""" , """classifier""" ) else: SCREAMING_SNAKE_CASE = """swin.""" + name return name def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Any: '''simple docstring''' for key in orig_state_dict.copy().keys(): SCREAMING_SNAKE_CASE = orig_state_dict.pop(_SCREAMING_SNAKE_CASE ) if "mask" in key: continue elif "qkv" in key: SCREAMING_SNAKE_CASE = key.split(""".""" ) SCREAMING_SNAKE_CASE = int(key_split[1] ) SCREAMING_SNAKE_CASE = int(key_split[3] ) SCREAMING_SNAKE_CASE = model.swin.encoder.layers[layer_num].blocks[block_num].attention.self.all_head_size if "weight" in key: SCREAMING_SNAKE_CASE = val[:dim, :] SCREAMING_SNAKE_CASE = val[ dim : dim * 2, : ] SCREAMING_SNAKE_CASE = val[-dim:, :] else: SCREAMING_SNAKE_CASE = val[ :dim ] SCREAMING_SNAKE_CASE = val[ dim : dim * 2 ] SCREAMING_SNAKE_CASE = val[ -dim: ] else: SCREAMING_SNAKE_CASE = val return orig_state_dict def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> List[str]: '''simple docstring''' SCREAMING_SNAKE_CASE = timm.create_model(_SCREAMING_SNAKE_CASE , pretrained=_SCREAMING_SNAKE_CASE ) timm_model.eval() SCREAMING_SNAKE_CASE = get_swin_config(_SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE = SwinForImageClassification(_SCREAMING_SNAKE_CASE ) model.eval() SCREAMING_SNAKE_CASE = convert_state_dict(timm_model.state_dict() , _SCREAMING_SNAKE_CASE ) model.load_state_dict(_SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE = """http://images.cocodataset.org/val2017/000000039769.jpg""" SCREAMING_SNAKE_CASE = AutoImageProcessor.from_pretrained("""microsoft/{}""".format(swin_name.replace("""_""" , """-""" ) ) ) SCREAMING_SNAKE_CASE = Image.open(requests.get(_SCREAMING_SNAKE_CASE , stream=_SCREAMING_SNAKE_CASE ).raw ) SCREAMING_SNAKE_CASE = image_processor(images=_SCREAMING_SNAKE_CASE , return_tensors="""pt""" ) SCREAMING_SNAKE_CASE = timm_model(inputs["""pixel_values"""] ) SCREAMING_SNAKE_CASE = model(**_SCREAMING_SNAKE_CASE ).logits assert torch.allclose(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , atol=1E-3 ) print(F"""Saving model {swin_name} to {pytorch_dump_folder_path}""" ) model.save_pretrained(_SCREAMING_SNAKE_CASE ) print(F"""Saving image processor to {pytorch_dump_folder_path}""" ) image_processor.save_pretrained(_SCREAMING_SNAKE_CASE ) if __name__ == "__main__": SCREAMING_SNAKE_CASE_ = argparse.ArgumentParser() # Required parameters parser.add_argument( """--swin_name""", default="""swin_tiny_patch4_window7_224""", type=str, help="""Name of the Swin timm model you'd like to convert.""", ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model directory.""" ) SCREAMING_SNAKE_CASE_ = parser.parse_args() convert_swin_checkpoint(args.swin_name, args.pytorch_dump_folder_path)
296
0
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices A =logging.get_logger(__name__) A ={ 'facebook/convnextv2-tiny-1k-224': 'https://huggingface.co/facebook/convnextv2-tiny-1k-224/resolve/main/config.json', } class _a ( __a , __a ): __a : Union[str, Any] = """convnextv2""" def __init__( self : str , lowercase : Optional[Any]=3 , lowercase : Optional[Any]=4 , lowercase : Tuple=4 , lowercase : Optional[int]=None , lowercase : Optional[int]=None , lowercase : List[Any]="gelu" , lowercase : str=0.02 , lowercase : List[Any]=1E-12 , lowercase : List[str]=0.0 , lowercase : Dict=224 , lowercase : Dict=None , lowercase : List[Any]=None , **lowercase : int , ): '''simple docstring''' super().__init__(**lowercase ) UpperCAmelCase = num_channels UpperCAmelCase = patch_size UpperCAmelCase = num_stages UpperCAmelCase = [96, 192, 384, 768] if hidden_sizes is None else hidden_sizes UpperCAmelCase = [3, 3, 9, 3] if depths is None else depths UpperCAmelCase = hidden_act UpperCAmelCase = initializer_range UpperCAmelCase = layer_norm_eps UpperCAmelCase = drop_path_rate UpperCAmelCase = image_size UpperCAmelCase = ['''stem'''] + [f"stage{idx}" for idx in range(1 , len(self.depths ) + 1 )] UpperCAmelCase , UpperCAmelCase = get_aligned_output_features_output_indices( out_features=lowercase , out_indices=lowercase , stage_names=self.stage_names )
34
import os from distutils.util import strtobool def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Tuple: '''simple docstring''' for e in env_keys: SCREAMING_SNAKE_CASE = int(os.environ.get(_SCREAMING_SNAKE_CASE , -1 ) ) if val >= 0: return val return default def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=False ) -> Optional[int]: '''simple docstring''' SCREAMING_SNAKE_CASE = os.environ.get(_SCREAMING_SNAKE_CASE , str(_SCREAMING_SNAKE_CASE ) ) return strtobool(_SCREAMING_SNAKE_CASE ) == 1 # As its name indicates `strtobool` actually returns an int... def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE="no" ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE = os.environ.get(_SCREAMING_SNAKE_CASE , str(_SCREAMING_SNAKE_CASE ) ) return value
296
0
'''simple docstring''' import bza import gzip import lzma import os import shutil import struct import tarfile import warnings import zipfile from abc import ABC, abstractmethod from pathlib import Path from typing import Dict, List, Optional, Type, Union from .. import config from .filelock import FileLock from .logging import get_logger __a = get_logger(__name__) class UpperCAmelCase_ : """simple docstring""" def __init__( self : Any , snake_case_ : Optional[str] = None ): snake_case__ : List[Any] = ( os.path.join(snake_case_ , config.EXTRACTED_DATASETS_DIR ) if cache_dir else config.EXTRACTED_DATASETS_PATH ) snake_case__ : Any = Extractor def lowerCamelCase ( self : Optional[Any] , snake_case_ : str ): from .file_utils import hash_url_to_filename # Path where we extract compressed archives # We extract in the cache dir, and get the extracted path name by hashing the original path" snake_case__ : str = os.path.abspath(snake_case_ ) return os.path.join(self.extract_dir , hash_url_to_filename(snake_case_ ) ) def lowerCamelCase ( self : Optional[Any] , snake_case_ : str , snake_case_ : bool ): return force_extract or ( not os.path.isfile(snake_case_ ) and not (os.path.isdir(snake_case_ ) and os.listdir(snake_case_ )) ) def lowerCamelCase ( self : str , snake_case_ : str , snake_case_ : bool = False ): snake_case__ : Dict = self.extractor.infer_extractor_format(snake_case_ ) if not extractor_format: return input_path snake_case__ : List[Any] = self._get_output_path(snake_case_ ) if self._do_extract(snake_case_ , snake_case_ ): self.extractor.extract(snake_case_ , snake_case_ , snake_case_ ) return output_path class UpperCAmelCase_ ( _a ): """simple docstring""" @classmethod @abstractmethod def lowerCamelCase ( cls : Optional[int] , snake_case_ : Union[Path, str] , **snake_case_ : Tuple ): ... @staticmethod @abstractmethod def lowerCamelCase ( snake_case_ : Union[Path, str] , snake_case_ : Union[Path, str] ): ... class UpperCAmelCase_ ( _a , _a ): """simple docstring""" lowercase = [] @staticmethod def lowerCamelCase ( snake_case_ : Union[Path, str] , snake_case_ : int ): with open(snake_case_ , """rb""" ) as f: return f.read(snake_case_ ) @classmethod def lowerCamelCase ( cls : Any , snake_case_ : Union[Path, str] , snake_case_ : bytes = b"" ): if not magic_number: snake_case__ : Optional[Any] = max(len(snake_case_ ) for cls_magic_number in cls.magic_numbers ) try: snake_case__ : List[str] = cls.read_magic_number(snake_case_ , snake_case_ ) except OSError: return False return any(magic_number.startswith(snake_case_ ) for cls_magic_number in cls.magic_numbers ) class UpperCAmelCase_ ( _a ): """simple docstring""" @classmethod def lowerCamelCase ( cls : Union[str, Any] , snake_case_ : Union[Path, str] , **snake_case_ : Union[str, Any] ): return tarfile.is_tarfile(snake_case_ ) @staticmethod def lowerCamelCase ( snake_case_ : List[str] , snake_case_ : Optional[Any] ): def resolved(snake_case_ : str ) -> str: return os.path.realpath(os.path.abspath(snake_case_ ) ) def badpath(snake_case_ : str , snake_case_ : str ) -> bool: # joinpath will ignore base if path is absolute return not resolved(os.path.join(snake_case_ , snake_case_ ) ).startswith(snake_case_ ) def badlink(snake_case_ : str , snake_case_ : str ) -> bool: # Links are interpreted relative to the directory containing the link snake_case__ : List[Any] = resolved(os.path.join(snake_case_ , os.path.dirname(info.name ) ) ) return badpath(info.linkname , base=snake_case_ ) snake_case__ : Optional[int] = resolved(snake_case_ ) for finfo in members: if badpath(finfo.name , snake_case_ ): logger.error(f"Extraction of {finfo.name} is blocked (illegal path)" ) elif finfo.issym() and badlink(snake_case_ , snake_case_ ): logger.error(f"Extraction of {finfo.name} is blocked: Symlink to {finfo.linkname}" ) elif finfo.islnk() and badlink(snake_case_ , snake_case_ ): logger.error(f"Extraction of {finfo.name} is blocked: Hard link to {finfo.linkname}" ) else: yield finfo @staticmethod def lowerCamelCase ( snake_case_ : Union[Path, str] , snake_case_ : Union[Path, str] ): os.makedirs(snake_case_ , exist_ok=snake_case_ ) snake_case__ : List[Any] = tarfile.open(snake_case_ ) tar_file.extractall(snake_case_ , members=TarExtractor.safemembers(snake_case_ , snake_case_ ) ) tar_file.close() class UpperCAmelCase_ ( _a ): """simple docstring""" lowercase = [b"\x1F\x8B"] @staticmethod def lowerCamelCase ( snake_case_ : Union[Path, str] , snake_case_ : Union[Path, str] ): with gzip.open(snake_case_ , """rb""" ) as gzip_file: with open(snake_case_ , """wb""" ) as extracted_file: shutil.copyfileobj(snake_case_ , snake_case_ ) class UpperCAmelCase_ ( _a ): """simple docstring""" lowercase = [ b"PK\x03\x04", b"PK\x05\x06", # empty archive b"PK\x07\x08", # spanned archive ] @classmethod def lowerCamelCase ( cls : int , snake_case_ : Union[Path, str] , snake_case_ : bytes = b"" ): if super().is_extractable(snake_case_ , magic_number=snake_case_ ): return True try: # Alternative version of zipfile.is_zipfile that has less false positives, but misses executable zip archives. # From: https://github.com/python/cpython/pull/5053 from zipfile import ( _CD_SIGNATURE, _ECD_DISK_NUMBER, _ECD_DISK_START, _ECD_ENTRIES_TOTAL, _ECD_OFFSET, _ECD_SIZE, _EndRecData, sizeCentralDir, stringCentralDir, structCentralDir, ) with open(snake_case_ , """rb""" ) as fp: snake_case__ : Any = _EndRecData(snake_case_ ) if endrec: if endrec[_ECD_ENTRIES_TOTAL] == 0 and endrec[_ECD_SIZE] == 0 and endrec[_ECD_OFFSET] == 0: return True # Empty zipfiles are still zipfiles elif endrec[_ECD_DISK_NUMBER] == endrec[_ECD_DISK_START]: fp.seek(endrec[_ECD_OFFSET] ) # Central directory is on the same disk if fp.tell() == endrec[_ECD_OFFSET] and endrec[_ECD_SIZE] >= sizeCentralDir: snake_case__ : List[str] = fp.read(snake_case_ ) # CD is where we expect it to be if len(snake_case_ ) == sizeCentralDir: snake_case__ : Dict = struct.unpack(snake_case_ , snake_case_ ) # CD is the right size if centdir[_CD_SIGNATURE] == stringCentralDir: return True # First central directory entry has correct magic number return False except Exception: # catch all errors in case future python versions change the zipfile internals return False @staticmethod def lowerCamelCase ( snake_case_ : Union[Path, str] , snake_case_ : Union[Path, str] ): os.makedirs(snake_case_ , exist_ok=snake_case_ ) with zipfile.ZipFile(snake_case_ , """r""" ) as zip_file: zip_file.extractall(snake_case_ ) zip_file.close() class UpperCAmelCase_ ( _a ): """simple docstring""" lowercase = [b"\xFD\x37\x7A\x58\x5A\x00"] @staticmethod def lowerCamelCase ( snake_case_ : Union[Path, str] , snake_case_ : Union[Path, str] ): with lzma.open(snake_case_ ) as compressed_file: with open(snake_case_ , """wb""" ) as extracted_file: shutil.copyfileobj(snake_case_ , snake_case_ ) class UpperCAmelCase_ ( _a ): """simple docstring""" lowercase = [b"Rar!\x1a\x07\x00", b"Rar!\x1a\x07\x01\x00"] # RAR_ID # RAR5_ID @staticmethod def lowerCamelCase ( snake_case_ : Union[Path, str] , snake_case_ : Union[Path, str] ): if not config.RARFILE_AVAILABLE: raise ImportError("""Please pip install rarfile""" ) import rarfile os.makedirs(snake_case_ , exist_ok=snake_case_ ) snake_case__ : Tuple = rarfile.RarFile(snake_case_ ) rf.extractall(snake_case_ ) rf.close() class UpperCAmelCase_ ( _a ): """simple docstring""" lowercase = [b"\x28\xb5\x2F\xFD"] @staticmethod def lowerCamelCase ( snake_case_ : Union[Path, str] , snake_case_ : Union[Path, str] ): if not config.ZSTANDARD_AVAILABLE: raise ImportError("""Please pip install zstandard""" ) import zstandard as zstd snake_case__ : Dict = zstd.ZstdDecompressor() with open(snake_case_ , """rb""" ) as ifh, open(snake_case_ , """wb""" ) as ofh: dctx.copy_stream(snake_case_ , snake_case_ ) class UpperCAmelCase_ ( _a ): """simple docstring""" lowercase = [b"\x42\x5A\x68"] @staticmethod def lowerCamelCase ( snake_case_ : Union[Path, str] , snake_case_ : Union[Path, str] ): with bza.open(snake_case_ , """rb""" ) as compressed_file: with open(snake_case_ , """wb""" ) as extracted_file: shutil.copyfileobj(snake_case_ , snake_case_ ) class UpperCAmelCase_ ( _a ): """simple docstring""" lowercase = [b"\x37\x7A\xBC\xAF\x27\x1C"] @staticmethod def lowerCamelCase ( snake_case_ : Union[Path, str] , snake_case_ : Union[Path, str] ): if not config.PY7ZR_AVAILABLE: raise ImportError("""Please pip install py7zr""" ) import pyazr os.makedirs(snake_case_ , exist_ok=snake_case_ ) with pyazr.SevenZipFile(snake_case_ , """r""" ) as archive: archive.extractall(snake_case_ ) class UpperCAmelCase_ ( _a ): """simple docstring""" lowercase = [b"\x04\x22\x4D\x18"] @staticmethod def lowerCamelCase ( snake_case_ : Union[Path, str] , snake_case_ : Union[Path, str] ): if not config.LZ4_AVAILABLE: raise ImportError("""Please pip install lz4""" ) import lza.frame with lza.frame.open(snake_case_ , """rb""" ) as compressed_file: with open(snake_case_ , """wb""" ) as extracted_file: shutil.copyfileobj(snake_case_ , snake_case_ ) class UpperCAmelCase_ : """simple docstring""" lowercase = { "tar": TarExtractor, "gzip": GzipExtractor, "zip": ZipExtractor, "xz": XzExtractor, "rar": RarExtractor, "zstd": ZstdExtractor, "bz2": BzipaExtractor, "7z": SevenZipExtractor, # <Added version="2.4.0"/> "lz4": LzaExtractor, # <Added version="2.4.0"/> } @classmethod def lowerCamelCase ( cls : List[str] ): return max( len(snake_case_ ) for extractor in cls.extractors.values() if issubclass(snake_case_ , snake_case_ ) for extractor_magic_number in extractor.magic_numbers ) @staticmethod def lowerCamelCase ( snake_case_ : Union[Path, str] , snake_case_ : int ): try: return MagicNumberBaseExtractor.read_magic_number(snake_case_ , magic_number_length=snake_case_ ) except OSError: return b"" @classmethod def lowerCamelCase ( cls : int , snake_case_ : Union[Path, str] , snake_case_ : bool = False ): warnings.warn( """Method 'is_extractable' was deprecated in version 2.4.0 and will be removed in 3.0.0. """ """Use 'infer_extractor_format' instead.""" , category=snake_case_ , ) snake_case__ : str = cls.infer_extractor_format(snake_case_ ) if extractor_format: return True if not return_extractor else (True, cls.extractors[extractor_format]) return False if not return_extractor else (False, None) @classmethod def lowerCamelCase ( cls : Optional[int] , snake_case_ : Union[Path, str] ): # <Added version="2.4.0"/> snake_case__ : str = cls._get_magic_number_max_length() snake_case__ : Dict = cls._read_magic_number(snake_case_ , snake_case_ ) for extractor_format, extractor in cls.extractors.items(): if extractor.is_extractable(snake_case_ , magic_number=snake_case_ ): return extractor_format @classmethod def lowerCamelCase ( cls : Any , snake_case_ : Union[Path, str] , snake_case_ : Union[Path, str] , snake_case_ : Optional[str] = None , snake_case_ : Optional[BaseExtractor] = "deprecated" , ): os.makedirs(os.path.dirname(snake_case_ ) , exist_ok=snake_case_ ) # Prevent parallel extractions snake_case__ : str = str(Path(snake_case_ ).with_suffix(""".lock""" ) ) with FileLock(snake_case_ ): shutil.rmtree(snake_case_ , ignore_errors=snake_case_ ) if extractor_format or extractor != "deprecated": if extractor != "deprecated" or not isinstance(snake_case_ , snake_case_ ): # passed as positional arg warnings.warn( """Parameter 'extractor' was deprecated in version 2.4.0 and will be removed in 3.0.0. """ """Use 'extractor_format' instead.""" , category=snake_case_ , ) snake_case__ : int = extractor if extractor != """deprecated""" else extractor_format else: snake_case__ : str = cls.extractors[extractor_format] return extractor.extract(snake_case_ , snake_case_ ) else: warnings.warn( """Parameter 'extractor_format' was made required in version 2.4.0 and not passing it will raise an """ """exception in 3.0.0.""" , category=snake_case_ , ) for extractor in cls.extractors.values(): if extractor.is_extractable(snake_case_ ): return extractor.extract(snake_case_ , snake_case_ )
35
import dataclasses import json import warnings from dataclasses import dataclass, field from time import time from typing import List from ..utils import logging SCREAMING_SNAKE_CASE_ = logging.get_logger(__name__) def __lowercase ( _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None ) -> List[str]: '''simple docstring''' return field(default_factory=lambda: default , metadata=_SCREAMING_SNAKE_CASE ) @dataclass class UpperCamelCase__ : '''simple docstring''' __snake_case : 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" ) } , ) __snake_case : List[int] = list_field( default=[8] , metadata={"help": "List of batch sizes for which memory and time performance will be evaluated"} ) __snake_case : List[int] = list_field( default=[8, 32, 128, 512] , metadata={"help": "List of sequence lengths for which memory and time performance will be evaluated"} , ) __snake_case : bool = field( default=lowerCAmelCase_ , metadata={"help": "Whether to benchmark inference of model. Inference can be disabled via --no-inference."} , ) __snake_case : bool = field( default=lowerCAmelCase_ , metadata={"help": "Whether to run on available cuda devices. Cuda can be disabled via --no-cuda."} , ) __snake_case : bool = field( default=lowerCAmelCase_ , metadata={"help": "Whether to run on available tpu devices. TPU can be disabled via --no-tpu."} ) __snake_case : bool = field(default=lowerCAmelCase_ , metadata={"help": "Use FP16 to accelerate inference."} ) __snake_case : bool = field(default=lowerCAmelCase_ , metadata={"help": "Benchmark training of model"} ) __snake_case : bool = field(default=lowerCAmelCase_ , metadata={"help": "Verbose memory tracing"} ) __snake_case : bool = field( default=lowerCAmelCase_ , metadata={"help": "Whether to perform speed measurements. Speed measurements can be disabled via --no-speed."} , ) __snake_case : bool = field( default=lowerCAmelCase_ , metadata={ "help": "Whether to perform memory measurements. Memory measurements can be disabled via --no-memory" } , ) __snake_case : bool = field(default=lowerCAmelCase_ , metadata={"help": "Trace memory line by line"} ) __snake_case : bool = field(default=lowerCAmelCase_ , metadata={"help": "Save result to a CSV file"} ) __snake_case : bool = field(default=lowerCAmelCase_ , metadata={"help": "Save all print statements in a log file"} ) __snake_case : bool = field(default=lowerCAmelCase_ , metadata={"help": "Whether to print environment information"} ) __snake_case : bool = field( default=lowerCAmelCase_ , 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." ) } , ) __snake_case : str = field( default=F"inference_time_{round(time() )}.csv" , metadata={"help": "CSV filename used if saving time results to csv."} , ) __snake_case : str = field( default=F"inference_memory_{round(time() )}.csv" , metadata={"help": "CSV filename used if saving memory results to csv."} , ) __snake_case : str = field( default=F"train_time_{round(time() )}.csv" , metadata={"help": "CSV filename used if saving time results to csv for training."} , ) __snake_case : str = field( default=F"train_memory_{round(time() )}.csv" , metadata={"help": "CSV filename used if saving memory results to csv for training."} , ) __snake_case : str = field( default=F"env_info_{round(time() )}.csv" , metadata={"help": "CSV filename used if saving environment information."} , ) __snake_case : str = field( default=F"log_{round(time() )}.csv" , metadata={"help": "Log filename used if print statements are saved in log."} , ) __snake_case : int = field(default=3 , metadata={"help": "Times an experiment will be run."} ) __snake_case : bool = field( default=lowerCAmelCase_ , metadata={ "help": ( "Instead of loading the model as defined in `config.architectures` if exists, just load the pretrain" " model weights." ) } , ) def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ) -> Dict: '''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 SCREAMING_SNAKE_CASE__ ( self : Optional[int] ) -> Any: '''simple docstring''' return json.dumps(dataclasses.asdict(self ) ,indent=2 ) @property def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ) -> List[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 SCREAMING_SNAKE_CASE__ ( self : Optional[int] ) -> int: '''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
296
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 _snake_case = get_tests_dir("fixtures/test_sentencepiece_bpe.model") class UpperCAmelCase_ ( a , unittest.TestCase): lowerCamelCase__ = BartphoTokenizer lowerCamelCase__ = False lowerCamelCase__ = True def snake_case__ ( self): '''simple docstring''' super().setUp() _lowerCAmelCase : str = ["▁This", "▁is", "▁a", "▁t", "est"] _lowerCAmelCase : List[str] = dict(zip(__a, range(len(__a)))) _lowerCAmelCase : Optional[Any] = {"unk_token": "<unk>"} _lowerCAmelCase : Optional[int] = 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 : Optional[Any] = BartphoTokenizer(__a, self.monolingual_vocab_file, **self.special_tokens_map) tokenizer.save_pretrained(self.tmpdirname) def snake_case__ ( self, **__a): '''simple docstring''' kwargs.update(self.special_tokens_map) return BartphoTokenizer.from_pretrained(self.tmpdirname, **__a) def snake_case__ ( self, __a): '''simple docstring''' _lowerCAmelCase : Union[str, Any] = "This is a là test" _lowerCAmelCase : Optional[int] = "This is a<unk><unk> test" return input_text, output_text def snake_case__ ( self): '''simple docstring''' _lowerCAmelCase : Optional[int] = BartphoTokenizer(__a, self.monolingual_vocab_file, **self.special_tokens_map) _lowerCAmelCase : List[Any] = "This is a là test" _lowerCAmelCase : str = "▁This ▁is ▁a ▁l à ▁t est".split() _lowerCAmelCase : str = tokenizer.tokenize(__a) self.assertListEqual(__a, __a) _lowerCAmelCase : Tuple = tokens + [tokenizer.unk_token] _lowerCAmelCase : List[str] = [4, 5, 6, 3, 3, 7, 8, 3] self.assertListEqual(tokenizer.convert_tokens_to_ids(__a), __a)
36
import math import unittest def __lowercase ( _SCREAMING_SNAKE_CASE ) -> bool: '''simple docstring''' assert isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) and ( number >= 0 ), "'number' must been an int and positive" if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(math.sqrt(_SCREAMING_SNAKE_CASE ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True class UpperCamelCase__ ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE__ ( self : Dict ) -> Tuple: '''simple docstring''' self.assertTrue(is_prime(2 ) ) self.assertTrue(is_prime(3 ) ) self.assertTrue(is_prime(5 ) ) self.assertTrue(is_prime(7 ) ) self.assertTrue(is_prime(11 ) ) self.assertTrue(is_prime(13 ) ) self.assertTrue(is_prime(17 ) ) self.assertTrue(is_prime(19 ) ) self.assertTrue(is_prime(23 ) ) self.assertTrue(is_prime(29 ) ) def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ) -> Tuple: '''simple docstring''' with self.assertRaises(lowerCamelCase__ ): is_prime(-19 ) self.assertFalse( is_prime(0 ) ,"""Zero doesn't have any positive factors, primes must have exactly two.""" ,) self.assertFalse( is_prime(1 ) ,"""One only has 1 positive factor, primes must have exactly two.""" ,) self.assertFalse(is_prime(2 * 2 ) ) self.assertFalse(is_prime(2 * 3 ) ) self.assertFalse(is_prime(3 * 3 ) ) self.assertFalse(is_prime(3 * 5 ) ) self.assertFalse(is_prime(3 * 5 * 7 ) ) if __name__ == "__main__": unittest.main()
296
0
'''simple docstring''' from maths.prime_factors import prime_factors def _SCREAMING_SNAKE_CASE ( UpperCamelCase ): """simple docstring""" if not isinstance(UpperCamelCase , UpperCamelCase ): lowerCAmelCase__ : int = f"""Input value of [number={number}] must be an integer""" raise TypeError(UpperCamelCase ) if number < 1: raise ValueError("""Input must be a positive integer""" ) return -1 if len(prime_factors(UpperCamelCase ) ) % 2 else 1 if __name__ == "__main__": import doctest doctest.testmod()
37
import random class UpperCamelCase__ : '''simple docstring''' @staticmethod def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ : str ) -> tuple[list[int], list[int]]: '''simple docstring''' SCREAMING_SNAKE_CASE = [ord(lowerCamelCase__ ) for i in text] SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = [] for i in plain: SCREAMING_SNAKE_CASE = random.randint(1 ,300 ) SCREAMING_SNAKE_CASE = (i + k) * k cipher.append(lowerCamelCase__ ) key.append(lowerCamelCase__ ) return cipher, key @staticmethod def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ : list[int] ,lowerCamelCase__ : list[int] ) -> str: '''simple docstring''' SCREAMING_SNAKE_CASE = [] for i in range(len(lowerCamelCase__ ) ): SCREAMING_SNAKE_CASE = int((cipher[i] - (key[i]) ** 2) / key[i] ) plain.append(chr(lowerCamelCase__ ) ) return "".join(lowerCamelCase__ ) if __name__ == "__main__": SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = Onepad().encrypt("""Hello""") print(c, k) print(Onepad().decrypt(c, k))
296
0
import warnings 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 _SCREAMING_SNAKE_CASE ( _a ): snake_case__ : Union[str, Any] = ["""image_processor""", """tokenizer"""] snake_case__ : Optional[Any] = """FlavaImageProcessor""" snake_case__ : List[str] = ("""BertTokenizer""", """BertTokenizerFast""") def __init__( self : List[Any] , __lowerCamelCase : List[str]=None , __lowerCamelCase : Dict=None , **__lowerCamelCase : Tuple ): UpperCamelCase :Union[str, Any] = None if "feature_extractor" in kwargs: warnings.warn( """The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`""" """ instead.""" , __lowerCamelCase , ) UpperCamelCase :List[Any] = kwargs.pop("""feature_extractor""" ) UpperCamelCase :int = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError("""You need to specify an `image_processor`.""" ) if tokenizer is None: raise ValueError("""You need to specify a `tokenizer`.""" ) super().__init__(__lowerCamelCase , __lowerCamelCase ) UpperCamelCase :Optional[int] = self.image_processor def __call__( self : Optional[Any] , __lowerCamelCase : Optional[ImageInput] = None , __lowerCamelCase : Optional[Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]]] = None , __lowerCamelCase : bool = True , __lowerCamelCase : Union[bool, str, PaddingStrategy] = False , __lowerCamelCase : Union[bool, str, TruncationStrategy] = False , __lowerCamelCase : Optional[int] = None , __lowerCamelCase : int = 0 , __lowerCamelCase : Optional[int] = None , __lowerCamelCase : Optional[bool] = None , __lowerCamelCase : Optional[bool] = None , __lowerCamelCase : Optional[bool] = None , __lowerCamelCase : Optional[bool] = None , __lowerCamelCase : bool = False , __lowerCamelCase : bool = False , __lowerCamelCase : bool = False , __lowerCamelCase : bool = False , __lowerCamelCase : bool = True , __lowerCamelCase : Optional[Union[str, TensorType]] = None , **__lowerCamelCase : int , ): if text is None and images is None: raise ValueError("""You have to specify either text or images. Both cannot be none.""" ) if text is not None: UpperCamelCase :List[str] = self.tokenizer( text=__lowerCamelCase , add_special_tokens=__lowerCamelCase , padding=__lowerCamelCase , truncation=__lowerCamelCase , max_length=__lowerCamelCase , stride=__lowerCamelCase , pad_to_multiple_of=__lowerCamelCase , return_token_type_ids=__lowerCamelCase , return_attention_mask=__lowerCamelCase , return_overflowing_tokens=__lowerCamelCase , return_special_tokens_mask=__lowerCamelCase , return_offsets_mapping=__lowerCamelCase , return_length=__lowerCamelCase , verbose=__lowerCamelCase , return_tensors=__lowerCamelCase , **__lowerCamelCase , ) if images is not None: UpperCamelCase :Dict = self.image_processor( __lowerCamelCase , return_image_mask=__lowerCamelCase , return_codebook_pixels=__lowerCamelCase , return_tensors=__lowerCamelCase , **__lowerCamelCase , ) if text is not None and images is not None: encoding.update(__lowerCamelCase ) return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**__lowerCamelCase ) , tensor_type=__lowerCamelCase ) def _A ( self : Any , *__lowerCamelCase : int , **__lowerCamelCase : Optional[int] ): return self.tokenizer.batch_decode(*__lowerCamelCase , **__lowerCamelCase ) def _A ( self : Union[str, Any] , *__lowerCamelCase : Dict , **__lowerCamelCase : List[str] ): return self.tokenizer.decode(*__lowerCamelCase , **__lowerCamelCase ) @property def _A ( self : Tuple ): UpperCamelCase :Optional[Any] = self.tokenizer.model_input_names UpperCamelCase :Any = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) ) @property def _A ( self : Optional[Any] ): warnings.warn( """`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.""" , __lowerCamelCase , ) return self.image_processor_class @property def _A ( self : List[Any] ): warnings.warn( """`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.""" , __lowerCamelCase , ) return self.image_processor
38
from typing import List from ...configuration_utils import PretrainedConfig from ...utils import logging SCREAMING_SNAKE_CASE_ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE_ = { """snap-research/efficientformer-l1-300""": ( """https://huggingface.co/snap-research/efficientformer-l1-300/resolve/main/config.json""" ), } class UpperCamelCase__ ( lowerCAmelCase_ ): '''simple docstring''' __snake_case : int = "efficientformer" def __init__( self : Optional[int] ,lowerCamelCase__ : List[int] = [3, 2, 6, 4] ,lowerCamelCase__ : List[int] = [48, 96, 224, 448] ,lowerCamelCase__ : List[bool] = [True, True, True, True] ,lowerCamelCase__ : int = 448 ,lowerCamelCase__ : int = 32 ,lowerCamelCase__ : int = 4 ,lowerCamelCase__ : int = 7 ,lowerCamelCase__ : int = 5 ,lowerCamelCase__ : int = 8 ,lowerCamelCase__ : int = 4 ,lowerCamelCase__ : float = 0.0 ,lowerCamelCase__ : int = 16 ,lowerCamelCase__ : int = 3 ,lowerCamelCase__ : int = 3 ,lowerCamelCase__ : int = 3 ,lowerCamelCase__ : int = 2 ,lowerCamelCase__ : int = 1 ,lowerCamelCase__ : float = 0.0 ,lowerCamelCase__ : int = 1 ,lowerCamelCase__ : bool = True ,lowerCamelCase__ : bool = True ,lowerCamelCase__ : float = 1e-5 ,lowerCamelCase__ : str = "gelu" ,lowerCamelCase__ : float = 0.02 ,lowerCamelCase__ : float = 1e-1_2 ,lowerCamelCase__ : int = 224 ,lowerCamelCase__ : float = 1e-0_5 ,**lowerCamelCase__ : str ,) -> None: '''simple docstring''' super().__init__(**lowerCamelCase__ ) SCREAMING_SNAKE_CASE = hidden_act SCREAMING_SNAKE_CASE = hidden_dropout_prob SCREAMING_SNAKE_CASE = hidden_sizes SCREAMING_SNAKE_CASE = num_hidden_layers SCREAMING_SNAKE_CASE = num_attention_heads SCREAMING_SNAKE_CASE = initializer_range SCREAMING_SNAKE_CASE = layer_norm_eps SCREAMING_SNAKE_CASE = patch_size SCREAMING_SNAKE_CASE = num_channels SCREAMING_SNAKE_CASE = depths SCREAMING_SNAKE_CASE = mlp_expansion_ratio SCREAMING_SNAKE_CASE = downsamples SCREAMING_SNAKE_CASE = dim SCREAMING_SNAKE_CASE = key_dim SCREAMING_SNAKE_CASE = attention_ratio SCREAMING_SNAKE_CASE = resolution SCREAMING_SNAKE_CASE = pool_size SCREAMING_SNAKE_CASE = downsample_patch_size SCREAMING_SNAKE_CASE = downsample_stride SCREAMING_SNAKE_CASE = downsample_pad SCREAMING_SNAKE_CASE = drop_path_rate SCREAMING_SNAKE_CASE = num_metaad_blocks SCREAMING_SNAKE_CASE = distillation SCREAMING_SNAKE_CASE = use_layer_scale SCREAMING_SNAKE_CASE = layer_scale_init_value SCREAMING_SNAKE_CASE = image_size SCREAMING_SNAKE_CASE = batch_norm_eps
296
0
from typing import TYPE_CHECKING from ....utils import _LazyModule _a = {'''tokenization_tapex''': ['''TapexTokenizer''']} if TYPE_CHECKING: from .tokenization_tapex import TapexTokenizer else: import sys _a = _LazyModule(__name__, globals()['''__file__'''], _import_structure)
39
import importlib import shutil import threading import warnings from typing import List import fsspec import fsspec.asyn from . import compression from .hffilesystem import HfFileSystem SCREAMING_SNAKE_CASE_ = importlib.util.find_spec("""s3fs""") is not None if _has_safs: from .safilesystem import SaFileSystem # noqa: F401 SCREAMING_SNAKE_CASE_ = [ compression.BzaFileSystem, compression.GzipFileSystem, compression.LzaFileSystem, compression.XzFileSystem, compression.ZstdFileSystem, ] # Register custom filesystems for fs_class in COMPRESSION_FILESYSTEMS + [HfFileSystem]: if fs_class.protocol in fsspec.registry and fsspec.registry[fs_class.protocol] is not fs_class: warnings.warn(F'''A filesystem protocol was already set for {fs_class.protocol} and will be overwritten.''') fsspec.register_implementation(fs_class.protocol, fs_class, clobber=True) def __lowercase ( _SCREAMING_SNAKE_CASE ) -> str: '''simple docstring''' if "://" in dataset_path: SCREAMING_SNAKE_CASE = dataset_path.split("""://""" )[1] return dataset_path def __lowercase ( _SCREAMING_SNAKE_CASE ) -> bool: '''simple docstring''' if fs is not None and fs.protocol != "file": return True else: return False def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Dict: '''simple docstring''' SCREAMING_SNAKE_CASE = not is_remote_filesystem(_SCREAMING_SNAKE_CASE ) if is_local: # LocalFileSystem.mv does copy + rm, it is more efficient to simply move a local directory shutil.move(fs._strip_protocol(_SCREAMING_SNAKE_CASE ) , fs._strip_protocol(_SCREAMING_SNAKE_CASE ) ) else: fs.mv(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , recursive=_SCREAMING_SNAKE_CASE ) def __lowercase ( ) -> None: '''simple docstring''' if hasattr(fsspec.asyn , """reset_lock""" ): # for future fsspec>2022.05.0 fsspec.asyn.reset_lock() else: SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = threading.Lock()
296
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) __lowercase = { """configuration_encodec""": [ """ENCODEC_PRETRAINED_CONFIG_ARCHIVE_MAP""", """EncodecConfig""", ], """feature_extraction_encodec""": ["""EncodecFeatureExtractor"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowercase = [ """ENCODEC_PRETRAINED_MODEL_ARCHIVE_LIST""", """EncodecModel""", """EncodecPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_encodec import ( ENCODEC_PRETRAINED_CONFIG_ARCHIVE_MAP, EncodecConfig, ) from .feature_extraction_encodec import EncodecFeatureExtractor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_encodec import ( ENCODEC_PRETRAINED_MODEL_ARCHIVE_LIST, EncodecModel, EncodecPreTrainedModel, ) else: import sys __lowercase = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
40
import unittest import numpy as np import torch from diffusers import KarrasVePipeline, KarrasVeScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class UpperCamelCase__ ( unittest.TestCase ): '''simple docstring''' @property def SCREAMING_SNAKE_CASE__ ( self : str ) -> Optional[int]: '''simple docstring''' torch.manual_seed(0 ) SCREAMING_SNAKE_CASE = UNetaDModel( block_out_channels=(32, 64) ,layers_per_block=2 ,sample_size=32 ,in_channels=3 ,out_channels=3 ,down_block_types=("""DownBlock2D""", """AttnDownBlock2D""") ,up_block_types=("""AttnUpBlock2D""", """UpBlock2D""") ,) return model def SCREAMING_SNAKE_CASE__ ( self : Tuple ) -> Union[str, Any]: '''simple docstring''' SCREAMING_SNAKE_CASE = self.dummy_uncond_unet SCREAMING_SNAKE_CASE = KarrasVeScheduler() SCREAMING_SNAKE_CASE = KarrasVePipeline(unet=lowerCamelCase__ ,scheduler=lowerCamelCase__ ) pipe.to(lowerCamelCase__ ) pipe.set_progress_bar_config(disable=lowerCamelCase__ ) SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE = pipe(num_inference_steps=2 ,generator=lowerCamelCase__ ,output_type="""numpy""" ).images SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE = pipe(num_inference_steps=2 ,generator=lowerCamelCase__ ,output_type="""numpy""" ,return_dict=lowerCamelCase__ )[0] SCREAMING_SNAKE_CASE = image[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) SCREAMING_SNAKE_CASE = np.array([0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 @slow @require_torch class UpperCamelCase__ ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ) -> Optional[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE = """google/ncsnpp-celebahq-256""" SCREAMING_SNAKE_CASE = UNetaDModel.from_pretrained(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = KarrasVeScheduler() SCREAMING_SNAKE_CASE = KarrasVePipeline(unet=lowerCamelCase__ ,scheduler=lowerCamelCase__ ) pipe.to(lowerCamelCase__ ) pipe.set_progress_bar_config(disable=lowerCamelCase__ ) SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE = pipe(num_inference_steps=20 ,generator=lowerCamelCase__ ,output_type="""numpy""" ).images SCREAMING_SNAKE_CASE = image[0, -3:, -3:, -1] assert image.shape == (1, 256, 256, 3) SCREAMING_SNAKE_CASE = np.array([0.578, 0.5811, 0.5924, 0.5809, 0.587, 0.5886, 0.5861, 0.5802, 0.586] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
296
0